Ejemplo n.º 1
0
        private async Task CollectResult(ProcessExecutionResult runResult)
        {
            if (!_waitedForExit && !runResult.TimedOut)
            {
                // mlaunch couldn't wait for exit for some reason. Let's assume the app exits when the test listener completes.
                _mainLog.WriteLine("Waiting for listener to complete, since mlaunch won't tell.");
                if (!await _listener.CompletionTask.TimeoutAfter(_timeout - _timeoutWatch.Elapsed))
                {
                    runResult.TimedOut = true;
                }
            }

            if (runResult.TimedOut)
            {
                _timedout = true;
                Success   = false;
                _mainLog.WriteLine(TimeoutMessage, _timeout.TotalMinutes);
            }
            else if (runResult.Succeeded)
            {
                _mainLog.WriteLine(CompletionMessage);
                Success = true;
            }
            else
            {
                _mainLog.WriteLine(FailureMessage);
                Success = false;
            }
        }
Ejemplo n.º 2
0
        public static ProcessExecutionResult ExecuteProcess(string workingDirectory, string filepath, string arguments)
        {
            ProcessExecutionResult result = new ProcessExecutionResult();
            Process process = new Process();

            process.StartInfo.FileName         = filepath;
            process.StartInfo.Arguments        = arguments;
            process.StartInfo.WorkingDirectory = workingDirectory;

            process.StartInfo.RedirectStandardError  = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute        = false;



            StringBuilder   testLogOut = new StringBuilder();
            StringBuilder   testLogErr = new StringBuilder();
            ProcessListener listen     = new ProcessListener(process);

            listen.StdOutNewLineReady += ((obj) => testLogOut.AppendLine("stdout:" + obj));             // Log StdOut
            listen.StdErrNewLineReady += ((obj) => testLogErr.AppendLine("stderror:" + obj));           // Log StdError

            process.Start();
            listen.Begin();
            process.WaitForExit();

            result.StandardError  = testLogErr.ToString();
            result.StandardOutput = testLogOut.ToString();

            listen.Dispose();
            process.Dispose();

            return(result);
        }
        public ProcessExecutionResult Execute(string fileName, string inputData, int timeLimit, int memoryLimit)
        {
            var process = new DifferentUserProcessExecutor(fileName, Environment.UserDomainName, UserName, Password);

            process.SetTextToWrite(inputData);

            var executorInfo = process.Start(timeLimit, memoryLimit);

            var result = new ProcessExecutionResult
            {
                ReceivedOutput          = executorInfo.StandardOutputContent,
                ErrorOutput             = executorInfo.StandardErrorContent,
                ExitCode                = process.Process.ExitCode,
                Type                    = ProcessExecutionResultType.Success,
                TimeWorked              = process.Process.ExitTime - process.Process.StartTime,
                MemoryUsed              = executorInfo.MaxMemoryUsed,
                PrivilegedProcessorTime = process.Process.PrivilegedProcessorTime,
                UserProcessorTime       = process.Process.UserProcessorTime,
            };

            if (executorInfo.ProcessKilledBecauseOfTimeLimit)
            {
                result.Type = ProcessExecutionResultType.TimeLimit;
            }

            if (!string.IsNullOrEmpty(executorInfo.StandardErrorContent))
            {
                result.Type = ProcessExecutionResultType.RunTimeError;
            }

            return(result);
        }
        public IProcessResponse <ImageConfig> Process(ProcessExecutionResult response)
        {
            if (string.IsNullOrEmpty(response.StdOut))
            {
                Response = response.ToResponse(false, "Empty response", new ImageConfig());
                return(this);
            }

            if (response.ExitCode != 0)
            {
                Response = response.ToErrorResponse(new ImageConfig());
                return(this);
            }


            var arr = response.StdOutAsArry;
            var sb  = new StringBuilder();

            for (var i = 1; i < arr.Length - 1; i++)
            {
                sb.AppendLine(arr[i]);
            }

            var container = sb.ToString();

            Response = response.ToResponse(true, string.Empty, JsonConvert.DeserializeObject <ImageConfig>(container));
            return(this);
        }
