Beispiel #1
0
 public bool Remove(Guid jobId)
 {
     lock (syncLock)
     {
         if (JobRuntimePool.ContainsKey(jobId))
         {
             JobRuntimeInfo jobRuntimeInfo = null;
             JobRuntimePool.TryGetValue(jobId, out jobRuntimeInfo);
             if (jobRuntimeInfo != null)
             {
                 var tiggerKey = new TriggerKey(jobRuntimeInfo.JobModel.JobName,
                                                jobRuntimeInfo.JobModel.JobGroup);
                 scheduler.PauseTrigger(tiggerKey);
                 scheduler.UnscheduleJob(tiggerKey);
                 scheduler.DeleteJob(new JobKey(jobRuntimeInfo.JobModel.JobName,
                                                jobRuntimeInfo.JobModel.JobGroup));
                 JobRuntimePool.TryRemove(jobId, out jobRuntimeInfo);
                 JobOperator.UpdateJobStatus(jobRuntimeInfo.JobModel.ID, 0);
                 if (!JobRuntimePool.Any(p => p.Value.AppDomain == jobRuntimeInfo.AppDomain))
                 {
                     AppDomainLoader <BaseJob> .UnLoad(jobRuntimeInfo.AppDomain);
                 }
                 return(true);
             }
         }
         return(false);
     }
 }
Beispiel #2
0
        private static int restartAsAdmin(XS.ScriptContext context, string[] args, bool hidden)
        {
            context.WriteLine(XS.OutputType.Info, "** Administrative privileges are required to run this script.\n** Please confirm to continue.");

            int n = AppDomainLoader.RunWithElevatedContext(
                delegate(XS.ScriptContext ctx)
            {
                XS.ScriptContextScope.DefaultContext = ctx;
                try
                {
                    return(MainWithContext(ctx, args));
                }
                finally
                {
                    XS.ScriptContextScope.DefaultContext = null;
                }
            }, hidden);

            if (n == -1)
            {
                throw new XS.ScriptRuntimeException("An error occured while granting administrative privileges.");
            }
            if (n != 0)
            {
                throw new XS.ScriptRuntimeException("An error occured during script execution.");
            }
            return(0);
        }
Beispiel #3
0
        static void CompilerTest(string[] args)
        {
            var compiler = new CSharpCompiler();
            var dllPath  = Path.GetFullPath("TestClasses") + CommonFolders.Sep + "TestApp.dll";
            var results  = compiler.Compile("TestApp", "TestClasses", new List <string> {
                Path.GetFullPath("TestClasses/TestClass1.cs"),
                Path.GetFullPath("TestClasses/TestClass2.cs")
            });

            foreach (CompilerError err in results.Errors)
            {
                Console.WriteLine($"{(err.IsWarning ? "WARNING :" : "ERROR  :")} {err.ErrorText}");
            }

            if (!results.Errors.HasErrors)
            {
                var loader = new AppDomainLoader("TestApp", dllPath);

                if (loader.IsLoaded)
                {
                    var testClass1 = loader.RunRemoteFunc <object>(() => {
                        Console.WriteLine(AppDomain.CurrentDomain.SetupInformation.ApplicationName);

                        return(null);
                    });
                }
            }
        }
        public void should_call_search_assembly_event()
        {
            var directoriestolook = "";

            var loader = new AppDomainLoader { FindAssemblyMethod = MockAssemblySearchEvent };
            loader.Search(new[]{directoriestolook});
            Assembly.Load("FakeAssemblyname");
            Assert.IsTrue(_eventCalled);
        }
Beispiel #5
0
        private void button1_Click(object sender, EventArgs e)
        {
            //var o =  new CryptoHelper().Encrypt("cofnig");
            //var m = new CryptoHelper().Decrypt(o);
            //var a = 1;
            //CompressHelper.UnCompress(@"E:\111.zip",@"E:\111");


            //SqlHelper.ExcuteSql("server=192.168.17.201;Initial Catalog=dyd_bs_task;User ID=sa;Password=Xx~!@#;", (c) =>
            //{
            //    Domain.Dal.tb_version_dal versiondal = new Domain.Dal.tb_version_dal();
            //    versiondal.Edit(c, new tb_version_model()
            //    {
            //        id = 6,
            //        taskid = 8,
            //        version = 1,
            //        versioncreatetime = DateTime.Now,
            //        zipfile = System.IO.File.ReadAllBytes(@"E:\8.rar"),
            //        zipfilename = "8.rar"
            //    });
            //});

            XXF.BaseService.TaskManager.SystemRuntime.TaskAppConfigInfo tai = new XXF.BaseService.TaskManager.SystemRuntime.TaskAppConfigInfo();
            tai.Add("ConfigConnectString", @"server=10.4.11.12;Initial Catalog=ky_monitor;User ID=dev;Password=dev201404");
            string o = new XXF.Serialization.JsonHelper().Serializer(tai);
            NodeTaskRuntimeInfo taskruntimeinfo = new NodeTaskRuntimeInfo();

            var dlltask = new AppDomainLoader <BaseDllTask>().Load(AppDomain.CurrentDomain.BaseDirectory + @"a\debug\EPlatformServer.exe", "EPlatformServer.Task.CenterProviderManagerTask", out taskruntimeinfo.Domain);

            dlltask.TryRun();
            MessageBox.Show("ok");
            //int a = 1;

            //EmailHelper email = new EmailHelper();
            //email.mailFrom = "*****@*****.**";
            //email.mailPwd = "472790378@";
            //email.mailSubject = "11";
            //email.mailBody = "111";
            //email.isbodyHtml = true;    //是否是HTML
            //email.host = "smtp.163.com";//如果是QQ邮箱则:smtp:qq.com,依次类推
            //email.mailToArray = new string[] { "*****@*****.**" };//接收者邮件集合
            //email.mailCcArray = new string[] { };//抄送者邮件集合
            //if (email.Send())
            //{


            //}
            //else
            //{

            //}
        }
