public static int HandleSilentDownload(DownloadBookOptions options)
 {
     // This task will be all the program does. We need to do enough setup so that
     // the download code can work, then tear it down.
     Program.SetUpErrorHandling();
     try
     {
         using (var applicationContainer = new ApplicationContainer())
         {
             Program.SetUpLocalization(applicationContainer);
             Browser.SetUpXulRunner();
             Browser.XulRunnerShutdown += Program.OnXulRunnerShutdown;
             LocalizationManager.SetUILanguage(Settings.Default.UserInterfaceLanguage, false);
             var transfer = new BookTransfer(new BloomParseClient(), ProjectContext.CreateBloomS3Client(),
                 applicationContainer.BookThumbNailer, new BookDownloadStartingEvent()) /*not hooked to anything*/;
             // Since Bloom is not a normal console app, when run from a command line, the new command prompt
             // appears at once. The extra newlines here are attempting to separate this from our output.
             Console.WriteLine("\nstarting download");
             transfer.HandleDownloadWithoutProgress(options.Url, options.DestinationPath);
             Console.WriteLine(("\ndownload complete\n"));
         }
         return 0;
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.Message);
         Console.WriteLine(ex.Message);
         Console.WriteLine(ex.StackTrace);
         return 1;
     }
 }
 public GearRegistry(ApplicationContainer container)
 {
     this.container = container;
     string baseDir = Path.Combine(this.container.ContainerDir, "gear-registry");
     Directory.CreateDirectory(baseDir);
     this.registryFile = Path.Combine(baseDir, "gear-registry.json");
     if(!File.Exists(this.registryFile))
         File.Create(this.registryFile);
     this.container.SetRoPermissions(this.registryFile);
     this.backupFile = Path.Combine(baseDir, "gear-registry.json.bak");
     this.lockFile = Path.Combine(baseDir, "gear-registry.lock");
     Load();
 }
        private void CleanUp()
        {
            // NOTE: Service can't recieve and process requests here, so you can destroy all resources

            ApplicationContainer.Dispose();
        }
        private async Task StartApplication()
        {
            // NOTE: Service not yet recieve and process requests here

            await ApplicationContainer.Resolve <IStartupManager>().StartAsync();
        }
Beispiel #5
0
 protected void RegisterEvents(ref IApplicationLifetime applicationLifetime)
 {
     Log.Logger.LogEventDebug(LoggerEvents.STARTUP, LoggerTemplates.REGISTER_EVENT, nameof(ApplicationContainer), nameof(applicationLifetime.ApplicationStopped));
     applicationLifetime.ApplicationStopped.Register(() => ApplicationContainer.Dispose());
 }
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var settingsManager = Configuration.LoadSettings <AppSettings>(options =>
            {
                options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString);
                options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName);
                options.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}";
            });

#if !DEBUG
            services.AddApplicationInsightsTelemetry();
#endif

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new AutoMapperProfile(settingsManager.CurrentValue.PartnerApiService
                                                    .MoneyDecimalPointStringPrecision));
            });

            services.AddSingleton(mappingConfig.CreateMapper());

            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddMvcOptions(opt =>
            {
                opt.Filters.Add(typeof(MaintenanceFilter));
                opt.Filters.Add(typeof(NoContentFilter));
            })
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver =
                    new Newtonsoft.Json.Serialization.DefaultContractResolver();
            })
            .AddFluentValidation(opt =>
            {
                opt.RegisterValidatorsFromAssembly(Assembly.GetEntryAssembly());
            });

            services.Configure <MvcOptions>(opts =>
            {
                var formatter         = opts.OutputFormatters.FirstOrDefault(i => i.GetType() == typeof(JsonOutputFormatter));
                var jsonFormatter     = formatter as JsonOutputFormatter;
                var formatterSettings = jsonFormatter == null
                    ? JsonSerializerSettingsProvider.CreateSerializerSettings()
                    : jsonFormatter.PublicSerializerSettings;
                if (formatter != null)
                {
                    opts.OutputFormatters.RemoveType <JsonOutputFormatter>();
                }
                formatterSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ";
                var jsonOutputFormatter            = new JsonOutputFormatter(formatterSettings, ArrayPool <char> .Create());
                opts.OutputFormatters.Insert(0, jsonOutputFormatter);
            });

            _appSettings = settingsManager.CurrentValue;

            services.AddSwaggerGen(options =>
            {
                options.DefaultLykkeConfiguration(ApiVersion, ApiTitle);
                options.OperationFilter <ApiKeyHeaderOperationFilter>();
            });

            services.Configure <ApiBehaviorOptions>(options =>
            {
                // Wrap failed model state into LykkeApiErrorResponse.
                //options.InvalidModelStateResponseFactory = InvalidModelStateResponseFactory.CreateInvalidModelResponse;
            });

            services.AddLykkeLogging(
                settingsManager.ConnectionString(s => s.PartnerApiService.Db.LogsConnString),
                "PartnerApiServiceLogs",
                _appSettings.SlackNotifications.AzureQueue.ConnectionString,
                _appSettings.SlackNotifications.AzureQueue.QueueName);

            var builder = new ContainerBuilder();

            builder.Populate(services);

            builder.RegisterModule(new AutofacModule(settingsManager));

            ApplicationContainer = builder.Build();
            InvalidModelStateResponseFactory.Logger = ApplicationContainer.Resolve <ILogFactory>()
                                                      .CreateLog(nameof(InvalidModelStateResponseFactory));

            return(new AutofacServiceProvider(ApplicationContainer));
        }
 public DomainEventController(ApplicationContainer applicationContainer)
 {
     _domainEventResolver  = applicationContainer.DomainEventResolver;
     _domainEventProjector = applicationContainer.DomainEventAppliers;
 }
 protected override INancyEngine GetEngineInternal()
 {
     return(ApplicationContainer.Build(typeof(INancyEngine)) as INancyEngine);
 }