Ejemplo n.º 5
0
        public static ProcessExecutionResult ExecuteProcess(string workingDirectory, string filepath, string arguments)
        {
            ProcessExecutionResult result = new ProcessExecutionResult();
            Process process = new Process();
            process.StartInfo.FileName = filepath;
            process.StartInfo.Arguments = arguments;
            process.StartInfo.WorkingDirectory = workingDirectory;

            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;

            StringBuilder testLogOut = new StringBuilder();
            StringBuilder testLogErr = new StringBuilder();
            ProcessListener listen = new ProcessListener(process);
            listen.StdOutNewLineReady += ((obj) => testLogOut.AppendLine("stdout:" + obj)); // Log StdOut
            listen.StdErrNewLineReady += ((obj) => testLogErr.AppendLine("stderror:" + obj)); // Log StdError

            process.Start();
            listen.Begin();
            process.WaitForExit();

            result.StandardError = testLogErr.ToString();
            result.StandardOutput = testLogOut.ToString();

            listen.Dispose();
            process.Dispose();

            return result;
        }
Ejemplo n.º 6
0
        public IProcessResponse <Container> Process(ProcessExecutionResult response)
        {
            if (string.IsNullOrEmpty(response.StdOut))
            {
                Response = response.ToResponse(false, "Empty response", new Container());
                return(this);
            }

            if (response.ExitCode != 0)
            {
                Response = response.ToErrorResponse(new Container());
                return(this);
            }


            var arr = response.StdOutAsArry;
            var sb  = new StringBuilder();

            for (var i = 1; i < arr.Length - 1; i++)
            {
                sb.AppendLine(arr[i]);
            }

            var container = sb.ToString();
            var obj       = JsonConvert.DeserializeObject <Container>(container);

            obj.Name = TrimIfBeginsWithSlash(obj.Name);

            Response = response.ToResponse(true, string.Empty, obj);
            return(this);
        }
Ejemplo n.º 7
0
 public IProcessResponse <string> Process(ProcessExecutionResult response)
 {
     Response = response.ExitCode != 0
 ? response.ToErrorResponse(string.Empty)
 : response.ToResponse(true, string.Empty, string.Empty);
     return(this);
 }
        private static void DisplayError(Exception ex, ProcessExecutionResult status)
        {
            IVsOutputWindowPane outputPane = Package.GetGlobalService(typeof(SVsGeneralOutputWindowPane)) as IVsOutputWindowPane;

            outputPane.Activate();

            if (status == ProcessExecutionResult.AuthDenied)
            {
                outputPane.OutputString("Visual Studio restart operation was cancelled by the user." + Environment.NewLine);
            }
            else
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("An exceptions has been trown while trying to start an elevated Visual Studio, see details below.");
                sb.AppendLine(ex.ToString());

                string diagnostics = sb.ToString();

                outputPane.OutputString(diagnostics);
                IVsActivityLog log = Package.GetGlobalService(typeof(SVsActivityLog)) as IVsActivityLog;
                log.LogEntry((uint)__ACTIVITYLOG_ENTRYTYPE.ALE_ERROR, "MidnightDevelopers.VsRestarter", diagnostics);
            }

            //EnvDTE.OutputWindow.OutputWindow.Parent.Activate();
        }
        private void ProcessTests(
            ProcessExecutionResult processExecutionResult,
            ExecutionContext executionContext,
            ExecutionResult result)
        {
            var jsonResult = JsonExecutionResult.Parse(processExecutionResult.ReceivedOutput, true, true);

            var index = 0;

            result.TestResults = new List <TestResult>();
            foreach (var test in executionContext.Tests)
            {
                var testResult = new TestResult
                {
                    Id         = test.Id,
                    TimeUsed   = (int)processExecutionResult.TimeWorked.TotalMilliseconds,
                    MemoryUsed = (int)processExecutionResult.MemoryUsed,
                };

                if (jsonResult.PassingTestsIndexes.Contains(index))
                {
                    testResult.ResultType = TestRunResultType.CorrectAnswer;
                }
                else
                {
                    testResult.ResultType     = TestRunResultType.WrongAnswer;
                    testResult.CheckerDetails = new CheckerDetails {
                        Comment = "Test failed."
                    };
                }

                result.TestResults.Add(testResult);
                index++;
            }
        }
