コード例 #1
0
 public override void Initialize(IHostContext hostContext)
 {
     base.Initialize(hostContext);
     Trace.Verbose("Creating _store");
     _store = hostContext.GetService<IConfigurationStore>();
     Trace.Verbose("store created");
     _term = hostContext.GetService<ITerminal>();
 }
コード例 #2
0
ファイル: JobDispatcher.cs プロジェクト: codedebug/vsts-agent
        public override void Initialize(IHostContext hostContext)
        {
            base.Initialize(hostContext);

            // get pool id from config
            var configurationStore = hostContext.GetService<IConfigurationStore>();
            AgentSettings agentSetting = configurationStore.GetSettings();
            _poolId = agentSetting.PoolId;
        }
コード例 #3
0
        public CommandLineParser(IHostContext hostContext, string[] secretArgNames)
        {
            _secretMasker = hostContext.GetService<ISecretMasker>();
            _trace = hostContext.GetTrace(nameof(CommandLineParser));

            Commands = new List<string>();
            Flags = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            Args = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            SecretArgNames = new HashSet<string>(secretArgNames ?? new string[0], StringComparer.OrdinalIgnoreCase);
        }
コード例 #4
0
        public override void Initialize(IHostContext hostContext)
        {
            base.Initialize(hostContext);

            // Register all command extensions
            var extensionManager = hostContext.GetService<IExtensionManager>();
            foreach (var commandExt in extensionManager.GetExtensions<IWorkerCommandExtension>() ?? new List<IWorkerCommandExtension>())
            {
                Trace.Info($"Register command extension for area {commandExt.CommandArea}");
                _commandExtensions[commandExt.CommandArea] = commandExt;
            }
        }
コード例 #5
0
        // Constructor.
        public CommandSettings(IHostContext context, string[] args)
        {
            ArgUtil.NotNull(context, nameof(context));
            _context = context;
            _promptManager = context.GetService<IPromptManager>();
            _trace = context.GetTrace(nameof(CommandSettings));

            // Parse the command line args.
            _parser = new CommandLineParser(
                hostContext: context,
                secretArgNames: Constants.Agent.CommandLine.Args.Secrets);
            _parser.Parse(args);
        }
コード例 #6
0
        public override VssCredentials GetVssCredentials(IHostContext context)
        {
            var clientId = this.CredentialData.Data.GetValueOrDefault("clientId", null);
            var authorizationUrl = this.CredentialData.Data.GetValueOrDefault("authorizationUrl", null);

            // We expect the key to be in the machine store at this point. Configuration should have set all of
            // this up correctly so we can use the key to generate access tokens.
            var keyManager = context.GetService<IRSAKeyManager>();
            var signingCredentials = VssSigningCredentials.Create(() => keyManager.GetKey());
            var clientCredential = new VssOAuthJwtBearerClientCredential(clientId, authorizationUrl, signingCredentials);
            var agentCredential = new VssOAuthCredential(new Uri(authorizationUrl, UriKind.Absolute), VssOAuthGrant.ClientCredentials, clientCredential);

            // Construct a credentials cache with a single OAuth credential for communication. The windows credential
            // is explicitly set to null to ensure we never do that negotiation.
            return new VssCredentials(null, agentCredential, CredentialPromptType.DoNotPrompt);
        }
