Example #1
0
        internal CommandResult(ICommand command, Token token, CommandResult?parent = null)
            : base(command ?? throw new ArgumentNullException(nameof(command)), parent)
        {
            Command = command;

            Token = token ?? throw new ArgumentNullException(nameof(token));
        }
Example #2
0
        public bool TryGetValue(
            IValueDescriptor valueDescriptor,
            BindingContext?bindingContext,
            out object?boundValue
            )
        {
            if (!string.IsNullOrEmpty(valueDescriptor.ValueName))
            {
                CommandResult?commandResult = bindingContext?.ParseResult.CommandResult;

                while (commandResult != null)
                {
                    if (commandResult.TryGetValueForOption(valueDescriptor, out var optionValue))
                    {
                        boundValue = optionValue;
                        return(true);
                    }

                    if (
                        commandResult.TryGetValueForArgument(valueDescriptor, out var argumentValue)
                        )
                    {
                        boundValue = argumentValue;
                        return(true);
                    }

                    commandResult = commandResult.Parent as CommandResult;
                }
            }

            boundValue = null;
            return(false);
        }
Example #3
0
        public CommandResult Execute(Script script,
                                     IVariables variables,
                                     ICommandLineRunner commandLineRunner,
                                     Dictionary <string, string>?environmentVars = null)
        {
            var environmentVariablesIncludingProxy = environmentVars ?? new Dictionary <string, string>();

            foreach (var proxyVariable in ProxyEnvironmentVariablesGenerator.GenerateProxyEnvironmentVariables())
            {
                environmentVariablesIncludingProxy[proxyVariable.Key] = proxyVariable.Value;
            }

            var prepared = PrepareExecution(script, variables, environmentVariablesIncludingProxy);

            CommandResult?result = null;

            foreach (var execution in prepared)
            {
                if (variables.IsSet(CopyWorkingDirectoryVariable))
                {
                    CopyWorkingDirectory(variables,
                                         execution.CommandLineInvocation.WorkingDirectory,
                                         execution.CommandLineInvocation.Arguments);
                }

                try
                {
                    if (execution.CommandLineInvocation.Isolate)
                    {
                        using (SemaphoreFactory.Get()
                               .Acquire("CalamariSynchronizeProcess",
                                        "Waiting for other process to finish executing script"))
                        {
                            result = commandLineRunner.Execute(execution.CommandLineInvocation);
                        }
                    }
                    else
                    {
                        result = commandLineRunner.Execute(execution.CommandLineInvocation);
                    }

                    if (result.ExitCode != 0)
                    {
                        return(result);
                    }
                }
                finally
                {
                    foreach (var temporaryFile in execution.TemporaryFiles)
                    {
                        var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();
                        fileSystem.DeleteFile(temporaryFile, FailureOptions.IgnoreFailure);
                    }
                }
            }

            return(result !);
        }
        protected override void VisitRootCommandNode(RootCommandNode rootCommandNode)
        {
            _rootCommandResult = new RootCommandResult(
                rootCommandNode.Command,
                rootCommandNode.Token);
            _rootCommandResult.ValidationMessages = _parser.Configuration.ValidationMessages;

            _innermostCommandResult = _rootCommandResult;
        }
Example #5
0
        public static CommandResult Deserialize(BuildXLReader reader)
        {
            CommandType commandType = (CommandType)reader.ReadByte();

            CommandResult?result = null;

            switch (commandType)
            {
            case CommandType.Get:
                result = new GetResult()
                {
                    Value = reader.ReadNullableByteArray(),
                };

                break;

            case CommandType.Set:
                result = new SetResult()
                {
                    Set = reader.ReadBoolean(),
                };
                break;

            case CommandType.CompareExchange:
                result = new CompareExchangeResult()
                {
                    Previous  = reader.ReadNullableByteArray(),
                    Exchanged = reader.ReadBoolean(),
                };
                break;

            case CommandType.CompareRemove:
                result = new CompareRemoveResult()
                {
                    Value = reader.ReadNullableByteArray(),
                };
                break;

            case CommandType.Remove:
                result = new RemoveResult();
                break;

            case CommandType.PrefixEnumerate:
                result = new PrefixEnumerateResult(reader.ReadReadOnlyList(r =>
                {
                    var key   = r.ReadNullableByteArray();
                    var value = r.ReadNullableByteArray();
                    return(new KeyValuePair <ByteString, ByteString>(key, value));
                }));

                break;
            }
            Contract.AssertNotNull(result);

            return(result);
        }
