Ejemplo n.º 1
0
        public JobRunner([Import(AllowDefault = true)] Settings settings, [ImportMany] IEnumerable<WorkerJob> jobs)
        {
            _settings = settings ?? new Settings();
            Jobs = jobs.ToDictionary(j => j.GetType().Name, StringComparer.OrdinalIgnoreCase);
            _subject.OnNext(Unit.Default);

            foreach (var job in Jobs.Values)
            {
                try
                {
                    job.Initialize(_settings);
                }
                catch (Exception ex)
                {
                    _logger.ErrorException(String.Format("{2} Initializing '{0}': {1}", job.GetType().Name, ex.Message, ex.GetType().Name), ex);
                }
            }
        }
Ejemplo n.º 2
0
        public WorkerRole(Settings settings)
        {
            string logDir = Path.Combine(Environment.CurrentDirectory, "Logs");

            try
            {
                // Configure NLog
                LoggingConfiguration config = new LoggingConfiguration();

                // Console Target
                var consoleTarget = new SnazzyConsoleTarget();
                config.AddTarget("console", consoleTarget);
                consoleTarget.Layout = "[${logger:shortName=true}] ${message}";

                // Get the logs resource if it exists and use it as the log dir
                try
                {
                    if (RoleEnvironment.IsAvailable)
                    {
                        LocalResource logsResource = RoleEnvironment.GetLocalResource("Logs");
                        logDir = logsResource.RootPath;
                    }
                }
                catch (Exception)
                {
                    // Just use basedir.
                }

                // File Target
                FileTarget jobLogTarget = new FileTarget()
                {
                    FileName = Path.Combine(logDir, "Jobs", "${logger:shortName=true}.log.json"),
                    ArchiveFileName = Path.Combine(logDir, "Jobs", "${logger:shortName=true}.${date:yyyy-MM-dd}.log")
                };
                ConfigureFileTarget(jobLogTarget);
                config.AddTarget("file-job", jobLogTarget);
                FileTarget hostTarget = new FileTarget()
                {
                    FileName = Path.Combine(logDir, "Host", "Host.log.json"),
                    ArchiveFileName = Path.Combine(logDir, "Host", "Host.${date:yyyy-MM-dd}.log")
                };
                ConfigureFileTarget(hostTarget);
                config.AddTarget("file-host", hostTarget);
                FileTarget globalTarget = new FileTarget()
                {
                    FileName = Path.Combine(logDir, "Master", "Master.log.json")
                };
                ConfigureFileTarget(globalTarget);
                globalTarget.MaxArchiveFiles = 1;
                globalTarget.ArchiveAboveSize = 1024 * 1024;
                globalTarget.EnableFileDelete = true;
                globalTarget.DeleteOldFileOnStartup = true;
                globalTarget.AutoFlush = true;
                config.AddTarget("file-master", globalTarget);

                TraceTarget traceTarget = new TraceTarget()
                {
                    Layout = "[${logger:shortName=true}][${date:yyyy-MM-ddTHHmmss}]${message}"
                };
                config.AddTarget("trace", traceTarget);

                LoggingRule allMessagesToConsole = new LoggingRule("*", NLog.LogLevel.Trace, consoleTarget);
                config.LoggingRules.Add(allMessagesToConsole);
                LoggingRule allMessagesToGlobal = new LoggingRule("*", NLog.LogLevel.Debug, globalTarget);
                config.LoggingRules.Add(allMessagesToGlobal);
                LoggingRule allMessagesToTrace = new LoggingRule("*", NLog.LogLevel.Debug, traceTarget);
                config.LoggingRules.Add(allMessagesToTrace);

                // All other rules transfer all kinds of log messages EXCEPT Trace.
                LoggingRule hostToFile = new LoggingRule("JobRunner", NLog.LogLevel.Debug, hostTarget);
                config.LoggingRules.Add(hostToFile);

                LoggingRule roleToFile = new LoggingRule("WorkerRole", NLog.LogLevel.Debug, hostTarget);
                config.LoggingRules.Add(roleToFile);

                LoggingRule jobLogs = new LoggingRule("Job.*", NLog.LogLevel.Debug, jobLogTarget);
                config.LoggingRules.Add(jobLogs);

                LogManager.Configuration = config;

                _logger = LogManager.GetLogger("WorkerRole");
            }
            catch (Exception ex)
            {
                File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "FatalError.txt"), ex.ToString());
            }

            _logger.Info("Logging Enabled to {0}", logDir);

            try
            {
                if (RoleEnvironment.IsAvailable)
                {
                    ConfigureAzureDiagnostics(logDir);
                }
                else
                {
                    _logger.Info("Skipping Azure Diagnostics, we aren't in Azure");
                }
            }
            catch (Exception ex)
            {
                _logger.InfoException("Skipping Azure Diagnostics, we got an exception trying to check if we are in Azure", ex);
            }

            try
            {
                _runner = LoadJobRunner(settings);
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Error loading Job Runner", ex);
            }
        }
Ejemplo n.º 3
0
        private static JobRunner LoadJobRunner(Settings settings)
        {
            AssemblyCatalog catalog = new AssemblyCatalog(typeof(WorkerRole).Assembly);
            var container = new CompositionContainer(catalog);

            // Load settings
            settings = settings ?? new Settings();
            container.ComposeExportedValue(settings);

            // Get the job runner
            return container.GetExportedValue<JobRunner>();
        }
Ejemplo n.º 4
0
        public static void Execute(string jobName, bool continuous, IDictionary<string, string> overrideSettings)
        {
            // Create the settings manager
            var settings = new Settings(overrideSettings);
            var worker = new WorkerRole(settings);

            // See which mode we're in
            if (String.IsNullOrWhiteSpace(jobName))
            {
                // Run ALL THE JOBS!
                worker.OnStart();
                worker.Run();
                Console.WriteLine("Worker is running. Press ENTER to stop");
                Console.ReadLine();
                worker.Stop();
                worker.OnStop();
            }
            else
            {
                // Run JUST ONE JOB!
                if (!continuous)
                {
                    worker.RunSingleJob(jobName);
                }
                else
                {
                    worker.RunSingleJobContinuously(jobName);
                }
            }
        }