Exemple #1
0
        public void LoadExtension(string fileName)
        {
            if (!File.Exists(fileName))
            {
                return;
            }

            _fileName = fileName;

            Assembly assembly = LoadAssembly(fileName);

            if (!_loadedAssemblyList.ContainsKey(assembly.FullName))
            {
                _loadedAssemblyList.Add(assembly.FullName, assembly);
            }
            foreach (Type t in assembly.GetTypes())
            {
                if (t.GetInterface("IExtension") != null)
                {
                    IExtension extension = (IExtension)assembly.CreateInstance(t.FullName);
                    if (extension != null &&
                        ExtensionManager.GetInstance().GetExtensionByName(extension.GetExtensionName()) == null &&
                        !_extensionList.ContainsKey(extension.GetExtensionName()))
                    {
                        _extensionList.Add(extension.GetExtensionName(), extension);
                        EventRouter.GetInstance().FireEvent("Extension_Loaded", (object)extension, null);
                        Console.WriteLine(
                            $"[Info - {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}/ExtensionManager]:{extension.GetExtensionName()} has been loaded");
                    }
                }
            }
        }
Exemple #2
0
 public void Initialize()
 {
     foreach (var extension in _extensionList)
     {
         extension.Value.Initialize();
         EventRouter.GetInstance().FireEvent("Extension_Initialize", null, extension.Value.GetExtensionName());
     }
 }
Exemple #3
0
 public void SetEnvironment(ExtensionManager extensionManager, EventRouter eventRouter, CronTab cronTab, BaseStorage storage, string rootPath)
 {
     ExtensionManager.GetInstance(extensionManager);
     EventRouter.GetInstance(eventRouter);
     //AppDomain.MonitoringIsEnabled = true;
     AppDomain.CurrentDomain.AssemblyResolve += _currentAppDomain_AssemblyResolve;
     _loadedAssemblyList = new Dictionary <string, Assembly>();
     _extensionList      = new Dictionary <string, IExtension>();
     _metaAssemblyList   = new Dictionary <string, Assembly>();
     IOManager.SetDefaultDataStorage(storage);
     IOManager.SetRootPath(rootPath);
     CronTab.GetInstance(cronTab);
 }
Exemple #4
0
        public void WakeUp(object sender, object eventArgs)
        {
            DateTime now = DateTime.Now;

            if (_isWakeUp)
            {
                return;
            }
            _isWakeUp = true;
            try
            {
                foreach (var taskConfig in _taskConfig)
                {
                    bool isAllComplete = taskConfig.ThreadPool.TrueForAll(item => !item.IsAlive);
                    if (isAllComplete)
                    {
                        taskConfig.ThreadPool.Clear();
                    }
                    if (taskConfig.NextDateTime.HasValue && taskConfig.NextDateTime <= DateTime.Now)
                    {
                        string executionId = Common.MD5(Clock.GetTimeStamp(true) + taskConfig.TargetType.Name);
                        if (taskConfig.ThreadPool.Count > 0 && !taskConfig.TargetType.IsAsync)
                        {
                            continue;
                        }
                        taskConfig.LastRunTime = now;
                        TaskThread thread = taskConfig.TargetType.Run(executionId);
                        taskConfig.ThreadPool.Add(thread);
                        taskConfig.GoNext();
                    }
                }
            }
            catch (Exception ex)
            {
                EventRouter.GetInstance().FireEvent("Error_Occurred", "CronTab",
                                                    "Fatal error:" + ex.GetBaseException().Message + "\n\t" + ex.GetBaseException().StackTrace);
            }
            finally
            {
                _isWakeUp = false;
            }
        }
Exemple #5
0
        public TaskThread Run(string executionId)
        {
            TaskThread taskThread = new TaskThread(new Thread((o) =>
            {
                try
                {
                    Method.Invoke(executionId);
                }
                catch (Exception ex)
                {
                    EventRouter.GetInstance().FireEvent("Warn_Occurred", this,
                                                        $"Execute task {Method} failed: {(ex.InnerException == null ? ex.Message : ex.InnerException.Message)}\nStack trace:\n{ex.StackTrace}");
                }
            }), MaximumExecuteTime, executionId)
            {
                CreateTime = DateTime.Now
            };

            return(taskThread);
        }
        public void LoadExtension(string fileName, bool autoInitialize = false)
        {
            if (!File.Exists(fileName))
            {
                return;
            }

            string assemblyName = Path.GetFileName(fileName);

            if (!_isUseSeparateAppdomain && Array.Find(AppDomain.CurrentDomain.GetAssemblies(),
                                                       assembly => assembly.GetName().Name == Path.GetFileNameWithoutExtension(fileName)) != null)
            {
                Console.WriteLine(
                    $"[Warning - {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}/ExtensionManager]:An existing extension has been loaded in default appdomain.");
                return;
            }

            ExtensionDomain existExtensionDomain = _extensionDomainList.Find(ed => ed.AssemblyName == assemblyName);

            if (existExtensionDomain != null && _isUseSeparateAppdomain)
            {
                existExtensionDomain.Proxy.Uninitialize();
                _extensionDomainList.Remove(existExtensionDomain);
            }

            ExtensionProxy proxy;
            AppDomain      ownerDomain;

            if (_isUseSeparateAppdomain)
            {
                Evidence       evidence       = new Evidence();
                AppDomainSetup appDomainSetup = new AppDomainSetup();
                appDomainSetup.ShadowCopyFiles = "true";
                appDomainSetup.ApplicationBase = Environment.CurrentDirectory;
                appDomainSetup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
                ownerDomain = AppDomain.CreateDomain(fileName, evidence, appDomainSetup);

                Type type = typeof(ExtensionProxy);
                proxy =
                    (ExtensionProxy)ownerDomain.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName);
            }
            else
            {
                ownerDomain = AppDomain.CurrentDomain;
                proxy       = new ExtensionProxy();
            }

            proxy.SetEnvironment(ExtensionManager.GetInstance(), EventRouter.GetInstance(), CronTab.GetInstance(),
                                 IOManager.GetDefaultDataStorage(), IOManager.GetRootPath());
            proxy.LoadExtension(fileName);
            _extensionDomainList.Add(new ExtensionDomain()
            {
                Domain       = ownerDomain,
                Proxy        = proxy,
                AssemblyName = assemblyName,
                IsAbandoned  = false
            });
            if (autoInitialize)
            {
                proxy.Initialize();
            }
            if (existExtensionDomain != null && _isUseSeparateAppdomain)
            {
                AppDomain.Unload(existExtensionDomain.Domain);
            }
        }