Example #6
0
 /// <summary>
 /// Create new command values.
 /// </summary>
 /// <param name="Command">The command.</param>
 /// <param name="UpstreamCommand">The optional received upstream command.</param>
 /// <param name="Response">The command response.</param>
 /// <param name="Result">The (later async) command result.</param>
 private CommandValues(IOCPICommand Command,
                       IOCPICommand UpstreamCommand,
                       CommandResponse Response = null,
                       CommandResult?Result     = null)
 {
     this.Command         = Command;
     this.UpstreamCommand = UpstreamCommand;
     this.Response        = Response;
     this.Result          = Result;
 }
 internal OptionResult(
     Option option,
     Token?token          = null,
     CommandResult?parent = null) :
     base(option ?? throw new ArgumentNullException(nameof(option)),
          parent)
 {
     Option = option;
     Token  = token;
 }
    public bool TryGetValue(
        IValueDescriptor valueDescriptor,
        BindingContext?bindingContext,
        out object?boundValue)
    {
        if (!string.IsNullOrEmpty(valueDescriptor.ValueName))
        {
            CommandResult?commandResult = bindingContext?.ParseResult.CommandResult;

            while (commandResult is { })
        protected override void VisitCommandNode(CommandNode commandNode)
        {
            var commandResult = new CommandResult(
                commandNode.Command,
                commandNode.Token,
                _innermostCommandResult
                );

            _innermostCommandResult !.Children.Add(commandResult);

            _innermostCommandResult = commandResult;
        }
Example #10
0
        private void InvokeCommand(Action<CommandResult> callback, Action<int> progressCallback, String commandName, params string[] args)
        {
            StringBuilder commandString = new StringBuilder();
            if (!VerifyCommandName(commandName))
                throw new Exception("Invalid command name!");

            String separator = "";
            foreach (var arg in args)
            {
                commandString.Append(separator);
                commandString.Append(arg);
                separator = "|";
            }

            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                ErrorDialog = false,
                FileName = ExecutablePath,
                RedirectStandardOutput = true,
                Arguments = "-stringcommand:" + commandString.ToString()
            };

            ExecutingProcess = Process.Start(startInfo);
            ExecutingProcess.BeginOutputReadLine();

            PendingResult = new CommandResult { CommandName = commandName };

            IsExecuting = true;
            TaskThread = new Thread(() =>
            {
                //throw; // NOT YET IMPLEMENTED, SHOULD BE READING FROM STANDARD OUTPUT AND BE EMITTING DATA EVENTS
                var output = ExecutingProcess.StandardOutput.ReadToEnd();

                //  Update PendingResult

                ExecutingProcess.WaitForExit();

                callback(PendingResult.Value);
                PendingResult = null;
                ExecutingProcess = null;
                IsExecuting = false;
            });
        }
Example #11
0
        /// <summary>
        /// 带有超时重试功能的fastboot指令执行器
        /// </summary>
        /// <param name="executor"></param>
        /// <param name="args"></param>
        /// <param name="retryTimes"></param>
        /// <param name="maxTimeout"></param>
        /// <exception cref="TimeoutException">超过重试次数</exception>
        /// <exception cref="ArgumentException">参数不合理</exception>
        /// <returns></returns>
        public static CommandResult FastbootWithRetry(this ICommandExecutor executor, string args,
                                                      IDevice?device = null, int retryTimes = 10, int maxTimeout = 300)
        {
            if (retryTimes * maxTimeout <= 0)
            {
                throw new ArgumentException("retryTimes and maxTimeout should not be smaller than 0");
            }
            const int INTERVAL_BETWEEN_PER_RETRY = 20;

            /*
             * 由于某些原因,部分设备上的fastboot指令会有玄学问题
             *因此此处实现了一个重试机制,尽可能获取到正确的值
             */
            CommandResult?result = null;

            for (int crtTime = 1; crtTime <= retryTimes; crtTime++)
            {
                CommandResult routine()
                {
                    return(device == null?executor.Fastboot(args) : executor.Fastboot(device, args));
                }

                Task.Run(() =>
                {
                    result = routine();
                });

                Thread.Sleep((int)maxTimeout);

                if (result != null && !result.Output.Contains("GetVar Variable Not found"))
                {
                    break;
                }
                else
                {
                    executor.CancelCurrent();
                    Thread.Sleep(INTERVAL_BETWEEN_PER_RETRY);
                }
            }
            if (result == null)
            {
                throw new TimeoutException();
            }
            return(result);
        }
        /// <summary>
        /// 开始执行
        /// </summary>
        /// <exception cref="CommandErrorException">达到重试上限</exception>
        /// <returns></returns>
        public CommandResult Execute()
        {
            CommandResult?result = null;

            for (int crtTime = 1; crtTime <= MaxTimes; crtTime++)
            {
                Task.Run(() => result = executor.Fastboot(device, command));
                Thread.Sleep(WAIT_TIME);
                if (result == null)
                {
                    executor.CancelCurrent();
                    Thread.Sleep(INTERVAL);
                }
                else
                {
                    break;
                }
            }
            return(result ?? throw new CommandErrorException("Reachec limit of try."));
        }
Example #13
0
        private static SymbolResult GetSymbolResult <T>(Option <T> option, ParseResult parseResult, CommandResult?commmandResult)
        {
            SymbolResult?symbolResult = null;

            while (!(commmandResult is null) && symbolResult is null)
            {
                symbolResult   = parseResult.RootCommandResult.FindResultFor(option);
                commmandResult = commmandResult.Parent as CommandResult;
            }

            return(symbolResult);
        }
        private void NestedCommandExecuted(CommandResult result)
        {
            switch (result)
            {
                case CommandResult.Deferred:
                    return;
                case CommandResult.None:
                case CommandResult.Succeeded:
                    _result = ++_completedAttempts > 1 ? CommandResult.Succeeded : CommandResult.None;
                    break;
                case CommandResult.Failed:
                    _completedAttempts++;
                    if (_maximumAttempts != MaximumAttempts.Infinite && _completedAttempts >= _maximumAttempts)
                    {
                        _result = CommandResult.Failed;
                    }
                    break;
            }

            _executingNestedCommand = false;
        }
        protected override void Reset()
        {
            _completedAttempts = 0;
            _result = null;
            _executingNestedCommand = false;

            base.Reset();
        }
Example #16
0
        ///// <summary>
        ///// 在fastboot状态时获取设备的某些变量值
        ///// </summary>
        ///// <param name="device"></param>
        ///// <param name="key"></param>
        ///// <exception cref="CommandErrorException">命令执行失败</exception>
        ///// <exception cref="InvalidOperationException">设备状态有误</exception>
        ///// <returns></returns>
        //public static string FastbootGetVar(this IDevice device, string key, int? maxTimeout = 1000)
        //{
        //    //device.RefreshState();
        //    if (device.State != DeviceState.Fastboot) throw new InvalidOperationException("Device state not right.");
        //    CommandResult? result = null;
        //    if (maxTimeout != null)
        //    {
        //        using var executor = new HestExecutor();
        //        Task.Run(() =>
        //        {
        //            result = executor.Fastboot(device, $"getvar {key}");
        //        });
        //        Thread.Sleep((int)maxTimeout);
        //        if (result == null)
        //        {
        //            executor.Dispose();
        //            throw new CommandErrorException("Get Var Operation'used time reached timeout limit or other error occurs.");
        //        }
        //    }
        //    else
        //    {
        //        result = device.Fastboot($"getvar {key}");
        //    }
        //    //TODO
        //}

        /// <summary>
        /// 在fastboot状态时获取设备的某些变量值 (fastboot getvar指令的封装)
        /// </summary>
        /// <param name="device"></param>
        /// <param name="key"></param>
        /// <exception cref="CommandErrorException">命令执行失败</exception>
        /// <exception cref="InvalidOperationException">设备状态有误</exception>
        /// <exception cref="KeyNotFoundException">未找到对应键的值</exception>
        /// <returns></returns>
        public static string GetVar(this IDevice device, string key)
        {
            if (device.State != DeviceState.Fastboot)
            {
                throw new InvalidOperationException("Device's state not correct: should be bootloader mode");
            }
            string command = $"getvar {key}";

            using var hestExecutor = new HestExecutor(BasicBooter.CommandProcedureManager);

            /*
             * 由于某些原因,部分设备上的fastboot getvar指令会有玄学问题
             *因此此处实现了一个重试机制,尽可能获取到正确的值
             */
            const int     MAX_TIMEOUT = 100;
            const int     MAX_TIMES   = 10;
            const int     INTERVAL    = 20;
            CommandResult?result      = null;

            for (int crtTime = 1; crtTime <= MAX_TIMES; crtTime++)
            {
                Task.Run(() =>
                {
                    result = hestExecutor.Fastboot(device, command);
                });

                Thread.Sleep(MAX_TIMEOUT);

                if (result != null && !result.Output.Contains("GetVar Variable Not found"))
                {
                    break;
                }
                else
                {
                    hestExecutor.CancelCurrent();
                    Thread.Sleep(INTERVAL);
                }
            }

            //达到尝试上线或已经获取到正确结果

            if (result == null)
            {
                throw new CommandErrorException("Operation: 'fastboot getvar' reached limit of times of retry.");
            }
            else if (result.Output.Contains("GetVar Variable Not found", true))
            {
                throw new KeyNotFoundException();
            }
            else if (result.ExitCode != 0)
            {
                throw new CommandErrorException(result.Output, result.ExitCode);
            }
            else
            {
                var match = Regex.Match(result.Output, key + @":\s(?<value>[\w|\d]+)");
                if (match.Success)
                {
                    return(match.Result("${value}"));
                }
                else
                {
                    throw new CommandErrorException("Fail to parse output: " + result.Output, result.ExitCode);
                }
            }
        }
Example #17
0
        private static SymbolResult GetSymbolResult <T>(Argument <T> argumeent, ParseResult parseResult, CommandResult?commmandResult)
        {
            SymbolResult?symbolResult = null;

            while (!(commmandResult is null) && symbolResult is null)
            {
                symbolResult   = parseResult.RootCommandResult.FindResultFor(argumeent);
                commmandResult = commmandResult.Parent as CommandResult;
            }

            return(symbolResult);
        }
Example #18
0
        private void NestedCommandExecuted(CommandResult result)
        {
            switch (result)
            {
                case CommandResult.Deferred:
                    return;
                case CommandResult.None:
                case CommandResult.Succeeded:
                    _result = _totalRepeats > TotalRepeats.Infinite && ++_repeats == _totalRepeats ? CommandResult.Succeeded : (CommandResult?)null;
                    break;
                case CommandResult.Failed:
                    _result = CommandResult.Failed;
                    break;
            }

            _executingNestedCommand = false;
        }
Example #19
0
        protected override void Reset()
        {
            _repeats = 0;
            _result = null;
            _executingNestedCommand = false;

            base.Reset();
        }
Example #20
0
        private void InvokeCommand(Action<CommandResult> callback, Action<int> progressCallback, String commandName, params string[] args)
        {
            StringBuilder commandString = new StringBuilder();
            if (!VerifyCommandName(commandName))
                throw new Exception("Invalid command name!");

            String separator = "";
            foreach (var arg in args)
            {
                commandString.Append(separator);
                commandString.Append(arg);
                separator = "|";
            }

            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                CreateNoWindow = true,
                UseShellExecute = false,
                ErrorDialog = false,
                FileName = ExecutablePath,
                RedirectStandardOutput = true,
                Arguments = "-stringcommand:" + commandString.ToString()
            };

            ExecutingProcess = Process.Start(startInfo);
            ExecutingProcess.BeginOutputReadLine();

            PendingResult = new CommandResult { CommandName = commandName };

            ExecutingProcess.OutputDataReceived += (sender, e) =>
            {
                if (OnOutputReceived != null)
                    OnOutputReceived(e.Data);
            };

            //  Spawn waiting thread
            IsExecuting = true;
            TaskThread = new Thread(() =>
            {
                //  Update PendingResult

                ExecutingProcess.WaitForExit();

                callback(PendingResult.Value);
                PendingResult = null;
                ExecutingProcess = null;
                IsExecuting = false;
            });
        }