Пример #1
0
        private CurrentHostContext(IHostConfig configuration, ContextSettings settings)
        {
            Audit      = configuration.Runtime.Audit;
            Config     = configuration;
            UserTokens = new List <string>();

            var logger      = LogFactory.CreateInstance(configuration.Runtime.LogInfo);
            var commandArgs = new CommandArgs(configuration.Runtime.Parameters);
            var cache       = CacheFactory.Create(configuration.Caching);

            cache.ItemRemoved += (sender, args) =>
            {
                Log.Debug("Item removed from cache: " + args.CacheKey + " Reason : " + args.RemoveReason);
                if (args.Value is AuthenticationOutput)
                {
                    // User has been removed from cache. Login expired
                    UserTokens.Remove(args.CacheKey);
                }
            };

            CurrentContext.CreateDefault(logger, commandArgs, cache);

            //override the passwords if encrypted
            if (configuration.Certificate.Encryption != null)
            {
                var certificate = configuration.Certificate.Encryption.GetX509Certificate();
                if (certificate != null)
                {
                    DecryptPasswords(configuration, certificate);
                }
            }

            CommandFactory = settings.CommandFactory;
            Provider       = GetDatabaseProviderInstance(configuration);
        }
Пример #2
0
        internal static HostContext CreateFrom(string configFilePath, ContextSettings settings)
        {
            if (string.IsNullOrEmpty(configFilePath))
            {
                throw new ArgumentNullException("configFilePath");
            }

            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            // No change in config file, so dont need to re load it
            if (!string.IsNullOrEmpty(_configFilePath) && _configFilePath.Equals(configFilePath))
            {
                return(_current);
            }

            if (!File.Exists(configFilePath))
            {
                throw new ConfigurationErrorsException("Could not find config file: " + configFilePath);
            }

            _config         = File.ReadAllText(configFilePath).FromJsonToObject <HostConfig>();
            _configFilePath = configFilePath;
            _current        = new HostContext(_config, settings);
            return(_current);
        }
Пример #3
0
        internal static AzureContext CreateFrom(Stream configStream, ContextSettings settings)
        {
            if (configStream == null)
                throw new ArgumentNullException("configStream");

            if (settings == null)
                throw new ArgumentNullException("settings");

            _config = configStream.ReadToEnd().FromJsonToObject<HostConfig>();
            _current = new AzureContext(_config, settings);
            return _current;
        }
Пример #4
0
        public static IContext CreateDefault(IHostConfig configuration, ContextSettings settings)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            return(_defaultContext ?? (_defaultContext = new CurrentHostContext(configuration, settings)));
        }
Пример #5
0
        internal static AzureContext CreateFrom(string configFilePath, ContextSettings settings)
        {
            if (string.IsNullOrEmpty(configFilePath))
                throw new ArgumentNullException("configFilePath");

            if (settings == null)
                throw new ArgumentNullException("settings");

            if (!File.Exists(configFilePath))
                throw new ConfigurationErrorsException("Could not find config file: " + configFilePath);

            _config = File.ReadAllText(configFilePath).FromJsonToObject<HostConfig>();
            _current = new AzureContext(_config, settings);
            return _current;
        }
Пример #6
0
        internal static HostContext CreateFrom(string configFilePath, ContextSettings settings)
        {
            if (string.IsNullOrEmpty(configFilePath))
                throw new ArgumentNullException("configFilePath");

            if (settings == null)
                throw new ArgumentNullException("settings");

            // No change in config file, so dont need to re load it
            if (!string.IsNullOrEmpty(_configFilePath) && _configFilePath.Equals(configFilePath))
                return _current;

            if (!File.Exists(configFilePath))
                throw new ConfigurationErrorsException("Could not find config file: " + configFilePath);

            _config = File.ReadAllText(configFilePath).FromJsonToObject<HostConfig>();
            _configFilePath = configFilePath;
            _current = new HostContext(_config, settings);
            return _current;
        }
