private void RunCommand(VsFileItem itemInView)
        {
            if (this.isRunning)
            {
                return;
            }

            this.isRunning               = true;
            this.model.CanRunAnalysis    = false;
            this.model.AnalysisIsRunning = true;
            try
            {
                var bw = new BackgroundWorker {
                    WorkerReportsProgress = true
                };

                bw.RunWorkerCompleted += delegate
                {
                    this.isRunning               = false;
                    this.model.CanRunAnalysis    = true;
                    this.model.AnalysisIsRunning = false;
                };

                bw.DoWork +=
                    delegate {
                    var commandIssues = PluginOperation.ExecuteCommand(itemInView);
                    Application.Current.Dispatcher.Invoke(
                        delegate
                    {
                        this.model.UpdateLocalIssues(this, new LocalAnalysisEventCommandAnalsysisComplete(itemInView, commandIssues));
                    });
                };

                bw.RunWorkerAsync();
            }
            catch (Exception ex)
            {
                this.notification.ReportMessage(new Message()
                {
                    Id = "PluginWrapper", Data = "Failed to Run Command : " + this.Name
                });
                this.notification.ReportException(ex);
            }
        }
        public void Run()
        {
            MQueryCommand.TryUpdatePluginTaskLastStartTime(Id, DateTime.UtcNow);
            if (!Directory.Exists(_pluginDirectiryPath))
            {
                MLogger.Error($"Directory not exists: {_pluginDirectiryPath}");
                return;
            }

            string pluginFileFullPath = Path.Combine(_pluginDirectiryPath, PluginFileName);

            if (!File.Exists(pluginFileFullPath))
            {
                MLogger.Error($"File not exists: {pluginFileFullPath}");
                return;
            }

            var res = PluginOperationAdapter.GetFromDll(pluginFileFullPath);

            if (!res.IsComplete)
            {
                MLogger.Error(res.Message);
            }

            try
            {
                PluginOperation pluginOperation = res.PluginOperationInstance;
                Assembly        pluginAssembly  = Assembly.Load(File.ReadAllBytes(pluginOperation.DllFullPath));
                Type            pluginOperationAttributesType = null;

                if (!string.IsNullOrEmpty(pluginOperation.AttributesTypeName))
                {
                    pluginOperationAttributesType = pluginAssembly.GetType(pluginOperation.AttributesTypeName);
                }

                Type pluginOperationType = pluginAssembly.GetType(pluginOperation.OperationTypeName);
                MagicUpdaterCommon.Abstract.Operation operation = null;
                string settingsJson = null;
                if (pluginOperationAttributesType != null)
                {
                    string pluginSettingsJsonFileFullPath = Path.Combine(_pluginDirectiryPath, $"{PluginFileName.Replace($"{Path.GetExtension(PluginFileName)}", "")}.json");

                    if (!File.Exists(pluginSettingsJsonFileFullPath))
                    {
                        MLogger.Error($"Missing settings json for plugin operation: {pluginSettingsJsonFileFullPath}");
                        return;
                    }

                    settingsJson = File.ReadAllText(pluginSettingsJsonFileFullPath);
                }

                if (pluginOperationType.GetConstructors()[0].GetParameters().Length == 2)
                {
                    operation = (MagicUpdaterCommon.Abstract.Operation)Activator.CreateInstance(pluginOperationType, 0, settingsJson);
                }
                else
                {
                    operation = (MagicUpdaterCommon.Abstract.Operation)Activator.CreateInstance(pluginOperationType, 0);
                }

                if (operation != null)
                {
                    operation.Run();
                }
                else
                {
                    MLogger.Error("Plugin operation instance is null!");
                }
            }
            catch (Exception ex)
            {
                MLogger.Error(ex.ToString());
            }

            MQueryCommand.TryUpdatePluginTaskLastEndTime(Id, DateTime.UtcNow);

            DateTime period = new DateTime(1889, 1, 1, 0, 0, 0);

            switch ((ShedulerTaskModes)Mode)
            {
            case ShedulerTaskModes.Once:
                MQueryCommand.TrySetPluginTaskEnabled(Id, false);

                period = new DateTime(1889, 1, 1, 0, 0, 0);
                break;

            case ShedulerTaskModes.Daily:
                period = DateTime.UtcNow.AddDays(1);
                break;

            case ShedulerTaskModes.Weekly:
                period = DateTime.UtcNow.AddDays(7);
                break;

            case ShedulerTaskModes.Monthly:
                period = DateTime.UtcNow.AddMonths(1);
                break;

            case ShedulerTaskModes.Hours:
                period = DateTime.UtcNow.AddHours(RepeatValue ?? 0);
                break;

            case ShedulerTaskModes.Minutes:
                period = DateTime.UtcNow.AddMinutes(RepeatValue ?? 0);
                break;
            }

            MQueryCommand.TryUpdatePluginTaskNextStartTime(Id, period);
        }