Ejemplo n.º 10
0
        public IProcessResponse <IDictionary <string, string> > Process(ProcessExecutionResult response)
        {
            var dict = new Dictionary <string, string>();

            if (string.IsNullOrEmpty(response.StdOut))
            {
                Response = response.ToResponse(false, "No data", (IDictionary <string, string>)dict);
                return(this);
            }

            var lines = response.StdOutAsArry;

            foreach (var line in lines)
            {
                if (line.StartsWith("export") || line.StartsWith("SET "))
                {
                    var idx   = line.StartsWith("SET ") ? 4 : 8;
                    var nv    = line.Substring(idx, line.Length - idx).Split('=');
                    var key   = nv[0].Trim();
                    var value = nv[1].Trim();

                    dict.Add(key, 4 == idx ? value : value.Substring(1, value.Length - 2));
                }
            }

            Response = response.ToResponse(true, string.Empty, (IDictionary <string, string>)dict);
            return(this);
        }
Ejemplo n.º 11
0
        protected TestResult GetTestResult(
            ProcessExecutionResult processExecutionResult,
            TestContext test,
            IChecker checker)
        {
            var message = "Failing tests are not captured correctly. Please contact an Administrator.";

            var errorMatch      = ErrorsInTestsRegex.Match(processExecutionResult.ReceivedOutput);
            var failedTestMatch = FailedTestsRegex.Match(processExecutionResult.ReceivedOutput);

            if (errorMatch.Success)
            {
                processExecutionResult.ErrorOutput = errorMatch.Groups[1].Value;
                processExecutionResult.Type        = ProcessExecutionResultType.RunTimeError;
            }
            else if (failedTestMatch.Success)
            {
                message = failedTestMatch.Groups[1].Value;
            }
            else if (SuccessTestsRegex.IsMatch(processExecutionResult.ReceivedOutput))
            {
                message = TestPassedMessage;
            }

            var testResult = this.CheckAndGetTestResult(
                test,
                processExecutionResult,
                checker,
                message);

            return(testResult);
        }
        public IProcessResponse <IList <DockerImageRowResponse> > Process(ProcessExecutionResult response)
        {
            if (response.ExitCode != 0)
            {
                Response = response.ToErrorResponse((IList <DockerImageRowResponse>) new List <DockerImageRowResponse>());
                return(this);
            }

            var list = new List <DockerImageRowResponse>();

            foreach (var row in response.StdOutAsArry)
            {
                var items = row.Split(';');
                if (items.Length != 3)
                {
                    continue;
                }

                list.Add(new DockerImageRowResponse
                {
                    Id   = items[0].ToPlainId(),
                    Name = items[1],
                    Tags = new[] { items[2] }
                });
            }

            Response = response.ToResponse(true, string.Empty, (IList <DockerImageRowResponse>)list);
            return(this);
        }
