Example #1
0
 void IStartupService.OnStarting(StartupContext context)
 {
     if (this.onStarting != null)
     {
         this.onStarting.Invoke(context);
     }
 }
Example #2
0
        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="context">启动上下文</param>
        private void StartService(StartupContext context)
        {
            if (this.startServices == null)
            {
                return;
            }

            if (context == null)
            {
                return;
            }

            this.startServices.Sort(this.StartServiceComparison);
            foreach (var service in this.startServices)
            {
                if (service == null)
                {
                    continue;
                }

                service.OnStarting(context);
            }

            foreach (var service in this.lastStartServices)
            {
                if (service == null)
                {
                    continue;
                }

                service.OnStarting(context);
            }
        }
Example #3
0
        public static void Main(string[] args)
        {
            try
            {
                var startupArgs = new StartupContext(args);
                try
                {
                    NzbDroneLogger.Register(startupArgs, false, true);
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("NLog Exception: " + ex.ToString());
                    throw;
                }
                Bootstrap.Start(startupArgs, new ConsoleAlerts());
            }
            catch (SocketException e)
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("");
                Logger.Fatal(e.Message + ". This can happen if another instance of Radarr is already running another application is using the same port (default: 7878) or the user has insufficient permissions");
                Exit(ExitCodes.RecoverableFailure);
            }
            catch (Exception e)
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("");
                Logger.Fatal(e, "EPIC FAIL!");
                Exit(ExitCodes.UnknownFailure);
            }

            Logger.Info("Exiting main.");

            Exit(ExitCodes.Normal);
        }
Example #4
0
        public override void ConfigureServices(StartupContext context, IServiceCollection services)
        {
            services.AddNybus(nybus =>
            {
                nybus.UseConfiguration(context.Configuration);

                nybus.UseRabbitMqBusEngine(rabbitMq =>
                {
                    rabbitMq.UseConfiguration();

                    rabbitMq.Configure(configuration => configuration.CommandQueueFactory = new StaticQueueFactory("NetCoreRabbitMqWindowsService"));
                });

                /* EVENTS */

                /* This will subscribe the event TestEvent to any IEventHandler<TestEvent> available */
                nybus.SubscribeToEvent <TestEvent>();

                /* This will subscribe the event TestEvent to an instance of TestEventHandler */
                // nybus.SubscribeToEvent<TestEvent, TestEventHandler>();

                /* This will subscribe the event TestEvent to the asynchronous delegate */
                // nybus.SubscribeToEvent<TestEvent>(async (dispatcher, eventContext) => { await DoSomethingAsync(); });

                /* This will subscribe the event TestEvent to the synchronous delegate */
                // nybus.SubscribeToEvent<TestEvent>((dispatcher, eventContext) => { DoSomething(); });


                /* COMMANDS */

                /* This will subscribe the command TestCommand to any ICommandHandler<TestCommand> available */
                nybus.SubscribeToCommand <TestCommand>();

                /* This will subscribe the command TestCommand to an instance of TestCommandHandler */
                // nybus.SubscribeToCommand<TestCommand, TestCommandHandler>();

                /* This will subscribe the command TestCommand to the asynchronous delegate */
                // nybus.SubscribeToCommand<TestCommand>(async (dispatcher, commandContext) => { await DoSomethingAsync(); });

                /* This will subscribe the command TestCommand to the synchronous delegate */
                // nybus.SubscribeToCommand<TestCommand>((dispatcher, commandContext) => { DoSomething(); });
            });

            /* EVENTS */

            /* This will register the event handler TestEventHandler as a handler for TestEvent */
            // services.AddEventHandler<TestEvent, TestEventHandler>();

            /* This will register the event handler TestEventHandler as a handler for all supported events */
            services.AddEventHandler <TestEventHandler>();


            /* COMMANDS */

            /* This will register the command handler TestCommandHandler as a handler for TestCommand */
            // services.AddCommandHandler<TestCommand, TestCommandHandler>();

            /* This will register the command handler TestCommandHandler as a handler for all supported Commands */
            services.AddCommandHandler <TestCommandHandler>();
        }
        public void should_use_path_from_arg_if_provided()
        {
            var args = new StartupContext("-data=\"c:\\users\\test\\\"");

            Mocker.SetConstant <IStartupContext>(args);
            Subject.AppDataFolder.Should().Be("c:\\users\\test\\");
        }