Beispiel #6
0
        public static void Start()
        {
            PrepareErrorHandle();

            var root = ConfigurationManager.AppSettings["serviceRoot"];
            Directory.CreateDirectory(root);
            //配置初始化
            log4net.Config.XmlConfigurator.Configure();
            _log = new Log4NetLogger(log4net.LogManager.GetLogger(typeof(Program)));
            _loader = new AppDomainLoader(root, _log);
            WriteTip("开始扫描发布目录:" + ConfigurationManager.AppSettings["serviceRoot"], true);
            _loader.Scan();
            WriteTip("扫描完毕", true);
        }
Beispiel #7
0
        public static void Start()
        {
            PrepareErrorHandle();

            var root = ConfigurationManager.AppSettings["serviceRoot"];

            Directory.CreateDirectory(root);
            //配置初始化
            log4net.Config.XmlConfigurator.Configure();
            _log    = new Log4NetLogger(log4net.LogManager.GetLogger(typeof(Program)));
            _loader = new AppDomainLoader(root, _log);
            WriteTip("开始扫描发布目录:" + ConfigurationManager.AppSettings["serviceRoot"], true);
            _loader.Scan();
            WriteTip("扫描完毕", true);
        }
Beispiel #8
0
        public static int Main(string[] args)
        {
            try
            {
                // Disable fatal error message popups by SetErrorMode(SEM_FAILCRITICALERRORS)
                SetErrorMode(1);

                return(AppDomainLoader.Loader(args) ?? Main2(args));
            }
            catch (System.Security.SecurityException)
            {
                Console.Error.WriteLine("Code security exception. Please copy the module to a local hard drive and try again.");
                return(-3);
            }
        }
Beispiel #9
0
        static void Main(string[] args)
        {
            //Instrumentor
            Workspace workspace = new Workspace();

            workspace.MakeReady();
            var instrumetor = new SOLPI.Instrumentor(AppDomainLoader.SOLPath + AppDomainLoader.SOLExe, workspace);

            instrumetor.Process();

            //Loader
            var loader = new AppDomainLoader();

            loader.LinkWithSOL();
            loader.Boot();
        }
Beispiel #10
0
        public static void Start(string root, bool auto)
        {
            PrepareErrorHandle();

            Directory.CreateDirectory(root);
            //配置初始化
            log4net.Config.XmlConfigurator.Configure();
            //特化的log
            var log = new Log4NetLogger(log4net.LogManager.GetLogger(typeof(Program)));

            Program._log = new AgentHandlerLog(log);

            _loader = new AppDomainLoader(root, Program._log, auto);
            WriteTip("开始扫描发布目录:" + root, true);
            if (!Program._single)
            {
                _loader.Scan();
            }
            else
            {
                _loader.LoadFrom(root);
            }
            WriteTip("扫描完毕", true);

            if (!Convert.ToBoolean(ConfigurationManager.AppSettings["appAgent_enable"]))
            {
                return;
            }

            //激活AppAgent
            WriteTip("启用AppAgent", true);
            new DefaultAgent(log
                             , ConfigurationManager.AppSettings["appAgent_master"]
                             , ConfigurationManager.AppSettings["appAgent_name"]
                             , ConfigurationManager.AppSettings["appAgent_description"]
                             , new CommandHandle())
            .Run();
        }