Ejemplo n.º 13
0
        public IProcessResponse <IList <StackPsResponse> > Process(ProcessExecutionResult response)
        {
            var list = new List <StackPsResponse>();
            var rows = response.StdOutAsArry;

            if (rows.Length > 0)
            {
                list.AddRange(from row in rows
                              select row.Split(';')
                              into s
                              where s.Length == 3
                              select new StackPsResponse
                {
                    Id           = s[0],
                    Stack        = s[1].Split('_')[0],
                    Name         = s[1].Split('_')[1],
                    Image        = s[2].Split(':')[0],
                    ImageVersion = s[2].Split(':')[1],
                    Node         = s[3],
                    DesiredState = s[4],
                    CurrentState = s[5],
                    Error        = s[6] ?? string.Empty,
                    Ports        = s[7] ?? string.Empty
                });
            }

            Response = response.ToResponse(true, string.Empty, (IList <StackPsResponse>)list);
            return(this);
        }
        public IProcessResponse <MachineConfiguration> Process(ProcessExecutionResult response)
        {
            if (string.IsNullOrEmpty(response.StdOut))
            {
                Response = response.ToResponse(false, "No response",
                                               new MachineConfiguration {
                    AuthConfig = new MachineAuthConfig()
                });
                return(this);
            }

            var j = JObject.Parse(response.StdOut);

            var str        = j["HostOptions"]["AuthOptions"].ToString();
            var ip         = j["Driver"]["IPAddress"].Value <string>();
            var authConfig = JsonConvert.DeserializeObject <MachineAuthConfig>(str);

            var config = new MachineConfiguration
            {
                AuthConfig    = authConfig,
                IpAddress     = string.IsNullOrEmpty(ip) ? IPAddress.None : IPAddress.Parse(ip),
                DriverName    = j["DriverName"].Value <string>(),
                MemorySizeMb  = j["Driver"]["Memory"].Value <int>(),
                Name          = j["Name"].Value <string>(),
                RequireTls    = j["HostOptions"]["EngineOptions"]["TlsVerify"].Value <bool>(),
                StorageSizeMb = j["Driver"]["DiskSize"].Value <int>(),
                CpuCount      = j["Driver"]["CPU"].Value <int>(),
                StorePath     = j["Driver"]["StorePath"].Value <string>()
            };

            Response = response.ToResponse(true, string.Empty, config);
            return(this);
        }
Ejemplo n.º 15
0
        protected TaskInfo StartMemorySamplingThread(
            IDisposable process,
            ProcessExecutionResult result)
        {
            var peakWorkingSetSize = default(long);

            var memorySamplingRunInBackgroundInfo = this.TasksService.RunWithInterval(
                MemoryIntervalBetweenTwoMemoryConsumptionRequests,
                () =>
            {
                switch (process)
                {
                case RestrictedProcess restrictedProcess:
                    {
                        peakWorkingSetSize = restrictedProcess.PeakWorkingSetSize;
                        break;
                    }

                case System.Diagnostics.Process systemProcess:
                    {
                        if (systemProcess.HasExited)
                        {
                            return;
                        }

                        peakWorkingSetSize = systemProcess.PeakWorkingSet64;
                        break;
                    }
                }

                result.MemoryUsed = Math.Max(result.MemoryUsed, peakWorkingSetSize);
            });

            return(memorySamplingRunInBackgroundInfo);
        }
Ejemplo n.º 16
0
        private SetupResult ProcessDeviceErrorCode(ProcessExecutionResult status)
        {
            if (IsHealthyAndRunning(status))
            {
                return(SetupResult.Success);
            }

            if (IsDriverUpdateRequired(status))
            {
                _tapInstallRunner.Update();
                return(SetupResult.Success);
            }

            if (IsDriverReinstallationRequired(status) && IsPcRestartRequired(status))
            {
                _logger.Log("TapAdapterInstaller: Driver is reinstalling and requesting restart.");
                _tapInstallRunner.Reinstall();

                return(SetupResult.RestartRequired);
            }

            if (IsDriverReinstallationRequired(status))
            {
                _logger.Log("TapAdapterInstaller: Driver is reinstalling.");
                _tapInstallRunner.Reinstall();

                return(SetupResult.Success);
            }

            _logger.Log($"TapAdapterInstaller: Installation failed. Status: {status}");
            return(SetupResult.Failure);
        }
