Beispiel #1
0
        public async Task ConnectAsync(VssConnection jobConnection)
        {
            if (HostContext.RunMode == RunMode.Local)
            {
                return;
            }

            _connection = jobConnection;
            int attemptCount = 5;

            while (!_connection.HasAuthenticated && attemptCount-- > 0)
            {
                try
                {
                    await _connection.ConnectAsync();

                    break;
                }
                catch (Exception ex) when(attemptCount > 0)
                {
                    Trace.Info($"Catch exception during connect. {attemptCount} attemp left.");
                    Trace.Error(ex);
                }

                await Task.Delay(100);
            }

            _taskAgentClient = _connection.GetClient <TaskAgentHttpClient>();
            _hasConnection   = true;
        }
Beispiel #2
0
        public async Task ConnectAsync(VssConnection jobConnection)
        {
            ArgUtil.NotNull(jobConnection, nameof(jobConnection));
            _connection = jobConnection;
            int attemptCount = 5;

            while (!_connection.HasAuthenticated && attemptCount-- > 0)
            {
                try
                {
                    await _connection.ConnectAsync();

                    break;
                }
                catch (Exception ex) when(attemptCount > 0)
                {
                    Trace.Info($"Catch exception during connect. {attemptCount} attempt left.");
                    Trace.Error(ex);
                }

                await Task.Delay(100);
            }

            _taskAgentClient = _connection.GetClient <TaskAgentHttpClient>();
            _hasConnection   = true;
        }
Beispiel #3
0
        protected bool Connect(string PAT, string organisation)
        {
            var uriString = $"https://dev.azure.com/{organisation}";

            Console.Write($"Connecting to Azure DevOps REST API, {uriString} ...");
            try
            {
                _credentials     = new VssBasicCredential(string.Empty, PAT);
                _connection      = new VssConnection(new Uri(uriString), _credentials);
                _projectClient   = _connection.GetClient <ProjectHttpClient>();
                _buildClient     = _connection.GetClient <BuildHttpClient>();
                _releaseClient   = _connection.GetClient <ReleaseHttpClient>();
                _taskAgentClient = _connection.GetClient <TaskAgentHttpClient>();
                _extensionClient = _connection.GetClient <ExtensionManagementHttpClient>();
                _endpointClient  = _connection.GetClient <ServiceEndpointHttpClient>();
                _apiService      = new ApiService(PAT);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Console.WriteLine($"Unable to authenticate with Azure DevOps REST API :(");
                return(false);
            }
            Console.WriteLine($" connected :)");
            return(true);
        }
Beispiel #4
0
        public async Task <TaskDefinition> GetTaskDefinition(string taskName, int version)
        {
            if (_httpClient == null)
            {
                _httpClient = ConnectToServer(_configuration);
            }

            if (_taskDefenitions == null)
            {
                _taskDefenitions = await _httpClient.GetTaskDefinitionsAsync();

                _taskDefenitions = FilterWithinMajorVersion(_taskDefenitions);
            }

            TaskDefinition taskDefinition;

            //If taskVersion is -1, we always get the latest version.
            if (version == -1)
            {
                var maxVersion = _taskDefenitions.Where(t => t.Name == taskName).Max(t => t.Version);
                taskDefinition = _taskDefenitions.FirstOrDefault(t => t.Name == taskName && t.Version == maxVersion);
            }
            else
            {
                taskDefinition = _taskDefenitions.FirstOrDefault(t => t.Version.Major == version && t.Name == taskName);
            }

            if (taskDefinition == null)
            {
                throw new ArgumentException($"Can't find definition for task '{taskName}' and version '{version}'");
            }

            return(taskDefinition);
        }