Beispiel #9
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var settingsManager = Configuration.LoadSettings <AppSettings>(options =>
            {
                options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString);
                options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName);
                options.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}";
            });

#if !DEBUG
            services.AddApplicationInsightsTelemetry();
#endif

            services.AddAutoMapper(typeof(AutoMapperProfile));

            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddMvcOptions(opt => { opt.Filters.Add(typeof(NoContentFilter)); })
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver =
                    new Newtonsoft.Json.Serialization.DefaultContractResolver();
            })
            .AddFluentValidation(opt =>
            {
                opt.RegisterValidatorsFromAssembly(Assembly.GetEntryAssembly());
            });

            services.Configure <MvcOptions>(opts =>
            {
                var formatter         = opts.OutputFormatters.FirstOrDefault(i => i.GetType() == typeof(JsonOutputFormatter));
                var jsonFormatter     = formatter as JsonOutputFormatter;
                var formatterSettings = jsonFormatter == null
                    ? JsonSerializerSettingsProvider.CreateSerializerSettings()
                    : jsonFormatter.PublicSerializerSettings;
                if (formatter != null)
                {
                    opts.OutputFormatters.RemoveType <JsonOutputFormatter>();
                }
                formatterSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss.fffZ";
                var jsonOutputFormatter            = new JsonOutputFormatter(formatterSettings, ArrayPool <char> .Create());
                opts.OutputFormatters.Insert(0, jsonOutputFormatter);
            });

            _appSettings = settingsManager.CurrentValue;

            services.AddSwaggerGen(options =>
            {
                options.DefaultLykkeConfiguration(ApiVersion, ApiTitle);
                options.OperationFilter <ObsoleteOperationDescriptionFilter>();
                options.OperationFilter <ApiKeyHeaderOperationFilter>();
            });

            services.Configure <ApiBehaviorOptions>(options =>
            {
                // Wrap failed model state into LykkeApiErrorResponse.
                //options.InvalidModelStateResponseFactory = InvalidModelStateResponseFactory.CreateInvalidModelResponse;
            });

            services.AddAuthentication(o =>
            {
                o.DefaultForbidScheme = IISDefaults.AuthenticationScheme;
            });

            services.AddLykkeLogging(
                settingsManager.ConnectionString(s => s.AdminApiService.Db.LogsConnString),
                "AdminApiServiceLogs",
                _appSettings.SlackNotifications.AzureQueue.ConnectionString,
                _appSettings.SlackNotifications.AzureQueue.QueueName,
                logBuilder => logBuilder
                .AddSanitizingFilter(new Regex(@"(\\?""?[Pp]assword\\?""?:\s*\\?"")(.*?)(\\?"")"), "$1*$3")
                .AddSanitizingFilter(new Regex(@"(\\?""?[Ll]ogin\\?""?:\s*\\?"")(.*?)(\\?"")"), "$1*$3")
                .AddSanitizingFilter(new Regex(@"(\\?""?[Ee]mail\\?""?:\s*\\?"")(.*?)(\\?"")"), "$1*$3"));

            var builder = new ContainerBuilder();

            builder.Populate(services);

            builder.RegisterModule(new AutofacModule(settingsManager));
            var adminSettings = settingsManager.CurrentValue.AdminApiService;
            builder.RegisterModule(
                new DomainServices.AutofacModule(
                    adminSettings.TokenSymbol,
                    adminSettings.IsPublicBlockchainFeatureDisabled,
                    adminSettings.MobileAppImageDoOptimization,
                    adminSettings.MobileAppImageMinWidth,
                    adminSettings.MobileAppImageWarningFileSizeInKB,
                    adminSettings.SuggestedAdminPasswordLength,
                    adminSettings.IsPhoneVerificationDisabled));

            ApplicationContainer = builder.Build();
            InvalidModelStateResponseFactory.Logger = ApplicationContainer.Resolve <ILogFactory>()
                                                      .CreateLog(nameof(InvalidModelStateResponseFactory));

            return(new AutofacServiceProvider(ApplicationContainer));
        }
 /// <summary>
 /// Creates a per request child/nested container
 /// </summary>
 /// <returns>Request container instance</returns>
 protected override ILifetimeScope CreateRequestContainer(NancyContext context)
 {
     return(ApplicationContainer.BeginLifetimeScope());
 }
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver =
                        new DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration("v1", "BlockchainWallets API");
                });

                var builder     = new ContainerBuilder();
                var appSettings = Configuration.LoadSettings <AppSettings>(o =>
                {
                    o.SetConnString(s => s.SlackNotifications.AzureQueue.ConnectionString);
                    o.SetQueueName(s => s.SlackNotifications.AzureQueue.QueueName);
                    o.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}";
                });

                var slackSettings = appSettings.CurrentValue.SlackNotifications;


                services.AddLykkeLogging(
                    appSettings.ConnectionString(x => x.BlockchainWalletsService.Db.LogsConnString),
                    "BlockchainWalletsLog",
                    slackSettings.AzureQueue.ConnectionString,
                    slackSettings.AzureQueue.QueueName,
                    logging =>
                {
                    logging.AddAdditionalSlackChannel("CommonBlockChainIntegration");
                    logging.AddAdditionalSlackChannel("CommonBlockChainIntegrationImportantMessages", options =>
                    {
                        options.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Warning;
                    });
                }
                    );

                builder
                .RegisterModule(new CqrsModule(appSettings.CurrentValue.BlockchainWalletsService.Cqrs))
                .RegisterModule(new RepositoriesModule(appSettings.Nested(x => x.BlockchainWalletsService.Db)))
                .RegisterModule(new ServiceModule(
                                    appSettings.CurrentValue.BlockchainsIntegration,
                                    appSettings.CurrentValue.BlockchainSignFacadeClient,
                                    appSettings.CurrentValue,
                                    appSettings.CurrentValue.AssetsServiceClient,
                                    appSettings.CurrentValue.BlockchainWalletsService));

                builder.Populate(services);

                ApplicationContainer = builder.Build();

                Log            = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);
                HealthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                if (Log != null)
                {
                    Log.Critical(ex);
                }
                else
                {
                    FatalErrorStdOut(ex);
                }

                throw;
            }
        }
 public DomainEventController(ApplicationContainer applicationContainer)
 {
     _domainEventResolver = applicationContainer.DomainEventResolver;
     _domainEventHandler  = applicationContainer.DomainEventHandlerContainer;
 }
 protected virtual ILifetimeScope GetLifetimeScopeCore(Action <ContainerBuilder> configurationAction)
 {
     return((configurationAction == null)
                ? ApplicationContainer.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag)
                : ApplicationContainer.BeginLifetimeScope(MatchingScopeLifetimeTags.RequestLifetimeScopeTag, configurationAction));
 }
