Exemplo n.º 1
0
        public static async Task MainAsync(string[] args)
        {
            if (args.Length > 0 && string.Equals("dbg", args[0], StringComparison.OrdinalIgnoreCase))
            {
                args = args.Skip(1).ToArray();
                Debugger.Launch();
            }

            NgJob job = null;

            try
            {
                // Get arguments
                var arguments = CommandHelpers.GetArguments(args, 1);

                // Ensure that SSLv3 is disabled and that Tls v1.2 is enabled.
                ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

                // Determine the job name
                if (args.Length == 0)
                {
                    throw new ArgumentException("Missing job name argument.");
                }

                var jobName = args[0];
                TelemetryConfiguration.Active.TelemetryInitializers.Add(new JobNameTelemetryInitializer(jobName));

                // Configure ApplicationInsights
                ApplicationInsights.Initialize(arguments.GetOrDefault <string>(Arguments.InstrumentationKey));

                // Create an ILoggerFactory
                var loggerConfiguration = LoggingSetup.CreateDefaultLoggerConfiguration(withConsoleLogger: true);
                loggerConfiguration.WriteTo.File("Log.txt", retainedFileCountLimit: 3, fileSizeLimitBytes: 1000000, rollOnFileSizeLimit: true);

                var loggerFactory = LoggingSetup.CreateLoggerFactory(loggerConfiguration, LogEventLevel.Debug);

                // Create a logger that is scoped to this class (only)
                _logger = loggerFactory.CreateLogger <Program>();

                var cancellationTokenSource = new CancellationTokenSource();

                // Create an ITelemetryService
                var telemetryService = new TelemetryService(new TelemetryClient());

                // Allow jobs to set global custom dimensions
                TelemetryConfiguration.Active.TelemetryInitializers.Add(new JobPropertiesTelemetryInitializer(telemetryService));

                job = NgJobFactory.GetJob(jobName, telemetryService, loggerFactory);
                await job.RunAsync(arguments, cancellationTokenSource.Token);
            }
            catch (ArgumentException ae)
            {
                _logger?.LogError("A required argument was not found or was malformed/invalid: {Exception}", ae);

                Console.WriteLine(job != null ? job.GetUsage() : NgJob.GetUsageBase());
            }
            catch (Exception e)
            {
                _logger?.LogCritical("A critical exception occured in ng.exe! {Exception}", e);
            }

            Trace.Close();
            TelemetryConfiguration.Active.TelemetryChannel.Flush();
        }
Exemplo n.º 2
0
        public static async Task MainAsync(string[] args)
        {
            if (args.Length > 0 && string.Equals("dbg", args[0], StringComparison.OrdinalIgnoreCase))
            {
                args = args.Skip(1).ToArray();
                Debugger.Launch();
            }

            NgJob job = null;
            ApplicationInsightsConfiguration applicationInsightsConfiguration = null;
            int exitCode = 0;

            try
            {
                // Get arguments
                var arguments = CommandHelpers.GetArguments(args, 1, out var secretInjector);

                // Ensure that SSLv3 is disabled and that Tls v1.2 is enabled.
                ServicePointManager.SecurityProtocol &= ~SecurityProtocolType.Ssl3;
                ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;

                // Determine the job name
                if (args.Length == 0)
                {
                    throw new ArgumentException("Missing job name argument.");
                }

                var jobName                  = args[0];
                var instanceName             = arguments.GetOrDefault(Arguments.InstanceName, jobName);
                var instrumentationKey       = arguments.GetOrDefault <string>(Arguments.InstrumentationKey);
                var heartbeatIntervalSeconds = arguments.GetOrDefault <int>(Arguments.HeartbeatIntervalSeconds);

                applicationInsightsConfiguration = ConfigureApplicationInsights(
                    instrumentationKey,
                    heartbeatIntervalSeconds,
                    jobName,
                    instanceName,
                    out var telemetryClient,
                    out var telemetryGlobalDimensions);

                var loggerFactory = ConfigureLoggerFactory(applicationInsightsConfiguration);

                InitializeServiceProvider(
                    arguments,
                    secretInjector,
                    applicationInsightsConfiguration,
                    telemetryClient,
                    loggerFactory);

                job = NgJobFactory.GetJob(jobName, loggerFactory, telemetryClient, telemetryGlobalDimensions);
                job.SetSecretInjector(secretInjector);

                // This tells Application Insights that, even though a heartbeat is reported,
                // the state of the application is unhealthy when the exitcode is different from zero.
                // The heartbeat metadata is enriched with the job loop exit code.
                applicationInsightsConfiguration.DiagnosticsTelemetryModule?.AddOrSetHeartbeatProperty(
                    HeartbeatProperty_JobLoopExitCode,
                    exitCode.ToString(),
                    isHealthy: exitCode == 0);

                var cancellationTokenSource = new CancellationTokenSource();
                await job.RunAsync(arguments, cancellationTokenSource.Token);

                exitCode = 0;
            }
            catch (ArgumentException ae)
            {
                exitCode = 1;
                _logger?.LogError("A required argument was not found or was malformed/invalid: {Exception}", ae);

                Console.WriteLine(job != null ? job.GetUsage() : NgJob.GetUsageBase());
            }
            catch (KeyNotFoundException knfe)
            {
                exitCode = 1;
                _logger?.LogError("An expected key was not found. One possible cause of this is required argument has not been provided: {Exception}", knfe);

                Console.WriteLine(job != null ? job.GetUsage() : NgJob.GetUsageBase());
            }
            catch (Exception e)
            {
                exitCode = 1;
                _logger?.LogCritical("A critical exception occured in ng.exe! {Exception}", e);
            }

            applicationInsightsConfiguration.DiagnosticsTelemetryModule?.SetHeartbeatProperty(
                HeartbeatProperty_JobLoopExitCode,
                exitCode.ToString(),
                isHealthy: exitCode == 0);

            Trace.Close();
            applicationInsightsConfiguration?.TelemetryConfiguration.TelemetryChannel.Flush();
        }