Example #6
0
        public static Response SaveChanges(StartupContext db)
        {
            try
            {
                db.SaveChanges();
                return(new Response {
                    Succedeed = true,
                });
            }
            catch (Exception ex)
            {
                var response = new Response {
                    Succedeed = false,
                };
                if (ex.InnerException != null &&
                    ex.InnerException.InnerException != null &&
                    ex.InnerException.InnerException.Message.Contains("_Index"))
                {
                    response.Message = "Ya existe un registro con ese nombre";
                }
                else if (ex.InnerException != null &&
                         ex.InnerException.InnerException != null &&
                         ex.InnerException.InnerException.Message.Contains("REFERENCE"))
                {
                    response.Message = "El registro no puede ser borrado porque tiene otros registros relacionados";
                }
                else
                {
                    response.Message = ex.Message;
                }

                return(response);
            }
        }
        public void should_parse_single_flag(string arg)
        {
            var args = new StartupContext(new[] { arg });

            args.Flags.Should().HaveCount(1);
            args.Flags.Contains("t").Should().BeTrue();
        }
Example #8
0
 public ActionResult Edit(User user)
 {
     if (ModelState.IsValid)
     {
         var db2         = new StartupContext();
         var currentUser = db2.Users.Find(user.UserId);
         if (currentUser.UserName != user.UserName)
         {
             UserHelper.UpdateUserName(currentUser.UserName, user.UserName);
         }
         if (user.PhotoFile != null)
         {
             var folder   = "~/Content/Users";
             var file     = string.Format("{0}.jpg", user.UserId);
             var response = FilesHelper.UploadPhoto(user.PhotoFile, folder, file);
             if (response)
             {
                 var pic = string.Format("{0}/{1}.jpg", folder, user.UserId);
                 user.Photo           = pic;
                 db.Entry(user).State = EntityState.Modified;
                 db.SaveChanges();
             }
         }
         db2.Dispose();
         return(RedirectToAction("Index"));
     }
     ViewBag.CityId    = new SelectList(db.Cities, "CityId", "Name", user.CityId);
     ViewBag.CompanyId = new SelectList(db.Companies, "CompanyId", "Name", user.CompanyId);
     ViewBag.CountryId = new SelectList(db.Countries, "CountryId", "Name", user.CountryId);
     return(View(user));
 }
Example #9
0
        public static void Main(string[] args)
        {
            try
            {
                var startupContext = new StartupContext(args);
                NzbDroneLogger.Register(startupContext, true, true);

                Logger.Info("Starting Prowlarr Update Client");

                var container = new Container(rules => rules.WithNzbDroneRules())
                                .AutoAddServices(new List <string> {
                    "Prowlarr.Update"
                })
                                .AddNzbDroneLogger()
                                .AddStartupContext(startupContext);

                container.Resolve <InitializeLogger>().Initialize();
                container.Resolve <UpdateApp>().Start(args);

                Logger.Info("Update completed successfully");
            }
            catch (Exception e)
            {
                Logger.Fatal(e, "An error has occurred while applying update package.");
            }
        }
        public void should_parse_args_with_alues(string arg)
        {
            var args = new StartupContext(new[] { arg });

            args.Args.Should().HaveCount(1);
            args.Args["key"].Should().Be("value");
        }
Example #11
0
        public static void Main(string[] args)
        {
            try
            {
                var startupArgs = new StartupContext(args);
                NzbDroneLogger.Register(startupArgs, false, true);
                Bootstrap.Start(startupArgs, new ConsoleAlerts());
            }
            catch (SocketException exception)
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("");
                Logger.Fatal(exception.Message + ". This can happen if another instance of Sonarr is already running another application is using the same port (default: 8989) or the user has insufficient permissions");
                System.Console.WriteLine("Press any key to exit...");
                System.Console.ReadLine();
                Environment.Exit(1);
            }
            catch (Exception e)
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("");
                Logger.FatalException("EPIC FAIL!", e);
                System.Console.WriteLine("Press any key to exit...");
                System.Console.ReadLine();
                Environment.Exit(1);
            }

            Logger.Info("Exiting main.");

            //Need this to terminate on mono (thanks nlog)
            LogManager.Configuration = null;
            Environment.Exit(0);
        }