Beispiel #14
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                var appSettings = Configuration.LoadSettings <AppSettings>();

                services.AddMvcCore().AddVersionedApiExplorer(opt =>
                {
                    opt.GroupNameFormat           = "'v'VVV";
                    opt.SubstituteApiVersionInUrl = true;
                });

                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    options.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                });

                services.AddApiVersioning(opt =>
                {
                    opt.ReportApiVersions = true;
                    opt.AssumeDefaultVersionWhenUnspecified = true;
                    opt.DefaultApiVersion = new ApiVersion(1, 0);
                });

                services.AddSwaggerGen(options =>
                {
                    var provider = services.BuildServiceProvider().GetRequiredService <IApiVersionDescriptionProvider>();

                    foreach (var description in provider.ApiVersionDescriptions)
                    {
                        options.SwaggerDoc(
                            $"{description.GroupName}",
                            new Info
                        {
                            Version     = description.GroupName,
                            Title       = "PayAPI",
                            Description =
                                @"**Lykke PayAPI** is the set of API methods aimed to provide customers the out-of-the-box functionality for their 
clients to make payments in BTC, ETH and other assets depending on customer needs.

#### Allowed HTTPs requests:
- **POST** : To create resource 
- **PUT** : To update resource
- **GET** : To get a resource or list of resources
- **DELETE** : To delete resource

#### Description Of Usual Server Responses:
- 200 `OK` - the request was successful (some API calls may return 201 instead).
- 201 `Created` - the request was successful and a resource was created.
- 204 `No Content` - the request was successful but there is no representation to return (i.e. the response is empty).
- 400 `Bad Request` - the request could not be understood or was missing required parameters.
- 401 `Unauthorized` - authentication failed or user doesn't have permissions for requested operation.
- 403 `Forbidden` - access denied.
- 404 `Not Found` - resource was not found."
                        });

                        options.DescribeAllEnumsAsStrings();
                        options.EnableXmsEnumExtension();

                        #region EnableXmlDocumentation
                        var basePath      = PlatformServices.Default.Application.ApplicationBasePath;
                        var entryAssembly = Assembly.GetEntryAssembly();

                        //Set the comments path for the swagger json and ui.
                        var xmlPath = Path.Combine(basePath, $"{entryAssembly.GetName().Name}.xml");

                        if (File.Exists(xmlPath))
                        {
                            options.IncludeXmlComments(xmlPath);
                        }
                        #endregion

                        options.MakeResponseValueTypesRequired();
                        // this filter produced null exception: options.OperationFilter<FormFileUploadOperationFilter>();
                    }

                    options.OperationFilter <SwaggerDefaultValues>();
                    options.OperationFilter <HeaderAccessOperationFilter>();
                    options.OperationFilter <SwaggerExtensionsFilter>();
                });

                services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = LykkePayConstants.AuthenticationScheme;
                    options.DefaultChallengeScheme    = LykkePayConstants.AuthenticationScheme;
                })
                .AddScheme <LykkePayAuthOptions, LykkePayAuthHandler>(LykkePayConstants.AuthenticationScheme,
                                                                      LykkePayConstants.AuthenticationScheme, options => { })
                .AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer           = true,
                        ValidIssuer              = appSettings.CurrentValue.PayAPI.JwtSecurity.Issuer,
                        ValidateAudience         = true,
                        ValidAudience            = appSettings.CurrentValue.PayAPI.JwtSecurity.Audience,
                        ValidateLifetime         = true,
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(appSettings.CurrentValue.PayAPI.JwtSecurity.Key))
                    };
                });

                var builder = new ContainerBuilder();

                services.AddLykkeLogging
                (
                    appSettings.ConnectionString(x => x.PayAPI.Db.LogsConnString),
                    "PayAPILog",
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName
                );

                builder.RegisterModule(new ServiceModule(appSettings));
                builder.Populate(services);
                ApplicationContainer = builder.Build();

                _log            = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);
                _healthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                Mapper.Initialize(cfg =>
                {
                    cfg.AddProfiles(typeof(AutoMapperProfile));
                    cfg.AddProfiles(typeof(Services.AutoMapperProfile));
                });

                Mapper.AssertConfigurationIsValid();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                _log?.Critical(ex);
                throw;
            }
        }
