/// <summary> /// Starts an Amazon EBS-backed AMI that you've previously stopped. Instances that use Amazon EBS volumes as their root devices can be quickly stopped /// and started. When an instance is stopped, the compute resources are released and you are not billed for hourly instance usage. However, your root partition /// Amazon EBS volume remains, continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Each /// time you transition an instance from stopped to started, Amazon EC2 charges a full instance hour, even if transitions happen multiple times within a single hour. /// </summary> /// <param name="instances">A list of instance IDs to be started.</param> /// <param name="settings">The <see cref="EC2Settings"/> used during the request to AWS.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async Task <bool> StartInstances(IList <string> instances, EC2Settings settings, CancellationToken cancellationToken = default(CancellationToken)) { if ((instances == null) || (instances.Count == 0)) { throw new ArgumentNullException("instances"); } //Create Request AmazonEC2Client client = this.CreateClient(settings); StartInstancesRequest request = new StartInstancesRequest(); foreach (string instance in instances) { request.InstanceIds.Add(instance); } //Check Response StartInstancesResponse response = await client.StartInstancesAsync(request, cancellationToken); if (response.HttpStatusCode == HttpStatusCode.OK) { _Log.Verbose("Successfully started instances '{0}'", string.Join(",", instances)); return(true); } else { _Log.Error("Failed to start instances '{0}'", string.Join(",", instances)); return(false); } }
private bool Copy(IFile source, IFile destination) { if (!source.Exists) { _log.Error("Could not find file {0}.", source.Path.FullPath); return(false); } if (destination.Exists) { _log.Error("The file {0} already exist.", destination.Path.FullPath); return(false); } using (var input = source.OpenRead()) using (var output = destination.OpenWrite()) { using (var reader = new StreamReader(input)) using (var writer = new StreamWriter(output)) { while (true) { var line = reader.ReadLine(); if (line == null) { break; } writer.WriteLine(line); } } } return(true); }
/// <summary> /// The application entry point. /// </summary> /// <returns>The application exit code.</returns> public static int Main() { ICakeLog log = null; try { // Parse arguments. var args = ArgumentTokenizer .Tokenize(Environment.CommandLine) .Skip(1) // Skip executable. .ToArray(); var builder = new CakeContainerBuilder(); builder.Registry.RegisterModule(new CakeModule()); builder.Registry.RegisterModule(new CoreModule()); builder.Registry.RegisterModule(new NuGetModule()); // Build the container. using (var container = builder.Build()) { // Resolve the log. log = container.Resolve <ICakeLog>(); // Parse the options. var parser = container.Resolve <IArgumentParser>(); var options = parser.Parse(args); // Set verbosity. log.Verbosity = options.Verbosity; // Rebuild the container. builder = new CakeContainerBuilder(); builder.Registry.RegisterModule(new ArgumentsModule(options)); builder.Registry.RegisterModule(new ConfigurationModule(container, options)); builder.Registry.RegisterModule(new ScriptingModule(options)); builder.Update(container); // Load all modules. var loader = container.Resolve <ModuleLoader>(); loader.LoadModules(container, options); // Resolve and run the application. var application = container.Resolve <CakeApplication>(); return(application.Run(options)); } } catch (Exception ex) { log = log ?? new CakeBuildLog(new CakeConsole()); if (log.Verbosity == Verbosity.Diagnostic) { log.Error("Error: {0}", ex); } else { log.Error("Error: {0}", ex.Message); } return(1); } }
public static async Task MigrateIssuesVersion(MigrateIssuesVersionSettings settings, ICakeLog logger) { try { var jira = Atlassian.Jira.Jira.CreateRestClient(settings.Host, settings.User, settings.Password); logger.Information($"Finding issues on version {settings.FromVersion}..."); var issuesToMove = await jira.Issues.GetIssuesFromJqlAsync($"project = {settings.Project} and fixVersion is not EMPTY and fixVersion IN (\"{settings.FromVersion}\")"); foreach (var issue in issuesToMove) { logger.Information($"Moving issue {issue.Key} from {settings.FromVersion} to {settings.ToVersion}"); issue.FixVersions.Remove(settings.FromVersion); issue.FixVersions.Add(settings.ToVersion); await jira.Issues.UpdateIssueAsync(issue); } logger.Information("Issue migration complete!"); } catch (Exception ex) { logger.Error($"Error migrating issues: {ex.Message}"); if (ex.InnerException != null) { logger.Error(ex.InnerException); } } }
internal async Task ExecuteTaskAsync(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, bool isTarget, CakeReport report) { if (!ShouldTaskExecute(task, isTarget)) { SkipTask(context, strategy, task); return; } // Reset the stop watch. stopWatch.Reset(); stopWatch.Start(); PerformTaskSetup(context, strategy, task, false); bool exceptionWasThrown = false; try { // Execute the task. await strategy.ExecuteAsync(task, context); } catch (Exception exception) { _log.Error("An error occured when executing task '{0}'.", task.Name); exceptionWasThrown = true; // Got an error reporter? if (task.ErrorReporter != null) { ReportErrors(strategy, task.ErrorReporter, exception); } // Got an error handler? if (task.ErrorHandler != null) { HandleErrors(strategy, task.ErrorHandler, exception); } else { // No error handler defined for this task. // Rethrow the exception and let it propagate. throw; } } finally { if (task.FinallyHandler != null) { strategy.InvokeFinally(task.FinallyHandler); } PerformTaskTeardown(context, strategy, task, stopWatch.Elapsed, false, exceptionWasThrown); } // Add the task results to the report. report.Add(task.Name, stopWatch.Elapsed); }
public bool CreateApplicationVersion(string applicationName, string description, string versionLabel, string s3Bucket, string s3Key, bool autoCreateApplication, ElasticBeanstalkSettings settings) { if (string.IsNullOrEmpty(applicationName)) { throw new ArgumentNullException("applicationName"); } if (string.IsNullOrEmpty(description)) { throw new ArgumentNullException("description"); } if (string.IsNullOrEmpty(versionLabel)) { throw new ArgumentNullException("versionLabel"); } if (string.IsNullOrEmpty(s3Bucket)) { throw new ArgumentNullException("s3Bucket"); } if (string.IsNullOrEmpty(s3Key)) { throw new ArgumentNullException("s3Key"); } try { var client = GetClient(settings); client.CreateApplicationVersion(new CreateApplicationVersionRequest { ApplicationName = applicationName, AutoCreateApplication = autoCreateApplication, Description = description, //Process = true, VersionLabel = versionLabel, SourceBundle = new S3Location { S3Bucket = s3Bucket, S3Key = s3Key } }); } catch (Exception ex) { _Log.Error("Failed to create new application version '{0}'", ex.Message); return(false); } _Log.Verbose("Successfully created new application version '{0}' for application '{1}'", versionLabel, applicationName); return(true); }
public Dictionary <string, string> Parse(IEnumerable <string> args) { if (args == null) { throw new ArgumentNullException("args"); } var options = new Dictionary <string, string>(); var isParsingOptions = false; var arguments = args.ToList(); foreach (var arg in arguments) { var value = arg.UnQuote(); if (isParsingOptions) { if (IsOption(value)) { if (!ParseOption(value, options)) { return(options); } } else { _log.Error("More than one build script specified."); return(options); } } else { try { // If they didn't provide a specific build script, search for a default. if (IsOption(arg)) { if (!ParseOption(value, options)) { return(options); } } } finally { // Start parsing options. isParsingOptions = true; } } } return(options); }
private async Task ExecuteTaskAsync(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, CakeReport report) { stopWatch.Restart(); PerformTaskSetup(context, strategy, task, false); var exceptionWasThrown = false; try { // Execute the task. await strategy.ExecuteAsync(task, context).ConfigureAwait(false); } catch (Exception exception) { _log.Error("An error occurred when executing task '{0}'.", task.Name); exceptionWasThrown = true; // Got an error reporter? if (task.ErrorReporter != null) { ReportErrors(strategy, task.ErrorReporter, exception); } // Got an error handler? if (task.ErrorHandler != null) { HandleErrors(strategy, task.ErrorHandler, exception); } else { // No error handler defined for this task. // Rethrow the exception and let it propagate. throw; } } finally { if (task.FinallyHandler != null) { strategy.InvokeFinally(task.FinallyHandler); } PerformTaskTeardown(context, strategy, task, stopWatch.Elapsed, false, exceptionWasThrown); } // Add the task results to the report if (IsDelegatedTask(task)) { report.AddDelegated(task.Name, stopWatch.Elapsed); } else { report.Add(task.Name, CakeReportEntryCategory.Task, stopWatch.Elapsed); } }
public static int OutputError(ICakeLog log, Exception exception) { if (log.Verbosity == Verbosity.Diagnostic) { log.Error("Error: {0}", exception); } else { log.Error("Error: {0}", exception.Message); } return(1); }
public CakeOptions Parse(IEnumerable <string> args) { if (args == null) { throw new ArgumentNullException("args"); } var options = new CakeOptions(); var isParsingOptions = false; foreach (var arg in args) { var value = arg.UnQuote(); if (isParsingOptions) { if (IsOption(value)) { if (!ParseOption(value, options)) { return(null); } } else { _log.Error("More than one build script specified."); return(null); } } else { try { if (IsOption(arg)) { _log.Error("First argument must be the build script."); return(null); } // Quoted? options.Script = new FilePath(value); } finally { // Start parsing options. isParsingOptions = true; } } } return(options); }
/// <summary> /// Deploys an application revision through the specified deployment group. /// </summary> /// <param name="applicationName">The name of an AWS CodeDeploy application associated with the applicable IAM user or AWS account.</param> /// <param name="deploymentGroup">The name of the deployment group.</param> /// <param name="settings">The <see cref="DeploySettings"/> used during the request to AWS.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async Task <bool> CreateDeployment(string applicationName, string deploymentGroup, DeploySettings settings, CancellationToken cancellationToken = default(CancellationToken)) { if (String.IsNullOrEmpty(applicationName)) { throw new ArgumentNullException("applicationName"); } if (String.IsNullOrEmpty(deploymentGroup)) { throw new ArgumentNullException("deploymentGroup"); } // Create Request AmazonCodeDeployClient client = this.CreateClient(settings); CreateDeploymentRequest request = new CreateDeploymentRequest(); request.ApplicationName = applicationName; request.DeploymentGroupName = deploymentGroup; request.Revision = new RevisionLocation() { RevisionType = RevisionLocationType.S3, S3Location = new S3Location() { BundleType = BundleType.Zip, Bucket = settings.S3Bucket, Key = settings.S3Key, Version = settings.S3Version } }; // Check Response CreateDeploymentResponse response = await client.CreateDeploymentAsync(request, cancellationToken); if (response.HttpStatusCode == HttpStatusCode.OK) { _Log.Verbose("Successfully deployed application '{0}'", applicationName); return(true); } else { _Log.Error("Failed to deploy application '{0}'", applicationName); return(false); } }
private ScriptAlias CreateAlias(Tuple <MethodInfo, ScriptAliasType> alias) { var method = alias.Item1; var type = alias.Item2; try { var namespaces = new HashSet <string>(StringComparer.Ordinal); // Import the method's namespace to the session. var methodNamespace = method.GetNamespace(); if (!string.IsNullOrWhiteSpace(methodNamespace)) { namespaces.Add(methodNamespace); } // Find out if the method want us to import more namespaces. var namespaceAttributes = method.GetCustomAttributes <CakeNamespaceImportAttribute>(); foreach (var namespaceAttribute in namespaceAttributes) { namespaces.Add(namespaceAttribute.Namespace); } // Find out if the class contains any more namespaces. namespaceAttributes = method.DeclaringType.GetTypeInfo().GetCustomAttributes <CakeNamespaceImportAttribute>(); foreach (var namespaceAttribute in namespaceAttributes) { namespaces.Add(namespaceAttribute.Namespace); } // Find out if the assembly has been decorated with any more namespaces namespaceAttributes = method.DeclaringType.GetTypeInfo().Assembly.GetCustomAttributes <CakeNamespaceImportAttribute>(); foreach (var namespaceAttribute in namespaceAttributes) { namespaces.Add(namespaceAttribute.Namespace); } return(new ScriptAlias(method, type, namespaces)); } catch (Exception ex) { // Log this error. const string format = "An error occurred while generating code for alias {0}."; _log.Error(format, method.GetSignature(false)); _log.Error("Error: {0}", ex.Message); } return(null); }
private void Error_DataReady(object sender, EventArgs e) { var error = sender as PipelineReader <object>; if (error == null) { return; } if (_successful && error.Count > 0) { _successful = false; } while (error.Count > 0) { var errorItem = error.Read(); if (errorItem != null) { var pso = new PSObject(errorItem); _pipelineResults.Add(pso); _Log.Error(Verbosity.Normal, errorItem.ToString().EscapeCurleyBrackets()); } } }
public ProjectStatus GetAnalysisResults(SonarResultsSettings settings, string analysisId) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } try { String sonarUrl = settings.Url; if (!Utility.ValidateUrl(sonarUrl)) { throw new ArgumentException("Invalid SonarQube URL"); } if (settings.IsAuthEnabled) { _Client.Authenticator = settings.GetAuthenticator; } _Logger.Information($"Initializing analysis request"); string url = String.Format(_AnalysisUrl, sonarUrl, analysisId); var request = new RestRequest(url, Method.POST); _Logger.Information($"Setting API endpoint to {url} [POST]"); request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; var queryResult = _Client.Execute <ProjectStatusWrapper>(request); ValidateResult(queryResult); ProjectStatusWrapper x = queryResult.Data; return(x.ProjectStatus); } catch (Exception ex) { _Logger.Error($"An error occured while retrieving Analysis Status from SonarQube - {ex.Message}"); throw; } }
public static bool ExecuteSqlFile(this ICakeContext context, FilePath path, SqlQuerySettings settings) { if (path == null) { throw new ArgumentNullException("path"); } if (settings == null) { throw new ArgumentNullException("settings"); } ICakeLog log = settings.AllowLogs ? context.Log : new Logging.QuietLog(); IFile file = context.FileSystem.GetFile(path); if (file.Exists) { string query = file.ReadBytes().GetString(); return(context.ExecuteSqlQuery(query, settings)); } else { log.Error("Missing sql file {0}", path.FullPath); return(false); } }
public void Execute(Script script) { // Generate the script code. var generator = new RoslynCodeGenerator(); var code = generator.Generate(script); // Warn about any code generation excluded namespaces foreach (var @namespace in script.ExcludedNamespaces) { _log.Warning("Namespace {0} excluded by code generation, affected methods:\r\n\t{1}", @namespace.Key, string.Join("\r\n\t", @namespace.Value)); } // Create the script options dynamically. var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default .AddImports(Namespaces.Except(script.ExcludedNamespaces.Keys)) .AddReferences(References) .AddReferences(ReferencePaths.Select(r => r.FullPath)) .WithEmitDebugInformation(_settings.Debug) .WithMetadataResolver(Microsoft.CodeAnalysis.Scripting.ScriptMetadataResolver.Default); var roslynScript = CSharpScript.Create(code, options, _host.GetType()); _log.Verbose("Compiling build script..."); var compilation = roslynScript.GetCompilation(); var diagnostics = compilation.GetDiagnostics(); var errors = new List <Diagnostic>(); foreach (var diagnostic in diagnostics) { switch (diagnostic.Severity) { case DiagnosticSeverity.Info: _log.Information(diagnostic.ToString()); break; case DiagnosticSeverity.Warning: _log.Warning(diagnostic.ToString()); break; case DiagnosticSeverity.Error: _log.Error(diagnostic.ToString()); errors.Add(diagnostic); break; default: break; } } if (errors.Any()) { var errorMessages = string.Join(Environment.NewLine, errors.Select(x => x.ToString())); var message = string.Format(CultureInfo.InvariantCulture, "Error(s) occurred when compiling build script:{0}{1}", Environment.NewLine, errorMessages); throw new CakeException(message); } roslynScript.RunAsync(_host).Wait(); }
public Task GetTaskResults(SonarResultsSettings settings, string taskId) { try { string sonarUrl = settings.Url; if (settings.IsAuthEnabled) { _Client.Authenticator = settings.GetAuthenticator; } if (!Utility.ValidateUrl(sonarUrl)) { throw new ArgumentException("Invalid SonarQube URL"); } string url = String.Format(_TaskUrl, sonarUrl, taskId); _Logger.Information($"Initializing request"); var request = new RestRequest(url, Method.POST); _Logger.Information($"Setting Content-Type to application/json"); request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; _Logger.Information($"Retrieving task status from {url} [POST]"); //Debugger.Launch(); var queryResult = _Client.Execute <TaskWrapper>(request); ValidateResult(queryResult); TaskWrapper x = queryResult.Data; return(x.Task); } catch (Exception ex) { _Logger.Error($"An error occured while retrieving Task Status from SonarQube - {ex.Message}"); throw; } }
private static void ConvertTextToPdf(string markdownText, string outputFile, Action <Settings> settingsAction, ICakeLog log, string sourceWorkingDirectory) { if (!CanWriteToOutputFile(outputFile)) { log.Error("Please close the output file first: " + outputFile); return; } var settings = new Settings(); settingsAction?.Invoke(settings); if (string.IsNullOrEmpty(settings.WorkingDirectory)) { settings.WorkingDirectory = sourceWorkingDirectory; } string htmlFile = Path.Combine(Path.GetTempPath(), $"convert{Guid.NewGuid().ToString("n")}.html"); settings.MarkdownPipeline.DebugLog = Console.Out; var html = Markdown.ToHtml(markdownText, settings.MarkdownPipeline.Build()); var baseDirectory = GetBaseDirectory(); html = ApplyTheme(html, settings, log, baseDirectory, settings.WorkingDirectory); try { File.WriteAllText(htmlFile, html); var generator = new PdfGenerator(); var exitCode = generator.ConvertToPdf(htmlFile, outputFile, settings.Pdf, baseDirectory, log); if (exitCode != 0) { log.Error("Error creating pdf document. Exit code: " + exitCode); log.Error(generator.ExecutionOutputText); } } finally { if (File.Exists(htmlFile)) { File.Delete(htmlFile); } } }
public void Log(MessageLevel level, string message, params object[] args) { switch (level) { case MessageLevel.Warning: _log.Warning(message, args); break; case MessageLevel.Error: _log.Error(message, args); break; default: _log.Debug(message, args); break; } }
private static string ApplyTheme(string html, Settings settings, ICakeLog log, string baseDirectory, string workingDirectory) { if (string.IsNullOrEmpty(settings.CssFile)) { settings.CssFile = Path.Combine(baseDirectory, $"Themes\\{settings.Theme}\\Theme.css"); } if (string.IsNullOrEmpty(settings.HtmlTemplateFile)) { settings.HtmlTemplateFile = Path.Combine(baseDirectory, $"Themes\\{settings.Theme}\\Theme.html"); } if (!Path.IsPathRooted(settings.CssFile)) { settings.CssFile = Path.GetFullPath(settings.CssFile); } if (!Path.IsPathRooted(settings.HtmlTemplateFile)) { settings.HtmlTemplateFile = Path.GetFullPath(settings.HtmlTemplateFile); } if (!File.Exists(settings.CssFile)) { log.Error($"CSS file '{settings.CssFile}' not found!"); } if (!File.Exists(settings.HtmlTemplateFile)) { log.Error($"Html template file '{settings.HtmlTemplateFile}' not found!"); } var template = File.ReadAllText(settings.HtmlTemplateFile); if (!workingDirectory.EndsWith("\\") && !workingDirectory.EndsWith("/")) { workingDirectory += "\\"; } return(template .Replace("{$html}", html) .Replace("{$cssFile}", settings.CssFile) .Replace("{$docPath}", workingDirectory)); }
private void ExecuteTask(ICakeContext context, IExecutionStrategy strategy, Stopwatch stopWatch, CakeTask task, CakeReport report) { // Reset the stop watch. stopWatch.Reset(); stopWatch.Start(); try { // Execute the task. strategy.Execute(task, context); } catch (Exception exception) { _log.Error("An error occured when executing task.", task.Name); // Got an error reporter? if (task.ErrorReporter != null) { ReportErrors(strategy, task.ErrorReporter, exception); } // Got an error handler? if (task.ErrorHandler != null) { HandleErrors(strategy, task.ErrorHandler, exception); } else { // No error handler defined for this task. // Rethrow the exception and let it propagate. throw; } } finally { if (task.FinallyHandler != null) { strategy.InvokeFinally(task.FinallyHandler); } } // Add the task results to the report. report.Add(task.Name, stopWatch.Elapsed); }
/// <summary> /// Uploads a collection of files to S3. For large uploads, the file will be divided and uploaded in parts /// using Amazon S3's multipart API. The parts will be reassembled as one object in Amazon S3. /// </summary> /// <param name="paths">The paths to upload.</param> /// <param name="settings">The <see cref="SyncSettings"/> required to upload to Amazon S3.</param> public void Upload(IList <SyncPath> paths, SyncSettings settings) { foreach (SyncPath path in paths) { try { UploadSettings copied = new UploadSettings() { WorkingDirectory = settings.WorkingDirectory, AccessKey = settings.AccessKey, SecretKey = settings.SecretKey, Credentials = settings.Credentials, Region = settings.Region, BucketName = settings.BucketName, EncryptionMethod = settings.EncryptionMethod, EncryptionKey = settings.EncryptionKey, EncryptionKeyMD5 = settings.EncryptionKeyMD5, CannedACL = settings.CannedACL, StorageClass = settings.StorageClass, KeyManagementServiceKeyId = settings.KeyManagementServiceKeyId, Headers = new HeadersCollection(), GenerateContentType = settings.GenerateContentType, GenerateETag = settings.GenerateETag }; if (!String.IsNullOrEmpty(path.ETag)) { copied.Headers["ETag"] = path.ETag; } this.Upload(path.Path, path.Key, copied); } catch (Exception ex) { _Log.Error(ex.Message); } } }
public bool Generate(DirectoryPath path) { var version = _prober.GetVersion("Cake"); if (string.IsNullOrWhiteSpace(version)) { _log.Error("Could not resolve latest package version."); return(false); } return(Generate(path, version)); }
private static int LogException <T>(ICakeLog log, T ex) where T : Exception { log = log ?? new CakeBuildLog(new CakeConsole()); if (log.Verbosity == Verbosity.Diagnostic) { log.Error("Error: {0}", ex); } else { log.Error("Error: {0}", ex.Message); var aex = ex as AggregateException; if (aex != null) { foreach (var exception in aex.Flatten().InnerExceptions) { log.Error("\t{0}", exception.Message); } } } return(1); }
/// <summary> /// Parses the provided string to a <see cref="Verbosity"/>. /// </summary> /// <param name="value">The string to parse.</param> /// <param name="verbosity">The verbosity.</param> /// <returns><c>true</c> if parsing succeeded; otherwise <c>false</c>.</returns> public bool TryParse(string value, out Verbosity verbosity) { var result = _lookup.TryGetValue(value, out verbosity); if (!result) { const string format = "The value '{0}' is not a valid verbosity."; var message = string.Format(CultureInfo.InvariantCulture, format, value); _log.Error(message); } return(result); }
public static void SonarQubeResults(this ICakeContext context, SonarResultsSettings settings) { string taskId = SonarTaskIdRetriever.GetTaskId(context); ICakeLog logger = context.Log; logger.Information("Creating a Sonar Task Retriever Client"); SonarTaskClient taskClient = new SonarTaskClient(context); SonarAnalysisClient analysisClient = new SonarAnalysisClient(context); while (true) { var taskResults = taskClient.GetTaskResults(settings, taskId); //until the status is SUCCESS, CANCELED or FAILED if (taskResults.Status != "SUCCESS" && taskResults.Status != "CANCELED" && taskResults.Status != "FAILED") { Thread.Sleep(10000); } else { if (taskResults.Status == "SUCCESS") { var analysisStatus = analysisClient.GetAnalysisResults(settings, taskResults.AnalysisId); logger.Information(analysisStatus); if (analysisStatus.Status == "ERROR" || analysisStatus.Status == "FAILED") { logger.Error($"SonarQube analysis returned {analysisStatus.Status}"); throw new CakeException("SonarQube analysis Failed. Breaking the build"); } logger.Information($"SonarQube analysis returned {analysisStatus.Status}"); } else { logger.Error($"SonarQube Task Failed! - STATUS => {taskResults.Status}"); throw new CakeException($"SonarQube task returned {taskResults.Status}"); } break; } } }
/// <summary> /// Adds new instances to the load balancer. /// Once the instance is registered, it starts receiving traffic and requests from the load balancer. /// Any instance that is not in any of the Availability Zones registered for the load balancer will be moved to the OutOfService state. /// It will move to the InService state when the Availability Zone is added to the load balancer. /// </summary> /// <param name="loadBalancer">The name associated with the load balancer.</param> /// <param name="instances">A list of instance IDs that should be registered with the load balancer.</param> /// <param name="settings">The <see cref="LoadBalancingSettings"/> used during the request to AWS.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async Task <bool> RegisterInstances(string loadBalancer, IList <string> instances, LoadBalancingSettings settings, CancellationToken cancellationToken = default(CancellationToken)) { if (String.IsNullOrEmpty(loadBalancer)) { throw new ArgumentNullException("loadBalancer"); } if ((instances == null) || (instances.Count == 0)) { throw new ArgumentNullException("instances"); } //Create Request AmazonElasticLoadBalancingClient client = this.CreateClient(settings); RegisterInstancesWithLoadBalancerRequest request = new RegisterInstancesWithLoadBalancerRequest(); request.LoadBalancerName = loadBalancer; foreach (string instance in instances) { request.Instances.Add(new Instance(instance)); } //Check Response RegisterInstancesWithLoadBalancerResponse response = await client.RegisterInstancesWithLoadBalancerAsync(request, cancellationToken); if (response.HttpStatusCode == HttpStatusCode.OK) { _Log.Verbose("Successfully registered instances '{0}'", string.Join(",", instances)); return(true); } else { _Log.Error("Failed to register instances '{0}'", string.Join(",", instances)); return(false); } }
private static int LogException <T>(ICakeLog log, T ex) where T : Exception { log = log ?? new CakeBuildLog( new CakeConsole(new CakeEnvironment(new CakePlatform(), new CakeRuntime()))); if (log.Verbosity == Verbosity.Diagnostic) { log.Error("Error: {0}", ex); } else { log.Error("Error: {0}", ex.Message); if (ex is AggregateException aex) { foreach (var exception in aex.Flatten().InnerExceptions) { log.Error("\t{0}", exception.Message); } } } return(1); }
/// <summary> /// Performs the build teardown. /// </summary> /// <param name="strategy">The <see cref="IExecutionStrategy"/> use to execute the teardown.</param> /// <param name="exceptionWasThrown">True if an exception was thrown on execution; otherwise false.</param> protected virtual void PerformTeardown(IExecutionStrategy strategy, bool exceptionWasThrown) { if (TeardownAction == null) { return; } try { strategy.PerformTeardown(TeardownAction); } catch (Exception ex) { Log.Error("An error occured in the custom teardown action."); if (!exceptionWasThrown) { // If no other exception was thrown, we throw this one. throw; } Log.Error("Teardown error: {0}", ex.ToString()); } }
public static async Task CreateJiraIssue(CreateIssueSettings settings, ICakeLog logger) { try { logger.Information($"Creating jira issue '{settings.Summary}' on {settings.Project}"); var jira = CreateJira(settings); var issueSettings = new CreateIssueFields(settings.Project); var issue = new Issue(jira, issueSettings) { Reporter = settings.Reporter, Summary = settings.Summary, Description = settings.Description, Environment = settings.Environment, Assignee = settings.Assignee, DueDate = settings.DueDate }; if (settings.Priority != 0) { issue.Priority = new IssuePriority(settings.Priority.ToString(CultureInfo.InvariantCulture)); } if (settings.Type != 0) { issue.Type = new IssueType(settings.Type.ToString(CultureInfo.InvariantCulture)); } if (settings.Labels != null) { issue.Labels.AddRange(settings.Labels); } var createdIssueKey = await issue.Jira.Issues.CreateIssueAsync(issue); if (!string.IsNullOrEmpty(createdIssueKey)) { logger.Information($"Jira issue '{settings.Summary}' created with key: " + createdIssueKey); } else { logger.Information($"Unable to create jira issue '{settings.Summary}'"); } } catch (Exception ex) { logger.Error($"Error creating issue '{settings.Summary}': {ex.Message}"); } }