Ejemplo n.º 1
0
 public AzureDevOpsTimeline(
     Extensions.Logging.ILogger <AzureDevOpsTimeline> logger,
     IOptionsSnapshot <AzureDevOpsTimelineOptions> options)
 {
     _logger  = logger;
     _options = options;
 }
Ejemplo n.º 2
0
    private static AsyncPolicy CreateRetryPolicy(IConfiguration configuration, Extensions.Logging.ILogger logger)
    {
        var retryMigrations = false;

        bool.TryParse(configuration["RetryMigrations"], out retryMigrations);

        // Only use a retry policy if configured to do so.
        // When running in an orchestrator/K8s, it will take care of restarting failed services.
        if (retryMigrations)
        {
            return(Policy.Handle <Exception>().
                   WaitAndRetryForeverAsync(
                       sleepDurationProvider: retry => TimeSpan.FromSeconds(5),
                       onRetry: (exception, retry, timeSpan) =>
            {
                logger.LogWarning(
                    exception,
                    "Exception {ExceptionType} with message {Message} detected during database migration (retry attempt {retry})",
                    exception.GetType().Name,
                    exception.Message,
                    retry);
            }
                       ));
        }

        return(Policy.NoOpAsync());
    }
Ejemplo n.º 3
0
 public NetworkSocket(Extensions.Logging.ILogger <NetworkProvider> logger, Socket socket)
 {
     _logger                      = logger;
     _socket                      = socket;
     _receiveEventArgs            = new SocketAsyncEventArgs();
     _receiveEventArgs.Completed += ReceiveAsyncCompleted;
 }