Beispiel #5
0
        public async Task RefreshConnectionAsync(AgentConnectionType connectionType, TimeSpan timeout)
        {
            Trace.Info($"Refresh {connectionType} VssConnection to get on a different AFD node.");
            switch (connectionType)
            {
            case AgentConnectionType.MessageQueue:
                _hasMessageConnection = false;
                _messageConnection    = await EstablishVssConnection(_messageConnection.Uri, _messageConnection.Credentials, timeout);

                _messageTaskAgentClient = _messageConnection.GetClient <TaskAgentHttpClient>();
                _hasMessageConnection   = true;
                break;

            case AgentConnectionType.JobRequest:
                _hasRequestConnection = false;
                _requestConnection    = await EstablishVssConnection(_requestConnection.Uri, _requestConnection.Credentials, timeout);

                _requestTaskAgentClient = _requestConnection.GetClient <TaskAgentHttpClient>();
                _hasRequestConnection   = true;
                break;

            case AgentConnectionType.Generic:
                _hasGenericConnection = false;
                _genericConnection    = await EstablishVssConnection(_genericConnection.Uri, _genericConnection.Credentials, timeout);

                _genericTaskAgentClient = _genericConnection.GetClient <TaskAgentHttpClient>();
                _hasGenericConnection   = true;
                break;

            default:
                throw new NotSupportedException(connectionType.ToString());
            }
        }
        public async Task ConnectAsync(Uri serverUrl, VssCredentials credentials)
        {
            if (HostContext.RunMode == RunMode.Local)
            {
                return;
            }

            // Perf: Kick off these 3 outbound calls in parallel and wait for all of them to finish.
            Task <VssConnection> task1 = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60));
            Task <VssConnection> task2 = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60));
            Task <VssConnection> task3 = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60));

            await Task.WhenAll(task1, task2, task3);

            _genericConnection = task1.Result;
            _messageConnection = task2.Result;
            _requestConnection = task3.Result;

            _genericTaskAgentClient = _genericConnection.GetClient <TaskAgentHttpClient>();
            _messageTaskAgentClient = _messageConnection.GetClient <TaskAgentHttpClient>();
            _requestTaskAgentClient = _requestConnection.GetClient <TaskAgentHttpClient>();

            _hasGenericConnection = true;
            _hasMessageConnection = true;
            _hasRequestConnection = true;
        }
        public DistributedTaskRequester()
        {
            VssCredentials creds = new VssBasicCredential(string.Empty, Credentials.TOKEN);

            VssConnection connection = new VssConnection(new Uri($"{Url}/{Credentials.ORGANIZATION}"), creds);

            _client = connection.GetClient <TaskAgentHttpClient>();
        }
Beispiel #8
0
 /// <summary>
 /// Initializes a new instance of ReleaseDefinitionActor
 /// </summary>
 /// <param name="actorService">The Microsoft.ServiceFabric.Actors.Runtime.ActorService that will host this actor instance.</param>
 /// <param name="actorId">The Microsoft.ServiceFabric.Actors.ActorId for this actor instance.</param>
 /// <param name="releaseHttpClient">release client</param>
 /// <param name="vstsConfiguration">vsts configuration</param>
 /// <param name="bigBrother">BB instance</param>
 /// <param name="taskAgentHttpClient">task agent client instance</param>
 public ReleaseDefinitionActor(ActorService actorService, ActorId actorId, ReleaseHttpClient2 releaseHttpClient,
                               VstsConfiguration vstsConfiguration, IBigBrother bigBrother, TaskAgentHttpClient taskAgentHttpClient) :
     base(actorService, actorId)
 {
     _releaseHttpClient   = releaseHttpClient;
     _vstsConfiguration   = vstsConfiguration;
     _bigBrother          = bigBrother;
     _taskAgentHttpClient = taskAgentHttpClient;
 }
        public VariableGroupVstsRepository(string account, string token, [NotNull] IParametersResolver parametersResolver)
        {
            _parametersResolver = parametersResolver ?? throw new ArgumentNullException(nameof(parametersResolver));

            _connection = new VssConnection(new Uri(string.Format(UrlFormat, account)),
                                            new VssBasicCredential(string.Empty, token));

            _client = _connection.GetClient <TaskAgentHttpClient>();
        }
Beispiel #10
0
        private async Task <TaskAgentHttpClient> GetTaskAgentClientAsync(CancellationToken cancellationToken)
        {
            if (cachedTaskAgentClient == null)
            {
                var connection = GetConnection();
                cachedTaskAgentClient = await connection.GetClientAsync <TaskAgentHttpClient>(cancellationToken);
            }

            return(cachedTaskAgentClient);
        }
