private void RunPythonAutomation(Job job, Automation automation, MachineCredential machineCredential, string mainScriptFilePath)
        {
            string pythonExecutable = GetPythonPath(machineCredential.UserName, "");
            string projectDir       = Path.GetDirectoryName(mainScriptFilePath);

            string commandsBatch = $"\"{pythonExecutable}\" -m pip install --upgrade pip && " +
                                   $"\"{pythonExecutable}\" -m pip install --user virtualenv && " +
                                   $"\"{pythonExecutable}\" -m venv \"{Path.Combine(projectDir, ".env3")}\" && " +
                                   $"\"{Path.Combine(projectDir, ".env3", "Scripts", "activate.bat")}\" && " +
                                   (File.Exists(Path.Combine(projectDir, "requirements.txt")) ? $"\"{pythonExecutable}\" -m pip install -r \"{Path.Combine(projectDir, "requirements.txt")}\" & " : "") +
                                   $"\"{pythonExecutable}\" \"{mainScriptFilePath}\" && " +
                                   $"deactivate";

            string batchFilePath = Path.Combine(projectDir, job.Id.ToString() + ".bat");

            File.WriteAllText(batchFilePath, commandsBatch);
            string logsFilePath = $"{mainScriptFilePath}.log";
            string cmdLine      = $"\"{batchFilePath}\" > \"{logsFilePath}\"";

            ProcessLauncher.PROCESS_INFORMATION procInfo;
            ProcessLauncher.LaunchProcess(cmdLine, machineCredential, out procInfo);

            var executionParams = GetJobExecutionParams(job, automation, mainScriptFilePath, null);

            SendLogsToServer(mainScriptFilePath, executionParams);

            return;
        }
        private void RunAutomation(Job job, Automation automation, MachineCredential machineCredential,
                                   string mainScriptFilePath, List <string> projectDependencies)
        {
            try
            {
                if (automation.AutomationEngine == "")
                {
                    automation.AutomationEngine = "OpenBots";
                }

                switch (automation.AutomationEngine.ToString())
                {
                case "OpenBots":
                    RunOpenBotsAutomation(job, automation, machineCredential, mainScriptFilePath, projectDependencies);
                    break;

                case "Python":
                    RunPythonAutomation(job, machineCredential, mainScriptFilePath);
                    break;

                default:
                    throw new NotImplementedException($"Specified execution engine \"{automation.AutomationEngine}\" is not implemented on the OpenBots Agent.");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private static bool GetSessionUserToken(MachineCredential machineCredential, ref IntPtr phUserToken, ref bool userLoggedOn)
        {
            var    bResult             = false;
            var    hImpersonationToken = IntPtr.Zero;
            string domainUsername      = $"{machineCredential.Domain}\\{machineCredential.UserName}";

            SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();

            sa.nLength = (uint)Marshal.SizeOf(sa);

            // Get Session Id of the active session.
            var activeSessionId = GetActiveUserSessionId(domainUsername);

            // If activeSessionId is invalid (No Active Session found for the Assigned User)
            if (activeSessionId == INVALID_SESSION_ID)
            {
                // Logon with the given user credentials (creating an active console session)
                bResult = userLoggedOn = LogonUser(machineCredential.UserName, machineCredential.Domain,
                                                   machineCredential.PasswordSecret, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref phUserToken);
            }
            else if (WTSQueryUserToken(activeSessionId, ref hImpersonationToken) != 0)
            {
                // Convert the impersonation token to a primary token
                bResult = DuplicateTokenEx(hImpersonationToken, 0, ref sa, (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation,
                                           (int)TOKEN_TYPE.TokenPrimary, ref phUserToken);

                CloseHandle(hImpersonationToken);
            }

            return(bResult);
        }
Beispiel #4
0
        private void RunPythonAutomation(string mainScriptFilePath, string projectName, ServerConnectionSettings settings)
        {
            string pythonExecutable = _executionManager.GetPythonPath(settings.UserName, "");
            string projectDir       = Path.GetDirectoryName(mainScriptFilePath);

            string commandsBatch = $"\"{pythonExecutable}\" -m pip install --upgrade pip && " +
                                   $"\"{pythonExecutable}\" -m pip install --user virtualenv && " +
                                   $"\"{pythonExecutable}\" -m venv \"{Path.Combine(projectDir, ".env3")}\" && " +
                                   $"\"{Path.Combine(projectDir, ".env3", "Scripts", "activate.bat")}\" && " +
                                   (File.Exists(Path.Combine(projectDir, "requirements.txt")) ? $"\"{pythonExecutable}\" -m pip install -r \"{Path.Combine(projectDir, "requirements.txt")}\" & " : "") +
                                   $"\"{pythonExecutable}\" \"{mainScriptFilePath}\" && " +
                                   $"deactivate";

            string batchFilePath = Path.Combine(projectDir, projectName + ".bat");

            File.WriteAllText(batchFilePath, commandsBatch);
            string logsFilePath = GetLogsFilePath(settings.LoggingValue1, AutomationType.Python, projectName);

            string cmdLine  = $"\"{batchFilePath}\" > \"{logsFilePath}\"";
            var    userInfo = new MachineCredential
            {
                Domain   = settings.DNSHost,
                UserName = settings.UserName
            };

            ProcessLauncher.PROCESS_INFORMATION procInfo;
            ProcessLauncher.LaunchProcess(cmdLine, userInfo, out procInfo);

            return;
        }
        private void RunOpenBotsAutomation(Job job, Automation automation, MachineCredential machineCredential, string mainScriptFilePath, List <string> projectDependencies)
        {
            var executionParams = GetExecutionParams(job, automation, mainScriptFilePath, projectDependencies);
            var executorPath    = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "OpenBots.Executor.exe").FirstOrDefault();
            var cmdLine         = $"\"{executorPath}\" \"{executionParams}\"";

            // launch the Executor
            ProcessLauncher.PROCESS_INFORMATION procInfo;
            ProcessLauncher.LaunchProcess(cmdLine, machineCredential, out procInfo);
            return;
        }
        private void RunPythonAutomation(Job job, MachineCredential machineCredential, string mainScriptFilePath)
        {
            string projectDir       = Path.GetDirectoryName(mainScriptFilePath);
            string assemblyPath     = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string pythonExecutable = GetPythonPath(machineCredential.UserName, "");
            string cmdLine          = $"powershell.exe -File \"{assemblyPath}\\Executors\\PythonExecutor.ps1\" \"{pythonExecutable}\" \"{projectDir}\" \"{mainScriptFilePath}\"";

            ProcessLauncher.PROCESS_INFORMATION procInfo;
            ProcessLauncher.LaunchProcess(cmdLine, machineCredential, out procInfo);

            return;
        }
Beispiel #7
0
        private void RunAttendedAutomation(string mainScriptFilePath, ServerConnectionSettings settings, List <string> projectDependencies)
        {
            var executionParams = GetExecutionParams(mainScriptFilePath, settings, projectDependencies);
            var userInfo        = new MachineCredential
            {
                Domain   = settings.DNSHost,
                UserName = settings.UserName
            };

            var executorPath = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "OpenBots.Executor.exe").FirstOrDefault();
            var cmdLine      = $"\"{executorPath}\" \"{executionParams}\"";

            // launch the Executor
            ProcessLauncher.PROCESS_INFORMATION procInfo;
            ProcessLauncher.LaunchProcess(cmdLine, userInfo, out procInfo);
        }
Beispiel #8
0
        /// <summary>
        /// Returns the credentialId
        /// </summary>
        /// <param name="credential"></param>
        /// <returns></returns>
        public string AddOrUpdateCredential(MachineCredential credential)
        {
            MachineCredential existingCredential = this.Credentials.FirstOrDefault(c => c.UserName.Equals(credential.UserName));

            if (existingCredential != null)
            {
                // Update the password and return the Id
                existingCredential.SetLoginPassword(credential.LoginPlainPassword);
                return(existingCredential.Id);
            }
            else
            {
                // Generate credential Id
                credential.Id = RandomUtils.GenerateString(6, (cId => !this.Credentials.Any(c => c.Id == cId)));
                this.Credentials.Add(credential);

                return(credential.Id);
            }
        }
        private void btnStepOneNext_Click(object sender, RoutedEventArgs e)
        {
            logger.Trace("btnStepOneNext Clicked.");

            string targetMachineName     = txtMachineName.Text?.Trim();
            string targetMachinePath     = txtTargetPath.Text?.Trim();
            string targetMachineUserName = txtTargetUserName.Text?.Trim();
            string targetMachinePassword = txtTargetUserPassword.Password?.Trim();

            if (string.IsNullOrEmpty(targetMachineName))
            {
                MessageBox.Show("机器名不可以为空,本机名请写LOCALHOST.", "提示");
                return;
            }

            MinerMachine clientMachine = new MinerMachine()
            {
                FullName = targetMachineName.ToUpper()
            };

            if (!clientMachine.IsLocalMachine() &&
                (string.IsNullOrEmpty(targetMachineName) || string.IsNullOrEmpty(targetMachinePassword)))
            {
                MessageBox.Show("请填写用于连接目标机器的用户名和密码信息", "提示");
                return;
            }

            if (!string.IsNullOrEmpty(targetMachineUserName) && !string.IsNullOrEmpty(targetMachinePassword))
            {
                MachineCredential credential = new MachineCredential();
                credential.UserName = targetMachineUserName.ToLower();
                credential.SetLoginPassword(targetMachinePassword);
                clientMachine.Credential = credential;
            }

            createdClient = new MinerClient(clientMachine, targetMachinePath);

            // Check whether this target is already in Miner Manager Client list

            // Check the machine name and path is accessasible
            StepOne_ValidateTargetMachine();
        }
Beispiel #10
0
        private void RunCSharpAutomation(string mainScriptFilePath, string projectName, ServerConnectionSettings settings)
        {
            string exePath = _executionManager.GetFullPathFromWindows("cscs.exe", settings.DNSHost, settings.UserName);

            if (exePath == null)
            {
                throw new Exception("CS-Script installation was not detected on the machine. Please perform the installation as outlined in the official documentation.");
            }

            var    logsFilePath = GetLogsFilePath(settings.LoggingValue1, AutomationType.CSScript, projectName);
            string cmdLine      = $"C:\\Windows\\System32\\cmd.exe /C cscs \"{mainScriptFilePath}\" > \"{logsFilePath}\"";
            var    userInfo     = new MachineCredential
            {
                Domain   = settings.DNSHost,
                UserName = settings.UserName
            };

            ProcessLauncher.PROCESS_INFORMATION procInfo;
            ProcessLauncher.LaunchProcess(cmdLine, userInfo, out procInfo);

            return;
        }
        private void RunCSharpAutomation(Job job, Automation automation, MachineCredential machineCredential, string mainScriptFilePath)
        {
            string exePath = GetFullPathFromWindows("cscs.exe", _connectionSettingsManager.ConnectionSettings.DNSHost,
                                                    _connectionSettingsManager.ConnectionSettings.UserName);

            if (exePath == null)
            {
                throw new Exception("CS-Script installation was not detected on the machine. Please perform the installation as outlined in the official documentation.");
            }

            var    logsFilePath = $"{mainScriptFilePath}.log";
            string cmdLine      = $"C:\\Windows\\System32\\cmd.exe /C cscs \"{mainScriptFilePath}\" > \"{logsFilePath}\"";

            ProcessLauncher.PROCESS_INFORMATION procInfo;
            ProcessLauncher.LaunchProcess(cmdLine, machineCredential, out procInfo);

            var executionParams = GetJobExecutionParams(job, automation, mainScriptFilePath, null);

            SendLogsToServer(mainScriptFilePath, executionParams);

            return;
        }
        private void RunAutomation(Job job, Automation automation, MachineCredential machineCredential,
                                   string mainScriptFilePath, string executionDirPath, List <string> projectDependencies)
        {
            try
            {
                if (automation.AutomationEngine == "")
                {
                    automation.AutomationEngine = "OpenBots";
                }

                var automationType = (AutomationType)Enum.Parse(typeof(AutomationType), automation.AutomationEngine);
                switch (automationType)
                {
                case AutomationType.OpenBots:
                    RunOpenBotsAutomation(job, automation, machineCredential, mainScriptFilePath, projectDependencies);
                    break;

                case AutomationType.Python:
                    RunPythonAutomation(job, automation, machineCredential, mainScriptFilePath);
                    break;

                case AutomationType.TagUI:
                    RunTagUIAutomation(job, automation, machineCredential, mainScriptFilePath, executionDirPath);
                    break;

                case AutomationType.CSScript:
                    RunCSharpAutomation(job, automation, machineCredential, mainScriptFilePath);
                    break;

                default:
                    throw new NotImplementedException($"Specified execution engine \"{automation.AutomationEngine}\" is not implemented on the OpenBots Agent.");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #13
0
        private void RunTagUIAutomation(string mainScriptFilePath, string projectName, ServerConnectionSettings settings, string executionDirPath)
        {
            string exePath = _executionManager.GetFullPathFromWindows("tagui", settings.DNSHost, settings.UserName);

            if (exePath == null)
            {
                throw new Exception("TagUI installation was not detected on the machine. Please perform the installation as outlined in the official documentation.");
            }

            // Create "tagui_logging" file for generating logs file
            var logFilePath = Path.Combine(Directory.GetParent(exePath).FullName, "tagui_logging");

            if (!File.Exists(logFilePath))
            {
                File.Create(Path.Combine(Directory.GetParent(exePath).FullName, "tagui_logging"));
            }

            // Copy Script Folder/Files to ".\tagui\flows" Directory
            var mainScriptPath = _executionManager.CopyTagUIAutomation(exePath, mainScriptFilePath, ref executionDirPath);
            var logsFilePath   = GetLogsFilePath(settings.LoggingValue1, AutomationType.TagUI, projectName);

            string cmdLine  = $"C:\\Windows\\System32\\cmd.exe /C tagui \"{mainScriptPath}\" > \"{logsFilePath}\"";
            var    userInfo = new MachineCredential
            {
                Domain   = settings.DNSHost,
                UserName = settings.UserName
            };

            ProcessLauncher.PROCESS_INFORMATION procInfo;
            ProcessLauncher.LaunchProcess(cmdLine, userInfo, out procInfo);

            // Delete TagUI Execution Directory
            Directory.Delete(executionDirPath, true);

            return;
        }
        private void RunTagUIAutomation(Job job, Automation automation, MachineCredential machineCredential,
                                        string mainScriptFilePath, string executionDirPath)
        {
            string exePath = GetFullPathFromWindows("tagui", _connectionSettingsManager.ConnectionSettings.DNSHost,
                                                    _connectionSettingsManager.ConnectionSettings.UserName);

            if (exePath == null)
            {
                throw new Exception("TagUI installation was not detected on the machine. Please perform the installation as outlined in the official documentation.");
            }

            // Create "tagui_logging" file for generating logs file
            var logFilePath = Path.Combine(Directory.GetParent(exePath).FullName, "tagui_logging");

            if (!File.Exists(logFilePath))
            {
                File.Create(Path.Combine(Directory.GetParent(exePath).FullName, "tagui_logging"));
            }

            // Copy Script Folder/Files to ".\tagui\flows" Directory
            var mainScriptPath = CopyTagUIAutomation(exePath, mainScriptFilePath, ref executionDirPath);

            string cmdLine = $"C:\\Windows\\System32\\cmd.exe /C tagui \"{mainScriptPath}\"";

            ProcessLauncher.PROCESS_INFORMATION procInfo;
            ProcessLauncher.LaunchProcess(cmdLine, machineCredential, out procInfo);

            var executionParams = GetJobExecutionParams(job, automation, mainScriptPath, null);

            SendLogsToServer(mainScriptPath, executionParams);

            // Delete TagUI Execution Directory
            Directory.Delete(executionDirPath, true);

            return;
        }
        /// <summary>
        /// Launches the given application with full admin rights, and in addition bypasses the Vista UAC prompt
        /// </summary>
        /// <param name="commandLine">The name of the application to launch</param>
        /// <param name="processInfo">Process information regarding the launched application that gets returned to the caller</param>
        /// <returns>Exit Code of the Process</returns>
        public static bool LaunchProcess(String commandLine, MachineCredential machineCredential, out PROCESS_INFORMATION processInfo)
        {
            uint    exitCode = 0;
            bool    userLoggedOn = false;
            Boolean pResult = false;
            IntPtr  hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero, envBlock = IntPtr.Zero;
            UInt32  pResultWait = WAIT_FAILED;

            processInfo = new PROCESS_INFORMATION();

            try
            {
                // obtain the currently active session id, then use it to generate an inpersonation token; every logged on user in the system has a unique session id
                bool sessionFound = GetSessionUserToken(machineCredential, ref hPToken, ref userLoggedOn);

                // If unable to find/create an Active User Session
                if (!sessionFound)
                {
                    throw new Exception($"Unable to Find/Create an Active User Session for provided Credential \"{machineCredential.Name}\" ");
                }

                // Security attibute structure used in DuplicateTokenEx and CreateProcessAsUser
                // I would prefer to not have to use a security attribute variable and to just
                // simply pass null and inherit (by default) the security attributes
                // of the existing token. However, in C# structures are value types and therefore
                // cannot be assigned the null value.
                SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
                sa.nLength = (uint)Marshal.SizeOf(sa);

                // By default CreateProcessAsUser creates a process on a non-interactive window station, meaning
                // the window station has a desktop that is invisible and the process is incapable of receiving
                // user input. To remedy this we set the lpDesktop parameter to indicate we want to enable user
                // interaction with the new process.
                STARTUPINFO si = new STARTUPINFO();
                si.cb        = (int)Marshal.SizeOf(si);
                si.lpDesktop = @"winsta0\default"; // interactive window station parameter; basically this indicates that the process created can display a GUI on the desktop

                // flags that specify the priority and creation method of the process
                int dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE | CREATE_UNICODE_ENVIRONMENT;

                if (!CreateEnvironmentBlock(ref envBlock, hPToken, false))
                {
                    throw new Exception("StartProcessAsCurrentUser: CreateEnvironmentBlock failed.");
                }

                // create a new process in the current user's logon session
                pResult = CreateProcessAsUser(hPToken,                  // client's access token
                                              null,                     // file to execute
                                              commandLine,              // command line
                                              ref sa,                   // pointer to process SECURITY_ATTRIBUTES
                                              ref sa,                   // pointer to thread SECURITY_ATTRIBUTES
                                              false,                    // handles are not inheritable
                                              dwCreationFlags,          // creation flags
                                              envBlock,                 // pointer to new environment block
                                              null,                     // name of current directory
                                              ref si,                   // pointer to STARTUPINFO structure
                                              out processInfo           // receives information about new process
                                              );

                if (!pResult)
                {
                    throw new Exception("CreateProcessAsUser error #" + Marshal.GetLastWin32Error());
                }

                pResultWait = WaitForSingleObject(processInfo.hProcess, INFINITE);
                if (pResultWait == WAIT_FAILED)
                {
                    throw new Exception("WaitForSingleObject error #" + Marshal.GetLastWin32Error());
                }

                GetExitCodeProcess(processInfo.hProcess, out exitCode);
            }
            finally
            {
                if (userLoggedOn)
                {
                    var activeConsoleSessionId = WTSGetActiveConsoleSessionId();
                    WTSLogoffSession(WTS_CURRENT_SERVER_HANDLE, (int)activeConsoleSessionId, true);
                }

                // invalidate the handles
                CloseHandle(hProcess);
                CloseHandle(hPToken);
                CloseHandle(hUserTokenDup);

                if (envBlock != IntPtr.Zero)
                {
                    DestroyEnvironmentBlock(envBlock);
                }
            }

            return(pResult); // return the result
        }
        private void ExecuteJob()
        {
            // Log Event
            _fileLogger.LogEvent("Job Execution", "Job execution started");

            // Peek Job
            var job = JobsQueueManager.PeekJob();

            // Log Event
            _fileLogger.LogEvent("Job Execution", "Attempt to fetch Automation Detail");

            // Get Automation Info
            var automation = AutomationsAPIManager.GetAutomation(_authAPIManager, job.AutomationId.ToString());

            // Update LastReportedMessage and LastReportedWork
            _agentHeartbeat.LastReportedMessage = "Job execution started";
            _agentHeartbeat.LastReportedWork    = automation.Name;

            // Log Event
            _fileLogger.LogEvent("Job Execution", "Attempt to download/retrieve Automation");

            string connectedUserName = _connectionSettingsManager.ConnectionSettings.UserName;
            string userDomainName    = _connectionSettingsManager.ConnectionSettings.DNSHost;

            // Download Automation and Extract Files and Return File Paths of ProjectConfig and MainScript
            automation.AutomationEngine = string.IsNullOrEmpty(automation.AutomationEngine) ? "OpenBots" : automation.AutomationEngine;
            string configFilePath;
            string executionDirPath;
            var    mainScriptFilePath = AutomationManager.DownloadAndExtractAutomation(_authAPIManager, automation, job.Id.ToString(), userDomainName, connectedUserName, out executionDirPath, out configFilePath);

            // Install Project Dependencies
            List <string> assembliesList = null;

            if (automation.AutomationEngine == "OpenBots")
            {
                NugetPackageManager.InstallProjectDependencies(configFilePath, userDomainName, connectedUserName);
                assembliesList = NugetPackageManager.LoadPackageAssemblies(configFilePath, userDomainName, connectedUserName);
            }

            // Log Event
            _fileLogger.LogEvent("Job Execution", "Attempt to update Job Status (Pre-execution)");

            // Create Automation Execution Log (Execution Started)
            _executionLog = ExecutionLogsAPIManager.CreateExecutionLog(_authAPIManager, new AutomationExecutionLog(
                                                                           null, false, null, DateTime.UtcNow, null, null, null, null, null, job.Id, job.AutomationId, job.AgentId,
                                                                           DateTime.UtcNow, null, null, null, "Job has started processing"));

            // Update Job Status (InProgress)
            JobsAPIManager.UpdateJobStatus(_authAPIManager, job.AgentId.ToString(), job.Id.ToString(),
                                           JobStatusType.InProgress, new JobErrorViewModel());

            // Update Job Start Time
            JobsAPIManager.UpdateJobPatch(_authAPIManager, job.Id.ToString(),
                                          new List <Operation>()
            {
                new Operation()
                {
                    Op = "replace", Path = "/startTime", Value = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffff'Z'")
                }
            });

            // Log Event
            _fileLogger.LogEvent("Job Execution", "Attempt to execute process");

            AgentViewModel    agent          = AgentsAPIManager.GetAgent(_authAPIManager, job.AgentId.ToString());
            var               userCredential = CredentialsAPIManager.GetCredentials(_authAPIManager, agent.CredentialId.ToString());
            MachineCredential credential     = new MachineCredential
            {
                Name           = userCredential.Name,
                Domain         = userCredential.Domain,
                UserName       = userCredential.UserName,
                PasswordSecret = userCredential.PasswordSecret
            };

            // Run Automation
            RunAutomation(job, automation, credential, mainScriptFilePath, executionDirPath, assembliesList);

            // Log Event
            _fileLogger.LogEvent("Job Execution", "Job execution completed");

            // Log Event
            _fileLogger.LogEvent("Job Execution", "Attempt to update Job Status (Post-execution)");

            // Update Job End Time
            JobsAPIManager.UpdateJobPatch(_authAPIManager, job.Id.ToString(),
                                          new List <Operation>()
            {
                new Operation()
                {
                    Op = "replace", Path = "/endTime", Value = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffff'Z'")
                },
                new Operation()
                {
                    Op = "replace", Path = "/isSuccessful", Value = true
                }
            });

            // Delete Job Directory
            try
            {
                Directory.Delete(executionDirPath, true);
            }
            catch (Exception)
            {
                // Appended 'Long Path Specifier' before the Directory Path
                Directory.Delete(@"\\?\" + executionDirPath, true);
            }

            // Update Automation Execution Log (Execution Finished)
            _executionLog.CompletedOn = DateTime.UtcNow;
            _executionLog.Status      = "Job has finished processing";
            ExecutionLogsAPIManager.UpdateExecutionLog(_authAPIManager, _executionLog);

            // Update Job Status (Completed)
            JobsAPIManager.UpdateJobStatus(_authAPIManager, job.AgentId.ToString(), job.Id.ToString(),
                                           JobStatusType.Completed, new JobErrorViewModel());

            _fileLogger.LogEvent("Job Execution", "Job status updated. Removing from queue.");

            // Dequeue the Job
            JobsQueueManager.DequeueJob();

            _isSuccessfulExecution = true;
            _agentHeartbeat.LastReportedMessage = "Job execution completed";
        }
Beispiel #17
0
        private void btnStepOneNext_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtTargetPath.Text))
            {
                MessageBox.Show("请输入安装矿机的有效路径", "提示");
                return;
            }

            deploymentFolderPath = txtTargetPath.Text.Trim();

            List <MinerMachine> machineList = dataGridMachines.GetAllMachines();

            if (machineList.Count == 0)
            {
                MessageBox.Show("请输入机器名称", "提示");
                return;
            }

            if ((machineList.Count > 1 || !machineList[0].IsLocalMachine()) &&
                string.IsNullOrWhiteSpace(txtTargetUserName.Text))
            {
                MessageBox.Show("请填写用于连接目标机器的用户名和密码信息", "提示");
                return;
            }

            if (!string.IsNullOrWhiteSpace(txtTargetUserName.Text))
            {
                string username = txtTargetUserName.Text.Trim();

                if (string.IsNullOrEmpty(txtTargetUserPassword.Password))
                {
                    MessageBox.Show("请输入用户的密码", "提示");
                    return;
                }

                string            password   = txtTargetUserPassword.Password.Trim();
                MachineCredential credential = new MachineCredential()
                {
                    UserName = username, LoginPlainPassword = password
                };

                // Consolidate the credentials
                foreach (MinerMachine m in machineList)
                {
                    m.Credential = credential;
                }
            }

            createdClients.Clear();
            for (int i = machineConnectivityCache.Count - 1; i >= 0; i--)
            {
                MachineConnectivity connectivity = machineConnectivityCache[i];
                if (!machineList.Any(m => m.FullName.Equals(connectivity.Machine.FullName)))
                {
                    machineConnectivityCache.RemoveAt(i);
                }
            }

            foreach (MinerMachine machine in machineList)
            {
                createdClients.Add(new MinerClient(machine, deploymentFolderPath));

                if (!machineConnectivityCache.Any(conn => conn.Machine.FullName.Equals(machine.FullName)))
                {
                    machineConnectivityCache.Add(new MachineConnectivity(machine));
                }
            }

            SwitchUIToStep(2);
        }