Beispiel #15
0
 public AuthorizedKeysFile(ApplicationContainer container, string filename = null)
 {
     this.Container = container;
     this.Filename  = string.IsNullOrEmpty(filename) ? Path.Combine(this.Container.ContainerDir, ".ssh", "authorized_keys") : filename;
 }
        ///// ------------------------------------------------------------------------------------
        //[Test]
        //[Category("SkipOnTeamCity")]
        //public void SetFilesToArchive_ParticipantFileDoNotExist_DoesNotCrash()
        //{
        //    var model = new Mock<ArchivingDlgViewModel>(MockBehavior.Loose, "SayMore", "ddo", "ddo-session", null);
        //    _session._participants = new[] { "ddo-person", "non-existant-person" };
        //    _session.SetFilesToArchive(model.Object);
        //	model.VerifyAll();
        //}
        #endregion

        #region Private helper methods
        private ProjectContext CreateProjectContext(ApplicationContainer appContext)
        {
            return(appContext.CreateProjectContext(_parentFolder.Combine("foo", "foo." + Project.ProjectSettingsFileExtension)));
        }
Beispiel #17
0
 /// <summary>
 /// Upload bloom books in the specified folder to the bloom library.
 /// Folders that contain exactly one .htm file are interpreted as books and uploaded.
 /// Other folders are searched recursively for children that appear to be bloom books.
 /// The parent folder of a bloom book is searched for a .bloomContainer file and, if one is found,
 /// the book is treated as part of that collection (e.g., for determining vernacular language).
 /// If no collection is found there it uses whatever collection was last open, or the current default.
 /// </summary>
 /// <param name="folder"></param>
 public void UploadFolder(string folder, ApplicationContainer container)
 {
     if (!LogIn(Settings.Default.WebUserId, Settings.Default.WebPassword))
     {
         SIL.Reporting.ErrorReport.NotifyUserOfProblem("Could not log you in using user='******' and pwd='" + Settings.Default.WebPassword+"'."+System.Environment.NewLine+
             "For some reason, from the command line, we cannot get these credentials out of Settings.Default. However if you place your command line arguments in the properties of the project in visual studio and run from there, it works. If you are already doing that and get this message, then try running Bloom normally (gui), go to publish, and make sure you are logged in. Then quit and try this again.");
         return;
     }
     using (var dlg = new BulkUploadProgressDlg())
     {
         var worker = new BackgroundWorker();
         worker.DoWork += BackgroundUpload;
         worker.RunWorkerCompleted += (sender, args) =>
         {
             dlg.Close();
         };
         worker.RunWorkerAsync(new object[] { folder, dlg, container });
         dlg.ShowDialog(); // waits until worker completed closes it.
     }
 }