Пример #7
0
        internal static void Main(string[] args)
        {
            IArguments argsDictionary = new CommandArgs(args);
            var backgroundService = new KonfDBH(argsDictionary);
            var services = new ServiceBase[] {backgroundService};

            if (argsDictionary.ContainsKey("install"))
            {
                ManagedInstallerClass.InstallHelper(new[]
                {
                    Assembly.GetExecutingAssembly().Location
                });
            }
            else if (argsDictionary.ContainsKey("uninstall"))
            {
                ManagedInstallerClass.InstallHelper(new[]
                {
                    "/u",
                    Assembly.GetExecutingAssembly().Location
                });
            }
            else if (argsDictionary.ContainsKey("console")) // console mode
            {
                #region Console

                var contextSettings = new ContextSettings
                {
                    CommandFactory = new CommandFactory()
                };
                HostContext.CreateFrom(argsDictionary.GetValue("configPath", "konfdb.json"), contextSettings);
                CurrentHostContext.Default.Log.Debug("Running in Console Mode");
                Console.SetWindowPosition(0, 0);
                Console.BackgroundColor = ConsoleColor.DarkGray;
                Console.ForegroundColor = ConsoleColor.White;
                Console.Clear();

                services.RunService();

                var shutdown = new ManualResetEvent(false);
                var thread = new Thread(() =>
                {
                    while (!shutdown.WaitOne(0))
                    {
                        Thread.Sleep(1000);
                    }
                });
                thread.Start();

                bool exitLoop = false;
                var commandService = backgroundService.ServiceFacade;
                string internalSessionId = Guid.NewGuid().ToString();
                while (!exitLoop)
                {
                    Console.Write(">");
                    string line = Console.ReadLine();

                    if (string.IsNullOrEmpty(line)) continue;

                    var commandOutput = commandService.ExecuteCommand(new ServiceRequestContext
                    {
                        Command = line,
                        Token = backgroundService.AuthenticationToken,
                        SessionId = internalSessionId
                    });
                    if (commandOutput == null) continue;

                    if (commandOutput.MessageType == CommandOutput.DisplayMessageType.Message)
                        Console.WriteLine(commandOutput.Data != null
                            ? commandOutput.Data.ToJson()
                            : commandOutput.DisplayMessage);
                    else if (commandOutput.MessageType == CommandOutput.DisplayMessageType.Error)
                        Console.WriteLine(commandOutput.DisplayMessage);

                    if (commandOutput.PostAction == CommandOutput.PostCommandAction.ExitApplication)
                    {
                        shutdown.Set();
                        thread.Join();

                        services.StopService();

                        CurrentHostContext.Default.Log.Info("Exiting...");

                        Thread.Sleep(500);

                        exitLoop = true;
                    }
                }

                #endregion
            }
            else
            {
                ServiceBase.Run(services);
            }
        }
Пример #8
0
 private AzureContext(IHostConfig configuration, ContextSettings settings)
 {
     CurrentHostContext.CreateDefault(configuration, settings);
 }
Пример #9
0
 internal static AzureContext CreateFrom(IHostConfig config, ContextSettings settings)
 {
     _config = config;
     _current = new AzureContext(_config, settings);
     return _current;
 }
Пример #10
0
 private HostContext(IHostConfig configuration, ContextSettings settings)
 {
     CurrentHostContext.CreateDefault(configuration, settings);
 }
Пример #11
0
        protected override void OnStart(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            var contextSettings = new ContextSettings
            {
                CommandFactory = new CommandFactory()
            };

            HostContext.CreateFrom(_arguments.GetValue("configPath", "konfdb.json"), contextSettings);
            CurrentHostContext.Default.Log.Info("Agent Started: DataManagement");

            #region Run Command Service

            ServiceFacade = new ServiceCore();
            string internalSessionId = Guid.NewGuid().ToString();
            // Ensure that the super user admin exists
            ServiceFacade.ExecuteCommand(new ServiceRequestContext
            {
                Command = String.Format("NewUser /name:{0} /pwd:{1} /cpwd:{1} /role:admin /silent",
                    CurrentHostContext.Default.Config.Runtime.SuperUser.Username,
                    CurrentHostContext.Default.Config.Runtime.SuperUser.Password),
                SessionId = internalSessionId
            });

            // Ensure that the super user readonly exists
            ServiceFacade.ExecuteCommand(new ServiceRequestContext
            {
                Command = String.Format("NewUser /name:{0}_ro /pwd:{1} /cpwd:{1} /role:readonly /silent",
                    CurrentHostContext.Default.Config.Runtime.SuperUser.Username,
                    CurrentHostContext.Default.Config.Runtime.SuperUser.Password),
                SessionId = internalSessionId
            });

            var serviceConfig = CurrentHostContext.Default.Config.Runtime.Server;
            _serviceHostNative = new WcfService<ICommandService<object>, NativeCommandService>("localhost",
                "CommandService");
            _serviceHostJson = new WcfService<ICommandService<string>, JsonCommandService>("localhost", "CommandService");

            for (int i = 0; i < serviceConfig.Count; i++)
            {
                var configuration = new BindingConfiguration
                {
                    Port = serviceConfig[i].Port.ToString(CultureInfo.InvariantCulture),
                    ServiceType = serviceConfig[i].GetWcfServiceType()
                };

                var binding = BindingFactory.Create(configuration);
                if (binding.DataTypes.IsSet(DataTypeSupport.Native))
                {
                    _serviceHostNative.AddBinding(binding);
                }
                else if (binding.DataTypes.IsSet(DataTypeSupport.Json))
                {
                    _serviceHostJson.AddBinding(binding);
                }
            }

            if (CurrentHostContext.Default.Config.Runtime.ServiceSecurity == ServiceSecurityMode.BasicSSL)
            {
                var serviceSecurity = new ServiceSecurity
                {
                    CertificateConfiguration = CurrentHostContext.Default.Config.Certificate.Default,
                    SecurityMode = CurrentHostContext.Default.Config.Runtime.ServiceSecurity
                };

                _serviceHostJson.SetSecured(serviceSecurity);
                _serviceHostNative.SetSecured(serviceSecurity);
            }

            _serviceHostNative.Host();
            _serviceHostJson.Host();

            var authOutput = ServiceFacade.ExecuteCommand(new ServiceRequestContext
            {
                Command = String.Format("UserAuth /name:{0} /pwd:{1}",
                    CurrentHostContext.Default.Config.Runtime.SuperUser.Username,
                    CurrentHostContext.Default.Config.Runtime.SuperUser.Password),
                SessionId = internalSessionId
            });

            var authenticationOutput = authOutput.Data as AuthenticationOutput;
            if (authenticationOutput == null)
            {
                throw new InvalidOperationException(
                    "Could not authenticate server user: "******"GetSettings",
                    SessionId = internalSessionId
                });
            if (settingsOutput != null && settingsOutput.Data != null)
            {
                var settings = (Dictionary<string, string>) settingsOutput.Data;
                foreach (var setting in settings)
                {
                    CurrentHostContext.Default.ApplicationParams.Add(setting.Key, setting.Value);
                }
            }

            //AppContext.Current.Log.Info("Agent Started: " + _serviceHostNative);
            //AppContext.Current.Log.Info("Agent Started: " + _serviceHostJson);

            #endregion

            _thread = new Thread(RunInBackground)
            {
                Name = "ShellService",
                IsBackground = true
            };

            _shutdownEvent = new ManualResetEvent(false);
            _thread.Start();
        }