Ejemplo n.º 17
0
        protected override IExecutionResult <TestResult> ExecuteAgainstTestsInput(
            IExecutionContext <TestsInputModel> executionContext)
        {
            var result = new ExecutionResult <TestResult>
            {
                IsCompiledSuccessfully = true
            };

            var processExecutionResult = new ProcessExecutionResult
            {
                Type           = ProcessExecutionResultType.Success,
                ReceivedOutput = executionContext.Code
            };

            var checker = executionContext.Input.GetChecker();

            foreach (var test in executionContext.Input.Tests)
            {
                var testResult = this.ExecuteAndCheckTest(
                    test,
                    processExecutionResult,
                    checker,
                    processExecutionResult.ReceivedOutput);

                result.Results.Add(testResult);
            }

            return(result);
        }
        private static void UpdateExecutionTime(string timeMeasurementFilePath, ProcessExecutionResult processExecutionResult, int timeLimit)
        {
            if (File.Exists(timeMeasurementFilePath))
            {
                long timeInNanoseconds;
                var  timeMeasurementFileContent = File.ReadAllText(timeMeasurementFilePath);
                if (long.TryParse(timeMeasurementFileContent, out timeInNanoseconds))
                {
                    processExecutionResult.TimeWorked = TimeSpan.FromMilliseconds((double)timeInNanoseconds / 1000000);

                    if (processExecutionResult.Type == ProcessExecutionResultType.TimeLimit &&
                        processExecutionResult.TimeWorked.TotalMilliseconds <= timeLimit)
                    {
                        // The time from the time measurement file is under the time limit
                        processExecutionResult.Type = ProcessExecutionResultType.Success;
                    }
                    else if (processExecutionResult.Type == ProcessExecutionResultType.Success &&
                             processExecutionResult.TimeWorked.TotalMilliseconds > timeLimit)
                    {
                        processExecutionResult.Type = ProcessExecutionResultType.TimeLimit;
                    }
                }

                File.Delete(timeMeasurementFilePath);
            }
        }
Ejemplo n.º 19
0
        public IProcessResponse <string> Process(ProcessExecutionResult response)
        {
            var success = response.ExitCode == 0;

            Response = response.ToResponse(success, response.StdErr, $"ExitCode={response.ExitCode}");

            return(this);
        }
Ejemplo n.º 20
0
        public IProcessResponse <IList <NetworkRow> > Process(ProcessExecutionResult response)
        {
            if (response.ExitCode != 0)
            {
                Response = response.ToErrorResponse((IList <NetworkRow>) new List <NetworkRow>());
                return(this);
            }

            if (string.IsNullOrEmpty(response.StdOut))
            {
                Response = response.ToResponse(false, "No response", (IList <NetworkRow>) new List <NetworkRow>());
                return(this);
            }

            var result = new List <NetworkRow>();

            foreach (var row in response.StdOutAsArry)
            {
                var items = row.Split(';');
                if (items.Length < 4)
                {
                    continue;
                }

                var created = DateTime.MinValue;
                var ipv6    = false;
                var intern  = false;

                if (items.Length > 4)
                {
                    bool.TryParse(items[4], out ipv6);
                }
                if (items.Length > 5)
                {
                    bool.TryParse(items[5], out intern);
                }
                if (items.Length > 6)
                {
                    var split         = items[6].Split(" ".ToCharArray());
                    var normalizedStr = $"{split[0]} {split[1]} {split[2].Insert(3, ":")}";
                    DateTime.TryParse(normalizedStr, out created);
                }

                result.Add(new NetworkRow
                {
                    Id       = items[0],
                    Name     = items[1],
                    Driver   = items[2],
                    Scope    = items[3],
                    IPv6     = ipv6,
                    Internal = intern,
                    Created  = created
                });
            }

            Response = response.ToResponse(true, string.Empty, (IList <NetworkRow>)result);
            return(this);
        }
Ejemplo n.º 21
0
        public IProcessResponse <string> Process(ProcessExecutionResult response)
        {
            var success =
                response.StdOutAsArray.All(
                    line => !line.StartsWith("Host does not exist") && !line.StartsWith("Incorrect Usage."));

            Response = response.ToResponse(success, string.Empty, string.Empty);
            return(this);
        }
