Ejemplo n.º 1
0
        /// <summary>
        /// Creating actor system for test
        /// </summary>
        /// <param name="output">
        /// Xunit output
        /// </param>
        /// <returns>
        /// actor system for test
        /// </returns>
        private static TestDescription CreateTestActorSystem(ITestOutputHelper output)
        {
            var loggerConfig =
                new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.TextWriter(new XunitOutputWriter(output));

            Serilog.Log.Logger = loggerConfig.CreateLogger();

            var containerBuilder = new ContainerBuilder();

            var configurator = new TConfigurator();

            foreach (var pluginInstaller in configurator.GetPluginInstallers())
            {
                pluginInstaller.Install(containerBuilder);
                containerBuilder.RegisterInstance(pluginInstaller).As <BaseInstaller>();
            }

            var config = configurator.GetAkkaConfig(containerBuilder);

            BaseInstaller.RunComponentRegistration(containerBuilder, config);

            var testActorSystem = ActorSystem.Create("test", config);

            containerBuilder.RegisterInstance(testActorSystem).As <ActorSystem>();
            containerBuilder.RegisterInstance(testActorSystem.Settings.Config).As <Config>();

            return(new TestDescription
            {
                System = testActorSystem,
                ContainerBuilder = containerBuilder,
                Configurator = configurator
            });
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Gets the akka system config
        /// </summary>
        /// <param name="containerBuilder">
        /// The container builder
        /// </param>
        /// <returns>
        /// The config
        /// </returns>
        public virtual Config GetAkkaConfig(ContainerBuilder containerBuilder)
        {
            var config = ConfigurationFactory.ParseString(
                @"
                akka.actor.serialize-messages = on
                akka.actor.serialize-creators = off
            ");

            return(BaseInstaller.GetStackedConfig(containerBuilder, config));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Performs the dependencies initialization
        /// </summary>
        /// <param name="config">The seeder configuration</param>
        /// <returns>The windsor container</returns>
        private static ContainerBuilder InitializeDependencies(Config config)
        {
            var container = new ContainerBuilder();

            container.RegisterInstallers();
            config = BaseInstaller.GetStackedConfig(container, config);
            container.RegisterInstance(config).As <Config>();
            BaseInstaller.RunComponentRegistration(container, config);
            return(container);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="HackedBaseActorTest"/> class.
        /// </summary>
        /// <param name="description">
        /// The description.
        /// </param>
        protected HackedBaseActorTest(TestDescription description) : base(description.System)
        {
            var containerBuilder = description.ContainerBuilder;

            containerBuilder.RegisterInstance(this.TestActor).As <IActorRef>().Named("testActor", typeof(IActorRef));
            this.Container = containerBuilder.Build();
            this.Sys.AddDependencyResolver(new AutoFacDependencyResolver(this.Container, this.Sys));

            if (description.Configurator.RunPostStart)
            {
                BaseInstaller.RunPostStart(containerBuilder, this.Container);
            }
        }
Ejemplo n.º 5
0
    public override void InstallBindings()
    {
        BaseInstaller.Install(Container);

        //SignalBusInstaller.Install(Container);

        //Container.Bind<SignalManager>().AsSingle();
        //Container.Bind<SaveLoadScript>().AsSingle();
        //Container.Bind<SoundController>().AsSingle();
        //Container.Bind<TimeController>().AsSingle();
        //Container.Bind<ScoreController>().AsSingle();
        //Container.BindFactory<PlayerController, PlayerController.PlayerFabrik>()
        //    .FromComponentInNewPrefab(_gameConfig.PlayerPrefab).WithGameObjectName("Player");
        //Container.BindFactory<float, float, float, CollumnsController, CollumnsController.Factory>()
        //    .FromComponentInNewPrefab(_gameConfig.WallPrefab).WithGameObjectName("wall");
        //Container.DeclareSignal<GameEndSignal>();
        //Container.DeclareSignal<AudioChange>();
        //Container.DeclareSignal<ScoreSignal>();
        //Container.DeclareSignal<ResumeSignal>();
    }
        public async Task SchemaDescriptionTest()
        {
            var checkAttributeArguments = new[]
            {
                ApiField.Scalar(
                    "attribute",
                    EnScalarType.String,
                    description: "attribute to check")
            };

            var objectFields = new[]
            {
                ApiField.Scalar(
                    "uid",
                    EnScalarType.Guid,
                    description: "The object unique identifier"),
                ApiField.Scalar("name", EnScalarType.String, description: "The object name"),
                ApiField.Scalar(
                    "attributes",
                    EnScalarType.String,
                    EnFieldFlags.IsArray,
                    description: "The object attributes"),
                ApiField.Scalar(
                    "checkAttribute",
                    EnScalarType.Boolean,
                    arguments: checkAttributeArguments,
                    description: "checks the attribute")
            };

            var objectType = new ApiObjectType("object", objectFields)
            {
                Description = "Some abstract object"
            };
            var apiField = objectType.CreateField(
                "new",
                description: "The new object data");

            var mutations = new[]
            {
                ApiMutation.CreateFromField(
                    ApiField.Object(
                        "objects_create",
                        "object",
                        arguments: new[] { apiField },
                        description: "creates a new object"),
                    ApiMutation.EnType.ConnectionCreate,
                    new List <ApiRequest>())
            };

            var api = new ApiDescription(
                "TestApi",
                "0.0.0.1",
                new[] { objectType },
                new[] { objectType.CreateField("objects", EnFieldFlags.IsConnection, "The objects dataset") },
                mutations)
            {
                Description = "The test api"
            };

            var provider = new MoqProvider {
                Description = api
            };
            var schema = SchemaGenerator.Generate(new List <ApiProvider> {
                provider
            });

            var errors = SchemaGenerator.CheckSchema(schema).Select(e => $"Schema type error: {e}")
                         .Union(SchemaGenerator.CheckSchemaIntrospection(schema))
                         .Select(e => $"Schema introspection error: {e}");

            var hasErrors = false;

            foreach (var error in errors)
            {
                hasErrors = true;
                this.output.WriteLine(error);
            }

            using (var printer = new SchemaPrinter(schema))
            {
                var description = printer.Print();
                this.output.WriteLine("-------- Schema -----------");
                this.output.WriteLine(description);
                Assert.False(string.IsNullOrWhiteSpace(description));
            }

            Assert.False(hasErrors);
            var query = BaseInstaller.ReadTextResource(
                this.GetType().GetTypeInfo().Assembly,
                "KlusterKite.Web.Tests.GraphQL.Resources.IntrospectionQuery.txt");

            var result = await new DocumentExecuter().ExecuteAsync(
                r =>
            {
                r.Schema = schema;

                r.Query = query;
            }).ConfigureAwait(true);
            var response = new DocumentWriter(true).Write(result);

            this.output.WriteLine(response);

            var expectedResponse = BaseInstaller.ReadTextResource(
                this.GetType().GetTypeInfo().Assembly,
                "KlusterKite.Web.Tests.GraphQL.Resources.SchemaDescriptionTestSnapshot.txt");

            Assert.Equal(CleanResponse(expectedResponse), CleanResponse(response));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Service main entry point
        /// </summary>
        /// <param name="args">
        /// Startup parameters
        /// </param>
        public static void Main(string[] args)
        {
            // preset logger
            var loggerConfig = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.ColoredConsole();
            var logger       = loggerConfig.CreateLogger();

            Log.Logger = logger;

            var arguments      = new Docopt().Apply(CommandUsage, args, exit: true);
            var configurations = new List <string>();

            ValueObject config;

            if (arguments.TryGetValue("--config", out config) && config != null)
            {
                configurations.Add(config.ToString());
                Console.WriteLine($@"Will use config from {config}");
            }

            Container = new ContainerBuilder();
#if APPDOMAIN
            AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
            {
                Log.Logger.Error(
                    eventArgs.ExceptionObject as Exception,
                    "{Type}: Unhandled domain exception {ExceptionMessage} from {SenderType}, terminating: {IsTerminating}\n{StackTrace}",
                    "System",
                    (eventArgs.ExceptionObject as Exception)?.Message,
                    sender?.GetType().Name ?? "unknown",
                    eventArgs.IsTerminating,
                    (eventArgs.ExceptionObject as Exception)?.StackTrace);
            };
#endif
#if CORECLR
            // todo: Handle exception
#endif

            var container = Bootstrapper.ConfigureAndStart(Container, configurations.ToArray());
            var system    = container.Resolve <ActorSystem>();
            Log.Logger.Warning("{Type}: Started", "System");
            Console.CancelKeyPress += (sender, eventArgs) =>
            {
                Log.Logger.Warning("{Type}: Shutdown sequence initiated", "System");
                var cluster = Akka.Cluster.Cluster.Get(system);

                var timeout = TimeSpan.FromSeconds(10);
                if (cluster.IsTerminated || cluster.State.Members.Count == 0)
                {
                    system.Terminate().Wait(timeout);
                }
                else
                {
                    cluster.LeaveAsync().Wait(timeout);
                    system.Terminate().Wait(timeout);
                }

                Log.Logger.Warning("{Type}: Hard stopped", "System");
                eventArgs.Cancel = true;
            };

            system.StartNameSpaceActorsFromConfiguration();
            BaseInstaller.RunPostStart(Container, container);

            var waitedTask = new System.Threading.Tasks.TaskCompletionSource <bool>();
            system.WhenTerminated.ContinueWith(task => waitedTask.SetResult(true));
            waitedTask.Task.Wait();
            Log.Logger.Warning("{Type}: Stopped", "System");
        }
Ejemplo n.º 8
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     BaseInstaller.InstallServices(services, Configuration);
 }
Ejemplo n.º 9
0
        /// <summary>
        ///  Dependency injection configuration
        /// </summary>
        /// <param name="containerBuilder">Dependency injection container</param>
        /// <param name="configurations">
        /// Startup parameters
        /// </param>
        /// <returns>The DI container</returns>
        public static IContainer ConfigureAndStart(ContainerBuilder containerBuilder, string[] configurations)
        {
            Console.WriteLine(@"Starting bootstrapper");

            containerBuilder.RegisterInstallers();

            Console.WriteLine(@"Preparing config");
            var config = BaseInstaller.GetStackedConfig(containerBuilder, CreateTopLevelConfig(configurations));

            Log.Debug($"Cluster configuration: seed-nodes { string.Join(", ", config.GetStringList("akka.cluster.seed-nodes") ?? new List<string>())}");
            Log.Debug($"Cluster configuration: min-nr-of-members { config.GetInt("akka.cluster.min-nr-of-members")}");
            var roles = string.Join(", ", config.GetStringList("akka.cluster.roles") ?? new List <string>());

            Log.Debug($"Cluster configuration: roles { roles}");
            Log.Debug($"Cluster node hostname: { config.GetString("akka.remote.helios.tcp.hostname") }");
            var publicHostName = config.GetString("akka.remote.helios.tcp.public-hostname");

            if (!string.IsNullOrWhiteSpace(publicHostName))
            {
                Log.Debug($"Cluster node public hostname: { publicHostName }");
            }

            containerBuilder.RegisterInstance(config).As <Config>();
            BaseInstaller.RunComponentRegistration(containerBuilder, config);

            Console.WriteLine(@"Config created");

            // log configuration
            LogEventLevel level;

            if (!Enum.TryParse(config.GetString("KlusterKite.Log.minimumLevel"), true, out level))
            {
                level = LogEventLevel.Verbose;
            }

            var actorSystem = ActorSystem.Create("KlusterKite", config);

            containerBuilder.RegisterInstance(actorSystem).As <ActorSystem>();
            var container = containerBuilder.Build();

            var loggerConfig  = new LoggerConfiguration().MinimumLevel.Is(level);
            var configurators = container.Resolve <IEnumerable <ILoggerConfigurator> >().ToList();

            configurators.ForEach(c => Log.Information("Using log configurator {TypeName}", c.GetType().FullName));

            loggerConfig = configurators.Aggregate(
                loggerConfig,
                (current, loggerConfigurator) => loggerConfigurator.Configure(current, config));

            var hostName = string.IsNullOrWhiteSpace(publicHostName)
                               ? config.GetString("akka.remote.helios.tcp.hostname")
                               : publicHostName;

            loggerConfig = loggerConfig.Enrich.WithProperty("hostName", hostName);
            loggerConfig = loggerConfig.Enrich.WithProperty("roles", roles);

            var logger = loggerConfig.CreateLogger();

            Log.Logger = logger;

            // log configuration finished

            // performing pre-start checks
            BaseInstaller.RunPreCheck(containerBuilder, config);

            // starting Akka system
            Console.WriteLine(@"starting akka system");
            actorSystem.AddDependencyResolver(new AutoFacDependencyResolver(container, actorSystem));

            Console.WriteLine(@"Bootstrapper start finished");

            return(container);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Service main entry point
        /// </summary>
        public static void Main()
        {
            var builder = new ContainerBuilder();

            try
            {
                builder.RegisterInstallers();
            }
            catch (ReflectionTypeLoadException exception)
            {
                foreach (var loaderException in exception.LoaderExceptions)
                {
                    throw loaderException;
                }

                throw;
            }

            var providedConfiguration = File.ReadAllText("config.hocon");
            var config = BaseInstaller.GetStackedConfig(
                builder,
                ConfigurationFactory.ParseString(providedConfiguration));

            builder.RegisterInstance(config).As <Config>();
            BaseInstaller.RunComponentRegistration(builder, config);

            var migratorTypeNames = config.GetStringList("KlusterKite.NodeManager.Migrators");

            foreach (var typeName in migratorTypeNames.Where(t => !string.IsNullOrWhiteSpace(t)))
            {
                var type = Type.GetType(typeName, false);
                if (type == null)
                {
                    Errors.Add(
                        new MigrationLogRecord
                    {
                        Type             = EnMigrationLogRecordType.Error,
                        Message          = $"Migrator type {typeName} was not found",
                        MigratorTypeName = typeName
                    });
                    continue;
                }

                if (!type.GetTypeInfo().GetInterfaces().Contains(typeof(IMigrator)))
                {
                    Errors.Add(
                        new MigrationLogRecord
                    {
                        Type             = EnMigrationLogRecordType.Error,
                        Message          = $"Type {typeName} doesn't implement IMigrator",
                        MigratorTypeName = typeName
                    });
                    continue;
                }

                builder.RegisterType(type).As <IMigrator>();
            }

            var context = builder.Build();

            Console.WriteLine(ProcessHelper.EOF);

            MigrationCollector collector;

            using (var standardInput = Console.OpenStandardInput())
            {
                collector = new StreamReader(standardInput).Receive() as MigrationCollector;
            }

            if (collector == null)
            {
                throw new InvalidOperationException("Received object is not a MigrationCollector");
            }

            collector.Errors.AddRange(Errors);
            if (Errors.Count == 0)
            {
                collector.Execute(context);
            }

            Console.Out.Send(collector);
        }