Exemple #7
0
 public static void BroadcastShutdownCommand()
 {
     EventRouter.GetInstance().FireEvent("System_Shutdown", null, null);
 }
Exemple #8
0
        static void Main(string[] args)
        {
            if (args.Length < 1 || !Directory.Exists(args[0]))
            {
                Console.WriteLine("Root path is not valid!");
                Console.WriteLine("exiting...");
                Console.ReadKey();
                return;
            }

            if (!AppDomain.CurrentDomain.IsDefaultAppDomain())
            {
                var entryPoint      = Assembly.GetExecutingAssembly();
                var applicationName = entryPoint.GetName().Name;
                var setup           = new AppDomainSetup();
                setup.ApplicationName = applicationName;
                setup.ShadowCopyFiles = "true";

                AppDomain domain = AppDomain.CreateDomain(
                    applicationName,
                    AppDomain.CurrentDomain.Evidence,
                    setup);

                try
                {
                    domain.ExecuteAssembly(entryPoint.Location, args);
                }
                finally
                {
                    AppDomain.Unload(domain);
                }
            }
            else
            {
                Console.WriteLine($"{Info.ProductName} v{Info.CoverVersion} at {Info.HostOperationSystem}");
                Console.WriteLine(
                    $"[Info - {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}/System]:EventRouter has been loaded");
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
                EventRouter.GetInstance();
                IOManager.SetRootPath(args[0]);
                IOManager.SetDefaultDataStorage(new FileDBStorage());
                bool             isUseSeparateAppdomain = args.Length >= 3 && args[2] == "separated";
                ExtensionManager extensionManager       = ExtensionManager.GetInstance(isUseSeparateAppdomain);
                Console.WriteLine(
                    $"[Info - {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}/System]:Core has been loaded");
                Console.WriteLine(
                    $"[Info - {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}/ExtensionManager]:Starting load other extension");
                extensionManager.InitializeExtension();
                Console.WriteLine(
                    $"[Info - {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}/ExtensionManager]:Loading other extension finished");
                Clock clock = new Clock();
                Console.WriteLine(
                    $"[Info - {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}/System]:SystemClock has been loaded");
                if (args.Length >= 2 && args[1] == "daemon")
                {
                    while (true)
                    {
                        Thread.Sleep(30000);
                    }
                }
                else
                {
                    while (true)
                    {
                        string command = Console.ReadLine().ToLower();
                        switch (command)
                        {
                        case "run":
                            Console.Write("Extension:");
                            string extensionName = Console.ReadLine();
                            Console.Write("Method:");
                            string method = Console.ReadLine();
                            Console.Write("Param(splited with ,):");
                            string[]     param     = Console.ReadLine().Split(',');
                            IExtension   extension = ExtensionManager.GetInstance().GetExtensionByName(extensionName);
                            BindingFlags flags     = BindingFlags.InvokeMethod | BindingFlags.Instance |
                                                     BindingFlags.Public;
                            if (!(extension is SharedObject))
                            {
                                Console.WriteLine("No such extension");
                                continue;
                            }

                            (extension as SharedObject).Invoke(method, flags, param);
                            Console.WriteLine("Excuted");
                            break;

                        case "event":
                            Console.Write("EventName:");
                            string eventName = Console.ReadLine();
                            EventRouter.GetInstance().FireEvent(eventName, null, null);
                            break;

                        case "analyze":
                            Console.WriteLine(AppDomain.CurrentDomain.FriendlyName);
                            Console.WriteLine("\tAllocated Memory:" +
                                              AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize / 1024 +
                                              " KB");
                            Console.WriteLine("\t     Used Memory:" +
                                              AppDomain.CurrentDomain.MonitoringSurvivedMemorySize / 1024 + " KB");
                            foreach (var extensionProxy in ExtensionManager.GetInstance().GetExtensionList())
                            {
                                Console.WriteLine(extensionProxy.DomainName);
                                Console.WriteLine("\tAllocated Memory:" +
                                                  extensionProxy.TotalAllocatedMemorySize / 1024 + " KB");
                                Console.WriteLine("\t     Used Memory:" + extensionProxy.SurvivedMemorySize / 1024 +
                                                  " KB");
                            }
                            break;

                        case "exit":
                            IOManager.BroadcastShutdownCommand();
                            return;
                        }
                    }
                }
            }
        }
Exemple #9
0
 private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
 {
     EventRouter.GetInstance().FireEvent("Error_Occurred", sender, ((Exception)e.ExceptionObject).ToString());
 }
Exemple #10
0
 private CronTab()
 {
     EventRouter.GetInstance().ListenTo("Clock_Tick", new CallBackDelegate(WakeUp), true);
     _taskConfig = new List <TaskConfig>();
     _isWakeUp   = false;
 }