Beispiel #11
0
        public static bool ScheduleJob(this IScheduler scheduler, JobInfo jobInfo)
        {
            Ensure.Requires <ArgumentNullException>(scheduler != null, "sheduler should not be null.");
            Ensure.Requires <ArgumentNullException>(jobInfo != null, "jobInfo should not be null.");

            try
            {
                var jobGroup = string.IsNullOrWhiteSpace(jobInfo.JobGroup) ? null : jobInfo.JobGroup;
                var jobKey   = new JobKey(jobInfo.JobName, jobGroup);
                if (!scheduler.CheckExists(jobKey))
                {
                    var appDomain = default(AppDomain);
                    var dllPath   = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Jobs", jobInfo.AssemblyName, $"{jobInfo.AssemblyName}.dll");
                    var job       = AppDomainLoader <BaseJob> .Load(dllPath, jobInfo.ClassName, out appDomain);

                    return(JobPoolManager.Instance.Add(jobInfo.ID, new JobRuntimeInfo
                    {
                        AppDomain = appDomain,
                        Job = job,
                        JobModel = jobInfo
                    }));
                }
                else
                {
                    if (jobInfo.Status == 1)
                    {
                        scheduler.ResumeJob(jobKey);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                Logger.Instance.Error(ex.Message);
                return(false);
            }
        }
        /// <summary>
        /// 任务的开启
        /// </summary>
        /// <param name="taskid"></param>
        /// <returns></returns>
        public bool Start(int taskid)
        {
            var taskruntimeinfo = TaskPoolManager.CreateInstance().Get(taskid.ToString());

            if (taskruntimeinfo != null)
            {
                throw new Exception("任务已在运行中");
            }

            taskruntimeinfo          = new NodeTaskRuntimeInfo();
            taskruntimeinfo.TaskLock = new TaskLock();
            SqlHelper.ExcuteSql(GlobalConfig.TaskDataBaseConnectString, (c) =>
            {
                tb_task_dal taskdal              = new tb_task_dal();
                taskruntimeinfo.TaskModel        = taskdal.Get(c, taskid);
                tb_version_dal versiondal        = new tb_version_dal();
                taskruntimeinfo.TaskVersionModel = versiondal.GetCurrentVersion(c, taskid, taskruntimeinfo.TaskModel.taskversion);
                //taskruntimeinfo.ProcessId=taskdal.GetProcess(c, taskid);
            });
            //如果异常退出,进程后没有更新

            /*if (taskruntimeinfo.TaskModel.task_type == TaskType.Service.Code)
             * {
             *
             * }*/
            string filelocalcachepath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\" + GlobalConfig.TaskDllCompressFileCacheDir + @"\" + taskruntimeinfo.TaskModel.id + @"\" + taskruntimeinfo.TaskModel.taskversion + @"\" +
                                        taskruntimeinfo.TaskVersionModel.zipfilename;
            string fileinstallpath             = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\" + GlobalConfig.TaskDllDir + @"\" + taskruntimeinfo.TaskModel.id;
            string fileinstallmainclassdllpath = fileinstallpath + @"\" + taskruntimeinfo.TaskModel.taskmainclassdllfilename;
            string taskshareddlldir            = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\" + GlobalConfig.TaskSharedDllsDir;
            string shelldlldir = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\" + GlobalConfig.TaskShellDir;

            XXF.Common.IOHelper.CreateDirectory(filelocalcachepath);
            XXF.Common.IOHelper.CreateDirectory(fileinstallpath);
            // File.WriteAllBytes(filelocalcachepath, taskruntimeinfo.TaskVersionModel.zipfile);
            FileStream fs = new FileStream(filelocalcachepath, FileMode.Create, FileAccess.ReadWrite);

            SqlHelper.ExcuteSql(GlobalConfig.TaskDataBaseConnectString, (c) =>
            {
                tb_version_dal versiondal = new tb_version_dal();
                versiondal.FillByteToFile(c, taskid, taskruntimeinfo.TaskModel.taskversion, fs);
            });
            fs.Close();
            if (Directory.Exists(fileinstallpath))
            {
                File.SetAttributes(fileinstallpath, FileAttributes.Normal);
                Directory.Delete(fileinstallpath, true);
            }
            CompressHelper.UnCompress(filelocalcachepath, fileinstallpath);
            //拷贝共享程序集

            XXF.Common.IOHelper.CopyDirectory(taskshareddlldir, fileinstallpath);
            //如果是module



            if (taskruntimeinfo.TaskModel.IsModule)
            {
                XXF.Common.IOHelper.CopyDirectory(shelldlldir, fileinstallpath);
            }
            LogHelper.AddTaskLog($"原程序集版本:{taskruntimeinfo.TaskVersionModel.assemblyversion}", taskid);
            //LogHelper.AddTaskLog($"程序集文件:{fileinstallmainclassdllpath}",taskid);
            string assemblyVersion = null;

            byte[] bytes = Encoding.Default.GetBytes(taskruntimeinfo.TaskModel
                                                     .taskappconfigjson);
            string jsonConfig = Convert.ToBase64String(bytes);
            bool   r          = false;

            if (taskruntimeinfo.TaskModel.task_type == TaskType.Service.Code)
            {
                bool            is_module = taskruntimeinfo.TaskModel.IsModule;
                IProcessBuilder builder;
                //当
                //
                try
                {
                    // string assemblyVersion = GetAssemblyVersion(fileinstallmainclassdllpath);
                    Process result;

                    string flag = taskruntimeinfo.TaskModel.ServiceFlag;



                    var startupParam = new ProcessStartupParam()
                    {
                        Flag             = flag, FileName = fileinstallmainclassdllpath,
                        FilePatten       = taskruntimeinfo.TaskModel.taskmainclassdllfilename,
                        Config           = jsonConfig, WorkDir = fileinstallpath,
                        Cron             = taskruntimeinfo.TaskModel.taskcron,
                        NameSpace        = taskruntimeinfo.TaskModel.taskmainclassnamespace,
                        TaskDbConnection = GlobalConfig.TaskDataBaseConnectString,
                        TaskModel        = taskruntimeinfo.TaskModel,
                        AppConfig        = new XXF.Serialization.JsonHelper().Deserialize <TaskAppConfigInfo>(taskruntimeinfo
                                                                                                              .TaskModel
                                                                                                              .taskappconfigjson)
                    };

                    builder = ProcessStart.GetInstance().GetBuilder(startupParam);
                    builder.GetMainFileName();
                    assemblyVersion = builder.GetAssemblyVersion();
                    //     taskruntimeinfo.TaskModel.taskmainclassdllfilename = builder.StartupParam.FileName;
                    result = builder.StartProcess();



                    r = StartProcess(taskid, taskruntimeinfo, result);
                }
                catch (Exception ex)
                {
                    LogHelper.AddTaskLog($"节点开启任务失败{ex.Message}", taskid);
                    throw;
                }
                // bool r = TaskPoolManager.CreateInstance().Add(taskid.ToString(), taskruntimeinfo);
                SqlHelper.ExcuteSql(GlobalConfig.TaskDataBaseConnectString, (c) =>
                {
                    tb_task_dal taskdal = new tb_task_dal();
                    //更新类型
                    taskdal.Edit(c, taskruntimeinfo.TaskModel);
                    taskdal.UpdateTaskState(c, taskid, (int)EnumTaskState.Running);
                    taskdal.UpdateProcess(c, taskid, taskruntimeinfo.Process.Id);
                    //程序集版本更新
                    if (!string.IsNullOrEmpty(assemblyVersion))
                    {
                        if (taskruntimeinfo.TaskVersionModel.assemblyversion != assemblyVersion)
                        {
                            taskruntimeinfo.TaskVersionModel.assemblyversion = assemblyVersion;
                            tb_version_dal versiondal = new tb_version_dal();
                            versiondal.UpdateAssemblyVersion(c, taskruntimeinfo.TaskVersionModel.id, assemblyVersion);
                        }
                    }
                });
                //
                if (taskruntimeinfo.TaskModel.IsRegister == 1)
                {
                    ConsulRegisteration item = _consulRegisterMgr.Parse(taskruntimeinfo.TaskModel);
                    item.Service = builder.GetService();
                    taskruntimeinfo.RegistService = item;
                    _consulRegisterMgr.Register(item);
                }

                LogHelper.AddTaskLog("节点开启任务成功", taskid);
                return(r);
            }
            else
            {
                //以dll加载的方式处理,基本已废弃
                assemblyVersion = GetAssemblyVersion(fileinstallmainclassdllpath);

                if (!string.IsNullOrEmpty(taskruntimeinfo.TaskModel.ServiceFlag))
                {
                    return(StartTaskProcess(taskid, taskruntimeinfo, fileinstallmainclassdllpath,
                                            fileinstallpath, jsonConfig, assemblyVersion));
                }
                else
                {
                    try
                    {
                        var dlltask = new AppDomainLoader <BaseDllTask>().Load(fileinstallmainclassdllpath,
                                                                               taskruntimeinfo.TaskModel.taskmainclassnamespace, out taskruntimeinfo.Domain);
                        //  dlltask.Domain = taskruntimeinfo.Domain;
                        var sdktaskmodel = new XXF.BaseService.TaskManager.model.tb_task_model();
                        PropertyHelper.Copy(taskruntimeinfo.TaskModel, sdktaskmodel);
                        dlltask.SystemRuntimeInfo = new TaskSystemRuntimeInfo()
                        {
                            TaskConnectString = GlobalConfig.TaskDataBaseConnectString,
                            TaskModel         = sdktaskmodel
                        };

                        dlltask.AppConfig = new TaskAppConfigInfo();
                        if (!string.IsNullOrEmpty(taskruntimeinfo.TaskModel.taskappconfigjson))
                        {
                            dlltask.AppConfig =
                                new XXF.Serialization.JsonHelper().Deserialize <TaskAppConfigInfo>(taskruntimeinfo
                                                                                                   .TaskModel
                                                                                                   .taskappconfigjson);
                        }

                        taskruntimeinfo.DllTask = dlltask;

                        /*   if (dlltask is IMicroService)
                         * {
                         *     taskruntimeinfo.TaskModel.task_type = TaskType.Service.Code;
                         * }
                         * else
                         * {
                         *     taskruntimeinfo.TaskModel.task_type = TaskType.Task.Code;
                         *
                         * }*/

                        r = TaskPoolManager.CreateInstance().Add(taskid.ToString(), taskruntimeinfo);
                        SqlHelper.ExcuteSql(GlobalConfig.TaskDataBaseConnectString, (c) =>
                        {
                            tb_task_dal taskdal = new tb_task_dal();
                            //更新类型
                            taskdal.Edit(c, taskruntimeinfo.TaskModel);
                            taskdal.UpdateTaskState(c, taskid, (int)EnumTaskState.Running);
                            //程序集版本更新
                            if (!string.IsNullOrEmpty(assemblyVersion))
                            {
                                if (taskruntimeinfo.TaskVersionModel.assemblyversion != assemblyVersion)
                                {
                                    taskruntimeinfo.TaskVersionModel.assemblyversion = assemblyVersion;
                                    tb_version_dal versiondal = new tb_version_dal();
                                    versiondal.UpdateAssemblyVersion(c, taskruntimeinfo.TaskVersionModel.id,
                                                                     assemblyVersion);
                                }
                            }
                        });

                        LogHelper.AddTaskLog("节点开启任务成功", taskid);
                        return(r);
                    }
                    catch (Exception exp)
                    {
                        DisposeTask(taskid, taskruntimeinfo, true);
                        throw exp;
                    }
                }
            }
        }
Beispiel #13
0
        // Real main
        static int MainWithContext(XS.ScriptContext context, string[] args)
        {
            AppDomainLoader.progress("MainWithContext: Entering --------------------");
            XS.CommandLineParameter[] param = new XS.CommandLineParameter[] {
                new XS.CommandLineParameter(xs.quiet, XS.CommandLineValueCount.None, null, "true"),
                new XS.CommandLineParameter(xs.debug, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.debugc, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.verbose, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.nocolors, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.wait, XS.CommandLineValueCount.None, null, "true"),
                new XS.CommandLineParameter(xs.save, XS.CommandLineValueCount.Single, null, "xsharper_save.xsh"),
                new XS.CommandLineParameter(xs.log, XS.CommandLineValueCount.Single, null, "xsharper.log"),
                new XS.CommandLineParameter(xs.requireAdmin, XS.CommandLineValueCount.None, null, "true"),
                new XS.CommandLineParameter(xs.last, XS.CommandLineValueCount.None, null, "true"),
                new XS.CommandLineParameter(xs.utf8, XS.CommandLineValueCount.None, "false", "true"),
                new XS.CommandLineParameter(xs.scriptargs, null, XS.CommandLineValueCount.Multiple, null, null)
            };
            param[param.Length - 1].Last = true;
            param[param.Length - 2].Last = true;

            XS.CommandLineParameters xsParams = new XS.CommandLineParameters(param, "//", false);
            foreach (XS.CommandLineParameter a in xsParams)
            {
                if (!string.IsNullOrEmpty(a.Name) && a.Name != xs.scriptargs)
                {
                    a.Switch = a.Name.Replace("xs.", "");
                }
            }


            int exitCode = 0;

            bool utf8 = false;

            foreach (string arg in args)
            {
                if (arg.Equals(xs.utf8.Replace("xs.", "//"), StringComparison.OrdinalIgnoreCase))
                {
                    utf8 = true;
                }
            }
            using (XS.ConsoleWithColors cout = new XS.ConsoleWithColors(Environment.GetEnvironmentVariable("XSH_COLORS"), utf8))
                using (XS.CtrlCInterceptor ctrl = new XS.CtrlCInterceptor())
                {
                    context.Output += cout.OnOutput;
                    ctrl.Output     = context.Error;
                    ctrl.Abort     += delegate { context.Abort(); };

                    AppDomainLoader.progress("MainWithContext: Console ready --------------------");
                    System.Diagnostics.Stopwatch w = System.Diagnostics.Stopwatch.StartNew();

                    try
                    {
                        AppDomainLoader.progress("MainWithContext: Before parse--------------------");
                        xsParams.Parse(context, args, false);
                        AppDomainLoader.progress("MainWithContext: Before set options--------------------");
                        setOutputOptions(context, cout);

                        AppDomainLoader.progress("MainWithContext: Before load--------------------");
                        $ {
                            GENERATED_CLASS
                        } cl = new $ {
                            GENERATED_CLASS
                        } ();
                        XS.Script s = cl.Script;
                        ctrl.IgnoreCtrlC = s.IgnoreCtrlC;
                        ctrl.AbortDelay  = XS.Utils.ToTimeSpan(s.AbortDelay) ?? ctrl.AbortDelay;
                        ctrl.ExitDelay   = XS.Utils.ToTimeSpan(s.ExitDelay) ?? ctrl.ExitDelay;


                        AppDomainLoader.progress("MainWithContext: After load--------------------");
                        if (context.IsSet(xs.save))
                        {
                            using (XS.ScriptContextScope r = new XS.ScriptContextScope(context))
                                s.Save(context.GetString(xs.save));
                        }
                        else
                        {
                            context.Compiler.AddRequireAdmin(XS.Utils.To <XS.RequireAdminMode>(context.GetStr(xs.requireAdmin, XS.RequireAdminMode.User.ToString())));
                            context.Compiler.AddRequireAdmin(s.RequireAdmin);
                            if (context.Compiler.RequireAdmin != XS.RequireAdminMode.User && !context.IsAdministrator)
                            {
                                return(restartAsAdmin(context, args, context.Compiler.RequireAdmin == XS.RequireAdminMode.Hidden));
                            }

                            AppDomainLoader.progress("MainWithContext: Before initialization --------------------");
                            context.Initialize(s);
                            AppDomainLoader.progress("MainWithContext: After initialization --------------------");
                            string[] parms = null;
                            if (context.IsSet(xs.scriptargs))
                            {
                                parms = context.GetStringArray(xs.scriptargs);
                            }

                            XS.ConsoleRedirector redir = new XS.ConsoleRedirector(context);
                            try
                            {
                                AppDomainLoader.progress("MainWithContext: Before executing --------------------");
                                object r = context.ExecuteScript(s, parms, XS.CallIsolation.High);
                                ctrl.KillAbortTimer();
                                AppDomainLoader.progress("MainWithContext: After executing --------------------");
                                if (r != null)
                                {
                                    int.TryParse(r.ToString(), out exitCode);
                                }
                            }
                            finally
                            {
                                ctrl.KillAbortTimer();
                                redir.Dispose();
                            }
                        }
                    }
                    catch (ThreadAbortException ae)
                    {
                        resetAbort(context);
                        context.WriteException(ae.InnerException);
                        exitCode = -1000;
                    }
                    catch (XS.ScriptTerminateException te)
                    {
                        resetAbort(context);
                        exitCode = te.ExitCode;
                        if (te.InnerException != null)
                        {
                            context.WriteException(te.InnerException);
                        }
                    }
                    catch (Exception e)
                    {
                        resetAbort(context);
                        context.WriteException(e);
                        exitCode = -1;
                    }
                    finally
                    {
                        resetAbort(context);
                    }
                    if (context.GetBool(xs.wait, false))
                    {
                        cout.WriteLine(XS.OutputType.Info, string.Format("Completed in {0} with exit code={1}. Press Enter to close...", w.Elapsed, exitCode));
                        Console.ReadLine();
                    }
                }
            return(exitCode);
        }
Beispiel #14
0
        /// <summary>
        /// 开启任务
        /// </summary>
        /// <param name="taskId"></param>
        public bool Start(int taskId)
        {
            var taskRuntime = TaskPoolManager.GetInstance().Get(taskId.ToString());
            if (taskRuntime != null)
            {
                throw new Exception("任务[" + taskRuntime.Task.TaskName + "]已在运行中");
            }

            taskRuntime = new NodeTaskRuntimeInfo();
            taskRuntime.TaskLock = new TaskLock();
            taskRuntime.Task = _Service.TaskService.GetTask(taskId);

            string localPath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\')
                                + "\\" + GlobalConfig.TaskDLLCacheDir
                                + "\\" + taskRuntime.Task.Id
                                + "\\" + taskRuntime.Task.TaskVersion.Id
                                + "\\" + taskRuntime.Task.TaskVersion.FileName;
            string installPath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\')
                                + "\\" + GlobalConfig.TaskDLLDir
                                + "\\" + taskRuntime.Task.Id;
            string sharePath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\')
                                + "\\" + GlobalConfig.TaskDLLShareDir;
            string mainClassPath = installPath + "\\" + taskRuntime.Task.TaskMainClassDLLName;

            IOHelper.DirMake(localPath);
            IOHelper.DirMake(installPath);
            File.WriteAllBytes(localPath, taskRuntime.Task.TaskVersion.ZipFile);
            CompressHelper.UnCompress(localPath, installPath);
            IOHelper.DirCopy(sharePath, installPath);

            try
            {
                var taskDLL = new AppDomainLoader<BaseTask>().Load(mainClassPath,
                            taskRuntime.Task.TaskMainClassNameSpace,
                            out taskRuntime.Domain);
                taskDLL.TaskRuntimeInfo = new TaskRuntimeInfo()
                {
                    TaskConnectString = GlobalConfig.TaskConnectString,
                    Task = new TaskManager.Model.Task()
                    {
                        Id = taskRuntime.Task.Id,
                        TaskName = taskRuntime.Task.TaskName,
                        Node_Id = taskRuntime.Task.Node.Id,
                        TaskCreateTime = taskRuntime.Task.TaskCreateTime,
                        TaskUpdateTime = taskRuntime.Task.TaskUpdateTime,
                        TaskLastStartTime = taskRuntime.Task.TaskLastStartTime,
                        TaskLastEndTime = taskRuntime.Task.TaskLastEndTime,
                        TaskLastErrorTime = taskRuntime.Task.TaskLastErrorTime,
                        TaskRunCount = taskRuntime.Task.TaskRunCount,
                        TaskErrorCount = taskRuntime.Task.TaskErrorCount,
                        TaskState = (int)taskRuntime.Task.TaskState,
                        TaskVersion_Id = taskRuntime.Task.TaskVersion.Id,
                        TaskConfiguration = taskRuntime.Task.TaskConfiguration,
                        TaskCron = taskRuntime.Task.TaskCron,
                        TaskMainClassDLLName = taskRuntime.Task.TaskMainClassDLLName,
                        TaskMainClassNameSpace = taskRuntime.Task.TaskMainClassNameSpace,
                        Creator_Id = taskRuntime.Task.Creator.Id,
                        CreateDate = taskRuntime.Task.CreateDate,
                        Remark = taskRuntime.Task.Remark
                    }
                };
                taskDLL.AppInfo = new TaskAppInfo();
                if (taskRuntime.Task.TaskConfiguration.IsNotNull())
                {
                    taskDLL.AppInfo = new JsonHelper().Deserialize<TaskAppInfo>(taskRuntime.Task.TaskConfiguration);
                }
                taskRuntime.TaskDLL = taskDLL;

                bool result = TaskPoolManager.GetInstance().Add(taskId.ToString(), taskRuntime);
                if (result)
                {
                    _Service.TaskService.UpdateTaskState(taskId, DataObject.Constants.TaskState.Running);
                }
                _Service.LogService.AddNodeLog(taskRuntime.Task.Node.Id,
                    "节点[" + taskRuntime.Task.Node.NodeName + "]开启任务[" + taskRuntime.Task.TaskName + "]成功!");
                return result;
            }
            catch (Exception ex)
            {
                Dispose(taskId, taskRuntime, true);
                throw ex;
            }
        }
        /// <summary>
        /// 任务的开启
        /// </summary>
        /// <param name="taskid"></param>
        /// <returns></returns>
        public bool Start(int taskid)
        {
            var taskruntimeinfo = TaskPoolManager.CreateInstance().Get(taskid.ToString());
            if (taskruntimeinfo != null)
            {
                throw new Exception("任务已在运行中");
            }

            taskruntimeinfo = new NodeTaskRuntimeInfo();
            taskruntimeinfo.TaskLock = new TaskLock();
            SqlHelper.ExcuteSql(GlobalConfig.TaskDataBaseConnectString, (c) =>
                {
                    tb_task_dal taskdal = new tb_task_dal();
                    taskruntimeinfo.TaskModel = taskdal.Get(c, taskid);
                    tb_version_dal versiondal = new tb_version_dal();
                    taskruntimeinfo.TaskVersionModel = versiondal.GetCurrentVersion(c, taskid, taskruntimeinfo.TaskModel.taskversion);
                });
            string filelocalcachepath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\"+GlobalConfig.TaskDllCompressFileCacheDir + @"\" + taskruntimeinfo.TaskModel.id + @"\" + taskruntimeinfo.TaskModel.taskversion + @"\" +
                taskruntimeinfo.TaskVersionModel.zipfilename;
            string fileinstallpath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\"+GlobalConfig.TaskDllDir + @"\" +  taskruntimeinfo.TaskModel.id ;
            string fileinstallmainclassdllpath = fileinstallpath + @"\" + taskruntimeinfo.TaskModel.taskmainclassdllfilename;
            string taskshareddlldir = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\" + GlobalConfig.TaskSharedDllsDir;
             
            XXF.Common.IOHelper.CreateDirectory(filelocalcachepath);
            XXF.Common.IOHelper.CreateDirectory(fileinstallpath);
            System.IO.File.WriteAllBytes(filelocalcachepath, taskruntimeinfo.TaskVersionModel.zipfile);

            CompressHelper.UnCompress(filelocalcachepath, fileinstallpath);
            //拷贝共享程序集
            XXF.Common.IOHelper.CopyDirectory(taskshareddlldir, fileinstallpath);
            try
            {
                var dlltask = new AppDomainLoader<BaseDllTask>().Load(fileinstallmainclassdllpath, taskruntimeinfo.TaskModel.taskmainclassnamespace, out taskruntimeinfo.Domain);
                var sdktaskmodel = new XXF.BaseService.TaskManager.model.tb_task_model();
                PropertyHelper.Copy(taskruntimeinfo.TaskModel, sdktaskmodel);
                dlltask.SystemRuntimeInfo = new TaskSystemRuntimeInfo()
                {
                    TaskConnectString = GlobalConfig.TaskDataBaseConnectString,
                    TaskModel = sdktaskmodel
                };

                dlltask.AppConfig = new TaskAppConfigInfo();
                if (!string.IsNullOrEmpty(taskruntimeinfo.TaskModel.taskappconfigjson))
                {
                    dlltask.AppConfig = new XXF.Serialization.JsonHelper().Deserialize<TaskAppConfigInfo>(taskruntimeinfo.TaskModel.taskappconfigjson);
                }
                taskruntimeinfo.DllTask = dlltask;
                bool r = TaskPoolManager.CreateInstance().Add(taskid.ToString(), taskruntimeinfo);
                SqlHelper.ExcuteSql(GlobalConfig.TaskDataBaseConnectString, (c) =>
                {
                    tb_task_dal taskdal = new tb_task_dal();
                    taskdal.UpdateTaskState(c, taskid, (int)EnumTaskState.Running);
                });
                LogHelper.AddTaskLog("节点开启任务成功", taskid);
                return r;
            }
            catch (Exception exp)
            {
                DisposeTask(taskid, taskruntimeinfo,true);
                throw exp;
            }
        }
Beispiel #16
0
        private void LoadTaskThreadMethod()
        {
            while (true)
            {
                lock (LoadTaskLockObj)
                {
                    var loadTaskResult = this._sdk.GetTasks(this._nodeId);
                    if (loadTaskResult.HasError)
                    {
                        this._taskLogger.Error("get task api error:{0}", loadTaskResult.ErrorMessage);
                        return;
                    }

                    //unload task
                    var unloadTaskIds = new List<string>();
                    foreach (var taskInfo in this._taskInfos)
                    {
                        if (!loadTaskResult.Data.Any(a => a.Id.Equals(taskInfo.Key)))
                        {
                            unloadTaskIds.Add(taskInfo.Key);
                        }
                    }
                    foreach (var unloadTaskId in unloadTaskIds)
                    {
                        var task = this._taskInfos[unloadTaskId];

                        _sched.PauseTrigger(task.Trigger.Key);
                        _sched.UnscheduleJob(task.Trigger.Key);
                        _sched.DeleteJob(task.JobDetail.Key);

                        TaskRuntimeInfo info = null;
                        if (!this._taskInfos.TryRemove(unloadTaskId, out info))
                        {
                            this._taskLogger.Error("Unload task fail, taskId:{0}", unloadTaskId);
                        }
                        else
                        {
                            try
                            {
                                AppDomain.Unload(info.AppDomain);

                                var taskFileUnzipFolderPath =
                                        ServiceFileHelper.GetTaskFileUnzipFolderPath(this._rootPath, unloadTaskId);
                                DirectoryAndFileHelper.DeleteFolder(taskFileUnzipFolderPath);
                            }
                            catch (Exception ex)
                            {
                                this._taskLogger.Error("卸载任务 {0} 异常:{1}", task.TaskInfo.Name, ex.Message);
                            }
                        }
                    }

                    //load task
                    foreach (var task in loadTaskResult.Data)
                    {
                        if (!this._taskInfos.ContainsKey(task.Id))
                        {
                            var taskDllFilePath = PrepareTaskFile(task);
                            if (string.IsNullOrEmpty(taskDllFilePath))
                            {
                                this._taskLogger.Error("PrepareTaskFile fail taskId:{0}", task.Id);
                                continue;
                            }

                            AppDomain domain = null;
                            BaseTask ta = null;
                            try
                            {
                                ta = new AppDomainLoader<BaseTask>().Load(taskDllFilePath, task.ClassName, out domain);
                            }
                            catch (Exception ex)
                            {
                                this._taskLogger.Fatal(string.Format("Load task AppDomain Exception:{0}", ex.Message));
                                continue;
                            }

                            IJobDetail job = new JobDetailImpl(task.Id, null, typeof(TaskJob));
                            ITrigger trigger = new CronTriggerImpl(task.Id, null, task.Cron);
                            _sched.ScheduleJob(job, trigger);

                            if (!this._taskInfos.TryAdd(task.Id, new TaskRuntimeInfo()
                            {
                                AppDomain = domain,
                                TaskInfo = task,
                                ExeTask = ta,
                                TmSdk = SdkFactory.CreateSdk(new SdkConfig(this._sdkHost)),
                                JobDetail = job,
                                Trigger = trigger,
                                Lock = new TaskLock()
                            }))
                            {
                                AppDomain.Unload(domain);

                                this._sched.PauseTrigger(trigger.Key);
                                this._sched.UnscheduleJob(trigger.Key);
                                this._sched.DeleteJob(job.Key);

                                var taskFileUnzipFolderPath =
                                    ServiceFileHelper.GetTaskFileUnzipFolderPath(this._rootPath, task.Id);
                                DirectoryAndFileHelper.DeleteFolder(taskFileUnzipFolderPath);

                                this._taskLogger.Error("add task fail, taskId:{0}", task.Id);
                            }
                        }
                    }
                }

                Thread.Sleep(1 * 60 * 1000);
            }
        }
Beispiel #17
0
        /// <summary>
        /// 任务的开启
        /// </summary>
        /// <param name="taskid"></param>
        /// <returns></returns>
        public bool Start(int taskid)
        {
            var taskruntimeinfo = TaskPoolManager.CreateInstance().Get(taskid.ToString());

            if (taskruntimeinfo != null)
            {
                throw new Exception("任务已在运行中");
            }

            taskruntimeinfo          = new NodeTaskRuntimeInfo();
            taskruntimeinfo.TaskLock = new TaskLock();
            SqlHelper.ExcuteSql(GlobalConfig.TaskDataBaseConnectString, (c) =>
            {
                tb_task_dal taskdal              = new tb_task_dal();
                taskruntimeinfo.TaskModel        = taskdal.Get(c, taskid);
                tb_version_dal versiondal        = new tb_version_dal();
                taskruntimeinfo.TaskVersionModel = versiondal.GetCurrentVersion(c, taskid, taskruntimeinfo.TaskModel.taskversion);
            });
            string filelocalcachepath = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\" + GlobalConfig.TaskDllCompressFileCacheDir + @"\" + taskruntimeinfo.TaskModel.id + @"\" + taskruntimeinfo.TaskModel.taskversion + @"\" +
                                        taskruntimeinfo.TaskVersionModel.zipfilename;
            string fileinstallpath             = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\" + GlobalConfig.TaskDllDir + @"\" + taskruntimeinfo.TaskModel.id;
            string fileinstallmainclassdllpath = fileinstallpath + @"\" + taskruntimeinfo.TaskModel.taskmainclassdllfilename;
            string taskshareddlldir            = AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\') + "\\" + GlobalConfig.TaskSharedDllsDir;

            BSF.Tool.IOHelper.CreateDirectory(filelocalcachepath);
            BSF.Tool.IOHelper.CreateDirectory(fileinstallpath);
            System.IO.File.WriteAllBytes(filelocalcachepath, taskruntimeinfo.TaskVersionModel.zipfile);

            CompressHelper.UnCompress(filelocalcachepath, fileinstallpath);
            //拷贝共享程序集
            BSF.Tool.IOHelper.CopyDirectory(taskshareddlldir, fileinstallpath);
            try
            {
                new TaskAssemblyRedirect().TryRebulidDll(fileinstallmainclassdllpath, taskruntimeinfo.TaskModel.taskmainclassnamespace);
                var dlltask      = new AppDomainLoader <BaseDllTask>().Load(fileinstallmainclassdllpath, taskruntimeinfo.TaskModel.taskmainclassnamespace, out taskruntimeinfo.Domain);
                var sdktaskmodel = new BSF.BaseService.TaskManager.Model.tb_task_model();
                PropertyHelper.Copy(taskruntimeinfo.TaskModel, sdktaskmodel);
                dlltask.SystemRuntimeInfo = new TaskSystemRuntimeInfo()
                {
                    TaskConnectString = GlobalConfig.TaskDataBaseConnectString,
                    TaskModel         = sdktaskmodel
                };
                //加载AppConfig配置
                var appconfig = new TaskAppConfigInfo();
                if (!string.IsNullOrEmpty(taskruntimeinfo.TaskModel.taskappconfigjson))
                {
                    appconfig = new BSF.Serialization.JsonProvider().Deserialize <TaskAppConfigInfo>(taskruntimeinfo.TaskModel.taskappconfigjson);
                }
                SqlHelper.ExcuteSql(GlobalConfig.TaskDataBaseConnectString, (c) =>
                {
                    tb_config_dal configdal = new tb_config_dal();
                    var cs = configdal.GetList(c);
                    foreach (var o in cs)
                    {
                        if (!appconfig.ContainsKey(o.configkey))
                        {
                            appconfig.Add(o.configkey, o.configvalue);
                        }
                    }
                });

                dlltask.AppConfig       = appconfig;
                taskruntimeinfo.DllTask = dlltask;
                bool r = TaskPoolManager.CreateInstance().Add(taskid.ToString(), taskruntimeinfo);
                SqlHelper.ExcuteSql(GlobalConfig.TaskDataBaseConnectString, (c) =>
                {
                    tb_task_dal taskdal = new tb_task_dal();
                    taskdal.UpdateTaskState(c, taskid, (int)EnumTaskState.Running);
                });
                LogHelper.AddTaskLog("节点开启任务成功", taskid);
                return(r);
            }
            catch (Exception exp)
            {
                DisposeTask(taskid, taskruntimeinfo, true);
                throw exp;
            }
        }