Beispiel #11
0
        public async Task ConnectAsync(VssConnection agentConnection)
        {
            _connection = agentConnection;
            if (!_connection.HasAuthenticated)
            {
                await _connection.ConnectAsync();
            }

            _taskAgentClient = _connection.GetClient<TaskAgentHttpClient>();
            _hasConnection = true;
        }
        public void DeleteATaskGroup()
        {
            string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;

            // Get a task agent client instance
            VssConnection       connection = Context.Connection;
            TaskAgentHttpClient taskClient = connection.GetClient <TaskAgentHttpClient>();

            // Delete the already created task group
            taskClient.DeleteTaskGroupAsync(project: projectName, taskGroupId: this.addedTaskGroupId).SyncResult();
        }
        public void DeleteDeploymentGroup()
        {
            String projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;

            // Get a task agent client instance
            VssConnection       connection = Context.Connection;
            TaskAgentHttpClient dgClient   = connection.GetClient <TaskAgentHttpClient>();

            // Delete deployment group by ID
            dgClient.DeleteDeploymentGroupAsync(project: projectName, deploymentGroupId: this.addedDeploymentGroupId).SyncResult();
        }
Beispiel #14
0
        public async Task ConnectAsync(VssConnection agentConnection)
        {
            _connection = agentConnection;
            if (!_connection.HasAuthenticated)
            {
                await _connection.ConnectAsync();
            }

            _taskAgentClient = _connection.GetClient <TaskAgentHttpClient>();
            _hasConnection   = true;
        }
Beispiel #15
0
        public async Task ConnectAsync(VssConnection agentConnection)
        {
            ArgUtil.NotNull(agentConnection, nameof(agentConnection));
            _connection = agentConnection;
            if (!_connection.HasAuthenticated)
            {
                await _connection.ConnectAsync();
            }

            _taskAgentClient = _connection.GetClient <TaskAgentHttpClient>();
            _hasConnection   = true;
        }
        public DeploymentGroup GetDeploymentGroupById()
        {
            String projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;

            // Get a task agent client instance
            VssConnection       connection = Context.Connection;
            TaskAgentHttpClient dgClient   = connection.GetClient <TaskAgentHttpClient>();

            // Get deployment group by Id
            DeploymentGroup deploymentGroup = dgClient.GetDeploymentGroupAsync(project: projectName, deploymentGroupId: this.addedDeploymentGroupId).Result;

            return(deploymentGroup);
        }
        public IList <DeploymentGroup> ListAllDeploymentGroups()
        {
            String projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;

            // Get a task agent client instance
            VssConnection       connection = Context.Connection;
            TaskAgentHttpClient dgClient   = connection.GetClient <TaskAgentHttpClient>();

            // List all deployment groups
            IList <DeploymentGroup> deploymentGroups = dgClient.GetDeploymentGroupsAsync(project: projectName).Result;

            return(deploymentGroups);
        }