Beispiel #18
0
        public void Test_AddSsh_Key()
        {
            ApplicationContainer container = TestHelper.CreateAppContainer();

            container.AddSshKey("AAAAB3NzaC1yc2EAAAADAQABAAABAQDh1D8gtGIYjXHaRCvZZeeFRJiJICiP03d3Intc0xtSHyIieogsr8pN3awTWS7V0prlT+hp6l1Sb20Vic/az9z3kSAoCL/eu+Nfcyc6oBhkkcnz2Ag/5bzstlRJmWahxIr+LT2bbqCiUTBaNWG5oKknQWQB+gryaKqzIfX2dPtKikvpSUNi+D8quQDscUmx9gCbFy3rhZNJiguylQaBngxfwtt/7y8bjcMRvucffrEfMQkPQvH0vOBoOJpigAqJtDyvyvQ7dZvOqGUPgw+rClG3f0fzy34u9i26LutxZiFOQKHX5GxoD3GcQ0XMOZJ5PDxmj4WJkgLFXzTnqTyKkHZh", "ssh-rsa", "5278c3410798909d9c000001-default");
        }
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddHttpClient();
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.ContractResolver =
                        new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration("v1", "ServiceStellarApi API");
                });

                EntityMetamodel.Configure(new AnnotationsBasedMetamodelProvider());

                var builder     = new ContainerBuilder();
                var appSettings = Configuration.LoadSettings <AppSettings>(options =>
                {
                    options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString);
                    options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName);
                    options.SenderName = AppEnvironment.Name;
                });

                services.AddSingleton <Lykke.Service.Stellar.Api.Core.Settings.AppSettings>(appSettings.CurrentValue);

                services.AddLykkeLogging(
                    appSettings.ConnectionString(x => x.StellarApiService.Db.LogsConnString),
                    "ServiceStellarApiLog",
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.CurrentValue.SlackNotifications.AzureQueue.QueueName,
                    logBuilder =>
                {
                    logBuilder.AddAdditionalSlackChannel("BlockChainIntegration", options =>
                    {
                        options.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Information;     // Let it be explicit
                    });

                    logBuilder.AddAdditionalSlackChannel("BlockChainIntegrationImportantMessages", options =>
                    {
                        options.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Warning;
                    });
                }
                    );

                builder.RegisterChaosKitty(appSettings.CurrentValue.StellarApiService.ChaosKitty);
                builder.RegisterModule(new StellarApiModule());
                builder.RegisterModule(new RepositoryModule(appSettings.Nested(x => x.StellarApiService)));
                builder.RegisterModule(new ServiceModule(appSettings.Nested(x => x.StellarApiService)));
                builder.Populate(services);

                ApplicationContainer = builder.Build();

                Log            = ApplicationContainer.Resolve <ILogFactory>().CreateLog(this);
                HealthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                Log?.Critical(ex);
                throw;
            }
        }
 private void CleanUp()
 {
     ApplicationContainer.Dispose();
 }
        public ReturnStatus Execute()
        {
            ReturnStatus returnStatus = new ReturnStatus();

            try
            {
                NodeConfig      config     = new NodeConfig();
                string          gearPath   = config.Get("GEAR_BASE_DIR");
                string[]        folders    = Directory.GetDirectories(gearPath);
                List <RubyHash> endpoints  = new List <RubyHash>();
                RubyHash        outputHash = new RubyHash();


                foreach (string folder in folders)
                {
                    string folderName = Path.GetFileName(folder);
                    if (!folderName.StartsWith("."))
                    {
                        ApplicationContainer        container = ApplicationContainer.GetFromUuid(folderName);
                        Dictionary <string, string> env       = Environ.ForGear(container.ContainerDir);

                        container.Cartridge.EachCartridge(cart =>
                        {
                            cart.Endpoints.ForEach(endpoint =>
                            {
                                RubyHash endpointHash = new RubyHash();

                                endpointHash.Add("cartridge_name", string.Format("{0}-{1}", cart.Name, cart.Version));
                                if (env.ContainsKey(endpoint.PublicPortName))
                                {
                                    endpointHash.Add("external_port", env[endpoint.PublicPortName]);
                                }
                                else
                                {
                                    endpointHash.Add("external_port", null);
                                }
                                endpointHash.Add("internal_address", env[endpoint.PrivateIpName]);
                                endpointHash.Add("internal_port", endpoint.PrivatePort);
                                endpointHash.Add("protocols", endpoint.Protocols);
                                endpointHash.Add("type", new List <string>());

                                if (cart.WebProxy)
                                {
                                    endpointHash["protocols"] = container.Cartridge.GetPrimaryCartridge().Endpoints.First().Protocols;
                                    endpointHash["type"]      = new List <string>()
                                    {
                                        "load_balancer"
                                    };
                                }
                                else if (cart.WebFramework)
                                {
                                    endpointHash["type"] = new List <string>()
                                    {
                                        "web_framework"
                                    };
                                }
                                else if (cart.Categories.Contains("database"))
                                {
                                    endpointHash["type"] = new List <string>()
                                    {
                                        "web_framework"
                                    };
                                }
                                else if (cart.Categories.Contains("plugin"))
                                {
                                    endpointHash["type"] = new List <string>()
                                    {
                                        "plugin"
                                    };
                                }
                                else
                                {
                                    endpointHash["type"] = new List <string>()
                                    {
                                        "other"
                                    };
                                }

                                if (endpoint.Mappings != null && endpoint.Mappings.Count > 0)
                                {
                                    List <RubyHash> mappingsList = new List <RubyHash>();
                                    foreach (Uhuru.Openshift.Common.Models.Endpoint.Mapping mapping in endpoint.Mappings)
                                    {
                                        RubyHash mappings = new RubyHash();
                                        mappings.Add("frontend", mapping.Frontend);
                                        mappings.Add("backend", mapping.Backend);
                                        mappingsList.Add(mappings);
                                    }
                                    endpointHash.Add("mappings", mappingsList);
                                }
                                endpoints.Add(endpointHash);
                            });
                        });
                        if (endpoints.Count > 0)
                        {
                            outputHash.Add(folderName, endpoints);
                        }
                    }
                }
                string output = Newtonsoft.Json.JsonConvert.SerializeObject(outputHash);
                returnStatus.Output   = output;
                returnStatus.ExitCode = 0;
            }
            catch (Exception ex)
            {
                Logger.Error("Error running get-all-gears-endpoints-action command: {0} - {1}", ex.Message, ex.StackTrace);
                returnStatus.Output   = ex.ToString();
                returnStatus.ExitCode = 1;
            }

            return(returnStatus);
        }
 protected override IContainer CreateRequestContainer(NancyContext context)
 {
     return(ApplicationContainer.OpenScope(Reuse.WebRequestScopeName));
 }
