private static void AddPlayerClient(this IServiceCollection services, ClientOptions clientOptions, ILoggerFactory loggerFactory)
        {
            var policy = GetPolicy(clientOptions.MaxRetryDelaySeconds, "Player Vm Api", loggerFactory);

            services.AddHttpClient("player", client =>
            {
                // Workaround to avoid TaskCanceledException after several retries. TODO: find a better way to handle this.
                client.Timeout = Timeout.InfiniteTimeSpan;
            })
            .AddHttpMessageHandler <AuthenticatingHandler>()
            .AddPolicyHandler(policy);

            services.AddScoped <IPlayerVmApiClient, PlayerVmApiClient>(p =>
            {
                var httpClientFactory = p.GetRequiredService <IHttpClientFactory>();
                var playerOptions     = p.GetRequiredService <PlayerOptions>();

                var uri = new Uri(playerOptions.VmApiUrl);

                var httpClient         = httpClientFactory.CreateClient("player");
                httpClient.BaseAddress = uri;

                var playerVmApiClient = new PlayerVmApiClient(httpClient, true)
                {
                    BaseUri = uri
                };

                return(playerVmApiClient);
            });
        }
Пример #2
0
        public static PlayerVmApiClient GetVmApiClient(IHttpClientFactory httpClientFactory, string apiUrl, TokenResponse tokenResponse)
        {
            var client    = ApiClientsExtensions.GetHttpClient(httpClientFactory, apiUrl, tokenResponse);
            var apiClient = new PlayerVmApiClient(client, true)
            {
                BaseUri = client.BaseAddress
            };

            return(apiClient);
        }
Пример #3
0
        private PlayerVmApiClient RefreshClient(PlayerVmApiClient clientObject, TokenResponse tokenResponse, CancellationToken ct)
        {
            // TODO: check for token expiration also
            if (clientObject == null)
            {
                clientObject = VmApiExtensions.GetVmApiClient(_httpClientFactory, _clientOptions.CurrentValue.urls.vmApi, tokenResponse);
            }

            return(clientObject);
        }
Пример #4
0
        public static void AddPlayerVmApiClient(this IServiceCollection services)
        {
            services.AddScoped <IPlayerVmApiClient, PlayerVmApiClient>(p =>
            {
                var httpContextAccessor = p.GetRequiredService <IHttpContextAccessor>();
                var httpClientFactory   = p.GetRequiredService <IHttpClientFactory>();
                var clientOptions       = p.GetRequiredService <ClientOptions>();

                var vmUri = new Uri(clientOptions.urls.vmApi);

                string authHeader = httpContextAccessor.HttpContext.Request.Headers["Authorization"];

                var httpClient         = httpClientFactory.CreateClient();
                httpClient.BaseAddress = vmUri;
                httpClient.DefaultRequestHeaders.Add("Authorization", authHeader);

                var apiClient = new PlayerVmApiClient(httpClient, true)
                {
                    BaseUri = vmUri
                };

                return(apiClient);
            });
        }
Пример #5
0
 public static async Task <IEnumerable <Player.Vm.Api.Models.Vm> > GetViewVmsAsync(PlayerVmApiClient playerVmApiClient, Guid viewId, CancellationToken ct)
 {
     try
     {
         var vms = (await playerVmApiClient.GetViewVmsAsync(viewId, null, true, false, ct)) as IEnumerable <Player.Vm.Api.Models.Vm>;
         return(vms);
     }
     catch (Exception ex)
     {
         return(null);
     }
 }
Пример #6
0
        private async STT.Task <List <ResultEntity> > CreateResultsAsync(TaskEntity taskToExecute, ScenarioEntity scenarioEntity, Guid userId, CancellationToken ct)
        {
            var  resultEntities = new List <ResultEntity>();
            Guid?viewId         = null;

            if (taskToExecute.VmMask.Count() == 0)
            {
                // this task has no VM's associated. Create one result entity.  Used to send a command to an API, etc.
                var resultEntity = NewResultEntity(taskToExecute, userId);
                resultEntities.Add(resultEntity);
            }
            else
            {
                // A scenario is assigned to a specific view
                viewId = scenarioEntity.ViewId;
                // at this point, the VmMask could contain an actual mask, or a comma separated list of VM ID's
                var vmMaskList = taskToExecute.VmMask.Split(",").ToList();
                var vmIdList   = new List <Guid>();
                var vmList     = new List <Player.Vm.Api.Models.Vm>();
                // create the ID list, if the mask is a list of Guid's. If not Guid's, vmIdList will end up empty.
                foreach (var mask in vmMaskList)
                {
                    Guid vmId;
                    if (Guid.TryParse(mask, out vmId))
                    {
                        vmIdList.Add(vmId);
                    }
                }
                // determine if VM's should match by Name or ID
                var matchName = vmIdList.Count() == 0;
                // create a VmList from the view ID and the VmMask matching criteria
                try
                {
                    using (var scope = _scopeFactory.CreateScope())
                    {
                        PlayerVmApiClient vmApiClient = null;
                        var tokenResponse             = await ApiClientsExtensions.GetToken(scope);

                        vmApiClient = RefreshClient(vmApiClient, tokenResponse, ct);
                        var viewVms = await VmApiExtensions.GetViewVmsAsync(vmApiClient, (Guid)viewId, ct);

                        foreach (var vm in viewVms)
                        {
                            if ((!matchName && vmIdList.Contains((Guid)vm.Id)) || (matchName && vm.Name.ToLower().Contains(taskToExecute.VmMask.ToLower())))
                            {
                                vmList.Add(vm);
                            }
                        }
                    }
                }
                catch (System.Exception)
                {
                    _logger.LogDebug($"CreateResultsAsync - No VM's found in view {viewId}");
                }
                // make sure we are only matching a SINGLE view
                if (vmList.Count() > 0)
                {
                    // create a result for each matched VM
                    foreach (var vm in vmList)
                    {
                        var resultEntity = NewResultEntity(taskToExecute, userId);
                        resultEntity.VmId   = vm.Id;
                        resultEntity.VmName = vm.Name;
                        resultEntities.Add(resultEntity);
                    }
                }
                else
                {
                    // Houston, we've had a problem.  Create a single result to show the error
                    var resultEntity = NewResultEntity(taskToExecute, userId);
                    if (viewId != null)
                    {
                        // The problem is that NO VM's matched
                        resultEntity.ActualOutput = $"No matched VMs!  VM Mask: {taskToExecute.VmMask}.";
                    }
                    else if (scenarioEntity != null)
                    {
                        // The problem is that this task did not have a scenario or a viewId
                        resultEntity.ActualOutput = $"There was no view associated with this task's scenario!  {taskToExecute.Name} ({taskToExecute.Id})";
                    }
                    else
                    {
                        // The problem is that this task did not have a scenario or a viewId
                        resultEntity.ActualOutput = $"There was no scenario associated with this task!  {taskToExecute.Name} ({taskToExecute.Id})";
                    }
                    _logger.LogError($"CreateResultsAsync - {resultEntity.ActualOutput}");
                    resultEntity.Status     = Data.TaskStatus.error;
                    resultEntity.StatusDate = DateTime.UtcNow;
                    resultEntities.Add(resultEntity);
                }
            }
            return(resultEntities);
        }