Beispiel #18
0
        private async Task <IEnumerable <Agent> > GetAllAgentsForInstance(TaskAgentHttpClient client, ILogger logger)
        {
            IEnumerable <Agent> allAgents = new List <Agent>();
            var pools = await client.GetAgentPoolsAsync();

            foreach (var p in pools.Where(x => x.IsHosted == false))
            {
                var agentsInPool = await client.GetAgentsAsync(p.Id, includeCapabilities : true);

                var convertedAgents = agentsInPool.Select(x => new Agent(x, p.Id));

                allAgents = allAgents.Concat(convertedAgents);
            }

            return(allAgents);
        }
        public TaskGroup CreateTaskGroup()
        {
            string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;

            // Get a task agent client instance
            VssConnection       connection = Context.Connection;
            TaskAgentHttpClient taskClient = connection.GetClient <TaskAgentHttpClient>();

            Dictionary <string, string> inputs = new Dictionary <string, string>()
            {
                { "scriptType", "inlineScript" },
                { "inlineScript", "Write-Host \"Hello World\"" },
            };
            // Task inside the task group
            TaskGroupStep taskGroupStep = new TaskGroupStep()
            {
                Enabled     = true,
                DisplayName = "PowerShell Script",
                Inputs      = inputs,
                Task        = new TaskDefinitionReference {
                    Id = new Guid("e213ff0f-5d5c-4791-802d-52ea3e7be1f1"), VersionSpec = "1.*", DefinitionType = "task"
                },
            };

            // Task group object
            TaskGroupCreateParameter taskGroup = new TaskGroupCreateParameter()
            {
                Category           = "Deploy",
                Name               = "PowerShell TG1",
                InstanceNameFormat = "Task group: TG",
                Version            = new TaskVersion {
                    IsTest = false, Major = 1, Minor = 0, Patch = 0
                }
            };

            taskGroup.Tasks.Add(taskGroupStep);

            // Create task group
            TaskGroup addedTg = taskClient.AddTaskGroupAsync(project: projectName, taskGroup: taskGroup).Result;

            this.addedTaskGroupId = addedTg.Id;

            // Show the added task group
            Context.Log("{0} {1}", addedTg.Id.ToString().PadLeft(6), addedTg.Name);

            return(addedTg);
        }
        public List <TaskGroup> AllTaskGroups()
        {
            string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;

            // Get a task agent client instance
            VssConnection       connection = Context.Connection;
            TaskAgentHttpClient taskClient = connection.GetClient <TaskAgentHttpClient>();

            // List all task groups
            List <TaskGroup> taskGroups = taskClient.GetTaskGroupsAsync(project: projectName).Result;

            foreach (TaskGroup taskGroup in taskGroups)
            {
                Context.Log("{0} {1}", taskGroup.Id.ToString().PadLeft(6), taskGroup.Name);
            }

            return(taskGroups);
        }
    internal static Task <VariableGroup> AddVariableGroupAsync(this TaskAgentHttpClient client, TeamProject project, string name, IDictionary <string, VariableValue> variables, string description = null)
    {
        if (client is null)
        {
            throw new ArgumentNullException(nameof(client));
        }

        if (project is null)
        {
            throw new ArgumentNullException(nameof(project));
        }

        if (string.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException($"'{nameof(name)}' cannot be null or whitespace.", nameof(name));
        }

        if (variables is null)
        {
            throw new ArgumentNullException(nameof(variables));
        }

        if (!variables.Any())
        {
            throw new ArgumentException($"'{nameof(name)}' must contain at least one variable.", nameof(variables));
        }

        return(client.AddVariableGroupAsync(new VariableGroupParameters()
        {
            Name = name,
            Description = description,
            Type = "Vsts",
            Variables = variables,
            VariableGroupProjectReferences = new List <VariableGroupProjectReference>()
            {
                new VariableGroupProjectReference()
                {
                    Name = name,
                    Description = description,
                    ProjectReference = project.ToVariableProjectReference()
                }
            }
        }));
    }
Beispiel #22
0
        public static void UpdateVariableGroup()
        {
            var tpc = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(new Uri(collectionUrl));
            TaskAgentHttpClient taskagentClient = tpc.GetClient <TaskAgentHttpClient>();

            var varGroup = taskagentClient.GetVariableGroupAsync(projectName, 1).GetAwaiter().GetResult();
            int varCount = varGroup.Variables.Count;
            var v        = varGroup.Variables["var1"];

            varGroup.Variables["var1"] = "val1";

            VariableGroupParameters varGroupParam = new VariableGroupParameters();

            varGroupParam.Variables = varGroup.Variables;
            varGroupParam.Name      = varGroup.Name;

            //change 1 with your variable group id
            taskagentClient.UpdateVariableGroupAsync(projectName, 1, varGroupParam).GetAwaiter().GetResult();
        }