Example #12
0
        /// <summary>
        /// 在程序宿主环境开始启动时刻,要处理的逻辑
        /// </summary>
        /// <param name="context">启动上下文</param>
        void IStartupService.OnStarting(StartupContext context)
        {
            var providers = this.initApiRouteProvider == null ? null : this.initApiRouteProvider.Invoke(this.a10HealthReport);

            if (providers.IsNullOrEmpty())
            {
                return;
            }

            var type = typeof(ApiUriDispatcher <>);

            foreach (var p in providers)
            {
                var gtype    = type.MakeGenericType(p.GetType());
                var instance = Activator.CreateInstance(gtype, p, this.a10HealthReport);
                if (this.LoggerBuilder != null && instance is IApiRouteLogTracker)
                {
                    ((IApiRouteLogTracker)instance).LoggerBuilder = this.LoggerBuilder;
                }

                context.ServiceRegister.RegisterInstance(instance, gtype);
            }

            a10HealthReport.Startup(this.secondInterval, providers);
        }
Example #13
0
        private MainAppContainerBuilder(StartupContext args, string[] assemblies)
            : base(args, assemblies)
        {
            AutoRegisterImplementations <NzbDronePersistentConnection>();

            Container.Register <INancyBootstrapper, NancyBootstrapper>();
        }
Example #14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            var caminhoDocumentacao = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WebSaude.Api.xml");

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "WebSaudeApi", Version = "v1"
                });
                if (File.Exists(caminhoDocumentacao))
                {
                    c.IncludeXmlComments(caminhoDocumentacao);
                }
                var security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } },
                };

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
                c.AddSecurityRequirement(security);
            });

            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettingsDto>(appSettingsSection);

            var appSettings = appSettingsSection.Get <AppSettingsDto>();
            var key         = Encoding.ASCII.GetBytes(appSettings.Secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            RepositoriesIoc.AdicionarDependencias(services);
            ServicesIoc.AdicionarDependencias(services);
            StartupContext.CreateConection(services, Configuration.GetConnectionString("WebSaude"));
        }
 private void ExecutePlugs(List<Assembly> assemblies)
 {
     var context = new StartupContext(assemblies);
     foreach (var plug in _plugins)
     {
         plug.OnStarting(context);
     }
 }
Example #16
0
        private MainAppContainerBuilder(StartupContext args, List <string> assemblies)
            : base(args, assemblies)
        {
            AutoRegisterImplementations <NzbDronePersistentConnection>();

            Container.Register <INancyBootstrapper, NancyBootstrapper>();
            Container.Register <IHttpDispatcher, FallbackHttpDispatcher>();
        }
Example #17
0
        private static IConfiguration GetConfiguration(StartupContext context)
        {
            var appFolder = new AppFolderInfo(context);

            return(new ConfigurationBuilder()
                   .AddXmlFile(appFolder.GetConfigPath(), optional: true, reloadOnChange: false)
                   .Build());
        }
Example #18
0
        public void SetUp()
        {
            var args = new StartupContext("first", "second");

            _container = MainAppContainerBuilder.BuildContainer(args);

            _container.Register <IMainDatabase>(new MainDatabase(null));
        }
Example #19
0
        public override void ConfigureServices(StartupContext context, IServiceCollection services)
        {
            services.AddNybus(nybus =>
            {
                nybus.UseConfiguration(context.Configuration);

                nybus.UseInMemoryBusEngine();
            });
        }
        private MainAppContainerBuilder(StartupContext args, string[] assemblies)
            : base(args, assemblies)
        {
            AutoRegisterImplementations <NzbDronePersistentConnection>();

            Container.Register(typeof(IBasicRepository <NamingConfig>), typeof(BasicRepository <NamingConfig>));

            Container.Register <INancyBootstrapper, NancyBootstrapper>();
        }
