Ejemplo n.º 1
0
        public async Task Instance_Delete_ClearRepo()
        {
            _deviceRepoManager.Setup(drm => drm.GetDeviceRepositoryAsync(NEW_DEVICE_REPO_ID, It.IsAny <EntityHeader>(), It.IsAny <EntityHeader>())).Returns((string id, EntityHeader user, EntityHeader org) =>
            {
                return(Task.FromResult <DeviceRepository>(new DeviceRepository()
                {
                    Id = NEW_DEVICE_REPO_ID,
                    Instance = new EntityHeader()
                    {
                        Id = DEVICE_INSTANCE_ID, Text = "dontcare"
                    },
                }));
            });

            var host = new DeploymentHost()
            {
                Id = "MYHOSTID", HostType = EntityHeader <HostTypes> .Create(HostTypes.Dedicated)
            };

            var instance = GetInstance();

            instance.PrimaryHost = new EntityHeader <DeploymentHost>()
            {
                Id = host.Id
            };

            _deploymentHostManager.Setup(dhm => dhm.GetDeploymentHostAsync(instance.PrimaryHost.Id, It.IsAny <EntityHeader>(), It.IsAny <EntityHeader>(), It.IsAny <Boolean>())).ReturnsAsync(host);
            _deploymentInstanceRepo.Setup(inst => inst.GetInstanceAsync(DEVICE_INSTANCE_ID)).ReturnsAsync(instance);
            await _instanceManager.DeleteInstanceAsync(instance.Id, ORG, USER);

            Assert.IsTrue(instance.IsArchived);
            /* Didn't change, don't call method to get or update the device repo */
            _deviceRepoManager.Verify(drm => drm.UpdateDeviceRepositoryAsync(It.Is <DeviceRepository>(rpo => rpo.Id == NEW_DEVICE_REPO_ID && rpo.Instance == null), It.IsAny <EntityHeader>(), It.IsAny <EntityHeader>()), Times.Once);
        }
        private DeploymentHost CreateHost(DeploymentInstance instance)
        {
            var host = new DeploymentHost
            {
                Id                = Guid.NewGuid().ToId(),
                HostType          = EntityHeader <HostTypes> .Create(HostTypes.Dedicated),
                CreatedBy         = instance.CreatedBy,
                Name              = $"{instance.Name} Host",
                LastUpdatedBy     = instance.LastUpdatedBy,
                OwnerOrganization = instance.OwnerOrganization,
                OwnerUser         = instance.OwnerUser,
                CreationDate      = instance.CreationDate,
                LastUpdatedDate   = instance.LastUpdatedDate,
                DedicatedInstance = new EntityHeader()
                {
                    Id = instance.Id, Text = instance.Name
                },
                Key                 = instance.Key,
                IsPublic            = false,
                Status              = EntityHeader <HostStatus> .Create(HostStatus.Offline),
                Size                = instance.Size,
                CloudProvider       = instance.CloudProvider,
                Subscription        = instance.Subscription,
                ContainerRepository = instance.ContainerRepository,
                ContainerTag        = instance.ContainerTag,
                DnsHostName         = instance.DnsHostName,
            };

            return(host);
        }