Beispiel #23
0
        public async Task ConnectAsync(Uri serverUrl, VssCredentials credentials)
        {
            var createGenericConnection = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(100));
            var createMessageConnection = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60));
            var createRequestConnection = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60));

            await Task.WhenAll(createGenericConnection, createMessageConnection, createRequestConnection);

            _genericConnection = await createGenericConnection;
            _messageConnection = await createMessageConnection;
            _requestConnection = await createRequestConnection;

            _genericTaskAgentClient = _genericConnection.GetClient <TaskAgentHttpClient>();
            _messageTaskAgentClient = _messageConnection.GetClient <TaskAgentHttpClient>();
            _requestTaskAgentClient = _requestConnection.GetClient <TaskAgentHttpClient>();

            _hasGenericConnection = true;
            _hasMessageConnection = true;
            _hasRequestConnection = true;
        }
        public DeploymentGroup CreateDeploymentGroup()
        {
            String projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;

            // Get a task agent client instance
            VssConnection       connection = Context.Connection;
            TaskAgentHttpClient dgClient   = connection.GetClient <TaskAgentHttpClient>();

            // Create deployment groups
            DeploymentGroupCreateParameter deploymentGroupCreateParameter = new DeploymentGroupCreateParameter()
            {
                Name        = "MyDeploymentGroup1",
                Description = "This deployment group is created to demnostrate the client usage"
            };

            DeploymentGroup addedDeploymentGroup = dgClient.AddDeploymentGroupAsync(projectName, deploymentGroupCreateParameter).Result;

            this.addedDeploymentGroupId = addedDeploymentGroup.Id;
            return(addedDeploymentGroup);
        }
Beispiel #25
0
        public async Task ConnectAsync(Uri serverUrl, VssCredentials credentials)
        {
            if (HostContext.RunMode == RunMode.Local)
            {
                return;
            }

            _genericConnection = await EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(100));

            _messageConnection = await EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60));

            _requestConnection = await EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60));

            _genericTaskAgentClient = _genericConnection.GetClient <TaskAgentHttpClient>();
            _messageTaskAgentClient = _messageConnection.GetClient <TaskAgentHttpClient>();
            _requestTaskAgentClient = _requestConnection.GetClient <TaskAgentHttpClient>();

            _hasGenericConnection = true;
            _hasMessageConnection = true;
            _hasRequestConnection = true;
        }
        public DeploymentGroup UpdateDeploymentGroup()
        {
            String projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;

            // Get a task agent client instance
            VssConnection       connection = Context.Connection;
            TaskAgentHttpClient dgClient   = connection.GetClient <TaskAgentHttpClient>();

            // Get task group to update
            DeploymentGroup deploymentGroup = dgClient.GetDeploymentGroupAsync(project: projectName, deploymentGroupId: this.addedDeploymentGroupId).Result;

            DeploymentGroupUpdateParameter deploymentGroupUpdateParameter = new DeploymentGroupUpdateParameter
            {
                Name        = deploymentGroup.Name + "-Update1",
                Description = "Description of this deployment group is updated"
            };

            // Update deployment group
            DeploymentGroup updatedDeploymentGroup = dgClient.UpdateDeploymentGroupAsync(project: projectName, deploymentGroupId: this.addedDeploymentGroupId, deploymentGroup: deploymentGroupUpdateParameter).Result;

            return(updatedDeploymentGroup);
        }
        public TaskGroup UpdateTaskGroup()
        {
            string projectName = ClientSampleHelpers.FindAnyProject(this.Context).Name;

            // Get a task agent client instance
            VssConnection       connection = Context.Connection;
            TaskAgentHttpClient taskClient = connection.GetClient <TaskAgentHttpClient>();

            // Get task group to update
            List <TaskGroup> taskGroups = taskClient.GetTaskGroupsAsync(project: projectName, taskGroupId: this.addedTaskGroupId).Result;

            Dictionary <string, string> inputs = new Dictionary <string, string>()
            {
                { "scriptType", "inlineScript" },
                { "inlineScript", "Write-Host \"New task\"" },
            };
            // New Task to be added in the task group
            TaskGroupStep newTask = new TaskGroupStep()
            {
                Enabled     = true,
                DisplayName = "PowerShell Script",
                Inputs      = inputs,
                Task        = new TaskDefinitionReference {
                    Id = new Guid("e213ff0f-5d5c-4791-802d-52ea3e7be1f1"), VersionSpec = "1.*", DefinitionType = "task"
                },
            };

            // Update comment in the task group object.
            TaskGroup taskGroup = taskGroups.FirstOrDefault();

            taskGroup.Comment = "Updated the task group";
            taskGroup.Tasks.Add(newTask);
            TaskGroupUpdateParameter taskGroupUpdateParams = GetTaskGroupUpdateParameter(taskGroup);
            TaskGroup updatedTaskGroup = taskClient.UpdateTaskGroupAsync(project: projectName, taskGroupId: taskGroup.Id, taskGroup: taskGroupUpdateParams).Result;

            Context.Log("{0} {1}", updatedTaskGroup.Id.ToString().PadLeft(6), updatedTaskGroup.Comment);

            return(updatedTaskGroup);
        }
    internal static Task <VariableGroup> UpdateVariableGroupAsync(this TaskAgentHttpClient client, TeamProject project, VariableGroup group)
    {
        if (client is null)
        {
            throw new ArgumentNullException(nameof(client));
        }

        if (project is null)
        {
            throw new ArgumentNullException(nameof(project));
        }

        if (group is null)
        {
            throw new ArgumentNullException(nameof(group));
        }

        var variableGroupProjectReferenced = group.VariableGroupProjectReferences ?? new List <VariableGroupProjectReference>();

        if (!variableGroupProjectReferenced.Any(r => project.Id.Equals(r.ProjectReference?.Id)))
        {
            variableGroupProjectReferenced.Add(new VariableGroupProjectReference()
            {
                Name             = group.Name,
                Description      = group.Description,
                ProjectReference = project.ToVariableProjectReference()
            });
        }

        return(client.UpdateVariableGroupAsync(group.Id, new VariableGroupParameters()
        {
            Name = group.Name,
            Description = group.Description,
            Type = group.Type,
            Variables = group.Variables,
            VariableGroupProjectReferences = variableGroupProjectReferenced
        }));
    }