Beispiel #23
0
 public void Dispose()
 {
     ApplicationContainer?.Dispose();
     ApplicationContainer = null;
 }
 protected override IEnumerable <IApplicationStartup> GetApplicationStartupTasks()
 {
     return(ApplicationContainer.Resolve <IEnumerable <IApplicationStartup> >());
 }
Beispiel #25
0
        public static int Handle(UploadParameters options)
        {
            try
            {
                Console.OutputEncoding = Encoding.UTF8;
            }
            catch (Exception)
            {
                // swallow. The above throws a handle error when run in Visual Studio
            }

            IsUploading = true;
            // -u user, and <path> are all required, so they must contain strings.
            // -d destination has a default value, so it also must contain a string.
            options.Path = options.Path.TrimEnd(new[] { '/', '\\', System.IO.Path.PathSeparator });             // remove any trailing slashes
            // validate the value for the upload destination.
            options.Dest = options.Dest.ToLowerInvariant();
            switch (options.Dest)
            {
            case UploadDestination.DryRun:
            case UploadDestination.Development:
            case UploadDestination.Production:
                break;

            default:
                Console.WriteLine($"Error: if present, upload destination (-d) must be one of {UploadDestination.DryRun}, {UploadDestination.Development}, or {UploadDestination.Production}");
                return(1);
            }
            BookUpload.Destination = options.Dest;                // must be set before calling SetupErrorHandling() (or BloomParseClient constructor)

            // This task will be all the program does. We need to do enough setup so that
            // the upload code can work, then tear it down.
            Program.SetUpErrorHandling();
            try
            {
                using (var applicationContainer = new ApplicationContainer())
                {
                    Program.SetUpLocalization(applicationContainer);
                    LocalizationManager.SetUILanguage(Settings.Default.UserInterfaceLanguage, false);
                    var singleBookUploader = new BookUpload(new BloomParseClient(), ProjectContext.CreateBloomS3Client(),
                                                            applicationContainer.BookThumbNailer);
                    var uploader = new BulkUploader(singleBookUploader);


                    // Since Bloom is not a normal console app, when run from a command line, the new command prompt
                    // appears at once. The extra newlines here are attempting to separate this from our output.
                    switch (options.Dest)
                    {
                    case UploadDestination.DryRun:
                        Console.WriteLine($"\nThe following actions would happen if you set destination to '{(BookUpload.UseSandboxByDefault ? UploadDestination.Development : UploadDestination.Production)}'.");
                        break;

                    case UploadDestination.Development:
                        Console.WriteLine("\nThe upload will go to dev.bloomlibrary.org.");
                        break;

                    case UploadDestination.Production:
                        Console.WriteLine("\nThe upload will go to bloomlibrary.org.");
                        break;
                    }
                    Console.WriteLine("\nStarting upload...");
                    uploader.BulkUpload(applicationContainer, options);
                    Console.WriteLine(("\nBulk upload complete.\n"));
                }
                return(0);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
                return(1);
            }
        }
 protected override IDiagnostics GetDiagnostics()
 {
     return(ApplicationContainer.Resolve <IDiagnostics>());
 }
        private async Task StopApplication()
        {
            // NOTE: Service still can recieve and process requests here, so take care about it if you add logic here.

            await ApplicationContainer.Resolve <IShutdownManager>().StopAsync();
        }
 protected override INancyEngine GetEngineInternal()
 {
     return(ApplicationContainer.Resolve <INancyEngine>());
 }
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.Converters.Add(new StringEnumConverter());
                    options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration(ApiVersion, ApiName);
                });

                var settingsManager = Configuration.LoadSettings <AppSettings>(options =>
                {
                    options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString);
                    options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName);
                    options.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}";
                });

                var appSettings = settingsManager.CurrentValue;

                if (appSettings.MonitoringServiceClient != null)
                {
                    _monitoringServiceUrl = appSettings.MonitoringServiceClient.MonitoringServiceUrl;
                }

                services.AddLykkeLogging(
                    settingsManager.ConnectionString(s => s.BlockchainHeartbeatJob.Db.LogsConnString),
                    "BlockchainHeartbeat",
                    appSettings.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.SlackNotifications.AzureQueue.QueueName,
                    p => {
                    p.AddAdditionalSlackChannel("CommonBlockChainIntegration");
                    p.AddAdditionalSlackChannel("CommonBlockChainIntegrationImportantMessages", x =>
                    {
                        x.MinLogLevel = Microsoft.Extensions.Logging.LogLevel.Warning;
                    });
                });

                var builder = new ContainerBuilder();
                builder.Populate(services);


                var modules = new IModule[]
                {
                    new JobModule(appSettings.BlockchainHeartbeatJob, appSettings.AssetsServiceClient),
                    new CqrsModule(appSettings.BlockchainHeartbeatJob.Cqrs),
                    new RepositoriesModule(settingsManager.Nested(p => p.BlockchainHeartbeatJob.Db))
                };

                foreach (var module in modules)
                {
                    builder.RegisterModule(module);
                }

                ApplicationContainer = builder.Build();

                var logFactory = ApplicationContainer.Resolve <ILogFactory>();
                _log            = logFactory.CreateLog(this);
                _healthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                if (_log == null)
                {
                    Console.WriteLine(ex);
                }
                else
                {
                    _log.Critical(ex);
                }
                throw;
            }
        }
 protected override IEnumerable <IRegistrations> GetRegistrationTasks()
 {
     return(ApplicationContainer.Resolve <IEnumerable <IRegistrations> >());
 }
 public AuthorizedKeysFile(ApplicationContainer container, string filename = null)
 {
     this.Container = container;
     this.Filename = string.IsNullOrEmpty(filename) ? Path.Combine(this.Container.ContainerDir, ".ssh", "authorized_keys") : filename;
 }
 //
 // Summary:
 //     Registers an Nancy.Configuration.INancyEnvironment instance in the container.
 //
 // Parameters:
 //   container:
 //     The container to register into.
 //
 //   environment:
 //     The Nancy.Configuration.INancyEnvironment instance to register.
 protected override void RegisterNancyEnvironment(TinyIoCContainer container, INancyEnvironment environment)
 {
     ApplicationContainer.Register <INancyEnvironment>(environment);
 }
 public ApplicationState(ApplicationContainer container)
 {
     this.container = container;
     this.Uuid = container.Uuid;
     this.stateFile = Path.Combine(this.container.ContainerDir, "app-root", "runtime", ".state");
 }