Ejemplo n.º 3
0
        public async Task Instance_Delete_ShouldNotDeleteIfNotDedicated()
        {
            _deviceRepoManager.Setup(drm => drm.GetDeviceRepositoryAsync(NEW_DEVICE_REPO_ID, It.IsAny <EntityHeader>(), It.IsAny <EntityHeader>())).ReturnsAsync(new DeviceRepository()
            {
                Id = NEW_DEVICE_REPO_ID, Instance = new EntityHeader()
                {
                    Id = DEVICE_INSTANCE_ID, Text = "dontcare"
                }
            });

            var host = new DeploymentHost()
            {
                Id = "MYHOSTID", HostType = EntityHeader <HostTypes> .Create(HostTypes.Free)
            };

            var instance = GetInstance();

            instance.PrimaryHost = new EntityHeader <DeploymentHost>()
            {
                Id = host.Id
            };

            _deploymentInstanceRepo.Setup(inst => inst.GetInstanceAsync(DEVICE_INSTANCE_ID)).ReturnsAsync(instance);

            _deploymentHostManager.Setup(dhm => dhm.GetDeploymentHostAsync(instance.PrimaryHost.Id, It.IsAny <EntityHeader>(), It.IsAny <EntityHeader>(), It.IsAny <Boolean>())).ReturnsAsync(host);

            await _instanceManager.DeleteInstanceAsync(instance.Id, ORG, USER);

            _deploymentHostManager.Verify(dhm => dhm.DeleteDeploymentHostAsync(host.Id, It.IsAny <EntityHeader>(), It.IsAny <EntityHeader>()), Times.Never);
        }
Ejemplo n.º 4
0
        public async Task <InvokeResult> AddDeploymentHostAsync(DeploymentHost host, EntityHeader org, EntityHeader user)
        {
            ValidationCheck(host, Actions.Create);
            await AuthorizeAsync(host, AuthorizeResult.AuthorizeActions.Create, user, org);

            await _deploymentHostRepo.AddDeploymentHostAsync(host);

            return(InvokeResult.Success);
        }
Ejemplo n.º 5
0
        public void Init()
        {
            _host = new DeploymentHost()
            {
                Id     = "MYHOSTID",
                Status = EntityHeader <HostStatus> .Create(HostStatus.Offline)
            };
            _hostRepo.Setup(hrs => hrs.GetDeploymentHostAsync(_host.Id, true)).ReturnsAsync(_host);

            _deploymentHostManager = new DeploymentHostManager(_hostRepo.Object, new Mock <IDeploymentActivityQueueManager>().Object, new Mock <IDeploymentActivityRepo>().Object,
                                                               new Mock <IDeploymentConnectorService>().Object, new Mock <IDeploymentInstanceRepo>().Object, new Mock <IAdminLogger>().Object, new Mock <IDeploymentHostStatusRepo>().Object, new Mock <IAppConfig>().Object,
                                                               new Mock <IDependencyManager>().Object, _security.Object);
        }