Beispiel #29
0
        public async Task ConnectAsync(Uri serverUrl, VssCredentials credentials)
        {
            // Establish the first connection before doing the rest in parallel to eliminate the redundant 401s.
            // issue: https://github.com/microsoft/azure-pipelines-agent/issues/3149
            Task <VssConnection> task1 = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(100));

            _genericConnection = await task1;

            Task <VssConnection> task2 = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60));
            Task <VssConnection> task3 = EstablishVssConnection(serverUrl, credentials, TimeSpan.FromSeconds(60));

            await Task.WhenAll(task2, task3);

            _messageConnection = task2.Result;
            _requestConnection = task3.Result;

            _genericTaskAgentClient = _genericConnection.GetClient <TaskAgentHttpClient>();
            _messageTaskAgentClient = _messageConnection.GetClient <TaskAgentHttpClient>();
            _requestTaskAgentClient = _requestConnection.GetClient <TaskAgentHttpClient>();

            _hasGenericConnection = true;
            _hasMessageConnection = true;
            _hasRequestConnection = true;
        }
Beispiel #30
0
        // Refresh connection is best effort. it should never throw exception
        public async Task RefreshConnectionAsync(RunnerConnectionType connectionType, TimeSpan timeout)
        {
            Trace.Info($"Refresh {connectionType} VssConnection to get on a different AFD node.");
            VssConnection newConnection = null;

            switch (connectionType)
            {
            case RunnerConnectionType.MessageQueue:
                try
                {
                    _hasMessageConnection = false;
                    newConnection         = await EstablishVssConnection(_messageConnection.Uri, _messageConnection.Credentials, timeout);

                    var client = newConnection.GetClient <TaskAgentHttpClient>();
                    _messageConnection      = newConnection;
                    _messageTaskAgentClient = client;
                }
                catch (Exception ex)
                {
                    Trace.Error($"Catch exception during reset {connectionType} connection.");
                    Trace.Error(ex);
                    newConnection?.Dispose();
                }
                finally
                {
                    _hasMessageConnection = true;
                }
                break;

            case RunnerConnectionType.JobRequest:
                try
                {
                    _hasRequestConnection = false;
                    newConnection         = await EstablishVssConnection(_requestConnection.Uri, _requestConnection.Credentials, timeout);

                    var client = newConnection.GetClient <TaskAgentHttpClient>();
                    _requestConnection      = newConnection;
                    _requestTaskAgentClient = client;
                }
                catch (Exception ex)
                {
                    Trace.Error($"Catch exception during reset {connectionType} connection.");
                    Trace.Error(ex);
                    newConnection?.Dispose();
                }
                finally
                {
                    _hasRequestConnection = true;
                }
                break;

            case RunnerConnectionType.Generic:
                try
                {
                    _hasGenericConnection = false;
                    newConnection         = await EstablishVssConnection(_genericConnection.Uri, _genericConnection.Credentials, timeout);

                    var client = newConnection.GetClient <TaskAgentHttpClient>();
                    _genericConnection      = newConnection;
                    _genericTaskAgentClient = client;
                }
                catch (Exception ex)
                {
                    Trace.Error($"Catch exception during reset {connectionType} connection.");
                    Trace.Error(ex);
                    newConnection?.Dispose();
                }
                finally
                {
                    _hasGenericConnection = true;
                }
                break;

            default:
                Trace.Error($"Unexpected connection type: {connectionType}.");
                break;
            }
        }