コード例 #7
0
        // Constructor.
        public CommandSettings(IHostContext context, string[] args, IScopedEnvironment environmentScope = null)
        {
            ArgUtil.NotNull(context, nameof(context));
            _promptManager = context.GetService <IPromptManager>();
            _trace         = context.GetTrace(nameof(CommandSettings));

            ParseArguments(args);

            if (environmentScope == null)
            {
                environmentScope = new SystemEnvironment();
            }

            // Mask secret arguments
            if (Configure != null)
            {
                context.SecretMasker.AddValue(Configure.Password);
                context.SecretMasker.AddValue(Configure.ProxyPassword);
                context.SecretMasker.AddValue(Configure.SslClientCert);
                context.SecretMasker.AddValue(Configure.Token);
                context.SecretMasker.AddValue(Configure.WindowsLogonPassword);
            }

            if (Remove != null)
            {
                context.SecretMasker.AddValue(Remove.Password);
                context.SecretMasker.AddValue(Remove.Token);
            }

            PrintArguments();

            // Store and remove any args passed via environment variables.
            var environment = environmentScope.GetEnvironmentVariables();

            string envPrefix = "VSTS_AGENT_INPUT_";

            foreach (DictionaryEntry entry in environment)
            {
                // Test if starts with VSTS_AGENT_INPUT_.
                string fullKey = entry.Key as string ?? string.Empty;
                if (fullKey.StartsWith(envPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    string val = (entry.Value as string ?? string.Empty).Trim();
                    if (!string.IsNullOrEmpty(val))
                    {
                        // Extract the name.
                        string name = fullKey.Substring(envPrefix.Length);

                        // Mask secrets.
                        bool secret = Constants.Agent.CommandLine.Args.Secrets.Any(x => string.Equals(x, name, StringComparison.OrdinalIgnoreCase));
                        if (secret)
                        {
                            context.SecretMasker.AddValue(val);
                        }

                        // Store the value.
                        _envArgs[name] = val;
                    }

                    // Remove from the environment block.
                    _trace.Info($"Removing env var: '{fullKey}'");
                    environmentScope.SetEnvironmentVariable(fullKey, null);
                }
            }
        }
コード例 #8
0
        // Return code definition: (this will be used by service host to determine whether it will re-launch agent.listener)
        // 0: Agent exit
        // 1: Terminate failure
        // 2: Retriable failure
        // 3: Exit for self update
        public async static Task <int> MainAsync(IHostContext context, string[] args)
        {
            Tracing trace = context.GetTrace("AgentProcess");

            trace.Info($"Agent built on {PlatformUtil.BuiltOnOS} ({PlatformUtil.BuiltOnArchitecture}) - {BuildConstants.AgentPackage.PackageName}.");
            trace.Info($"Agent built for {PlatformUtil.BuiltForOS} ({PlatformUtil.BuiltForArchitecture}).");
            trace.Info($"Running on {PlatformUtil.RunningOnOS} ({PlatformUtil.RunningOnArchitecture}).");
            trace.Info($"RuntimeInformation: {RuntimeInformation.OSDescription}.");
            context.WritePerfCounter("AgentProcessStarted");
            var terminal = context.GetService <ITerminal>();

            // TODO: check that the right supporting tools are available for this platform
            // (replaces the check for build platform vs runtime platform)

            try
            {
                trace.Info($"Version: {BuildConstants.AgentPackage.Version}");
                trace.Info($"Commit: {BuildConstants.Source.CommitHash}");
                trace.Info($"Culture: {CultureInfo.CurrentCulture.Name}");
                trace.Info($"UI Culture: {CultureInfo.CurrentUICulture.Name}");

                // Validate directory permissions.
                string agentDirectory = context.GetDirectory(WellKnownDirectory.Root);
                trace.Info($"Validating directory permissions for: '{agentDirectory}'");
                try
                {
                    IOUtil.ValidateExecutePermission(agentDirectory);
                }
                catch (Exception e)
                {
                    terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                    trace.Error(e);
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }

                if (PlatformUtil.RunningOnWindows)
                {
                    // Validate PowerShell 3.0 or higher is installed.
                    var powerShellExeUtil = context.GetService <IPowerShellExeUtil>();
                    try
                    {
                        powerShellExeUtil.GetPath();
                    }
                    catch (Exception e)
                    {
                        terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                        trace.Error(e);
                        return(Constants.Agent.ReturnCode.TerminatedError);
                    }

                    // Validate .NET Framework 4.5 or higher is installed.
                    if (!NetFrameworkUtil.Test(new Version(4, 5), trace))
                    {
                        terminal.WriteError(StringUtil.Loc("MinimumNetFramework"));
                        return(Constants.Agent.ReturnCode.TerminatedError);
                    }
                }

                // Add environment variables from .env file
                string envFile = Path.Combine(context.GetDirectory(WellKnownDirectory.Root), ".env");
                if (File.Exists(envFile))
                {
                    var envContents = File.ReadAllLines(envFile);
                    foreach (var env in envContents)
                    {
                        if (!string.IsNullOrEmpty(env) && env.IndexOf('=') > 0)
                        {
                            string envKey   = env.Substring(0, env.IndexOf('='));
                            string envValue = env.Substring(env.IndexOf('=') + 1);
                            Environment.SetEnvironmentVariable(envKey, envValue);
                        }
                    }
                }

                // Parse the command line args.
                var command = new CommandSettings(context, args);
                trace.Info("Arguments parsed");

                // Up front validation, warn for unrecognized commandline args.
                var unknownCommandlines = command.Validate();
                if (unknownCommandlines.Count > 0)
                {
                    terminal.WriteError(StringUtil.Loc("UnrecognizedCmdArgs", string.Join(", ", unknownCommandlines)));
                }

                // Defer to the Agent class to execute the command.
                IAgent agent = context.GetService <IAgent>();
                try
                {
                    return(await agent.ExecuteCommand(command));
                }
                catch (OperationCanceledException) when(context.AgentShutdownToken.IsCancellationRequested)
                {
                    trace.Info("Agent execution been cancelled.");
                    return(Constants.Agent.ReturnCode.Success);
                }
                catch (NonRetryableException e)
                {
                    terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                    trace.Error(e);
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
            }
            catch (Exception e)
            {
                terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                trace.Error(e);
                return(Constants.Agent.ReturnCode.RetryableError);
            }
        }
コード例 #9
0
 public override void Initialize(IHostContext hostContext)
 {
     base.Initialize(hostContext);
     _term        = hostContext.GetService <ITerminal>();
     _agentServer = HostContext.GetService <IAgentServer>();
 }
コード例 #10
0
        // Return code definition: (this will be used by service host to determine whether it will re-launch Runner.Listener)
        // 0: Runner exit
        // 1: Terminate failure
        // 2: Retriable failure
        // 3: Exit for self update
        private async static Task <int> MainAsync(IHostContext context, string[] args)
        {
            Tracing trace = context.GetTrace(nameof(GitHub.Runner.Listener));

            trace.Info($"Runner is built for {Constants.Runner.Platform} ({Constants.Runner.PlatformArchitecture}) - {BuildConstants.RunnerPackage.PackageName}.");
            trace.Info($"RuntimeInformation: {RuntimeInformation.OSDescription}.");
            context.WritePerfCounter("RunnerProcessStarted");
            var terminal = context.GetService <ITerminal>();

            // Validate the binaries intended for one OS are not running on a different OS.
            switch (Constants.Runner.Platform)
            {
            case Constants.OSPlatform.Linux:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    terminal.WriteLine("This runner version is built for Linux. Please install a correct build for your OS.");
                    return(Constants.Runner.ReturnCode.TerminatedError);
                }
                break;

            case Constants.OSPlatform.OSX:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    terminal.WriteLine("This runner version is built for OSX. Please install a correct build for your OS.");
                    return(Constants.Runner.ReturnCode.TerminatedError);
                }
                break;

            case Constants.OSPlatform.Windows:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    terminal.WriteLine("This runner version is built for Windows. Please install a correct build for your OS.");
                    return(Constants.Runner.ReturnCode.TerminatedError);
                }
                break;

            default:
                terminal.WriteLine($"Running the runner on this platform is not supported. The current platform is {RuntimeInformation.OSDescription} and it was built for {Constants.Runner.Platform.ToString()}.");
                return(Constants.Runner.ReturnCode.TerminatedError);
            }

            try
            {
                trace.Info($"Version: {BuildConstants.RunnerPackage.Version}");
                trace.Info($"Commit: {BuildConstants.Source.CommitHash}");
                trace.Info($"Culture: {CultureInfo.CurrentCulture.Name}");
                trace.Info($"UI Culture: {CultureInfo.CurrentUICulture.Name}");

                // Validate directory permissions.
                string runnerDirectory = context.GetDirectory(WellKnownDirectory.Root);
                trace.Info($"Validating directory permissions for: '{runnerDirectory}'");
                try
                {
                    IOUtil.ValidateExecutePermission(runnerDirectory);
                }
                catch (Exception e)
                {
                    terminal.WriteError($"An error occurred: {e.Message}");
                    trace.Error(e);
                    return(Constants.Runner.ReturnCode.TerminatedError);
                }

                // Parse the command line args.
                var command = new CommandSettings(context, args);
                trace.Info("Arguments parsed");

                // Up front validation, warn for unrecognized commandline args.
                var unknownCommandlines = command.Validate();
                if (unknownCommandlines.Count > 0)
                {
                    terminal.WriteError($"Unrecognized command-line input arguments: '{string.Join(", ", unknownCommandlines)}'. For usage refer to: .\\config.cmd --help or ./config.sh --help");
                }

                // Defer to the Runner class to execute the command.
                IRunner runner = context.GetService <IRunner>();
                try
                {
                    return(await runner.ExecuteCommand(command));
                }
                catch (OperationCanceledException) when(context.RunnerShutdownToken.IsCancellationRequested)
                {
                    trace.Info("Runner execution been cancelled.");
                    return(Constants.Runner.ReturnCode.Success);
                }
                catch (NonRetryableException e)
                {
                    terminal.WriteError($"An error occurred: {e.Message}");
                    trace.Error(e);
                    return(Constants.Runner.ReturnCode.TerminatedError);
                }
            }
            catch (Exception e)
            {
                terminal.WriteError($"An error occurred: {e.Message}");
                trace.Error(e);
                return(Constants.Runner.ReturnCode.RetryableError);
            }
        }
