public static PackageDeploymentData Create(IOperationExecutionContext context, ILogSink log, string description) { string baseUrl = SDK.BaseUrl; if (string.IsNullOrEmpty(baseUrl)) { log.LogDebug("Deployment will not be recorded in ProGet because the System.BaseUrl configuration setting is not set."); return(null); } string serverName = AH.CoalesceString(context?.ServerName, Environment.MachineName); string relativeUrl; if (SDK.ProductName == "BuildMaster") { dynamic bmContext = context; relativeUrl = $"applications/{bmContext.ApplicationId}/builds/build?releaseNumber={Uri.EscapeDataString(bmContext.ReleaseNumber)}&buildNumber={Uri.EscapeDataString(bmContext.BuildNumber)}"; } else { relativeUrl = "/deployment-sets/details?deploymentSetId=" + ((IStandardContext)context).DeploymentSetId; } return(new PackageDeploymentData(SDK.ProductName, baseUrl, relativeUrl, serverName, description)); }
protected override async Task ExecuteRaftAsync(IOperationExecutionContext context, RaftRepository actualRaft, RaftRepository raftShim) { var actualItems = await actualRaft.GetRaftItemsAsync(); var shimItems = await raftShim.GetRaftItemsAsync(); var actualLookup = actualItems.ToLookup(i => (i.ItemType, i.ItemName)); var shimLookup = shimItems.ToLookup(i => (i.ItemType, i.ItemName)); bool any = false; if (this.DeleteMissing) { foreach (var item in actualItems) { if (shimLookup.Contains((item.ItemType, item.ItemName))) { continue; } any = true; this.LogInformation($"Deleting {item.ItemType} {item.ItemName}, which is present in the raft but not locally."); await actualRaft.DeleteRaftItemAsync(item.ItemType, item.ItemName); } } foreach (var item in shimItems) { var actualItem = actualLookup[(item.ItemType, item.ItemName)].FirstOrDefault();
internal static async Task WrapInVirtualEnv(ILogSink logger, IOperationExecutionContext context, RemoteProcessStartInfo startInfo, string pythonExePath, string virtualEnv) { if (string.IsNullOrEmpty(virtualEnv)) { return; } var fileOps = await context.Agent.GetServiceAsync <IFileOperationsExecuter>(); if (!await fileOps.DirectoryExistsAsync(virtualEnv)) { var procExec = await context.Agent.GetServiceAsync <IRemoteProcessExecuter>(); logger.LogDebug($"Virtual environment in {virtualEnv} is not present. Attempting venv (Python 3.3+)..."); var success = false; using (var process = procExec.CreateProcess(new RemoteProcessStartInfo { FileName = pythonExePath, WorkingDirectory = context.WorkingDirectory, Arguments = "-m venv -- " + virtualEnv, })) { process.OutputDataReceived += (s, e) => logger.LogDebug("(venv) " + e.Data); process.ErrorDataReceived += (s, e) => logger.LogDebug("(venv) " + e.Data); await process.WaitAsync(context.CancellationToken); success = process.ExitCode == 0; } if (!success) { logger.LogDebug("Attempting virtualenv (any Python version, but requires separate installation)..."); using var process = procExec.CreateProcess( new RemoteProcessStartInfo { FileName = "virtualenv", WorkingDirectory = context.WorkingDirectory, Arguments = "-- " + virtualEnv, EnvironmentVariables = { ["VIRTUALENV_PYTHON"] = pythonExePath } } ); process.OutputDataReceived += (s, e) => logger.LogDebug("(virtualenv) " + e.Data); process.ErrorDataReceived += (s, e) => logger.LogDebug("(virtualenv) " + e.Data); await process.WaitAsync(context.CancellationToken); success = process.ExitCode == 0; } if (!success) { throw new ExecutionFailureException("Could not create a virtual environment. See debug logs from this operation for more information."); } } startInfo.FileName = (await fileOps.GetFileInfoAsync(fileOps.CombinePath(virtualEnv, "bin", "python"))).FullName; }
public override async Task ExecuteAsync(IOperationExecutionContext context) { var request = new Request { Status = this.Status, Comment = this.Comment, DryRun = context.Simulation, SourceRepo = this.FromRepository, TargetRepo = this.ToRepository, Copy = this.Copy, Scopes = this.Scopes, Properties = this.Properties.ToDictionary(p => p.Key, p => p.Value.AsEnumerable().Select(v => v.AsString())) }; await this.PostAsync($"api/build/promote/{Uri.EscapeUriString(this.BuildName)}/{Uri.EscapeUriString(this.BuildNumber)}", request, async response => { var result = await this.ParseResponseAsync <BuildResult>(response).ConfigureAwait(false); if (result.Messages != null) { foreach (var message in result.Messages) { this.Log(MessageLevels.ContainsKey(message.Level) ? MessageLevels[message.Level] : MessageLevel.Warning, message.Message); } } }, context.CancellationToken).ConfigureAwait(false); }
public override async Task ExecuteAsync(IOperationExecutionContext context) { var sourceDirectory = context.ResolvePath(this.SourceDirectory); this.LogInformation($"Concatenating files in {sourceDirectory}..."); var fileOps = await context.Agent.GetServiceAsync <IFileOperationsExecuter>(); var files = (await fileOps.GetFileSystemInfosAsync(sourceDirectory, new MaskingContext(this.Includes, this.Excludes)).ConfigureAwait(false)) .OfType <SlimFileInfo>() .ToList(); if (files.Count == 0) { this.LogWarning("No files to concatenate."); return; } var encoding = this.GetOrGuessEncoding(); var outputFileName = context.ResolvePath(this.OutputFile); this.LogInformation($"Concatenating {files.Count} files into {PathEx.GetFileName(outputFileName)}..."); this.LogDebug($"Output file {outputFileName}, encoding: {encoding.EncodingName}"); var outputDirectory = PathEx.GetDirectoryName(outputFileName); if (!string.IsNullOrEmpty(outputDirectory)) { await fileOps.CreateDirectoryAsync(outputDirectory).ConfigureAwait(false); } using (var outputStream = await fileOps.OpenFileAsync(outputFileName, FileMode.Create, FileAccess.Write).ConfigureAwait(false)) using (var outputWriter = new StreamWriter(outputStream, encoding)) { bool first = true; foreach (var file in files) { context.CancellationToken.ThrowIfCancellationRequested(); if (!first) { await outputWriter.WriteAsync(this.ContentSeparationText ?? "").ConfigureAwait(false); } else { first = false; } using (var inputStream = await fileOps.OpenFileAsync(file.FullName, FileMode.Open, FileAccess.Read).ConfigureAwait(false)) using (var inputReader = new StreamReader(inputStream)) { await inputReader.CopyToAsync(outputWriter, 4096, context.CancellationToken).ConfigureAwait(false); } } } this.LogInformation(outputFileName + " file created."); }
public override async Task ConfigureAsync(IOperationExecutionContext context) { var path = this.Template.Name; var fileOps = await context.Agent.GetServiceAsync <IFileOperationsExecuter>().ConfigureAwait(false); this.LogDebug($"Looking for {path}..."); bool directoryExists = await fileOps.DirectoryExistsAsync(path).ConfigureAwait(false); if (!this.Template.Exists) { if (directoryExists) { this.LogDebug("Directory exists, removing..."); await fileOps.DeleteDirectoryAsync(path).ConfigureAwait(false); this.LogInformation($"Deleted directory {path}."); } else { this.LogDebug("Directory does not exist."); } return; } if (!directoryExists) { this.LogDebug("Directory does not exist, creating..."); await fileOps.CreateDirectoryAsync(path).ConfigureAwait(false); } this.LogInformation($"Directory {path} configured."); }
public override async Task ExecuteAsync(IOperationExecutionContext context) { var gitlab = new GitLabClient(this.ApiUrl, this.UserName, this.Password, this.GroupName); var data = new Dictionary <string, object> { ["title"] = this.Title }; if (this.AdditionalProperties != null) { foreach (var p in this.AdditionalProperties) { data.Add(p.Key, p.Key == "confidential" ? bool.Parse(p.Value?.ToString()) : p.Key == "weight" ? int.Parse(p.Value?.ToString()) : p.Value); } } if (!string.IsNullOrEmpty(this.Body)) { data.Add("description", this.Body); } if (this.Labels != null) { data.Add("labels", string.Join(",", this.Labels)); } if (this.Assignees != null) { data.Add("assignee_ids", (await Task.WhenAll(this.Assignees.Select(name => gitlab.FindUserAsync(name, context.CancellationToken))).ConfigureAwait(false)).Where(id => id.HasValue)); } if (!string.IsNullOrEmpty(this.Milestone)) { data.Add("milestone_id", await gitlab.CreateMilestoneAsync(this.Milestone, this.ProjectName, context.CancellationToken).ConfigureAwait(false)); } this.IssueId = await gitlab.CreateIssueAsync(this.ProjectName, data, context.CancellationToken).ConfigureAwait(false); }
public override async Task ExecuteAsync(IOperationExecutionContext context) { var fileOps = await context.Agent.GetServiceAsync <IFileOperationsExecuter>().ConfigureAwait(false); var nugetExe = await this.GetNuGetExePathAsync(context).ConfigureAwait(false); if (string.IsNullOrEmpty(nugetExe)) { this.LogError("nuget.exe path was empty."); return; } var sourceDirectory = context.ResolvePath(this.SourceDirectory); var outputDirectory = context.ResolvePath(this.OutputDirectory, this.SourceDirectory); var fullProjectPath = context.ResolvePath(this.ProjectPath, this.SourceDirectory); if (!await fileOps.FileExistsAsync(fullProjectPath).ConfigureAwait(false)) { this.LogError(fullProjectPath + " does not exist."); return; } fileOps.CreateDirectory(outputDirectory); this.LogInformation($"Creating NuGet package from {fullProjectPath} to {outputDirectory}..."); await this.ExecuteNuGet(context, nugetExe, fullProjectPath, sourceDirectory, outputDirectory).ConfigureAwait(false); }
protected async Task CallRemoteAsync(IOperationExecutionContext context) { if (!this.ProxyRequest) { await this.PerformRequestAsync(context.CancellationToken).ConfigureAwait(false); return; } var executer = await context.Agent.TryGetServiceAsync <IRemoteJobExecuter>().ConfigureAwait(false); if (executer == null) { this.LogError($"\"Use server in context\" is not supported for this agent: {context.Agent.GetDescription()}"); return; } var job = new RemoteHttpJob { Operation = this }; job.MessageLogged += (s, e) => this.Log(e.Level, e.Message); context.CancellationToken.Register(() => job.Cancel()); await executer.ExecuteJobAsync(job).ConfigureAwait(false); }
public override async Task ConfigureAsync(IOperationExecutionContext context) { var gitlab = new GitLabClient(this.Template.ApiUrl, this.Template.UserName, this.Template.Password, this.Template.GroupName); var id = await gitlab.CreateMilestoneAsync(this.Template.Title, this.Template.ProjectName, context.CancellationToken).ConfigureAwait(false); var data = new Dictionary <string, object> { ["title"] = this.Template.Title }; if (this.Template.StartDate != null) { data.Add("start_date", AH.NullIf(this.Template.StartDate, string.Empty)); } if (this.Template.DueDate != null) { data.Add("due_date", AH.NullIf(this.Template.DueDate, string.Empty)); } if (this.Template.Description != null) { data.Add("description", this.Template.Description); } if (this.Template.State.HasValue) { data.Add("state_event", this.Template.State == GitLabMilestoneConfiguration.OpenOrClosed.open ? "activate" : "close"); } await gitlab.UpdateMilestoneAsync(id, this.Template.ProjectName, data, context.CancellationToken).ConfigureAwait(false); }
private async Task ExecuteNuGetAsync(IOperationExecutionContext context, string nugetExe, string args, string logArgs = null) { if (!string.IsNullOrWhiteSpace(this.AdditionalArguments)) { args += " " + this.AdditionalArguments; if (logArgs != null) { logArgs += this.AdditionalArguments; } } this.LogDebug("Executing: " + nugetExe + " " + (logArgs ?? args)); int exitCode = await this.ExecuteCommandLineAsync( context, new RemoteProcessStartInfo { FileName = nugetExe, Arguments = args } ).ConfigureAwait(false); if (exitCode != 0) { this.LogError($"NuGet.exe exited with code {exitCode}"); } }
public override async Task ExecuteAsync(IOperationExecutionContext context) { try { new Uri(this.Url); } catch (Exception ex) { this.LogError($"The {this.Method} request URL \"{this.Url}\" is invalid because: {ex.Message}"); return; } this.LogInformation($"Performing HTTP {this.Method} request to {this.Url}..."); if (this.Method == GetHttpMethod.DELETE) { using (var client = this.CreateClient()) using (var response = await client.DeleteAsync(this.Url, context.CancellationToken).ConfigureAwait(false)) { await this.ProcessResponseAsync(response).ConfigureAwait(false); } } else { using (var client = this.CreateClient()) using (var response = await client.GetAsync(this.Url, HttpCompletionOption.ResponseHeadersRead, context.CancellationToken).ConfigureAwait(false)) { await this.ProcessResponseAsync(response).ConfigureAwait(false); } } }
public override async Task ExecuteAsync(IOperationExecutionContext context) { string repositoryUrl = this.GetRepositoryUrl(); string branchDesc = string.IsNullOrEmpty(this.Branch) ? "" : $" on '{this.Branch}' branch"; this.LogInformation($"Tag '{repositoryUrl}'{branchDesc} as '{this.Tag}'..."); var client = this.CreateClient(context, repositoryUrl, WorkspacePath.Resolve(context, repositoryUrl, this.WorkspaceDiskPath)); bool valid = await client.IsRepositoryValidAsync().ConfigureAwait(false); if (!valid) { await client.CloneAsync( new GitCloneOptions { Branch = this.Branch, RecurseSubmodules = this.RecurseSubmodules } ).ConfigureAwait(false); } await client.UpdateAsync( new GitUpdateOptions { RecurseSubmodules = this.RecurseSubmodules, Branch = this.Branch, Tag = this.Tag } ).ConfigureAwait(false); await client.TagAsync(this.Tag).ConfigureAwait(false); this.LogInformation("Tag complete."); }
private async Task <string> GetVsTestPathAsync(IOperationExecutionContext context) { if (string.IsNullOrWhiteSpace(this.VsTestPath)) { this.LogDebug("$VsTestExePath variable not configured and VsTestPath not specified, attempting to find using vswhere.exe..."); var path = await this.FindVsTestConsoleWithVsWhereAsync(context).ConfigureAwait(false); if (path != null) { this.LogDebug("Using VS test path: " + path); return(path); } this.LogError("Unable to find vstest.console.exe. Verify that VSTest is installed and set a $VSTestExePath variable in context to its full path."); return(null); } else { this.LogDebug("VSTestExePath = " + this.VsTestPath); var fileOps = await context.Agent.GetServiceAsync <IFileOperationsExecuter>().ConfigureAwait(false); bool exists = await fileOps.FileExistsAsync(this.VsTestPath).ConfigureAwait(false); if (!exists) { this.LogError($"The file {this.VsTestPath} does not exist. Verify that VSTest is installed."); return(null); } return(this.VsTestPath); } }
public override async Task ExecuteAsync(IOperationExecutionContext context) { var buffer = new StringBuilder("upgrade --yes --fail-on-unfound ", 200); if (context.Simulation) { buffer.Append("--what-if "); } if (!string.IsNullOrEmpty(this.Version)) { buffer.Append("--version \""); buffer.Append(this.Version); buffer.Append("\" "); } buffer.Append('\"'); buffer.Append(this.PackageName); buffer.Append('\"'); int exitCode = await this.ExecuteCommandLineAsync( context, new RemoteProcessStartInfo { FileName = "choco", Arguments = buffer.ToString() } ).ConfigureAwait(false); if (exitCode != 0) { this.LogError("Process exited with code " + exitCode); } }
public override async Task ExecuteAsync(IOperationExecutionContext context) { await this.LoginAsync(context, this.ContainerSource); try { var containerSource = (ContainerSource)SecureResource.Create(this.ContainerSource, (IResourceResolutionContext)context); var containerId = new ContainerId(this.ContainerSource, containerSource?.RegistryPrefix, this.RepositoryName, this.Tag); if (!string.IsNullOrEmpty(this.ContainerSource)) { containerId = await this.PullAsync(context, containerId); } var containerConfigArgs = await this.GetContainerConfigText(context); if (containerConfigArgs == null) { return; } var escapeArg = GetEscapeArg(context); var args = new StringBuilder("run "); args.Append(containerConfigArgs); args.Append(' '); if (this.RunInBackground) { args.Append("-d "); } else if (string.IsNullOrWhiteSpace(this.ContainerName)) { args.Append("--rm "); } if (!string.IsNullOrWhiteSpace(this.ContainerName)) { args.Append($"--name {escapeArg(this.ContainerName)} "); } args.Append(escapeArg(containerId.FullName)); var argsText = args.ToString(); this.LogDebug($"Executing docker {argsText}..."); int result = await this.ExecuteCommandLineAsync( context, new RemoteProcessStartInfo { FileName = this.DockerExePath, Arguments = argsText } ); this.Log(result == 0 ? MessageLevel.Debug : MessageLevel.Error, "Docker exited with code " + result); } finally { await this.LogoutAsync(context, this.ContainerSource); } }
public override async Task <PersistedConfiguration> CollectAsync(IOperationExecutionContext context) { var path = this.Template.Name; var fileOps = await context.Agent.GetServiceAsync <IFileOperationsExecuter>().ConfigureAwait(false); this.LogDebug($"Looking for {path}..."); if (!await fileOps.DirectoryExistsAsync(path).ConfigureAwait(false)) { this.LogDebug("Directory does not exist."); return(new DirectoryConfiguration { Name = path, Exists = false }); } this.LogDebug("Directory exists, loading from disk..."); var config = new DirectoryConfiguration { Name = this.Template.Name }; var dir = await fileOps.GetDirectoryInfoAsync(path).ConfigureAwait(false); this.LogDebug("Directory configuration loaded."); return(config); }
public override sealed async Task ExecuteAsync(IOperationExecutionContext context) { if (context.Simulation) { switch (this.OperationType) { case SiteOperationType.Start: this.LogInformation($"Starting site {this.SiteName}..."); this.LogInformation($"Site {this.SiteName} state is now Started."); break; case SiteOperationType.Stop: this.LogInformation($"Stopping site {this.SiteName}..."); this.LogInformation($"Site {this.SiteName} state is now Stopped."); break; } } else { var job = new SiteJob { SiteName = this.SiteName, OperationType = this.OperationType }; job.MessageLogged += (s, e) => this.Log(e.Level, e.Message); var jobExecuter = context.Agent.GetService <IRemoteJobExecuter>(); await jobExecuter.ExecuteJobAsync(job, context.CancellationToken); } }
public override async Task ExecuteAsync(IOperationExecutionContext context) { var sourcePath = context.ResolvePath(this.SourceFileName); var targetPath = context.ResolvePath(this.TargetFileName); this.LogInformation($"Renaming {sourcePath} to {targetPath}..."); var fileOps = await context.Agent.GetServiceAsync <IFileOperationsExecuter>().ConfigureAwait(false); this.LogDebug($"Verifying source file {sourcePath} exists..."); if (!await fileOps.FileExistsAsync(sourcePath).ConfigureAwait(false)) { this.LogError("Source path does not exist."); return; } if (sourcePath.Equals(targetPath, StringComparison.OrdinalIgnoreCase)) { this.LogWarning("The source and target file names are the same."); return; } if (!this.Overwrite && await fileOps.FileExistsAsync(targetPath).ConfigureAwait(false)) { this.LogError(this.TargetFileName + " already exists and overwrite is set to false."); return; } await fileOps.MoveFileAsync(sourcePath, targetPath, this.Overwrite).ConfigureAwait(false); this.LogInformation("File renamed."); }
public override async Task ExecuteAsync(IOperationExecutionContext context) { var escapeArg = GetEscapeArg(context); var args = new StringBuilder("exec "); if (this.RunInBackground) args.Append("--detach "); if (this.Interactive) args.Append("--interactive "); if (!string.IsNullOrWhiteSpace(this.WorkDir)) args.Append($"--workdir {escapeArg(this.WorkDir)} "); if (!string.IsNullOrWhiteSpace(this.AdditionalArguments)) args.Append($"{this.AdditionalArguments} "); args.Append($"{escapeArg(this.ContainerName)} {this.Command}"); var argsText = args.ToString(); this.LogDebug($"Executing docker {argsText}..."); int result = await this.ExecuteCommandLineAsync( context, new RemoteProcessStartInfo { FileName = this.DockerExePath, Arguments = argsText } ); this.Log(result == 0 ? MessageLevel.Debug : MessageLevel.Error, "Docker exited with code " + result); }
public override async Task ExecuteAsync(IOperationExecutionContext context) { var zipFilePath = context.ResolvePath(this.FileName); var sourceDirectory = context.ResolvePath(this.DirectoryToZip); this.LogDebug($"Zipping {sourceDirectory} to {zipFilePath}..."); var fileOps = await context.Agent.GetServiceAsync <IFileOperationsExecuter>().ConfigureAwait(false); var targetDirectory = PathEx.GetDirectoryName(zipFilePath); this.LogDebug($"Ensuring that {targetDirectory} exists..."); await fileOps.CreateDirectoryAsync(targetDirectory).ConfigureAwait(false); this.LogInformation("Creating zip file..."); if (this.Overwrite) { this.LogDebug($"Deleting {zipFilePath} if it already exists..."); await fileOps.DeleteFileAsync(zipFilePath).ConfigureAwait(false); } else if (await fileOps.FileExistsAsync(zipFilePath).ConfigureAwait(false)) { this.LogDebug(zipFilePath + " aready exists."); this.LogError(zipFilePath + " already exists and overwrite is set to false."); } await fileOps.CreateZipFileAsync(sourceDirectory, zipFilePath).ConfigureAwait(false); this.LogInformation(zipFilePath + " file created."); }
protected GitClient CreateClient(IOperationExecutionContext context, string repositoryUrl, WorkspacePath workspacePath) { if (!string.IsNullOrEmpty(this.GitExePath)) { this.LogDebug($"Executable path specified, using Git command line client at '{this.GitExePath}'..."); return(new GitCommandLineClient( this.GitExePath, context.Agent.GetService <IRemoteProcessExecuter>(), context.Agent.GetService <IFileOperationsExecuter>(), new GitRepositoryInfo(workspacePath, repositoryUrl, this.UserName, this.Password), this, context.CancellationToken )); } else { this.LogDebug("No executable path specified, using built-in Git library..."); return(new RemoteLibGitSharpClient( context.Agent.TryGetService <IRemoteJobExecuter>(), context.WorkingDirectory, context.Simulation, context.CancellationToken, new GitRepositoryInfo(workspacePath, repositoryUrl, this.UserName, this.Password), this )); } }
public override async Task ExecuteAsync(IOperationExecutionContext context) { int exitCode = await SHUtil.ExecuteScriptAsync(context, new StringReader(this.ScriptText), null, this, this.Verbose, this.OutputLevel, this.ErrorLevel) ?? 0; bool exitCodeLogged = false; if (!string.IsNullOrWhiteSpace(this.SuccessExitCode)) { var comparator = ExitCodeComparator.TryParse(this.SuccessExitCode); if (comparator != null) { bool result = comparator.Evaluate(exitCode); if (result) { this.LogInformation($"Script exited with code: {exitCode} (success)"); } else { this.LogError($"Script exited with code: {exitCode} (failure)"); } exitCodeLogged = true; } } if (!exitCodeLogged) { this.LogDebug("Script exited with code: " + exitCode); } }
private async Task <ChocolateyInstalledConfiguration> CollectAsync(IOperationExecutionContext context) { if (this.Collected == null) { var output = await this.ExecuteChocolateyAsync(context, "upgrade --what-if --limit-output " + AH.ConcatNE("--source \"", this.Template.Source, "\" ") + "chocolatey", true); if (output == null) { this.Collected = new ChocolateyInstalledConfiguration { Version = "not-installed" }; } else { this.Collected = new ChocolateyInstalledConfiguration { Version = output[0][1], LatestVersion = output[0][2] }; } } return(this.Collected); }
public override async Task ExecuteAsync(IOperationExecutionContext context) { this.LogDebug($"Executing docker stop {this.ContainerName}..."); var escapeArg = GetEscapeArg(context); int result = await this.ExecuteCommandLineAsync( context, new RemoteProcessStartInfo { FileName = this.DockerExePath, Arguments = "stop " + escapeArg(this.ContainerName) } ); this.Log(result == 0 ? MessageLevel.Debug : (FailIfContinerDoesNotExist ? MessageLevel.Error : MessageLevel.Warning), "Docker exited with code " + result); if (this.Remove) { result = await this.ExecuteCommandLineAsync( context, new RemoteProcessStartInfo { FileName = this.DockerExePath, Arguments = "rm " + escapeArg(this.ContainerName) } ); this.Log(result == 0 ? MessageLevel.Debug : (FailIfContinerDoesNotExist ? MessageLevel.Error : MessageLevel.Warning), "Docker exited with code " + result); } }
public override async Task ExecuteAsync(IOperationExecutionContext context) { if (context.Simulation && !this.RunOnSimulation) { this.LogInformation("Executing PowerShell script..."); return; } var jobRunner = context.Agent.GetService <IRemoteJobExecuter>(); var job = new ExecutePowerShellJob { ScriptText = this.ScriptText, DebugLogging = this.DebugLogging, VerboseLogging = this.VerboseLogging, CollectOutput = false, LogOutput = true, Variables = PowerShellScriptRunner.ExtractVariables(this.ScriptText, context), Isolated = this.Isolated, WorkingDirectory = context.WorkingDirectory }; job.MessageLogged += (s, e) => this.Log(e.Level, e.Message); job.ProgressUpdate += (s, e) => Interlocked.Exchange(ref this.currentProgress, e); var result = (ExecutePowerShellJob.Result) await jobRunner.ExecuteJobAsync(job, context.CancellationToken); PSUtil.LogExit(this, result.ExitCode, this.SuccessExitCode); }
public override async Task ExecuteAsync(IOperationExecutionContext context) { try { new Uri(this.Url); } catch (Exception ex) { this.LogError($"The URL \"{this.Url}\" is invalid because: {ex.Message}"); return; } this.ResolvedFilePath = context.ResolvePath(this.FileName); this.LogDebug("File path resolved to: " + this.ResolvedFilePath); if (!this.ProxyRequest) { var fileOps = await context.Agent.GetServiceAsync <IFileOperationsExecuter>().ConfigureAwait(false); await fileOps.CreateDirectoryAsync(PathEx.GetDirectoryName(this.ResolvedFilePath)).ConfigureAwait(false); using (var fileStream = await fileOps.OpenFileAsync(this.ResolvedFilePath, FileMode.Create, FileAccess.Write).ConfigureAwait(false)) { this.LogInformation($"Downloading {this.Url} to {this.FileName}..."); await this.PerformRequestAsync(fileStream, context.CancellationToken).ConfigureAwait(false); this.LogInformation("HTTP file download completed."); return; } } this.LogInformation($"Downloading {this.Url} to {this.FileName}..."); await this.CallRemoteAsync(context).ConfigureAwait(false); this.LogInformation("HTTP file download completed."); }
public static PackageDeploymentData Create(IOperationExecutionContext context, ILogSink log, string description) { string baseUrl = SDK.BaseUrl; if (string.IsNullOrEmpty(baseUrl)) { log.LogDebug("Deployment will not be recorded in ProGet because the System.BaseUrl configuration setting is not set."); return(null); } string serverName = AH.CoalesceString(context?.ServerName, Environment.MachineName); string relativeUrl; if (SDK.ProductName == "BuildMaster") { relativeUrl = context.ExpandVariables($"applications/{((IStandardContext)context).ProjectId}/builds/build?releaseNumber=$UrlEncode($ReleaseNumber)&buildNumber=$UrlEncode($PackageNumber)").AsString(); } else if (SDK.ProductName == "Hedgehog") { relativeUrl = "deployment-sets/details?deploymentSetId=" + ((IStandardContext)context).DeploymentSetId; } else { relativeUrl = "executions/execution-in-progress?executionId=" + context.ExecutionId; } return(new PackageDeploymentData(SDK.ProductName, baseUrl, relativeUrl, serverName, description)); }
protected async Task ExecuteNuGetAsync(IOperationExecutionContext context, ToolInfo toolInfo, string args, string workingDirectory, string logArgs = null) { if (!string.IsNullOrWhiteSpace(this.AdditionalArguments)) { args += " " + this.AdditionalArguments; if (logArgs != null) { logArgs += this.AdditionalArguments; } } this.LogDebug("Executing: " + toolInfo.ExePath + " " + (logArgs ?? args)); int exitCode = await this.ExecuteCommandLineAsync( context, new RemoteProcessStartInfo { FileName = toolInfo.ExePath, Arguments = args, WorkingDirectory = workingDirectory } ).ConfigureAwait(false); if (exitCode != 0) { this.LogError($"NuGet exited with code {exitCode}"); } }
public override Task ExecuteAsync(IOperationExecutionContext context) { if (context.Simulation) { this.LogInformation("Executing PowerShell Script..."); return(Complete); } var fullScriptName = this.DefaultArgument.AsString(); if (fullScriptName == null) { this.LogError("Bad or missing script name."); return(Complete); } return(PSUtil.ExecuteScriptAsync( logger: this, context: context, fullScriptName: fullScriptName, arguments: this.NamedArguments, outArguments: this.OutArguments, collectOutput: false, progressUpdateHandler: (s, e) => Interlocked.Exchange(ref this.currentProgress, e) )); }