Example #21
0
        private static IConfiguration GetConfiguration(StartupContext context)
        {
            var appFolder = new AppFolderInfo(context);

            return(new ConfigurationBuilder()
                   .AddXmlFile(appFolder.GetConfigPath(), optional: true, reloadOnChange: false)
                   .AddInMemoryCollection(new List <KeyValuePair <string, string> > {
                new ("dataProtectionFolder", appFolder.GetDataProtectionPath())
            })
Example #22
0
        public static IContainer BuildContainer(StartupContext args)
        {
            var assemblies = new List <string>
            {
                "NzbDrone.Host",
                "NzbDrone.Core",
                "NzbDrone.Api",
                "NzbDrone.SignalR"
            };

            return(new MainAppContainerBuilder(args, assemblies).Container);
        }
Example #23
0
        /// <summary>
        /// Runs the cluster client startup task.
        /// </summary>
        /// <param name="cancellationToken">The cancellation token.</param>
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            await ClusterClient.Connect(async ex =>
            {
                cancellationToken.ThrowIfCancellationRequested();

                await Task.Delay(TimeSpan.FromMilliseconds(300), cancellationToken).ConfigureAwait(false);
                return(true);
            }).ConfigureAwait(false);

            StartupContext.MarkTaskAsComplete();
        }
Example #24
0
        public static IHostBuilder CreateConsoleHostBuilder(string[] args, StartupContext context)
        {
            var config = GetConfiguration(context);

            var bindAddress     = config.GetValue(nameof(ConfigFileProvider.BindAddress), "*");
            var port            = config.GetValue(nameof(ConfigFileProvider.Port), 8787);
            var sslPort         = config.GetValue(nameof(ConfigFileProvider.SslPort), 6868);
            var enableSsl       = config.GetValue(nameof(ConfigFileProvider.EnableSsl), false);
            var sslCertPath     = config.GetValue <string>(nameof(ConfigFileProvider.SslCertPath));
            var sslCertPassword = config.GetValue <string>(nameof(ConfigFileProvider.SslCertPassword));

            var urls = new List <string> {
                BuildUrl("http", bindAddress, port)
            };

            if (enableSsl && sslCertPath.IsNotNullOrWhiteSpace())
            {
                urls.Add(BuildUrl("https", bindAddress, sslPort));
            }

            return(new HostBuilder()
                   .UseContentRoot(Directory.GetCurrentDirectory())
                   .UseServiceProviderFactory(new DryIocServiceProviderFactory(new Container(rules => rules.WithNzbDroneRules())))
                   .ConfigureContainer <IContainer>(c =>
            {
                c.AutoAddServices(Bootstrap.ASSEMBLIES)
                .AddNzbDroneLogger()
                .AddDatabase()
                .AddStartupContext(context)
                .Resolve <IEventAggregator>().PublishEvent(new ApplicationStartingEvent());
            })
                   .ConfigureWebHost(builder =>
            {
                builder.UseConfiguration(config);
                builder.UseUrls(urls.ToArray());
                builder.UseKestrel(options =>
                {
                    if (enableSsl && sslCertPath.IsNotNullOrWhiteSpace())
                    {
                        options.ConfigureHttpsDefaults(configureOptions =>
                        {
                            configureOptions.ServerCertificate = ValidateSslCertificate(sslCertPath, sslCertPassword);
                        });
                    }
                });
                builder.ConfigureKestrel(serverOptions =>
                {
                    serverOptions.AllowSynchronousIO = true;
                    serverOptions.Limits.MaxRequestBodySize = null;
                });
                builder.UseStartup <Startup>();
            }));
        }
Example #25
0
        public static void Main(string[] args)
        {
            var startupArgs = new StartupContext(args);

            RadarrInstrumentation.Register(startupArgs, false, true);

            var bootstrap = new Bootstrap(startupArgs);

            bootstrap.Start();

            System.Console.ReadKey();
        }
Example #26
0
        static void Main(string[] args)
        {
            try
            {
                var oldColor = Console.ForegroundColor;

                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("AGN Gaming Radarr Hotpatch Loading...");
                Console.WriteLine("Attempting to bootstrap Radarr, here goes!");
                Console.ForegroundColor = oldColor;

                var patchManager = new PatchManager();

                var startupArgs = new StartupContext(args);
                try
                {
                    NzbDroneLogger.Register(startupArgs, false, true);
                }
                catch (Exception ex)
                {
                    System.Console.WriteLine("NLog Exception: " + ex.ToString());
                    throw;
                }

                if (patchManager.BeginPatching())
                {
                    Utility.WriteToConsole("All patches successful, starting Radarr.", ConsoleColor.Green);
                    Bootstrap.Start(startupArgs, new ConsoleAlerts());
                }
                else
                {
                    Console.WriteLine("");
                    Console.WriteLine("");
                    Logger.Fatal("Some HotPatch patches were not applied successfully.  Are you using a supported version of Radarr?");
                    Exit(ExitCodes.UnknownFailure);
                }
            }
            catch (SocketException e)
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("");
                Logger.Fatal(e.Message + ". This can happen if another instance of Radarr is already running another application is using the same port (default: 7878) or the user has insufficient permissions");
                Exit(ExitCodes.RecoverableFailure);
            }
            catch (Exception e)
            {
                System.Console.WriteLine("");
                System.Console.WriteLine("");
                Logger.Fatal(e, "EPIC FAIL!");
                Exit(ExitCodes.UnknownFailure);
            }
        }
        /// <summary>
        /// Decrypt and deserialize the specified context, and apply values from it to the
        /// startup cache context.
        /// </summary>
        /// <param name="encryptedContext">The encrypted assignment context.</param>
        /// <returns>The decrypted assignment context</returns>
        public virtual HostAssignmentContext SetContext(EncryptedHostAssignmentContext encryptedContext)
        {
            string decryptedContext      = SimpleWebTokenHelper.Decrypt(encryptedContext.EncryptedContext, environment: _environment);
            var    hostAssignmentContext = JsonConvert.DeserializeObject <HostAssignmentContext>(decryptedContext);

            // apply values from the context to our cached context
            Context = new StartupContext
            {
                Secrets = hostAssignmentContext.Secrets
            };

            return(hostAssignmentContext);
        }