Ejemplo n.º 6
0
        protected IDeploymentConnectorService GetConnector(DeploymentHost host, string organizationId, string instanceId)
        {
            if (host == null)
            {
                throw new ArgumentNullException(nameof(host));
            }

            return(IsRpc(host)
                ? _proxyFactory.Create <IDeploymentConnectorService>(new ProxySettings
            {
                OrganizationId = organizationId ?? throw new ArgumentNullException(nameof(organizationId)),
                InstanceId = instanceId ?? throw new ArgumentNullException(nameof(instanceId))
            })
        private HttpClient GetHttpClient(DeploymentHost host, EntityHeader org, EntityHeader usr, string method, string path)
        {
            var request     = new HttpClient();
            var requestId   = Guid.NewGuid().ToId();
            var requestDate = DateTime.UtcNow.ToString("R", System.Globalization.CultureInfo.InvariantCulture);

            request.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            request.DefaultRequestHeaders.Add("x-nuviot-client-request-id", requestId);
            request.DefaultRequestHeaders.Add("x-nuviot-orgid", org.Id);
            request.DefaultRequestHeaders.Add("x-nuviot-org", org.Text);
            request.DefaultRequestHeaders.Add("x-nuviot-userid", usr.Id);
            request.DefaultRequestHeaders.Add("x-nuviot-user", usr.Text);
            request.DefaultRequestHeaders.Add("x-nuviot-date", requestDate);
            request.DefaultRequestHeaders.Add("x-nuviot-version", CLIENT_VERSION);
            request.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("SharedKey", RequestSigningService.GetAuthHeaderValue(host, requestId, org.Id, usr.Id, method, path, requestDate));

            return(request);
        }
Ejemplo n.º 8
0
        public async Task <InvokeResult> UpdateDeploymentHostAsync(DeploymentHost host, EntityHeader org, EntityHeader user)
        {
            ValidationCheck(host, Actions.Update);

            var existingHost = await _deploymentHostRepo.GetDeploymentHostAsync(host.Id);

            if (host.Status.Value != existingHost.Status.Value)
            {
                await UpdateDeploymentHostStatusAsync(host.Id, host.Status.Value, host.ContainerTag.Text, org, user);
            }
            await CheckOwnershipOrSysAdminAsync(host, org, user);

            host.LastUpdatedDate = DateTime.UtcNow.ToJSONString();
            host.LastUpdatedBy   = user;
            await _deploymentHostRepo.UpdateDeploymentHostAsync(host);

            return(InvokeResult.Success);
        }
        protected async Task <InvokeResult> GetAsync(string path, DeploymentHost host, EntityHeader org, EntityHeader user, ListRequest listRequest = null)
        {
            using (var request = GetHttpClient(host, org, user, "GET", path))
            {
                try
                {
                    var uri = new Uri($"{host.AdminAPIUri}{path}");
                    Console.WriteLine(uri);
                    var response = await request.GetAsync(uri);

                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        return(JsonConvert.DeserializeObject <InvokeResult>(json));
                    }
                    else
                    {
                        _logger.AddCustomEvent(LogLevel.Error, "DeploymentConnectorService", $"{response.StatusCode} - {response.ReasonPhrase}",
                                               new KeyValuePair <string, string>("hostid", host.Id),
                                               new KeyValuePair <string, string>("path", path),
                                               new KeyValuePair <string, string>("orgid", org.Id),
                                               new KeyValuePair <string, string>("userid", user.Id));

                        return(DeploymentErrorCodes.ErrorCommunicatingWithhost.ToFailedInvocation($"{response.StatusCode} - {response.ReasonPhrase}"));
                    }
                }
                catch (Exception ex)
                {
                    _logger.AddCustomEvent(LogLevel.Error, "DeploymentConnectorService", ex.Message,
                                           new KeyValuePair <string, string>("hostid", host.Id),
                                           new KeyValuePair <string, string>("path", path),
                                           new KeyValuePair <string, string>("orgid", org.Id),
                                           new KeyValuePair <string, string>("userid", user.Id));

                    return(DeploymentErrorCodes.ErrorCommunicatingWithhost.ToFailedInvocation(ex.Message));
                }
            }
        }
Ejemplo n.º 10
0
 private InvokeResult CanTransitionToState(DeploymentHost host, DeploymentInstance instance, DeploymentActivityTaskTypes taskType, EntityHeader org, EntityHeader user)
 {
     return(InvokeResult.Success);
 }
Ejemplo n.º 11
0
        public Task <InvokeResult> UpdateAsync(DeploymentHost host, string instanceId, EntityHeader org, EntityHeader user)
        {
            var path = $"/api/instancemanager/update/{instanceId}";

            return(GetAsync(path, host, org, user));
        }
Ejemplo n.º 12
0
        public Task <InvokeResult <InstanceRuntimeDetails> > GetInstanceDetailsAsync(DeploymentHost host, string instanceId, EntityHeader org, EntityHeader user)
        {
            var path = $"/api/instancemanager/{instanceId}";

            return(GetAsync <InstanceRuntimeDetails>(path, host, org, user));
        }
Ejemplo n.º 13
0
        public async Task <ListResponse <InstanceRuntimeSummary> > GetDeployedInstancesAsync(DeploymentHost host, EntityHeader org, EntityHeader user)
        {
            var path         = $"/api/instancemanager/instances";
            var callResponse = await GetAsync <ListResponse <InstanceRuntimeSummary> >(path, host, org, user);

            if (callResponse.Successful)
            {
                if (callResponse.Result == null)
                {
                    var failedResponse = ListResponse <InstanceRuntimeSummary> .Create(null);

                    failedResponse.Errors.Add(new ErrorMessage("Null Response From Server."));
                    return(failedResponse);
                }
                else
                {
                    return(callResponse.Result);
                }
            }
            else
            {
                var failedResponse = ListResponse <InstanceRuntimeSummary> .Create(null);

                failedResponse.Concat(callResponse);
                return(failedResponse);
            }
        }
Ejemplo n.º 14
0
        public Task <InvokeResult <string> > GetRemoteMonitoringUriAsync(DeploymentHost host, string channel, string id, string verbosity, EntityHeader org, EntityHeader user)
        {
            var path = $"/api/websocket/{channel}/{id}/{verbosity}";

            return(GetAsync <string>(path, host, org, user));
        }
        protected async Task <InvokeResult> PutAsync <TPost>(string path, TPost post, DeploymentHost host, EntityHeader org, EntityHeader user)
        {
            using (var request = GetHttpClient(host, org, user, "PUT", path))
            {
                try
                {
                    var uri         = new Uri($"{host.AdminAPIUri}{path}");
                    var jsonContent = new StringContent(JsonConvert.SerializeObject(post), System.Text.Encoding.UTF8, "application/json");
                    var response    = await request.PutAsync(uri, jsonContent);

                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        return(JsonConvert.DeserializeObject <InvokeResult>(json));
                    }
                    else
                    {
                        _logger.AddCustomEvent(LogLevel.Error, "DeploymentConnectorService", $"{response.StatusCode} - {response.ReasonPhrase}",
                                               new KeyValuePair <string, string>("hostid", host.Id),
                                               new KeyValuePair <string, string>("path", path),
                                               new KeyValuePair <string, string>("orgid", org.Id),
                                               new KeyValuePair <string, string>("userid", user.Id));

                        return(DeploymentErrorCodes.ErrorCommunicatingWithhost.ToFailedInvocation($"{response.StatusCode} - {response.ReasonPhrase}"));
                    }
                }
                catch (Exception ex)
                {
                    _logger.AddCustomEvent(LogLevel.Error, "DeploymentConnectorService", ex.Message,
                                           new KeyValuePair <string, string>("hostid", host.Id),
                                           new KeyValuePair <string, string>("path", path),
                                           new KeyValuePair <string, string>("orgid", org.Id),
                                           new KeyValuePair <string, string>("userid", user.Id));

                    return(DeploymentErrorCodes.ErrorCommunicatingWithhost.ToFailedInvocation(ex.Message));
                }
            }
        }