Beispiel #31
0
        public async Task <int> RunAsync(CommandSettings command, CancellationToken token)
        {
            Trace.Info(nameof(RunAsync));
            var           configStore = HostContext.GetService <IConfigurationStore>();
            AgentSettings settings    = configStore.GetSettings();

            // Store the HTTP client.
            // todo: fix in master to allow URL to be empty and then rebase on master.
            const string DefaultUrl = "http://127.0.0.1/local-runner-default-url";
            string       url        = command.GetUrl(DefaultUrl);

            if (!string.Equals(url, DefaultUrl, StringComparison.Ordinal))
            {
                var    credentialManager     = HostContext.GetService <ICredentialManager>();
                string authType              = command.GetAuth(defaultValue: Constants.Configuration.Integrated);
                ICredentialProvider provider = credentialManager.GetCredentialProvider(authType);
                provider.EnsureCredential(HostContext, command, url);
                _httpClient = new TaskAgentHttpClient(new Uri(url), provider.GetVssCredentials(HostContext));
            }

            // Load the YAML file.
            string yamlFile = command.GetYaml();

            ArgUtil.File(yamlFile, nameof(yamlFile));
            var parseOptions = new ParseOptions
            {
                MaxFiles = 10,
                MustacheEvaluationMaxResultLength = 512 * 1024, // 512k string length
                MustacheEvaluationTimeout         = TimeSpan.FromSeconds(10),
                MustacheMaxDepth = 5,
            };
            var pipelineParser = new PipelineParser(new PipelineTraceWriter(), new PipelineFileProvider(), parseOptions);

            Pipelines.Process process = pipelineParser.Load(
                defaultRoot: Directory.GetCurrentDirectory(),
                path: yamlFile,
                mustacheContext: null,
                cancellationToken: HostContext.AgentShutdownToken);
            ArgUtil.NotNull(process, nameof(process));
            if (command.WhatIf)
            {
                return(Constants.Agent.ReturnCode.Success);
            }

            // Create job message.
            IJobDispatcher jobDispatcher = null;

            try
            {
                jobDispatcher = HostContext.CreateService <IJobDispatcher>();
                foreach (JobInfo job in await ConvertToJobMessagesAsync(process, token))
                {
                    job.RequestMessage.Environment.Variables[Constants.Variables.Agent.RunMode] = RunMode.Local.ToString();
                    jobDispatcher.Run(job.RequestMessage);
                    Task jobDispatch = jobDispatcher.WaitAsync(token);
                    if (!Task.WaitAll(new[] { jobDispatch }, job.Timeout))
                    {
                        jobDispatcher.Cancel(job.CancelMessage);

                        // Finish waiting on the same job dispatch task. The first call to WaitAsync dequeues
                        // the dispatch task and then proceeds to wait on it. So we need to continue awaiting
                        // the task instance (queue is now empty).
                        await jobDispatch;
                    }
                }
            }
            finally
            {
                if (jobDispatcher != null)
                {
                    await jobDispatcher.ShutdownAsync();
                }
            }

            return(Constants.Agent.ReturnCode.Success);
        }