Example #28
0
        public static IContainer BuildContainer(StartupContext args)
        {
            var assemblies = new List <string>
            {
                "Lidarr.Host",
                "Lidarr.Core",
                "Lidarr.SignalR",
                "Lidarr.Api.V1",
                "Lidarr.Http"
            };

            return(new MainAppContainerBuilder(args, assemblies).Container);
        }
Example #29
0
        public void SetUp()
        {
            var args = new StartupContext("first", "second");

            _container = MainAppContainerBuilder.BuildContainer(args);

            _container.Register <IMainDatabase>(new MainDatabase(null));

            // set up a dummy broadcaster to allow tests to resolve
            var mockBroadcaster = new Mock <IBroadcastSignalRMessage>();

            _container.Register <IBroadcastSignalRMessage>(mockBroadcaster.Object);
        }
Example #30
0
        public static void Start(StartupContext startupContext, IUserAlert userAlert, Action <IContainer> startCallback = null)
        {
            try
            {
                SecurityProtocolPolicy.Register();
                X509CertificateValidationPolicy.Register();

                Logger.Info("Starting Gamearr - {0} - Version {1}", Assembly.GetCallingAssembly().Location, Assembly.GetExecutingAssembly().GetName().Version);

                if (!PlatformValidation.IsValidate(userAlert))
                {
                    throw new TerminateApplicationException("Missing system requirements");
                }

                LongPathSupport.Enable();

                _container = MainAppContainerBuilder.BuildContainer(startupContext);
                _container.Resolve <InitializeLogger>().Initialize();
                _container.Resolve <IAppFolderFactory>().Register();
                _container.Resolve <IProvidePidFile>().Write();

                var appMode = GetApplicationMode(startupContext);

                Start(appMode, startupContext);

                if (startCallback != null)
                {
                    startCallback(_container);
                }

                else
                {
                    SpinToExit(appMode);
                }
            }
            catch (InvalidConfigFileException ex)
            {
                throw new GamearrStartupException(ex);
            }
            catch (AccessDeniedConfigFileException ex)
            {
                throw new GamearrStartupException(ex);
            }
            catch (TerminateApplicationException ex)
            {
                Logger.Info(ex.Message);
                LogManager.Configuration = null;
            }
        }
