/// <summary>
        /// 任务的卸载
        /// </summary>
        /// <param name="taskid"></param>
        /// <returns></returns>
        public bool Uninstall(int taskid)
        {
            var taskruntimeinfo = TaskPoolManager.CreateInstance().Get(taskid.ToString());

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

            bool r;

            if (taskruntimeinfo.TaskModel.task_type == TaskType.Service.Code ||
                (taskruntimeinfo.TaskModel.task_type == TaskType.Task.Code && taskruntimeinfo.TaskModel.ServiceFlag == "cron"))
            {
                try


                {
                    KillProcess(taskid.ToString(), taskruntimeinfo);
                    if (taskruntimeinfo.TaskModel.task_type == TaskType.Service.Code &&
                        taskruntimeinfo.TaskModel.IsRegister == 1)
                    {
                        ConsulRegisteration item = taskruntimeinfo.RegistService;// _consulRegisterMgr.Parse(taskruntimeinfo.TaskModel);
                        _consulRegisterMgr.UnRegister(item);
                    }

                    r = true;
                }
                catch (Exception ex)
                {
                    r = false;
                }
                LogHelper.AddTaskLog("节点卸载任务成功", taskid);
            }
            else
            {
                r = DisposeTask(taskid, taskruntimeinfo, true);
            }

            SqlHelper.ExcuteSql(GlobalConfig.TaskDataBaseConnectString, (c) =>
            {
                tb_task_dal taskdal = new tb_task_dal();
                taskdal.UpdateTaskState(c, taskid, (int)EnumTaskState.Stop);
                //update proc id
                taskdal.UpdateProcess(c, taskid, -1);
            });
            LogHelper.AddTaskLog("节点卸载任务成功", taskid);
            return(r);
        }