Ejemplo n.º 4
0
        static ILogger SetupLogger(IConfiguration configuration)
        {
            string logLevel = configuration.GetValue($"{Logger.RuntimeLogLevelEnvKey}", "info");

            Logger.SetLogLevel(logLevel);
            ILogger logger = Logger.Factory.CreateLogger <Program>();

            return(logger);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Start the debug server listening.
        /// </summary>
        /// <returns>A task that completes when the server is ready.</returns>
        public async Task StartAsync()
        {
            _jsonRpcServer = await JsonRpcServer.From(options =>
            {
                options.Serializer                = new DapProtocolSerializer();
                options.Reciever                  = new DapReciever();
                options.LoggerFactory             = _loggerFactory;
                Extensions.Logging.ILogger logger = options.LoggerFactory.CreateLogger("DebugOptionsStartup");

                // We need to let the PowerShell Context Service know that we are in a debug session
                // so that it doesn't send the powerShell/startDebugger message.
                _powerShellContextService = ServiceProvider.GetService <PowerShellContextService>();
                _powerShellContextService.IsDebugServerActive = true;

                // Needed to make sure PSReadLine's static properties are initialized in the pipeline thread.
                if (!s_hasRunPsrlStaticCtor && _usePSReadLine)
                {
                    s_hasRunPsrlStaticCtor = true;
                    _powerShellContextService
                    .ExecuteScriptStringAsync("[System.Runtime.CompilerServices.RuntimeHelpers]::RunClassConstructor([Microsoft.PowerShell.PSConsoleReadLine].TypeHandle)")
                    .Wait();
                }

                options.Services = new ServiceCollection()
                                   .AddPsesDebugServices(ServiceProvider, this, _useTempSession);

                options
                .WithInput(_inputStream)
                .WithOutput(_outputStream);

                logger.LogInformation("Adding handlers");

                options
                .WithHandler <InitializeHandler>()
                .WithHandler <LaunchHandler>()
                .WithHandler <AttachHandler>()
                .WithHandler <DisconnectHandler>()
                .WithHandler <SetFunctionBreakpointsHandler>()
                .WithHandler <SetExceptionBreakpointsHandler>()
                .WithHandler <ConfigurationDoneHandler>()
                .WithHandler <ThreadsHandler>()
                .WithHandler <SetBreakpointsHandler>()
                .WithHandler <StackTraceHandler>()
                .WithHandler <ScopesHandler>()
                .WithHandler <VariablesHandler>()
                .WithHandler <ContinueHandler>()
                .WithHandler <NextHandler>()
                .WithHandler <PauseHandler>()
                .WithHandler <StepInHandler>()
                .WithHandler <StepOutHandler>()
                .WithHandler <SourceHandler>()
                .WithHandler <SetVariableHandler>()
                .WithHandler <DebugEvaluateHandler>();

                logger.LogInformation("Handlers added");
            });
        }
Ejemplo n.º 6
0
        static Task Cleanup(Option <Agent> agentOption, ILogger logger)
        {
            var closeCts = new CancellationTokenSource(ShutdownWaitPeriod);

            try
            {
                return(agentOption.ForEachAsync(a => a.HandleShutdown(closeCts.Token)));
            }
            catch (Exception ex)
            {
                logger.LogError(AgentEventIds.Agent, ex, "Error on shutdown");
                return(Task.CompletedTask);
            }
        }
Ejemplo n.º 7
0
        static void LogLogo(ILogger logger)
        {
            logger.LogInformation(@"
        █████╗ ███████╗██╗   ██╗██████╗ ███████╗
       ██╔══██╗╚══███╔╝██║   ██║██╔══██╗██╔════╝
       ███████║  ███╔╝ ██║   ██║██████╔╝█████╗
       ██╔══██║ ███╔╝  ██║   ██║██╔══██╗██╔══╝
       ██║  ██║███████╗╚██████╔╝██║  ██║███████╗
       ╚═╝  ╚═╝╚══════╝ ╚═════╝ ╚═╝  ╚═╝╚══════╝

 ██╗ ██████╗ ████████╗    ███████╗██████╗  ██████╗ ███████╗
 ██║██╔═══██╗╚══██╔══╝    ██╔════╝██╔══██╗██╔════╝ ██╔════╝
 ██║██║   ██║   ██║       █████╗  ██║  ██║██║  ███╗█████╗
 ██║██║   ██║   ██║       ██╔══╝  ██║  ██║██║   ██║██╔══╝
 ██║╚██████╔╝   ██║       ███████╗██████╔╝╚██████╔╝███████╗
 ╚═╝ ╚═════╝    ╚═╝       ╚══════╝╚═════╝  ╚═════╝ ╚══════╝
");
        }
Ejemplo n.º 8
0
        public NetworkListener(Extensions.Logging.ILogger <NetworkProvider> logger, NetworkListenerSettings settings)
        {
            // TODO: logic to bind ipv4 and/or ipv6 ?
            _listener = new TcpListener(settings.IPEndPoint);

            if (settings.ExclusiveAddressUse.HasValue)
            {
                _listener.ExclusiveAddressUse = settings.ExclusiveAddressUse.Value;
            }

            if (settings.AllowNatTraversal.HasValue)
            {
                _listener.AllowNatTraversal(settings.AllowNatTraversal.Value);
            }

            _listenerBacklog = settings.ListenerBacklog;
            _socketNoDelay   = settings.NoDelay;
            _logger          = logger;
        }
Ejemplo n.º 9
0
        public static async Task <int> MainAsync(IConfiguration configuration)
        {
            // Bring up the logger before anything else so we can log errors ASAP
            ILogger logger = SetupLogger(configuration);

            logger.LogInformation("Starting module management agent.");

            VersionInfo versionInfo = VersionInfo.Get(VersionInfoFileName);

            if (versionInfo != VersionInfo.Empty)
            {
                logger.LogInformation($"Version - {versionInfo.ToString(true)}");
            }
            LogLogo(logger);

            string mode;

            string   configSourceConfig;
            string   backupConfigFilePath;
            int      maxRestartCount;
            TimeSpan intensiveCareTime;
            int      coolOffTimeUnitInSeconds;
            bool     usePersistentStorage;
            string   storagePath;
            string   edgeDeviceHostName;
            string   dockerLoggingDriver;
            Dictionary <string, string> dockerLoggingOptions;
            IEnumerable <AuthConfig>    dockerAuthConfig;
            int configRefreshFrequencySecs;

            try
            {
                mode = configuration.GetValue(Constants.ModeKey, "docker");
                configSourceConfig       = configuration.GetValue <string>("ConfigSource");
                backupConfigFilePath     = configuration.GetValue <string>("BackupConfigFilePath");
                maxRestartCount          = configuration.GetValue <int>("MaxRestartCount");
                intensiveCareTime        = TimeSpan.FromMinutes(configuration.GetValue <int>("IntensiveCareTimeInMinutes"));
                coolOffTimeUnitInSeconds = configuration.GetValue("CoolOffTimeUnitInSeconds", 10);
                usePersistentStorage     = configuration.GetValue("UsePersistentStorage", true);
                storagePath                = GetStoragePath(configuration);
                edgeDeviceHostName         = configuration.GetValue <string>(Constants.EdgeDeviceHostNameKey);
                dockerLoggingDriver        = configuration.GetValue <string>("DockerLoggingDriver");
                dockerLoggingOptions       = configuration.GetSection("DockerLoggingOptions").Get <Dictionary <string, string> >() ?? new Dictionary <string, string>();
                dockerAuthConfig           = configuration.GetSection("DockerRegistryAuth").Get <List <AuthConfig> >() ?? new List <AuthConfig>();
                configRefreshFrequencySecs = configuration.GetValue("ConfigRefreshFrequencySecs", 3600);
            }
            catch (Exception ex)
            {
                logger.LogCritical(AgentEventIds.Agent, ex, "Fatal error reading the Agent's configuration.");
                return(1);
            }

            IContainer container;

            try
            {
                var builder = new ContainerBuilder();
                builder.RegisterModule(new LoggingModule(dockerLoggingDriver, dockerLoggingOptions));
                Option <string>           productInfo      = versionInfo != VersionInfo.Empty ? Option.Some(versionInfo.ToString()) : Option.None <string>();
                Option <UpstreamProtocol> upstreamProtocol = configuration.GetValue <string>(Constants.UpstreamProtocolKey).ToUpstreamProtocol();
                switch (mode.ToLowerInvariant())
                {
                case Constants.DockerMode:
                    var    dockerUri = new Uri(configuration.GetValue <string>("DockerUri"));
                    string deviceConnectionString = configuration.GetValue <string>("DeviceConnectionString");
                    builder.RegisterModule(new AgentModule(maxRestartCount, intensiveCareTime, coolOffTimeUnitInSeconds, usePersistentStorage, storagePath));
                    builder.RegisterModule(new DockerModule(deviceConnectionString, edgeDeviceHostName, dockerUri, dockerAuthConfig, upstreamProtocol, productInfo));
                    break;

                case Constants.IotedgedMode:
                    string managementUri      = configuration.GetValue <string>(Constants.EdgeletManagementUriVariableName);
                    string workloadUri        = configuration.GetValue <string>(Constants.EdgeletWorkloadUriVariableName);
                    string iothubHostname     = configuration.GetValue <string>(Constants.IotHubHostnameVariableName);
                    string deviceId           = configuration.GetValue <string>(Constants.DeviceIdVariableName);
                    string moduleId           = configuration.GetValue(Constants.ModuleIdVariableName, Constants.EdgeAgentModuleIdentityName);
                    string moduleGenerationId = configuration.GetValue <string>(Constants.EdgeletModuleGenerationIdVariableName);
                    builder.RegisterModule(new AgentModule(maxRestartCount, intensiveCareTime, coolOffTimeUnitInSeconds, usePersistentStorage, storagePath, Option.Some(new Uri(workloadUri)), moduleId, Option.Some(moduleGenerationId)));
                    builder.RegisterModule(new EdgeletModule(iothubHostname, edgeDeviceHostName, deviceId, new Uri(managementUri), new Uri(workloadUri), dockerAuthConfig, upstreamProtocol, productInfo));
                    break;

                default:
                    throw new InvalidOperationException($"Mode '{mode}' not supported.");
                }

                switch (configSourceConfig.ToLowerInvariant())
                {
                case "twin":
                    builder.RegisterModule(new TwinConfigSourceModule(backupConfigFilePath, configuration, versionInfo, TimeSpan.FromSeconds(configRefreshFrequencySecs)));
                    break;

                case "local":
                    builder.RegisterModule(new FileConfigSourceModule("config.json", configuration));
                    break;

                default:
                    throw new InvalidOperationException($"ConfigSource '{configSourceConfig}' not supported.");
                }

                container = builder.Build();
            }
            catch (Exception ex)
            {
                logger.LogCritical(AgentEventIds.Agent, ex, "Fatal error building application.");
                return(1);
            }

            (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler)
                = ShutdownHandler.Init(ShutdownWaitPeriod, logger);

            int returnCode;

            using (IConfigSource unused = await container.Resolve <Task <IConfigSource> >())
            {
                Option <Agent> agentOption = Option.None <Agent>();

                try
                {
                    Agent agent = await container.Resolve <Task <Agent> >();

                    agentOption = Option.Some(agent);
                    while (!cts.Token.IsCancellationRequested)
                    {
                        try
                        {
                            await agent.ReconcileAsync(cts.Token);
                        }
                        catch (Exception ex) when(!ex.IsFatal())
                        {
                            logger.LogWarning(AgentEventIds.Agent, ex, "Agent reconcile concluded with errors.");
                        }
                        await Task.Delay(TimeSpan.FromSeconds(5), cts.Token);
                    }
                    logger.LogInformation("Closing module management agent.");

                    returnCode = 0;
                }
                catch (OperationCanceledException)
                {
                    logger.LogInformation("Main thread terminated");
                    returnCode = 0;
                }
                catch (Exception ex)
                {
                    logger.LogCritical(AgentEventIds.Agent, ex, "Fatal error starting Agent.");
                    returnCode = 1;
                }

                // Attempt to report shutdown of Agent
                await Cleanup(agentOption, logger);

                completed.Set();
            }
            handler.ForEach(h => GC.KeepAlive(h));
            return(returnCode);
        }
Ejemplo n.º 10
0
    public static async Task EnsureSeedData(IServiceScope scope, IConfiguration configuration, Extensions.Logging.ILogger logger)
    {
        var retryPolicy = CreateRetryPolicy(configuration, logger);
        var context     = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();

        await retryPolicy.ExecuteAsync(async() =>
        {
            await context.Database.MigrateAsync();

            var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();
            var alice   = await userMgr.FindByNameAsync("alice");

            if (alice == null)
            {
                alice = new ApplicationUser
                {
                    UserName       = "******",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                    CardHolderName = "Alice Smith",
                    CardNumber     = "4012888888881881",
                    CardType       = 1,
                    City           = "Redmond",
                    Country        = "U.S.",
                    Expiration     = "12/20",
                    Id             = Guid.NewGuid().ToString(),
                    LastName       = "Smith",
                    Name           = "Alice",
                    PhoneNumber    = "1234567890",
                    ZipCode        = "98052",
                    State          = "WA",
                    Street         = "15703 NE 61st Ct",
                    SecurityNumber = "123"
                };

                var result = userMgr.CreateAsync(alice, "Pass123$").Result;

                if (!result.Succeeded)
                {
                    throw new Exception(result.Errors.First().Description);
                }

                logger.LogDebug("alice created");
            }
            else
            {
                logger.LogDebug("alice already exists");
            }

            var bob = await userMgr.FindByNameAsync("bob");

            if (bob == null)
            {
                bob = new ApplicationUser
                {
                    UserName       = "******",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true,
                    CardHolderName = "Bob Smith",
                    CardNumber     = "4012888888881881",
                    CardType       = 1,
                    City           = "Redmond",
                    Country        = "U.S.",
                    Expiration     = "12/20",
                    Id             = Guid.NewGuid().ToString(),
                    LastName       = "Smith",
                    Name           = "Bob",
                    PhoneNumber    = "1234567890",
                    ZipCode        = "98052",
                    State          = "WA",
                    Street         = "15703 NE 61st Ct",
                    SecurityNumber = "456"
                };

                var result = await userMgr.CreateAsync(bob, "Pass123$");

                if (!result.Succeeded)
                {
                    throw new Exception(result.Errors.First().Description);
                }

                logger.LogDebug("bob created");
            }
            else
            {
                logger.LogDebug("bob already exists");
            }
        });
    }
Ejemplo n.º 11
0
 public ConsoleLogger(Extensions.Logging.ILogger logger)
 {
     _logger = logger;
 }