Example #31
0
        public static void Start(StartupContext startupContext, IUserAlert userAlert, Action <IContainer> startCallback = null)
        {
            try
            {
                Logger.Info("Starting Radarr - {0} - Version {1}",
#if NETCOREAPP
                            Process.GetCurrentProcess().MainModule.FileName,
#else
                            Assembly.GetCallingAssembly().Location,
#endif
                            Assembly.GetExecutingAssembly().GetName().Version);

                if (!PlatformValidation.IsValidate(userAlert))
                {
                    throw new TerminateApplicationException("Missing system requirements");
                }

                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

                _container = MainAppContainerBuilder.BuildContainer(startupContext);
                _container.Resolve <InitializeLogger>().Initialize();
                _container.Resolve <IAppFolderFactory>().Register();
                _container.Resolve <IProvidePidFile>().Write();

                var appMode = GetApplicationMode(startupContext);

                Start(appMode, startupContext);

                _container.Resolve <ICancelHandler>().Attach();

                if (startCallback != null)
                {
                    startCallback(_container);
                }
                else
                {
                    SpinToExit(appMode);
                }
            }
            catch (InvalidConfigFileException ex)
            {
                throw new RadarrStartupException(ex);
            }
            catch (TerminateApplicationException e)
            {
                Logger.Info(e.Message);
                LogManager.Configuration = null;
            }
        }
Example #32
0
        /// <summary>
        /// 检查是否有迷失的任务进程
        /// </summary>
        /// <param name="context"></param>
        private void CheckLostChild(StartupContext context)
        {
            if (!Directory.Exists(SimpleConfig.ProcessStatePath))
            {
                return;
            }

            foreach (var procInfo in Directory.GetFiles(Path.Combine(Environment.CurrentDirectory, SimpleConfig.ProcessStatePath)))
            {
                System.Diagnostics.Process p;
                int pid = 0;
                if (!int.TryParse( // 如果格式化为整型失败
                    procInfo.Substring(procInfo.LastIndexOf(Path.DirectorySeparatorChar) + 1), 
                    out pid))
                {
                    
                    try
                    {
                        File.Delete(procInfo);
                    }
                    catch { }
                    continue;
                }
                try
                {
                    p = System.Diagnostics.Process.GetProcessById(pid);
                }
                catch (Exception notFoundEx)
                {
                    // 说明该进程已退出
                    File.Delete(procInfo);
                    continue;
                }

                StartupContext pContext = null;
                try
                {
                    pContext =UtilityLib.Serializetion.Binary<StartupContext>.ReadObject(
                        Path.Combine(Environment.CurrentDirectory, SimpleConfig.ProcessStatePath, pid.ToString()));
                }
                catch (Exception formatEx)
                {
                    // 序列化失败,文件破坏,删除进程文件,退出迷失的进程
                    File.Delete(procInfo);
                    p.Kill();
                }

                if (context.Equals(pContext))
                {
                    // 重新接管该进程
                    this.TakeOverProc(pContext, p);
                    return;
                }
            }
        }