예제 #3
0
        public static async Task Main(string[] args)
        {
            // Parse the command line arguments
            PluginOperation operation = PluginOperation.List;
            string          lastArg = null, plugin = null, socketPath = Defaults.FullSocketPath;

            foreach (string arg in args)
            {
                if (lastArg == "-s" || lastArg == "--socket")
                {
                    socketPath = arg;
                }
                else if (lastArg == "install")
                {
                    operation = PluginOperation.Install;
                    plugin    = arg;
                }
                else if (lastArg == "start")
                {
                    operation = PluginOperation.Start;
                    plugin    = arg;
                }
                else if (lastArg == "set-data")
                {
                    operation = PluginOperation.SetData;
                    plugin    = arg;
                }
                else if (lastArg == "stop")
                {
                    operation = PluginOperation.Stop;
                    plugin    = arg;
                }
                else if (lastArg == "uninstall")
                {
                    operation = PluginOperation.Uninstall;
                    plugin    = arg;
                }
                else if (arg == "list")
                {
                    operation = PluginOperation.List;
                }
                else if (arg == "list-data")
                {
                    operation = PluginOperation.ListData;
                }
                else if (arg == "-h" || arg == "--help")
                {
                    Console.WriteLine("Available command line arguments:");
                    Console.WriteLine("list: List plugin status (default)");
                    Console.WriteLine("list-data: List plugin data");
                    Console.WriteLine("install <zipfile>: Install new ZIP bundle");
                    Console.WriteLine("start <id>: Start a plugin");
                    Console.WriteLine("set-data <id>:<key>=<value>: Set plugin data (JSON or text)");
                    Console.WriteLine("stop <id>: Stop a plugin");
                    Console.WriteLine("uninstall <id>: Uninstall a plugin");
                    Console.WriteLine("-s, --socket <socket>: UNIX socket to connect to");
                    Console.WriteLine("-h, --help: Display this help text");
                    return;
                }
                lastArg = arg;
            }

            // Create a new connection and connect to DuetControlServer
            using CommandConnection connection = new();
            await connection.Connect(socketPath);

            // Check what to do
            ObjectModel model;

            switch (operation)
            {
            case PluginOperation.List:
                model = await connection.GetObjectModel();

                if (model.Plugins.Count > 0)
                {
                    Console.WriteLine("{0,-24} {1,-16} {2,-16} {3,-24} {4,-24} {5,-12}", "Plugin", "Id", "Version", "Author", "License", "Status");
                    foreach (Plugin item in model.Plugins.Values)
                    {
                        if (item != null)
                        {
                            string pluginState = "n/a";
                            if (!string.IsNullOrEmpty(item.SbcExecutable))
                            {
                                pluginState = (item.Pid > 0) ? "Started" : "Stopped";
                            }
                            Console.WriteLine("{0,-24} {1,-16} {2,-16} {3,-24} {4,-24} {5,-12}", item.Name, item.Id, item.Version, item.Author, item.License, pluginState);
                        }
                    }
                }
                else
                {
                    Console.WriteLine("No plugins installed");
                }
                break;

            case PluginOperation.ListData:
                model = await connection.GetObjectModel();

                if (model.Plugins.Count > 0)
                {
                    foreach (Plugin item in model.Plugins.Values)
                    {
                        Console.WriteLine("Plugin {0}:", item.Id);
                        foreach (var kv in item.Data)
                        {
                            Console.WriteLine("{0} = {1}", kv.Key, JsonSerializer.Serialize(kv.Value, DuetAPI.Utility.JsonHelper.DefaultJsonOptions));
                        }
                        Console.WriteLine();
                    }
                }
                else
                {
                    Console.WriteLine("No plugins installed");
                }
                break;

            case PluginOperation.Install:
                try
                {
                    await connection.InstallPlugin(plugin);

                    Console.WriteLine("Plugin installed");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to install plugin: {0}", e.Message);
                }
                break;

            case PluginOperation.Start:
                try
                {
                    await connection.StartPlugin(plugin);

                    Console.WriteLine("Plugin started");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to start plugin: {0}", e.Message);
                }
                break;

            case PluginOperation.SetData:
                // Parse plugin argument in the format
                // <plugin>:<key>=<value>
                string pluginName = string.Empty, key = string.Empty, value = string.Empty;
                int    state = 0;
                foreach (char c in plugin)
                {
                    switch (state)
                    {
                    case 0:
                        if (c == ':')
                        {
                            state++;
                        }
                        else
                        {
                            pluginName += c;
                        }
                        break;

                    case 1:
                        if (c == '=')
                        {
                            state++;
                        }
                        else
                        {
                            key += c;
                        }
                        break;

                    case 2:
                        value += c;
                        break;
                    }
                }

                // Try to set the data
                try
                {
                    try
                    {
                        using JsonDocument json = JsonDocument.Parse(value);
                        await connection.SetPluginData(key, json.RootElement, pluginName);
                    }
                    catch (JsonException)
                    {
                        await connection.SetPluginData(key, value, pluginName);
                    }
                    Console.WriteLine("Plugin data set");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to set plugin data: {0}", e.Message);
                }
                break;

            case PluginOperation.Stop:
                try
                {
                    await connection.StopPlugin(plugin);

                    Console.WriteLine("Plugin stopped");
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to stop plugin: {0}", e.Message);
                }
                break;

            case PluginOperation.Uninstall:
                try
                {
                    await connection.UninstallPlugin(plugin);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Failed to uninstall plugin: {0}", e.Message);
                }
                break;
            }
        }