protected async Task WebClient(PhotonServerDefinition server, Func <WebClient, Task> clientTask) { var client = WebClientFactory.Create(server, Username, Password); try { await clientTask(client); } catch (WebException error) { if (error.Response is HttpWebResponse httpResponse) { if (httpResponse.StatusCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } if (httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new HttpUnauthorizedException(); } } throw; } finally { client.Dispose(); } }
private async Task BeginServerUpdate(PhotonServerDefinition server, HttpPackageIndex index) { ConsoleEx.Out.Write("Downloading Server update ", ConsoleColor.DarkCyan) .Write(index.Version, ConsoleColor.Cyan) .WriteLine("...", ConsoleColor.DarkCyan); var updateDirectory = Path.Combine(Configuration.Directory, "Updates"); var updateFilename = Path.Combine(updateDirectory, "Photon.Server.msi"); PathEx.CreatePath(updateDirectory); using (var client = new WebClient()) { var url = NetPath.Combine(Configuration.DownloadUrl, "server", index.Version, index.MsiFilename); await client.DownloadFileTaskAsync(url, updateFilename); } ConsoleEx.Out .WriteLine("Download Complete.", ConsoleColor.DarkBlue) .WriteLine("Uploading update to Server...", ConsoleColor.DarkCyan); await WebClientEx(server, client => { client.Method = "POST"; client.Url = NetPath.Combine(server.Url, "api/server/update"); client.ContentType = "application/octet-stream"; client.BodyFunc = () => File.Open(updateFilename, FileMode.Open, FileAccess.Read); }, null); ConsoleEx.Out.WriteLine("Upload Complete.", ConsoleColor.DarkBlue); }
private async Task Reconnect(PhotonServerDefinition server, string latestVersion, TimeSpan timeout) { using (var tokenSource = new CancellationTokenSource(timeout)) using (var client = new WebClient()) { var token = tokenSource.Token; while (true) { token.ThrowIfCancellationRequested(); try { var url = NetPath.Combine(server.Url, "api/version"); var version = await client.DownloadStringTaskAsync(url); if (!VersionTools.HasUpdates(version, latestVersion)) { break; } } catch (Exception error) when(error is SocketException || error is WebException) { await Task.Delay(1000, tokenSource.Token); } } } }
private async Task <HttpAgentUpdateResultResponse> GetResult(PhotonServerDefinition server, string sessionId) { HttpClientEx client = null; try { var url = NetPath.Combine(server.Url, "api/agent/update/result"); client = HttpClientEx.Get(url, new { session = sessionId, }); await client.Send(); return(client.ParseJsonResponse <HttpAgentUpdateResultResponse>()); } catch (HttpStatusCodeException error) { if (error.HttpCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } throw; } finally { client?.Dispose(); } }
public static WebClient Create(PhotonServerDefinition server, string username, string password) { var webClient = new WebClient(); try { webClient.BaseAddress = server.Url; if (!webClient.BaseAddress.EndsWith("/")) { webClient.BaseAddress += "/"; } if (!string.IsNullOrEmpty(username)) { var creds = Encoding.ASCII.GetBytes($"{username}:{password}"); var creds64 = Convert.ToBase64String(creds); webClient.Headers[HttpRequestHeader.Authorization] = $"Basic {creds64}"; } return(webClient); } catch { webClient.Dispose(); throw; } }
private async Task <HttpDeployResultResponse> GetResult(PhotonServerDefinition server, string sessionId) { return(await WebClient(server, async client => { client.QueryString["session"] = sessionId; var json = await client.DownloadStringTaskAsync("api/deploy/result"); return JsonConvert.DeserializeObject <HttpDeployResultResponse>(json); })); }
private async Task <HttpSessionStartResponse> StartSession(PhotonServerDefinition server, string[] agentIds, string updateFilename) { return(await WebClientEx(server, client => { client.Method = "POST"; client.Url = NetPath.Combine(server.Url, "api/agent/update/start"); client.Query = new { agents = string.Join(";", agentIds), }; client.BodyFunc = () => File.Open(updateFilename, FileMode.Open, FileAccess.Read); }, client => client.ParseJsonResponse <HttpSessionStartResponse>())); }
private async Task <HttpBuildStartResponse> StartSession(PhotonServerDefinition server) { return(await WebClientEx(server, client => { client.Url = NetPath.Combine(server.Url, "api/build/start"); client.Method = "POST"; client.Query = new { project = ProjectId, task = TaskName, refspec = GitRefspec, }; }, client => client.ParseJsonResponse <HttpBuildStartResponse>())); }
protected async Task <T> WebClientEx <T>(PhotonServerDefinition server, Action <HttpClientEx> requestAction, Func <HttpClientEx, T> responseAction) { HttpClientEx client = null; try { client = new HttpClientEx { Method = "GET", Username = Username, Password = Password, }; requestAction?.Invoke(client); await client.Send(); //if (client.ResponseBase.StatusCode == HttpStatusCode.Unauthorized) // throw new ApplicationException("Access not authorized!"); if (client.ResponseBase.StatusCode == HttpStatusCode.BadRequest) { var text = await client.GetResponseTextAsync(); throw new ApplicationException($"Bad Update Request! {text}"); } if (responseAction != null) { return(responseAction.Invoke(client)); } return(default(T)); } catch (HttpStatusCodeException error) { if (error.HttpCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } if (error.HttpCode == HttpStatusCode.Unauthorized) { throw new HttpUnauthorizedException(); } throw; } finally { client?.Dispose(); } }
private async Task <HttpSessionStartResponse> StartSession(PhotonServerDefinition server) { return(await WebClientEx(server, client => { client.Url = NetPath.Combine(server.Url, "api/deploy/start"); client.Method = "POST"; client.Query = new { project = ProjectId, package = ProjectPackageId, version = ProjectPackageVersion, env = Environment, }; }, client => client.ParseJsonResponse <HttpSessionStartResponse>())); }
private async Task <OutputData> UpdateOutput(PhotonServerDefinition server, string sessionId, int position) { return(await WebClientEx(server, client => { client.Url = NetPath.Combine(server.Url, "api/session/output"); client.Query = new { session = sessionId, start = position, }; }, client => { bool _complete; if (client.ResponseBase.StatusCode == HttpStatusCode.NotModified) { bool.TryParse(client.ResponseBase.Headers.Get("X-Complete"), out _complete); return new OutputData { IsComplete = _complete }; } var result = new OutputData(); if (bool.TryParse(client.ResponseBase.Headers.Get("X-Complete"), out _complete)) { result.IsComplete = _complete; } if (int.TryParse(client.ResponseBase.Headers.Get("X-Text-Pos"), out var _textPos)) { result.NewLength = _textPos; } using (var responseStream = client.ResponseBase.GetResponseStream()) { if (responseStream == null) { return result; } using (var reader = new StreamReader(responseStream)) { result.NewText = reader.ReadToEnd(); } } result.IsModified = true; return result; })); }
public async Task Run(CommandContext context) { var definition = new PhotonServerDefinition { Name = ServerName, Url = ServerUrl, Primary = ServerPrimary ?? false, }; context.Servers.Add(definition); if (ServerPrimary ?? false) { context.Servers.SetPrimary(ServerName); } await Task.Run(() => context.Servers.Save()); }
private async Task <HttpBuildStartResponse> StartSession(PhotonServerDefinition server, HttpBuildStartRequest request) { HttpClientEx client = null; MemoryStream requestStream = null; try { requestStream = new MemoryStream(); JsonSettings.Serializer.Serialize(requestStream, request, true); var url = NetPath.Combine(server.Url, "api/build/start"); client = HttpClientEx.Post(url, new { refspec = GitRefspec, }); requestStream.Seek(0, SeekOrigin.Begin); client.Body = requestStream; await client.Send(); if (client.ResponseBase.StatusCode == HttpStatusCode.BadRequest) { var text = await client.GetResponseTextAsync(); throw new ApplicationException($"Bad Build Request! {text}"); } return(client.ParseJsonResponse <HttpBuildStartResponse>()); } catch (HttpStatusCodeException error) { if (error.HttpCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } throw; } finally { requestStream?.Dispose(); client?.Dispose(); } }
protected async Task <T> WebClient <T>(PhotonServerDefinition server, Func <WebClient, Task <T> > clientTask) { var client = WebClientFactory.Create(server, Username, Password); try { return(await clientTask(client)); } catch (WebException error) { if (error.Response is HttpWebResponse httpResponse) { if (httpResponse.StatusCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } if (httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new HttpUnauthorizedException(); } if (httpResponse.StatusCode == HttpStatusCode.BadRequest) { string text = null; try { using (var stream = httpResponse.GetResponseStream()) using (var reader = new StreamReader(stream)) { text = await reader.ReadToEndAsync(); } } catch {} throw new ApplicationException($"Bad Request! {text}"); } } throw; } finally { client.Dispose(); } }
private async Task <HttpDeployStartResponse> StartSession(PhotonServerDefinition server) { HttpClientEx client = null; try { var url = NetPath.Combine(server.Url, "api/deploy/start"); client = HttpClientEx.Post(url, new { project = ProjectId, package = ProjectPackageId, version = ProjectPackageVersion, env = Environment, }); await client.Send(); if (client.ResponseBase.StatusCode == HttpStatusCode.BadRequest) { var text = await client.GetResponseTextAsync(); throw new ApplicationException($"Bad Deploy Request! {text}"); } return(client.ParseJsonResponse <HttpDeployStartResponse>()); } catch (HttpStatusCodeException error) { if (error.HttpCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } throw; } finally { client?.Dispose(); } }
private async Task <HttpAgentUpdateStartResponse> StartSession(PhotonServerDefinition server, string[] agentIds, string updateFilename) { HttpClientEx client = null; try { var url = NetPath.Combine(server.Url, "api/agent/update/start"); client = HttpClientEx.Post(url); client.Query = new { agents = string.Join(";", agentIds), }; client.BodyFunc = () => File.Open(updateFilename, FileMode.Open, FileAccess.Read); await client.Send(); if (client.ResponseBase.StatusCode == HttpStatusCode.BadRequest) { var text = await client.GetResponseTextAsync(); throw new ApplicationException($"Bad Update Request! {text}"); } return(client.ParseJsonResponse <HttpAgentUpdateStartResponse>()); } catch (HttpStatusCodeException error) { if (error.HttpCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } throw; } finally { client?.Dispose(); } }
private async Task Reconnect(PhotonServerDefinition server, string latestVersion, TimeSpan timeout) { using (var tokenSource = new CancellationTokenSource(timeout)) using (var webClient = WebClientFactory.Create(server, Username, Password)) { var token = tokenSource.Token; while (true) { token.ThrowIfCancellationRequested(); try { var version = await webClient.DownloadStringTaskAsync("api/version"); if (!VersionTools.HasUpdates(version, latestVersion)) { break; } } catch (Exception error) when(error is SocketException || error is WebException) { await Task.Delay(1000, tokenSource.Token); } } } }
private async Task <OutputData> UpdateOutput(PhotonServerDefinition server, string sessionId, int position) { HttpClientEx client = null; try { var url = NetPath.Combine(server.Url, "api/session/output"); client = HttpClientEx.Get(url, new { session = sessionId, start = position, }); await client.Send(); bool _complete; if (client.ResponseBase.StatusCode == HttpStatusCode.NotModified) { bool.TryParse(client.ResponseBase.Headers.Get("X-Complete"), out _complete); return(new OutputData { IsComplete = _complete }); } var result = new OutputData(); if (bool.TryParse(client.ResponseBase.Headers.Get("X-Complete"), out _complete)) { result.IsComplete = _complete; } if (int.TryParse(client.ResponseBase.Headers.Get("X-Text-Pos"), out var _textPos)) { result.NewLength = _textPos; } using (var responseStream = client.ResponseBase.GetResponseStream()) { if (responseStream == null) { return(result); } using (var reader = new StreamReader(responseStream)) { result.NewText = reader.ReadToEnd(); } } result.IsModified = true; return(result); } catch (HttpStatusCodeException error) { if (error.HttpCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } throw; } finally { client?.Dispose(); } }
private async Task BeginServerUpdate(PhotonServerDefinition server, HttpPackageIndex index) { ConsoleEx.Out.Write("Downloading Server update ", ConsoleColor.DarkCyan) .Write(index.Version, ConsoleColor.Cyan) .WriteLine("...", ConsoleColor.DarkCyan); string updateFilename; try { var url = NetPath.Combine(Configuration.DownloadUrl, "server", index.Version, index.MsiFilename); var updateDirectory = Path.Combine(Configuration.Directory, "Updates"); updateFilename = Path.Combine(updateDirectory, "Photon.Server.msi"); PathEx.CreatePath(updateDirectory); using (var client = HttpClientEx.Get(url)) { await client.Send(); using (var responseStream = client.ResponseBase.GetResponseStream()) { using (var fileStream = File.Open(updateFilename, FileMode.Create, FileAccess.Write)) if (responseStream != null) { await responseStream.CopyToAsync(fileStream); } } } ConsoleEx.Out.WriteLine("Download Complete.", ConsoleColor.DarkBlue); } catch (HttpStatusCodeException error) { if (error.HttpCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } throw; } ConsoleEx.Out.WriteLine("Uploading update to Server...", ConsoleColor.DarkCyan); try { var url = NetPath.Combine(server.Url, "api/server/update"); using (var client = HttpClientEx.Post(url)) { client.ContentType = "application/octet-stream"; client.BodyFunc = () => File.Open(updateFilename, FileMode.Open, FileAccess.Read); await client.Send(); if (client.ResponseBase.StatusCode == HttpStatusCode.BadRequest) { var text = await client.GetResponseTextAsync(); throw new ApplicationException($"Bad Update Request! {text}"); } } ConsoleEx.Out.WriteLine("Upload Complete.", ConsoleColor.DarkBlue); } catch (HttpStatusCodeException error) { if (error.HttpCode == HttpStatusCode.NotFound) { throw new ApplicationException($"Photon-Server instance '{server.Name}' not found!"); } throw; } }
public static WebClient Create(PhotonServerDefinition server) { return(Create(server, null, null)); }