コード例 #11
0
 public override void Initialize(IHostContext hostContext)
 {
     base.Initialize(hostContext);
     CommandManager = hostContext.GetService <IWorkerCommandManager>();
 }
コード例 #12
0
        public static HttpClientHandler CreateHttpClientHandler(this IHostContext context)
        {
            var handlerFactory = context.GetService <IHttpClientHandlerFactory>();

            return(handlerFactory.CreateClientHandler(context.WebProxy));
        }
コード例 #13
0
 public override void Initialize(IHostContext hostContext)
 {
     base.Initialize(hostContext);
     _term = hostContext.GetService<ITerminal>();
 }
コード例 #14
0
 public override void Initialize(IHostContext hostContext)
 {
     base.Initialize(hostContext);
     _jobServer = hostContext.GetService<IJobServer>();
 }
コード例 #15
0
 public override void Initialize(IHostContext hostContext)
 {
     base.Initialize(hostContext);
     _jobServer = hostContext.GetService <IJobServer>();
 }
コード例 #16
0
        // Return code definition: (this will be used by service host to determine whether it will re-launch agent.listener)
        // 0: Agent exit
        // 1: Terminate failure
        // 2: Retriable failure
        // 3: Exit for self update
        public async static Task <int> MainAsync(IHostContext context, string[] args)
        {
            Tracing trace = context.GetTrace("AgentProcess");

            trace.Info($"Agent is built for {Constants.Agent.Platform} - {BuildConstants.AgentPackage.PackageName}.");
            trace.Info($"RuntimeInformation: {RuntimeInformation.OSDescription}.");
            var terminal = context.GetService <ITerminal>();

            // Validate the binaries intended for one OS are not running on a different OS.
            switch (Constants.Agent.Platform)
            {
            case Constants.OSPlatform.Linux:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    terminal.WriteLine(StringUtil.Loc("NotLinux"));
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
                break;

            case Constants.OSPlatform.OSX:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    terminal.WriteLine(StringUtil.Loc("NotOSX"));
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
                break;

            case Constants.OSPlatform.Windows:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    terminal.WriteLine(StringUtil.Loc("NotWindows"));
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
                break;

            default:
                terminal.WriteLine(StringUtil.Loc("PlatformNotSupport", RuntimeInformation.OSDescription, Constants.Agent.Platform.ToString()));
                return(Constants.Agent.ReturnCode.TerminatedError);
            }

            try
            {
                trace.Info($"Version: {Constants.Agent.Version}");
                trace.Info($"Commit: {BuildConstants.Source.CommitHash}");
                trace.Info($"Culture: {CultureInfo.CurrentCulture.Name}");
                trace.Info($"UI Culture: {CultureInfo.CurrentUICulture.Name}");

                // Validate directory permissions.
                string agentDirectory = context.GetDirectory(WellKnownDirectory.Root);
                trace.Info($"Validating directory permissions for: '{agentDirectory}'");
                try
                {
                    IOUtil.ValidateExecutePermission(agentDirectory);
                }
                catch (Exception e)
                {
                    terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                    trace.Error(e);
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }

#if OS_WINDOWS
                // Validate PowerShell 3.0 or higher is installed.
                var powerShellExeUtil = context.GetService <IPowerShellExeUtil>();
                try
                {
                    powerShellExeUtil.GetPath();
                }
                catch (Exception e)
                {
                    terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                    trace.Error(e);
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }

                // Validate .NET Framework 4.5 or higher is installed.
                var netFrameworkUtil = context.GetService <INetFrameworkUtil>();
                if (!netFrameworkUtil.Test(new Version(4, 5)))
                {
                    terminal.WriteError(StringUtil.Loc("MinimumNetFramework"));
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
#endif

                // Add environment variables from .env file
                string envFile = Path.Combine(context.GetDirectory(WellKnownDirectory.Root), ".env");
                if (File.Exists(envFile))
                {
                    var envContents = File.ReadAllLines(envFile);
                    foreach (var env in envContents)
                    {
                        if (!string.IsNullOrEmpty(env) && env.IndexOf('=') > 0)
                        {
                            string envKey   = env.Substring(0, env.IndexOf('='));
                            string envValue = env.Substring(env.IndexOf('=') + 1);
                            Environment.SetEnvironmentVariable(envKey, envValue);
                        }
                    }
                }

                // Parse the command line args.
                var command = new CommandSettings(context, args);
                trace.Info("Arguments parsed");

                // Up front validation, warn for unrecognized commandline args.
                var unknownCommandlines = command.Validate();
                if (unknownCommandlines.Count > 0)
                {
                    terminal.WriteError(StringUtil.Loc("UnrecognizedCmdArgs", string.Join(", ", unknownCommandlines)));
                }

                // Defer to the Agent class to execute the command.
                IAgent agent = context.GetService <IAgent>();
                try
                {
                    return(await agent.ExecuteCommand(command));
                }
                catch (OperationCanceledException) when(context.AgentShutdownToken.IsCancellationRequested)
                {
                    trace.Info("Agent execution been cancelled.");
                    return(Constants.Agent.ReturnCode.Success);
                }
                catch (NonRetryableException e)
                {
                    terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                    trace.Error(e);
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
            }
            catch (Exception e)
            {
                terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                trace.Error(e);
                return(Constants.Agent.ReturnCode.RetryableError);
            }
        }
コード例 #17
0
 public CapabilitiesBuilder(IHostContext hostContext, CancellationToken cancellationToken)
 {
     ArgUtil.NotNull(hostContext, nameof(hostContext));
     _hostContext = hostContext;
     _cancellationToken = cancellationToken;
     _trace = _hostContext.GetTrace(this.GetType().Name);
     _whichUtil = _hostContext.GetService<IWhichUtil>();
 }
コード例 #18
0
ファイル: Terminal.cs プロジェクト: codedebug/vsts-agent
 public override void Initialize(IHostContext hostContext)
 {
     base.Initialize(hostContext);
     _secretMasker = hostContext.GetService<ISecretMasker>();
     Console.CancelKeyPress += Console_CancelKeyPress;
 }
コード例 #19
0
        // Return code definition: (this will be used by service host to determine whether it will re-launch agent.listener)
        // 0: Agent exit
        // 1: Terminate failure
        // 2: Retriable failure
        // 3: Exit for self update
        private async static Task <int> MainAsync(IHostContext context, string[] args)
        {
            Tracing trace = context.GetTrace("AgentProcess");

            trace.Info($"Agent package {BuildConstants.AgentPackage.PackageName}.");
            trace.Info($"Running on {PlatformUtil.HostOS} ({PlatformUtil.HostArchitecture}).");
            trace.Info($"RuntimeInformation: {RuntimeInformation.OSDescription}.");
            context.WritePerfCounter("AgentProcessStarted");
            var terminal = context.GetService <ITerminal>();

            // TODO: check that the right supporting tools are available for this platform
            // (replaces the check for build platform vs runtime platform)

            try
            {
                trace.Info($"Version: {BuildConstants.AgentPackage.Version}");
                trace.Info($"Commit: {BuildConstants.Source.CommitHash}");
                trace.Info($"Culture: {CultureInfo.CurrentCulture.Name}");
                trace.Info($"UI Culture: {CultureInfo.CurrentUICulture.Name}");

                // Validate directory permissions.
                string agentDirectory = context.GetDirectory(WellKnownDirectory.Root);
                trace.Info($"Validating directory permissions for: '{agentDirectory}'");
                try
                {
                    IOUtil.ValidateExecutePermission(agentDirectory);
                }
                catch (Exception e)
                {
                    terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                    trace.Error(e);
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }

                if (PlatformUtil.UseLegacyHttpHandler)
                {
                    trace.Warning($"You are using the legacy HTTP handler because you set ${AgentKnobs.LegacyHttpVariableName}.");
                    trace.Warning($"This feature will go away with .NET 5.0, and we recommend you don't use it.");
                    trace.Warning($"If you continue using it, you must ensure libcurl is installed on your system.");
                }

                if (PlatformUtil.RunningOnWindows)
                {
                    // Validate PowerShell 3.0 or higher is installed.
                    var powerShellExeUtil = context.GetService <IPowerShellExeUtil>();
                    try
                    {
                        powerShellExeUtil.GetPath();
                    }
                    catch (Exception e)
                    {
                        terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                        trace.Error(e);
                        return(Constants.Agent.ReturnCode.TerminatedError);
                    }

                    // Validate .NET Framework 4.5 or higher is installed.
                    if (!NetFrameworkUtil.Test(new Version(4, 5), trace))
                    {
                        terminal.WriteError(StringUtil.Loc("MinimumNetFramework"));
                        // warn only, like configurationmanager.cs does. this enables windows edition with just .netcore to work
                    }

                    // Upgrade process priority to avoid Listener starvation
                    using (Process p = Process.GetCurrentProcess())
                    {
                        try
                        {
                            p.PriorityClass = ProcessPriorityClass.AboveNormal;
                        }
                        catch (Exception e)
                        {
                            trace.Warning("Unable to change Windows process priority");
                            trace.Warning(e.Message);
                        }
                    }
                }

                // Add environment variables from .env file
                string envFile = Path.Combine(context.GetDirectory(WellKnownDirectory.Root), ".env");
                if (File.Exists(envFile))
                {
                    var envContents = File.ReadAllLines(envFile);
                    foreach (var env in envContents)
                    {
                        if (!string.IsNullOrEmpty(env) && env.IndexOf('=') > 0)
                        {
                            string envKey   = env.Substring(0, env.IndexOf('='));
                            string envValue = env.Substring(env.IndexOf('=') + 1);
                            Environment.SetEnvironmentVariable(envKey, envValue);
                        }
                    }
                }

                // Parse the command line args.
                var command = new CommandSettings(context, args, new SystemEnvironment());
                trace.Info("Arguments parsed");

                // Print any Parse Errros
                if (command.ParseErrors?.Any() == true)
                {
                    List <string> errorStr = new List <string>();

                    foreach (var error in command.ParseErrors)
                    {
                        if (error is TokenError tokenError)
                        {
                            errorStr.Add(tokenError.Token);
                        }
                        else
                        {
                            // Unknown type of error dump to log
                            terminal.WriteError(StringUtil.Loc("ErrorOccurred", error.Tag));
                        }
                    }

                    terminal.WriteError(
                        StringUtil.Loc("UnrecognizedCmdArgs",
                                       string.Join(", ", errorStr)));
                }

                // Defer to the Agent class to execute the command.
                IAgent agent = context.GetService <IAgent>();
                try
                {
                    return(await agent.ExecuteCommand(command));
                }
                catch (OperationCanceledException) when(context.AgentShutdownToken.IsCancellationRequested)
                {
                    trace.Info("Agent execution been cancelled.");
                    return(Constants.Agent.ReturnCode.Success);
                }
                catch (NonRetryableException e)
                {
                    terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                    trace.Error(e);
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
            }
            catch (Exception e)
            {
                terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                trace.Error(e);
                return(Constants.Agent.ReturnCode.RetryableError);
            }
        }
コード例 #20
0
        public override VssCredentials GetVssCredentials(IHostContext context)
        {
            ArgUtil.NotNull(context, nameof(context));
            Tracing trace = context.GetTrace(nameof(AadDeviceCodeAccessToken));

            trace.Info(nameof(GetVssCredentials));
            ArgUtil.NotNull(CredentialData, nameof(CredentialData));

            CredentialData.Data.TryGetValue(Constants.Agent.CommandLine.Args.Url, out string serverUrl);
            ArgUtil.NotNullOrEmpty(serverUrl, nameof(serverUrl));

            var tenantAuthorityUrl = GetTenantAuthorityUrl(context, serverUrl);

            if (tenantAuthorityUrl == null)
            {
                throw new NotSupportedException($"This Azure DevOps organization '{serverUrl}' is not backed by Azure Active Directory.");
            }

            LoggerCallbackHandler.LogCallback = ((LogLevel level, string message, bool containsPii) =>
            {
                switch (level)
                {
                case LogLevel.Information:
                    trace.Info(message);
                    break;

                case LogLevel.Error:
                    trace.Error(message);
                    break;

                case LogLevel.Warning:
                    trace.Warning(message);
                    break;

                default:
                    trace.Verbose(message);
                    break;
                }
            });

            LoggerCallbackHandler.UseDefaultLogging = false;
            AuthenticationContext ctx = new AuthenticationContext(tenantAuthorityUrl.AbsoluteUri);
            var queryParameters       = $"redirect_uri={Uri.EscapeDataString(new Uri(serverUrl).GetLeftPart(UriPartial.Authority))}";

            if (PlatformUtil.RunningOnMacOS)
            {
                throw new Exception("AAD isn't supported for MacOS");
            }
            DeviceCodeResult codeResult = ctx.AcquireDeviceCodeAsync("https://management.core.windows.net/", _azureDevOpsClientId, queryParameters).GetAwaiter().GetResult();

            var term = context.GetService <ITerminal>();

            term.WriteLine($"Please finish AAD device code flow in browser ({codeResult.VerificationUrl}), user code: {codeResult.UserCode}");
            if (string.Equals(CredentialData.Data[Constants.Agent.CommandLine.Flags.LaunchBrowser], bool.TrueString, StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    if (PlatformUtil.RunningOnWindows)
                    {
                        Process.Start(new ProcessStartInfo()
                        {
                            FileName = codeResult.VerificationUrl, UseShellExecute = true
                        });
                    }
                    else if (PlatformUtil.RunningOnLinux)
                    {
                        Process.Start(new ProcessStartInfo()
                        {
                            FileName = "xdg-open", Arguments = codeResult.VerificationUrl
                        });
                    }
                    else
                    {
                        throw new NotImplementedException("Unexpected platform");
                    }
                }
                catch (Exception ex)
                {
                    // not able to open browser, ex: xdg-open/open is not installed.
                    trace.Error(ex);
                    term.WriteLine($"Fail to open browser. {codeResult.Message}");
                }
            }

            AuthenticationResult authResult = ctx.AcquireTokenByDeviceCodeAsync(codeResult).GetAwaiter().GetResult();

            ArgUtil.NotNull(authResult, nameof(authResult));
            trace.Info($"receive AAD auth result with {authResult.AccessTokenType} token");

            var            aadCred = new VssAadCredential(new VssAadToken(authResult));
            VssCredentials creds   = new VssCredentials(null, aadCred, CredentialPromptType.DoNotPrompt);

            trace.Info("cred created");

            return(creds);
        }
コード例 #21
0
ファイル: Handler.cs プロジェクト: codedebug/vsts-agent
 public override void Initialize(IHostContext hostContext)
 {
     base.Initialize(hostContext);
     CommandManager = hostContext.GetService<IWorkerCommandManager>();
     Environment = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
 }
コード例 #22
0
 public override void Initialize(IHostContext hostContext)
 {
     base.Initialize(hostContext);
     _term = hostContext.GetService <ITerminal>();
     _deploymentGroupServer = HostContext.GetService <IDeploymentGroupServer>();
 }
コード例 #23
0
        // Return code definition: (this will be used by service host to determine whether it will re-launch agent.listener)
        // 0: Agent exit
        // 1: Terminate failure
        // 2: Retriable failure
        // 3: Exit for self update
        public async static Task <int> MainAsync(IHostContext context, string[] args)
        {
            Tracing trace = context.GetTrace("AgentProcess");

            trace.Info($"Agent is built for {Constants.Agent.Platform} - {BuildConstants.AgentPackage.PackageName}.");
            trace.Info($"RuntimeInformation: {RuntimeInformation.OSDescription}.");
            var terminal = context.GetService <ITerminal>();

            // Validate the binaries intended for one OS are not running on a different OS.
            switch (Constants.Agent.Platform)
            {
            case Constants.OSPlatform.Linux:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    terminal.WriteLine(StringUtil.Loc("NotLinux"));
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
                break;

            case Constants.OSPlatform.OSX:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    terminal.WriteLine(StringUtil.Loc("NotOSX"));
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
                break;

            case Constants.OSPlatform.Windows:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    terminal.WriteLine(StringUtil.Loc("NotWindows"));
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
                break;

            default:
                terminal.WriteLine(StringUtil.Loc("PlatformNotSupport", RuntimeInformation.OSDescription, Constants.Agent.Platform.ToString()));
                return(Constants.Agent.ReturnCode.TerminatedError);
            }

            try
            {
                trace.Info($"Version: {Constants.Agent.Version}");
                trace.Info($"Commit: {BuildConstants.Source.CommitHash}");
                trace.Info($"Culture: {CultureInfo.CurrentCulture.Name}");
                trace.Info($"UI Culture: {CultureInfo.CurrentUICulture.Name}");

                //
                // TODO (bryanmac): Need VsoAgent.exe compat shim for SCM
                //                  That shim will also provide a compat arg parse
                //                  and translate / to -- etc...
                //

                // Parse the command line args.
                var command = new CommandSettings(context, args);
                trace.Info("Arguments parsed");

                // Defer to the Agent class to execute the command.
                IAgent agent = context.GetService <IAgent>();
                using (agent.TokenSource = new CancellationTokenSource())
                {
                    try
                    {
                        return(await agent.ExecuteCommand(command));
                    }
                    catch (OperationCanceledException) when(agent.TokenSource.IsCancellationRequested)
                    {
                        trace.Info("Agent execution been cancelled.");
                        return(Constants.Agent.ReturnCode.Success);
                    }
                    catch (NonRetryableException e)
                    {
                        terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                        trace.Error(e);
                        return(Constants.Agent.ReturnCode.TerminatedError);
                    }
                }
            }
            catch (Exception e)
            {
                terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                trace.Error(e);
                return(Constants.Agent.ReturnCode.RetryableError);
            }
        }
コード例 #24
0
ファイル: Handler.cs プロジェクト: hannahpeng/vsts-agent
 public override void Initialize(IHostContext hostContext)
 {
     base.Initialize(hostContext);
     CommandManager = hostContext.GetService <IWorkerCommandManager>();
     Environment    = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
 }
コード例 #25
0
 public override void Initialize(IHostContext hostContext)
 {
     base.Initialize(hostContext);
     _secretMasker           = hostContext.GetService <ISecretMasker>();
     Console.CancelKeyPress += Console_CancelKeyPress;
 }
コード例 #26
0
 public sealed override void Initialize(IHostContext hostContext)
 {
     base.Initialize(hostContext);
     _term = hostContext.GetService <ITerminal>();
 }
コード例 #27
0
        // Return code definition: (this will be used by service host to determine whether it will re-launch agent.listener)
        // 0: Agent exit
        // 1: Terminate failure
        // 2: Retriable failure
        // 3: Exit for self update
        public async static Task <int> MainAsync(IHostContext context, string[] args)
        {
            Tracing trace = context.GetTrace("AgentProcess");

            trace.Info($"Agent is built for {Constants.Agent.Platform} - {BuildConstants.AgentPackage.PackageName}.");
            trace.Info($"RuntimeInformation: {RuntimeInformation.OSDescription}.");
            var terminal = context.GetService <ITerminal>();

            // Validate the binaries intended for one OS are not running on a different OS.
            switch (Constants.Agent.Platform)
            {
            case Constants.OSPlatform.Linux:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                {
                    terminal.WriteLine(StringUtil.Loc("NotLinux"));
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
                break;

            case Constants.OSPlatform.OSX:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
                {
                    terminal.WriteLine(StringUtil.Loc("NotOSX"));
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
                break;

            case Constants.OSPlatform.Windows:
                if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    terminal.WriteLine(StringUtil.Loc("NotWindows"));
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }
                break;

            default:
                terminal.WriteLine(StringUtil.Loc("PlatformNotSupport", RuntimeInformation.OSDescription, Constants.Agent.Platform.ToString()));
                return(Constants.Agent.ReturnCode.TerminatedError);
            }

            try
            {
                trace.Info($"Version: {Constants.Agent.Version}");
                trace.Info($"Commit: {BuildConstants.Source.CommitHash}");
                trace.Info($"Culture: {CultureInfo.CurrentCulture.Name}");
                trace.Info($"UI Culture: {CultureInfo.CurrentUICulture.Name}");

                // Validate directory permissions.
                string agentDirectory = context.GetDirectory(WellKnownDirectory.Root);
                trace.Info($"Validating directory permissions for: '{agentDirectory}'");
                try
                {
                    IOUtil.ValidateExecutePermission(agentDirectory);
                }
                catch (Exception e)
                {
                    terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                    trace.Error(e);
                    return(Constants.Agent.ReturnCode.TerminatedError);
                }

                // Parse the command line args.
                var command = new CommandSettings(context, args);
                trace.Info("Arguments parsed");

                // Up front validation, warn for unrecognized commandline args.
                var unknownCommandlines = command.Validate();
                if (unknownCommandlines.Count > 0)
                {
                    terminal.WriteError(StringUtil.Loc("UnrecognizedCmdArgs", string.Join(", ", unknownCommandlines)));
                }

                // Defer to the Agent class to execute the command.
                IAgent agent = context.GetService <IAgent>();
                using (agent.TokenSource = new CancellationTokenSource())
                {
                    try
                    {
                        return(await agent.ExecuteCommand(command));
                    }
                    catch (OperationCanceledException) when(agent.TokenSource.IsCancellationRequested)
                    {
                        trace.Info("Agent execution been cancelled.");
                        return(Constants.Agent.ReturnCode.Success);
                    }
                    catch (NonRetryableException e)
                    {
                        terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                        trace.Error(e);
                        return(Constants.Agent.ReturnCode.TerminatedError);
                    }
                }
            }
            catch (Exception e)
            {
                terminal.WriteError(StringUtil.Loc("ErrorOccurred", e.Message));
                trace.Error(e);
                return(Constants.Agent.ReturnCode.RetryableError);
            }
        }