Beispiel #2
0
        /// <summary>
        /// 任务的卸载
        /// </summary>
        /// <param name="taskid"></param>
        /// <returns></returns>
        public bool Uninstall(int taskid)
        {
            var taskruntimeinfo = TaskPoolManager.CreateInstance().Get(taskid.ToString());

            if (taskruntimeinfo == null)
            {
                throw new Exception("任务不在运行中");
            }
            var r = DisposeTask(taskid, taskruntimeinfo, true);

            SqlHelper.ExcuteSql(GlobalConfig.TaskDataBaseConnectString, (c) =>
            {
                tb_task_dal taskdal = new tb_task_dal();
                taskdal.UpdateTaskState(c, taskid, (int)EnumTaskState.Stop);
            });
            LogHelper.AddTaskLog("节点卸载任务成功", taskid);
            return(r);
        }
        private static bool StartProcess(int taskid, NodeTaskRuntimeInfo taskruntimeinfo, Process result)
        {
            taskruntimeinfo.Process = result;

            /*  AppDomain.CurrentDomain.DomainUnload += (s, e) =>
             *      {
             *          result.Kill();
             *          result.WaitForExit();
             *      };
             *      AppDomain.CurrentDomain.ProcessExit += (s, e) =>
             *      {
             *          result.Kill();
             *          result.WaitForExit();
             *      };
             *      AppDomain.CurrentDomain.UnhandledException += (s, e) =>
             *      {
             *          result.Kill();
             *          result.WaitForExit();
             *      };
             */
            //  Task a = Task.Factory.StartNew(() =>
            // {

            bool isStart = result.Start();

            ChildProcessTracker.AddProcess(result);



            Task.Factory.StartNew(() =>
            {
                while (!result.StandardOutput.EndOfStream)
                {
                    string line = result.StandardOutput.ReadLine();
                    // do something with line
                    LogHelper.AddTaskLog(line, taskid);
                }
            });
            bool r = TaskPoolManager.CreateInstance().AddInstance(taskid.ToString(), taskruntimeinfo);

            return(r);
        }
        public override Process StartProcess()
        {
            ProcessStartupParam parm = StartupParam;
            //
            //  string args= $" -jar {parm.FileName} --config {parm.Config} " ;

            string url = parm.AppConfig["service_url"];
            Uri    uri = null;

            try
            {
                uri = new Uri(url);
            }
            catch
            {
                string err = $"{url}不是正确的格式";
                LogHelper.AddTaskLog(err, parm.TaskModel.id);
                throw new Exception(err);
            }


            string args     = $" -jar {parm.FileName} --server.port={uri.Port} ";
            string fileName = GlobalConfig.JavaPath + @"\java ";

            LogHelper.AddTaskLog($"start:{fileName} {args}", parm.TaskModel.id);

            var result = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = fileName, //fileinstallmainclassdllpath,

                    Arguments              = args,
                    UseShellExecute        = false,
                    WorkingDirectory       = parm.WorkDir,
                    RedirectStandardOutput = true,
                    CreateNoWindow         = true,
                }
            };

            return(result);
        }
        public bool Run(int taskid)
        {
            var taskruntimeinfo = TaskPoolManager.CreateInstance().Get(taskid.ToString());

            if (taskruntimeinfo == null)
            {
                throw new Exception("任务不在运行中");
            }
            try
            {
                taskruntimeinfo.DllTask.TryRun();
                LogHelper.AddTaskLog("任务执行成功", taskid);
                return(true);
            }
            catch (Exception ex)
            {
                LogHelper.AddTaskError("任务执行失败", taskid, ex);

                return(false);
            }
        }
        public override Process StartProcess()
        {
            ProcessStartupParam param = StartupParam;

            XXF.Common.IOHelper.CopyDirectory(GlobalConfig.CronShell, param.WorkDir);
            TaskSystemRuntimeInfo info = new TaskSystemRuntimeInfo()
            {
                TaskModel         = new tb_task_model(),
                TaskConnectString = param.TaskDbConnection
            };

            PropertyHelper.Copy(param.TaskModel, info.TaskModel);
            byte[] bytes   = Encoding.Default.GetBytes(info.ToJson());
            string jobData = Convert.ToBase64String(bytes);
            string args    = $" --cron \"{param.Cron}\" " +
                             $" --dll {param.FileName}" +
                             $" --name_space {param.NameSpace} " +
                             $" --config {param.Config} " +
                             $" --job_data {jobData}";

            LogHelper.AddTaskLog($"args:{args}", param.TaskModel.id);
            var result = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = param.WorkDir + @"\" + "FastFish.Cron.exe ", //fileinstallmainclassdllpath,

                    Arguments              = args,
                    UseShellExecute        = false,
                    WorkingDirectory       = param.WorkDir,
                    RedirectStandardOutput = true,
                    CreateNoWindow         = true,
                }
            };

            return(result);
        }
Beispiel #7
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;
            }
        }
        /// <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;
                    }
                }
            }
        }
        private bool StartTaskProcess(int taskid, NodeTaskRuntimeInfo taskruntimeinfo, string
                                      fileinstallmainclassdllpath, string fileinstallpath, string jsonConfig,
                                      string assemblyVersion)
        {
            bool is_module = taskruntimeinfo.TaskModel.IsModule;

            //当
            //
            try
            {
                Process result;

                string flag = taskruntimeinfo.TaskModel.ServiceFlag;



                var startupParam = new ProcessStartupParam()
                {
                    Flag             = flag,
                    FileName         = fileinstallmainclassdllpath,
                    Config           = jsonConfig,
                    WorkDir          = fileinstallpath,
                    Cron             = taskruntimeinfo.TaskModel.taskcron,
                    NameSpace        = taskruntimeinfo.TaskModel.taskmainclassnamespace,
                    TaskDbConnection = GlobalConfig.TaskDataBaseConnectString,
                    TaskModel        = taskruntimeinfo.TaskModel
                };

                result = ProcessStart.GetInstance().Load(startupParam);



                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);
                    }
                }
            });
            //

            LogHelper.AddTaskLog("节点开启任务成功", taskid);
            return(r);
        }