Beispiel #34
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddMvc()
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.Converters.Add(new StringEnumConverter());
                    options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                });

                services.AddSwaggerGen(options =>
                {
                    options.DefaultLykkeConfiguration(ApiVersion, ApiName);
                });

                var settingsManager = Configuration.LoadSettings <AppSettings>(options =>
                {
                    options.SetConnString(x => x.SlackNotifications.AzureQueue.ConnectionString);
                    options.SetQueueName(x => x.SlackNotifications.AzureQueue.QueueName);
                    options.SenderName = $"{AppEnvironment.Name} {AppEnvironment.Version}";
                });

                var appSettings = settingsManager.CurrentValue;

                if (appSettings.MonitoringServiceClient != null)
                {
                    _monitoringServiceUrl = appSettings.MonitoringServiceClient.MonitoringServiceUrl;
                }

                services.AddLykkeLogging(
                    settingsManager.ConnectionString(s => s.OrderbooksBridgeJob.Db.LogsConnString),
                    "OrderbooksBridgeJobLog",
                    appSettings.SlackNotifications.AzureQueue.ConnectionString,
                    appSettings.SlackNotifications.AzureQueue.QueueName,
                    logging => {
                    logging.AddAdditionalSlackChannel("Bridges", options =>
                    {
                        options.MinLogLevel = LogLevel.Warning;
                        options.SpamGuard.DisableGuarding();
                        options.IncludeHealthNotifications();
                    });
                });

                var builder = new ContainerBuilder();
                builder.Populate(services);

                builder.RegisterModule(new JobModule(appSettings.OrderbooksBridgeJob, settingsManager));

                ApplicationContainer = builder.Build();

                var logFactory = ApplicationContainer.Resolve <ILogFactory>();
                _log            = logFactory.CreateLog(this);
                _healthNotifier = ApplicationContainer.Resolve <IHealthNotifier>();

                return(new AutofacServiceProvider(ApplicationContainer));
            }
            catch (Exception ex)
            {
                if (_log == null)
                {
                    Console.WriteLine(ex);
                }
                else
                {
                    _log.Critical(ex);
                }
                throw;
            }
        }