Example #33
0
        /// <summary>
        /// 构建任务进程
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private void BuildProcess(StartupContext context)
        {
            System.Diagnostics.Process process = new System.Diagnostics.Process();

            // 为子任务进程增加免守护标识
            context.AddArg(WithoutDefendCmd);

            // 配置进程信息,父子进程通过重定向错误输出来通信
            process.StartInfo = new System.Diagnostics.ProcessStartInfo(
                System.IO.Path.Combine(Environment.CurrentDirectory, SimpleConfig.SimpleShellName),
                context.GetCmd())
                {
                    WorkingDirectory = System.Environment.CurrentDirectory ,
                    RedirectStandardInput = false,
                    RedirectStandardOutput = false,
                    RedirectStandardError = true,
                    UseShellExecute = false
                };

            // 为子进程增加事件处理
            process.EnableRaisingEvents = true;
            process.Exited += new EventHandler(process_Exited); // 注册退出处理事件
            process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived); // 注册通信处理事件

            this.CurrentProc = process;
        }
Example #34
0
 /// <summary>
 /// 重新接管迷失的进程
 /// </summary>
 /// <param name="pContext"></param>
 /// <param name="proc"></param>
 private void TakeOverProc(StartupContext pContext, System.Diagnostics.Process proc)
 {
     this.ProcId = proc.Id;
     this.CurrentProc = proc;
     this.StartTime = proc.StartTime;
 }
Example #35
0
        /// <summary>
        /// 开始守护过程
        /// </summary>
        /// <param name="process"></param>
        /// <param name="context"></param>
        private void StartAndDefend(StartupContext context)
        {
            // 启动失败或出错的时候会尝试继续守护
            // 开始守护
            while (true)
            {
                bool failed = false;
                if (this.StartProcess(context) && !failed) // 如果进程已退出,则重启进程
                {
                    try
                    {
                        // 如果进程已退出,则failed为true
                        failed = this.CurrentProc.WaitForExit((int)TimeSpan.FromSeconds(30).TotalMilliseconds); // 等待程序退出30秒
                    }
                    catch { }
                }
                
                if(failed)
                {
                    // 程序启动失败,等待10秒后重试
                    try
                    {
                        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(10));
                        this.BuildProcess(context); // 启动失败则重置进程信息
                    }
                    catch(Exception e) 
                    {

                    }
                }
            }
        }
Example #36
0
        /// <summary>
        /// 启动进程
        /// </summary>
        /// <param name="proc"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        private bool StartProcess(StartupContext context)
        {
            // 检查是否有丢失的进程(即失去守护进程的)
            this.CheckLostChild(context);

            bool success = false;
            try
            {
                // 查看任务进程的状态
                success = !this.CurrentProc.HasExited;
            }
            catch { }

            if (!success) // 如果任务进程非正常执行则重新执行任务进程
            {
                try
                {
                    this.BuildProcess(context);
                    success = this.CurrentProc.Start();
                    if (success)
                    {
                        this.CurrentProc.BeginErrorReadLine();
                        this.ProcId = this.CurrentProc.Id;
                        this.StartTime = this.CurrentProc.StartTime;

                        // 保存正在运行的进程信息
                        StoreProcInfo(context, this.ProcId);

                        System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2)); // 等待两秒,待任务进程启动
                        Console.Title = string.Format("守护进程.For.ProcId.{0}.{1} At.{2}",
                            this.ProcId, context.TaskName, Environment.CurrentDirectory);
                    }
                }
                catch (Exception e)
                {
                    // DO STH
                }
            }
            return success;
        }
Example #37
0
        /// <summary>
        /// 保存进程信息到磁盘
        /// </summary>
        /// <param name="context"></param>
        /// <param name="p"></param>
        private void StoreProcInfo(StartupContext context, int pid)
        {
            // 说明进程不存在
            if (context == null || pid <= 0)
            {
                return;
            }

            if (!Directory.Exists(SimpleConfig.ProcessStatePath))
            {
                Directory.CreateDirectory(SimpleConfig.ProcessStatePath);
            }

            string path = Path.Combine(Environment.CurrentDirectory, SimpleConfig.ProcessStatePath, pid.ToString());
            if(File.Exists(path))
            {
                try
                {
                    File.Delete(path);
                }
                catch { }
            }

            
            try
            {
                UtilityLib.Serializetion.Binary<StartupContext>.WriteObject(context, path);
            }
            catch (Exception e)
            {
                // DO STH
            }
        }