Пример #12
0
        private CurrentHostContext(IHostConfig configuration, ContextSettings settings)
        {
            Audit = configuration.Runtime.Audit;
            Config = configuration;
            UserTokens = new List<string>();

            var logger = LogFactory.CreateInstance(configuration.Runtime.LogInfo);
            var commandArgs = new CommandArgs(configuration.Runtime.Parameters);
            var cache = CacheFactory.Create(configuration.Caching);
            cache.ItemRemoved += (sender, args) =>
            {
                Log.Debug("Item removed from cache: " + args.CacheKey + " Reason : " + args.RemoveReason);
                if (args.Value is AuthenticationOutput)
                {
                    // User has been removed from cache. Login expired
                    UserTokens.Remove(args.CacheKey);
                }
            };

            CurrentContext.CreateDefault(logger, commandArgs, cache);

            //override the passwords if encrypted
            if (configuration.Certificate.Encryption != null)
            {
                var certificate = configuration.Certificate.Encryption.GetX509Certificate();
                if (certificate != null)
                {
                    DecryptPasswords(configuration, certificate);
                }
            }

            CommandFactory = settings.CommandFactory;
            Provider = GetDatabaseProviderInstance(configuration);
        }
Пример #13
0
        public static IContext CreateDefault(IHostConfig configuration, ContextSettings settings)
        {
            if (configuration == null)
                throw new ArgumentNullException("configuration");

            if (settings == null)
                throw new ArgumentNullException("settings");

            return _defaultContext ?? (_defaultContext = new CurrentHostContext(configuration, settings));
        }
Пример #14
0
        public override bool OnStart()
        {
            try
            {
                // Set the maximum number of concurrent connections
                ServicePointManager.DefaultConnectionLimit = 12;

                // For information on handling configuration changes
                // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

                var contextSettings = new ContextSettings
                {
                    CommandFactory = new AzureCommandFactory(AppType.Server)
                };

                Trace.TraceInformation("Command Factory Initialized");
                var configMode = RoleEnvironment.GetConfigurationSettingValue("konfdb.configuration.mode");
                if (configMode.Equals("azure", StringComparison.InvariantCultureIgnoreCase))
                {
                    Trace.TraceInformation("mode: Azure");
                    var config = LoadConfigurationFromAzureUI();
                    AzureContext.CreateFrom(config, contextSettings);
                }
                else
                {
                    Trace.TraceInformation("mode: File");
                    AzureContext.CreateFrom("konfdb.json", contextSettings);
                }

                CurrentContext.Default.Log.Info("KonfDBAH Started Successfully!");

                return base.OnStart();
            }
            catch (Exception exception)
            {
                Trace.TraceError("OnStart Exception: " + exception);
            }

            return false;
        }