Beispiel #35
0
        /// <summary>
        /// Handles the recursion through directories: if a folder looks like a Bloom book upload it; otherwise, try its children.
        /// Invisible folders like .hg are ignored.
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="dlg"></param>
        /// <param name="container"></param>
        /// <param name="context"></param>
        private void UploadInternal(string folder, BulkUploadProgressDlg dlg, ApplicationContainer container, ref ProjectContext context)
        {
            if (Path.GetFileName(folder).StartsWith("."))
                return; // secret folder, probably .hg

            if (Directory.GetFiles(folder, "*.htm").Count() == 1)
            {
                // Exactly one htm file, assume this is a bloom book folder.
                dlg.Progress.WriteMessage("Starting to upload " + folder);

                // Make sure the files we want to upload are up to date.
                // Unfortunately this requires making a book object, which requires making a ProjectContext, which must be created with the
                // proper parent book collection if possible.
                var parent = Path.GetDirectoryName(folder);
                var collectionPath = Directory.GetFiles(parent, "*.bloomCollection").FirstOrDefault();
                if (collectionPath == null && context == null)
                {
                    collectionPath = Settings.Default.MruProjects.Latest;
                }
                if (context == null || context.SettingsPath != collectionPath)
                {
                    if (context != null)
                        context.Dispose();
                    // optimise: creating a context seems to be quite expensive. Probably the only thing we need to change is
                    // the collection. If we could update that in place...despite autofac being told it has lifetime scope...we would save some time.
                    // Note however that it's not good enough to just store it in the project context. The one that is actually in
                    // the autofac object (_scope in the ProjectContext) is used by autofac to create various objects, in particular, books.
                    context = container.CreateProjectContext(collectionPath);
                }
                var server = context.BookServer;
                var book = server.GetBookFromBookInfo(new BookInfo(folder, true));
                book.BringBookUpToDate(new NullProgress());

                // Assemble the various arguments needed to make the objects normally involved in an upload.
                // We leave some constructor arguments not actually needed for this purpose null.
                var bookSelection = new BookSelection();
                bookSelection.SelectBook(book);
                var currentEditableCollectionSelection = new CurrentEditableCollectionSelection();
                if (collectionPath != null)
                {
                    var collection = new BookCollection(collectionPath, BookCollection.CollectionType.SourceCollection,
                        bookSelection);
                    currentEditableCollectionSelection.SelectCollection(collection);
                }
                var publishModel = new PublishModel(bookSelection, new PdfMaker(), currentEditableCollectionSelection, null, server, _thumbnailer, null);
                publishModel.PageLayout = book.GetLayout();
                var view = new PublishView(publishModel, new SelectedTabChangedEvent(), new LocalizationChangedEvent(), this, null, null);
                string dummy;
                // Normally we let the user choose which languages to upload. Here, just the ones that have complete information.
                var langDict = book.AllLanguages;
                var languagesToUpload = langDict.Keys.Where(l => langDict[l]).ToArray();
                if (languagesToUpload.Any())
                    FullUpload(book, dlg.Progress, view, languagesToUpload, out dummy, dlg);
                return;
            }
            foreach (var sub in Directory.GetDirectories(folder))
                UploadInternal(sub, dlg, container, ref context);
        }
 protected override IEnumerable <IApplicationRegistrations> GetApplicationRegistrationTasks()
 {
     return
         (ApplicationContainer.BuildAll(typeof(IApplicationRegistrations)) as
          IEnumerable <IApplicationRegistrations>);
 }