Ejemplo n.º 22
0
        public IProcessResponse <string> Process(ProcessExecutionResult response)
        {
            var success =
                response.StdOutAsArry.All(
                    line => !line.StartsWith("Error") && !line.StartsWith("Can't remove") && !line.StartsWith("Incorrect Usage."));

            Response = response.ToResponse(success, string.Empty, string.Empty);
            return(this);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Reads all tags from matroska file and parses the XML for the requested tags (<paramref name="tagsToExtract"/>).
        /// </summary>
        /// <param name="tagsToExtract">Dictionary with tag names as keys.</param>
        public void ReadTags(IDictionary <string, IList <string> > tagsToExtract)
        {
            ProcessExecutionResult executionResult = null;
            // Calling EnsureLocalFileSystemAccess not necessary; access for external process ensured by ExecuteWithResourceAccess
            var arguments = string.Format("tags \"{0}\"", _lfsra.LocalFileSystemPath);

            try
            {
                lock (MKVEXTRACT_THROTTLE_LOCK)
                    executionResult = _lfsra.ExecuteWithResourceAccessAsync(_mkvExtractPath, arguments, _priorityClass).Result;
            }
            catch (AggregateException ae)
            {
                ae.Handle(e =>
                {
                    if (e is TaskCanceledException)
                    {
                        ServiceRegistration.Get <ILogger>().Warn("MatroskaInfoReader.ReadTags: External process aborted due to timeout: Executable='{0}', Arguments='{1}'", _mkvExtractPath, arguments);
                        return(true);
                    }
                    return(false);
                });
            }
            if (executionResult != null && executionResult.Success && !string.IsNullOrEmpty(executionResult.StandardOutput))
            {
                XDocument doc = XDocument.Parse(executionResult.StandardOutput);

                foreach (string key in new List <string>(tagsToExtract.Keys))
                {
                    string[] parts      = key.Split('.');
                    int?     targetType = null;
                    string   tagName;
                    if (parts.Length == 2)
                    {
                        targetType = int.Parse(parts[0]);
                        tagName    = parts[1];
                    }
                    else
                    {
                        tagName = parts[0];
                    }

                    var result = from simpleTag in GetTagsForTargetType(doc, targetType).Elements("Simple")
                                 let nameElement = simpleTag.Element("Name")
                                                   let stringElement = simpleTag.Element("String")
                                                                       where nameElement != null && nameElement.Value == tagName &&
                                                                       stringElement != null && !string.IsNullOrWhiteSpace(stringElement.Value)
                                                                       select stringElement.Value;

                    var resultList = result.ToList();
                    if (resultList.Any())
                    {
                        tagsToExtract[key] = resultList.ToList();
                    }
                }
            }
        }
Ejemplo n.º 24
0
        private bool IsHealthyAndRunning(ProcessExecutionResult result)
        {
            var status = _outputParser.ParseInstallerStatus(result.Output);

            return(status == DriverState.DeviceExists &&
                   status != DriverState.DeviceIsDisabled &&
                   status != DriverState.DeviceIsStopped &&
                   status != DriverState.DeviceHasAProblem);
        }
        public IProcessResponse <string> Process(ProcessExecutionResult response)
        {
            var arr = response.StdOutAsArry;

            Response = arr.Length == 0
        ? response.ToResponse(false, "No line", string.Empty)
        : response.ToResponse(true, string.Empty, arr[0]);

            return(this);
        }
Ejemplo n.º 26
0
 protected OutputResult GetOutputResult(ProcessExecutionResult processExecutionResult) =>
 new OutputResult
 {
     TimeUsed   = (int)processExecutionResult.TimeWorked.TotalMilliseconds,
     MemoryUsed = (int)processExecutionResult.MemoryUsed,
     ResultType = processExecutionResult.Type,
     Output     = string.IsNullOrWhiteSpace(processExecutionResult.ErrorOutput)
             ? processExecutionResult.ReceivedOutput
             : processExecutionResult.ErrorOutput
 };
 public static ProcessExecutionResult RunProcess(string fileName, string arguments = null, int timeout = default(int))
 {
     var outputBuilder = new List<string>();
     var errorOutputBuilder = new List<string>();
     var startInfo = new ProcessStartInfo(fileName, arguments)
     {
         UseShellExecute = false,
         CreateNoWindow = true,
         WindowStyle = ProcessWindowStyle.Hidden,
         RedirectStandardError = true,
         RedirectStandardOutput = true,
     };
     using (var process = new Process
     {
         StartInfo = startInfo
     })
     {
         process.ErrorDataReceived += (sendingProcess, outLine) =>
         {
             if (!string.IsNullOrEmpty(outLine.Data))
             {
                 errorOutputBuilder.Add(outLine.Data);
             }
         };
         process.OutputDataReceived += (sendingProcess, outLine) =>
         {
             if (!string.IsNullOrEmpty(outLine.Data))
             {
                 outputBuilder.Add(outLine.Data);
             }
         };
         process.Start();
         process.BeginErrorReadLine();
         process.BeginOutputReadLine();
         if (timeout != default(int))
         {
             if (!process.WaitForExit(timeout))
             {
                 process.Kill();
                 throw new TimeoutException();
             }
         }
         else
         {
             process.WaitForExit();
         }
         var processExecutionResult = new ProcessExecutionResult
         {
             ExitCode = process.ExitCode,
             ErrorOutput = string.Join("\r\n", errorOutputBuilder),
             Output = string.Join("\r\n", outputBuilder),
         };
         return processExecutionResult;
     }
 }
Ejemplo n.º 28
0
        public async Task <(string deviceName, ProcessExecutionResult result)> InstallApp(string appPath, TestTarget target, string deviceName = null, CancellationToken cancellationToken = default)
        {
            if (target.IsSimulator())
            {
                // We reset the simulator when running, so a separate install step does not make much sense.
                throw new InvalidOperationException("Installing to a simulator is not supported.");
            }

            if (!Directory.Exists(appPath))
            {
                throw new DirectoryNotFoundException("Failed to find the app bundle directory");
            }

            if (deviceName == null)
            {
                var device = await _deviceLoader.FindDevice(target.ToRunMode(), _mainLog, false, false);

                if (target.IsWatchOSTarget())
                {
                    deviceName = (await _deviceLoader.FindCompanionDevice(_mainLog, device)).Name;
                }
                else
                {
                    deviceName = device.Name;
                }
            }

            if (deviceName == null)
            {
                throw new NoDeviceFoundException();
            }

            var args = new MlaunchArguments();

            for (int i = -1; i < _verbosity; i++)
            {
                args.Add(new VerbosityArgument());
            }

            args.Add(new InstallAppOnDeviceArgument(appPath));
            args.Add(new DeviceNameArgument(deviceName));

            if (target.IsWatchOSTarget())
            {
                args.Add(new DeviceArgument("ios,watchos"));
            }

            var totalSize = Directory.GetFiles(appPath, "*", SearchOption.AllDirectories).Select((v) => new FileInfo(v).Length).Sum();

            _mainLog.WriteLine($"Installing '{appPath}' to '{deviceName}' ({totalSize / 1024.0 / 1024.0:N2} MB)");

            ProcessExecutionResult result = await _processManager.ExecuteCommandAsync(args, _mainLog, TimeSpan.FromHours(1), cancellation_token : cancellationToken);

            return(deviceName, result);
        }
Ejemplo n.º 29
0
        public IProcessResponse <IList <string> > Process(ProcessExecutionResult response)
        {
            if (response.ExitCode != 0)
            {
                Response = response.ToErrorResponse((IList <string>) new List <string>());
                return(this);
            }

            Response = response.ToResponse(true, string.Empty, (IList <string>) new List <string>(response.StdOutAsArry));
            return(this);
        }
Ejemplo n.º 30
0
        private void FixReceivedOutput(ProcessExecutionResult processExecutionResult)
        {
            var output = processExecutionResult.ErrorOutput ?? string.Empty;

            if (TestsRegex.IsMatch(output))
            {
                processExecutionResult.ReceivedOutput = output;
                processExecutionResult.ErrorOutput    = string.Empty;
                processExecutionResult.Type           = ProcessExecutionResultType.Success;
            }
        }
        public IProcessResponse <MachineConfiguration> Process(ProcessExecutionResult response)
        {
            if (string.IsNullOrEmpty(response.StdOut))
            {
                Response = response.ToResponse(false, "No response",
                                               new MachineConfiguration {
                    AuthConfig = new MachineAuthConfig()
                });
                return(this);
            }

            var j = JObject.Parse(response.StdOut);

            var str        = j["HostOptions"]["AuthOptions"].ToString();
            var ip         = j["Driver"]["IPAddress"].Value <string>();
            var authConfig = JsonConvert.DeserializeObject <MachineAuthConfig>(str);

            int memsize = 0;

            if (null != j["Driver"]["Memory"])
            {
                memsize = j["Driver"]["Memory"].Value <int>();
            }

            if (null != j["Driver"]["MemSize"])
            {
                memsize = j["Driver"]["MemSize"].Value <int>();
            }

            string hostname = string.Empty;

            if (!IPAddress.TryParse(ip, out var ipaddr))
            {
                hostname = ip;
                ipaddr   = IPAddress.None;
            }

            var config = new MachineConfiguration
            {
                AuthConfig    = authConfig,
                IpAddress     = ipaddr,
                Hostname      = hostname,
                DriverName    = null != j["DriverName"] ? j["DriverName"].Value <string>() : "unknown",
                MemorySizeMb  = memsize,
                Name          = null != j["Name"] ? j["Name"].Value <string>() : string.Empty,
                RequireTls    = j["HostOptions"]["EngineOptions"]["TlsVerify"].Value <bool>(),
                StorageSizeMb = j["Driver"]["DiskSize"]?.Value <int>() ?? 0,
                CpuCount      = j["Driver"]["CPU"]?.Value <int>() ?? 0,
                StorePath     = j["Driver"]["StorePath"]?.Value <string>() ?? string.Empty
            };

            Response = response.ToResponse(true, string.Empty, config);
            return(this);
        }
    public IProcessResponse<string> Process(ProcessExecutionResult response)
    {
      var success = response.ExitCode == 0 ||
                    response.StdOutAsArray.All(
                      line =>
                        !line.StartsWith("Error") && !line.StartsWith("Can't remove") &&
                        !line.StartsWith("Incorrect Usage."));

      Response = response.ToResponse(success, "Error Creating Machine", string.Empty);
      return this;
    }
Ejemplo n.º 33
0
 public void StartProcess(BenchEnvironment env,
     string cwd, string executable, string arguments,
     ProcessExitCallback cb, ProcessMonitoring monitoring)
 {
     if (IsDisposed)
     {
         throw new ObjectDisposedException(nameof(ConEmuExecutionHost));
     }
     if (!IsPowerShellExecutionHostRunning)
     {
         backupHost.StartProcess(env, cwd, executable, arguments, cb, monitoring);
         return;
     }
     var collectOutput = (monitoring & ProcessMonitoring.Output) == ProcessMonitoring.Output;
     var response = SendCommand("exec", cwd, executable, arguments);
     AsyncManager.StartTask(() =>
     {
         var exitCode = 999999;
         var transcriptPath = default(string);
         foreach (var l in response)
         {
             ParseExitCode(l, ref exitCode);
             ParseTranscriptPath(l, ref transcriptPath);
         }
         var output = default(string);
         if (collectOutput && transcriptPath != null && File.Exists(transcriptPath))
         {
             output = File.ReadAllText(transcriptPath, Encoding.Default);
             File.Delete(transcriptPath);
         }
         var result = new ProcessExecutionResult(exitCode, output);
         cb(result);
     });
 }