Ejemplo n.º 16
0
        public static string GetAuthHeaderValue(DeploymentHost host, string requestId, string orgId, string userId, string method, String resource, String date)
        {
            if (host == null)
            {
                throw new InvalidOperationException("Missing Host.");
            }
            if (String.IsNullOrEmpty(host.HostAccessKey1))
            {
                throw new InvalidOperationException("Missing Host Access Key.");
            }

            if (String.IsNullOrEmpty(method))
            {
                return("INVALID - MISSING HTTP METHOD");
            }
            if (String.IsNullOrEmpty(requestId))
            {
                return("INVALID - MISSING REQUEST ID");
            }
            if (String.IsNullOrEmpty(orgId))
            {
                return("INVALID - MISSGING ORG ID");
            }
            if (String.IsNullOrEmpty(userId))
            {
                return("INVALID - MISSING USER ID");
            }
            if (String.IsNullOrEmpty(date))
            {
                return("INVALID - MISSING DATE STAMP");
            }

            var canonicalizedString = $"{method}\n";

            canonicalizedString += $"{requestId}\n";
            canonicalizedString += $"{orgId}\n";
            canonicalizedString += $"{userId}\n";
            canonicalizedString += $"{date}\n";
            canonicalizedString += resource;

            var encData = Encoding.UTF8.GetBytes(canonicalizedString);

            var hmac = new HMac(new Sha256Digest());

            hmac.Init(new KeyParameter(Encoding.UTF8.GetBytes(host.HostAccessKey1)));

            var result = new byte[hmac.GetMacSize()];

            hmac.BlockUpdate(encData, 0, encData.Length);
            hmac.DoFinal(result, 0);

            var md5Sting = new StringBuilder(result.Length);

            for (var i = 0; i < result.Length; i++)
            {
                md5Sting.Append(result[i].ToString("X2"));
            }

            var headerValue = $"{requestId}:{md5Sting.ToString()}";

            return(headerValue);
        }
        protected async Task <ListResponse <T> > GetListResponseAsync <T>(string path, DeploymentHost host, EntityHeader org, EntityHeader user, ListRequest listRequest = null) where T : class
        {
            using (var request = GetHttpClient(host, org, user, "GET", path))
            {
                if (listRequest != null)
                {
                    if (!string.IsNullOrEmpty(listRequest.NextRowKey))
                    {
                        request.DefaultRequestHeaders.Add("x-nextrowkey", listRequest.NextRowKey);
                    }

                    if (!string.IsNullOrEmpty(listRequest.NextPartitionKey))
                    {
                        request.DefaultRequestHeaders.Add("x-nextpartitionkey", listRequest.NextPartitionKey);
                    }

                    if (!string.IsNullOrEmpty(listRequest.StartDate))
                    {
                        request.DefaultRequestHeaders.Add("x-filter-startdate", listRequest.StartDate);
                    }

                    if (!string.IsNullOrEmpty(listRequest.EndDate))
                    {
                        request.DefaultRequestHeaders.Add("x-filter-enddate", listRequest.EndDate);
                    }

                    request.DefaultRequestHeaders.Add("x-pagesize", listRequest.PageSize.ToString());
                    request.DefaultRequestHeaders.Add("x-pageindex", listRequest.PageIndex.ToString());
                }

                try
                {
                    var uri      = new Uri($"{host.AdminAPIUri}{path}");
                    var response = await request.GetAsync(uri);

                    if (response.IsSuccessStatusCode)
                    {
                        var json = await response.Content.ReadAsStringAsync();

                        return(JsonConvert.DeserializeObject <ListResponse <T> >(json));
                    }
                    else
                    {
                        _logger.AddCustomEvent(LogLevel.Error, "DeploymentConnectorService", $"{response.StatusCode} - {response.ReasonPhrase}",
                                               new KeyValuePair <string, string>("hostid", host.Id),
                                               new KeyValuePair <string, string>("path", path),
                                               new KeyValuePair <string, string>("orgid", org.Id),
                                               new KeyValuePair <string, string>("userid", user.Id));


                        var errResponse = new ListResponse <T>();
                        errResponse.Errors.Add(DeploymentErrorCodes.ErrorCommunicatingWithhost.ToErrorMessage($"{response.StatusCode} - {response.ReasonPhrase}"));
                        return(errResponse);
                    }
                }
                catch (Exception ex)
                {
                    _logger.AddCustomEvent(LogLevel.Error, "DeploymentConnectorService", ex.Message,
                                           new KeyValuePair <string, string>("hostid", host.Id),
                                           new KeyValuePair <string, string>("path", path),
                                           new KeyValuePair <string, string>("orgid", org.Id),
                                           new KeyValuePair <string, string>("userid", user.Id));

                    var errResponse = new ListResponse <T>();
                    errResponse.Errors.Add(DeploymentErrorCodes.ErrorCommunicatingWithhost.ToErrorMessage(ex.Message));
                    return(errResponse);
                }
            }
        }
Ejemplo n.º 18
0
 public Task <InvokeResult> UpdateHostAsync([FromBody] DeploymentHost host)
 {
     SetUpdatedProperties(host);
     return(_hostManager.UpdateDeploymentHostAsync(host, OrgEntityHeader, UserEntityHeader));
 }
Ejemplo n.º 19
0
 public Task <InvokeResult> AddHostAsync([FromBody] DeploymentHost host)
 {
     return(_hostManager.AddDeploymentHostAsync(host, OrgEntityHeader, UserEntityHeader));
 }