public JsonResult Action(Configuration configuration)
        {
            var json = new JsonResult();

            try
            {
                if (configuration == null)
                {
                    throw new Exception("Dashboard.Configurations.ConfigurationNotFound".LocalizedString());
                }

                var result = ConfigurationsService.Instance.UpdateConfigurationValue(configuration.Key, configuration.Value);

                if (result)
                {
                    json.Data = new { Success = true };
                }
                else
                {
                    throw new Exception("Dashboard.Configurations.UnableToUpdateConfigurations".LocalizedString());
                }

                ConfigurationsHelper.UpdateConfiguration(configuration);
            }
            catch (Exception ex)
            {
                json.Data = new { Success = false, Message = ex.Message };
            }

            return(json);
        }
Exemplo n.º 2
0
        private IDictionary <string, DeploymentStatus> GetDeviceStatuses(Configuration deployment)
        {
            string deploymentType = null;

            if (ConfigurationsHelper.IsEdgeDeployment(deployment))
            {
                deploymentType = PackageType.EdgeManifest.ToString();
            }
            else
            {
                deploymentType = PackageType.DeviceConfiguration.ToString();
            }

            deployment.Labels.TryGetValue(ConfigurationsHelper.CONFIG_TYPE_LABEL, out string configType);
            IDictionary <QueryType, String> Queries = GetQueries(deploymentType, configType);

            string deploymentId   = deployment.Id;
            var    appliedDevices = this.GetDevicesInQuery(Queries[QueryType.APPLIED], deploymentId);

            var deviceWithStatus = new Dictionary <string, DeploymentStatus>();

            if (!(ConfigurationsHelper.IsEdgeDeployment(deployment)) &&
                !(configType.Equals(ConfigType.Firmware.ToString())))
            {
                foreach (var devices in appliedDevices)
                {
                    deviceWithStatus.Add(devices, DeploymentStatus.Unknown);
                }

                return(deviceWithStatus);
            }

            var successfulDevices = this.GetDevicesInQuery(Queries[QueryType.SUCCESSFUL], deploymentId);
            var failedDevices     = this.GetDevicesInQuery(Queries[QueryType.FAILED], deploymentId);

            foreach (var successfulDevice in successfulDevices)
            {
                deviceWithStatus.Add(successfulDevice, DeploymentStatus.Succeeded);
            }

            foreach (var failedDevice in failedDevices)
            {
                deviceWithStatus.Add(failedDevice, DeploymentStatus.Failed);
            }

            foreach (var device in appliedDevices)
            {
                if (!successfulDevices.Contains(device) && !failedDevices.Contains(device))
                {
                    deviceWithStatus.Add(device, DeploymentStatus.Pending);
                }
            }

            return(deviceWithStatus);
        }
        private IDictionary <string, DeploymentStatus> GetDeviceStatuses(Configuration deployment)
        {
            string deploymentType = null;

            if (ConfigurationsHelper.IsEdgeDeployment(deployment))
            {
                deploymentType = PackageType.EdgeManifest.ToString();
            }
            else
            {
                deploymentType = PackageType.DeviceConfiguration.ToString();
            }

            deployment.Labels.TryGetValue(ConfigurationsHelper.ConfigTypeLabel, out string configType);
            var queries = GetQueries(deploymentType, configType);

            string deploymentId   = deployment.Id;
            var    appliedDevices = this.GetDevicesInQuery(queries[QueryType.APPLIED], deploymentId);

            var deviceWithStatus = new Dictionary <string, DeploymentStatus>();

            if (!ConfigurationsHelper.IsEdgeDeployment(deployment) && !configType.Equals(ConfigType.Firmware.ToString()))
            {
                foreach (var devices in appliedDevices)
                {
                    deviceWithStatus.Add(devices, DeploymentStatus.Unknown);
                }

                return(deviceWithStatus);
            }

            // Get reported status from custom Metrics if available otherwise use default queries
            var successfulDevices = this.GetDevicesInQuery(deployment.Metrics.Queries.ContainsKey(SuccessQueryName) ? deployment.Metrics.Queries[SuccessQueryName] : queries[QueryType.SUCCESSFUL], deploymentId);
            var failedDevices     = this.GetDevicesInQuery(deployment.Metrics.Queries.ContainsKey(FailedQueryName) ? deployment.Metrics.Queries[FailedQueryName] : queries[QueryType.FAILED], deploymentId);

            foreach (var successfulDevice in successfulDevices)
            {
                deviceWithStatus.Add(successfulDevice, DeploymentStatus.Succeeded);
            }

            foreach (var failedDevice in failedDevices)
            {
                deviceWithStatus.Add(failedDevice, DeploymentStatus.Failed);
            }

            foreach (var device in appliedDevices)
            {
                if (!successfulDevices.Contains(device) && !failedDevices.Contains(device))
                {
                    deviceWithStatus.Add(device, DeploymentStatus.Pending);
                }
            }

            return(deviceWithStatus);
        }
Exemplo n.º 4
0
        public async Task <DeploymentServiceModel> CreateAsync(DeploymentServiceModel model, string userId, string tenantId)
        {
            if (string.IsNullOrEmpty(model.DeviceGroupId))
            {
                throw new ArgumentNullException(DeviceGroupIdParameter);
            }

            if (string.IsNullOrEmpty(model.DeviceGroupQuery) && (model.DeviceIds == null || (model.DeviceIds != null && model.DeviceIds.Count() == 0)))
            {
                throw new ArgumentNullException(DeviceGroupQueryParameter);
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                throw new ArgumentNullException(NameParameter);
            }

            if (string.IsNullOrEmpty(model.PackageContent))
            {
                throw new ArgumentNullException(PackageContentParameter);
            }

            if (model.PackageType.Equals(PackageType.DeviceConfiguration) &&
                string.IsNullOrEmpty(model.ConfigType))
            {
                throw new ArgumentNullException(ConfigurationTypeParameter);
            }

            if (model.Priority < 0)
            {
                throw new ArgumentOutOfRangeException(
                          PriorityParameter,
                          model.Priority,
                          "The priority provided should be 0 or greater");
            }

            var configuration = ConfigurationsHelper.ToHubConfiguration(model);

            // TODO: Add specific exception handling when exception types are exposed
            // https://github.com/Azure/azure-iot-sdk-csharp/issues/649
            var result = new DeploymentServiceModel(await this.tenantHelper.GetRegistry().AddConfigurationAsync(configuration));

            // Setting the id so that deployment id is populated
            model.Id = result.Id;

            // Log a custom event to Application Insights
            this.deploymentLog.LogDeploymentCreate(model, tenantId, userId);

            return(result);
        }
        public DeploymentServiceModel(Configuration deployment)
        {
            if (string.IsNullOrEmpty(deployment.Id))
            {
                throw new ArgumentException($"Invalid deploymentId provided {deployment.Id}");
            }

            this.VerifyConfigurationLabel(deployment, ConfigurationsHelper.DeploymentNameLabel);
            this.VerifyConfigurationLabel(deployment, ConfigurationsHelper.DeploymentGroupIdLabel);
            this.VerifyConfigurationLabel(deployment, ConfigurationsHelper.RmCreatedLabel);

            this.Id   = deployment.Id;
            this.Name = deployment.Labels[ConfigurationsHelper.DeploymentNameLabel];
            this.CreatedDateTimeUtc = deployment.CreatedTimeUtc;
            this.DeviceGroupId      = deployment.Labels[ConfigurationsHelper.DeploymentGroupIdLabel];
            this.TargetCondition    = deployment.TargetCondition;

            if (deployment.Labels.ContainsKey(ConfigurationsHelper.DeploymentGroupNameLabel))
            {
                this.DeviceGroupName = deployment.Labels[ConfigurationsHelper.DeploymentGroupNameLabel];
            }

            if (deployment.Labels.ContainsKey(ConfigurationsHelper.DeploymentPackageNameLabel))
            {
                this.PackageName = deployment.Labels[ConfigurationsHelper.DeploymentPackageNameLabel];
            }

            this.Priority = deployment.Priority;

            if (ConfigurationsHelper.IsEdgeDeployment(deployment))
            {
                this.PackageType = PackageType.EdgeManifest;
            }
            else
            {
                this.PackageType = PackageType.DeviceConfiguration;
            }

            if (deployment.Labels.ContainsKey(ConfigurationsHelper.ConfigTypeLabel))
            {
                this.ConfigType = deployment.Labels[ConfigurationsHelper.ConfigTypeLabel];
            }
            else
            {
                this.ConfigType = string.Empty;
            }

            this.DeploymentMetrics = new DeploymentMetricsServiceModel(deployment.SystemMetrics, deployment.Metrics);
        }
        // IoT SDK's configurations is a deployment for RM.
        public DeploymentServiceModel(Configuration deployment)
        {
            if (string.IsNullOrEmpty(deployment.Id))
            {
                throw new ArgumentException($"Invalid deploymentId provided {deployment.Id}");
            }

            this.VerifyConfigurationLabel(deployment, ConfigurationsHelper.DEPLOYMENT_NAME_LABEL);
            this.VerifyConfigurationLabel(deployment, ConfigurationsHelper.DEPLOYMENT_GROUP_ID_LABEL);
            this.VerifyConfigurationLabel(deployment, ConfigurationsHelper.RM_CREATED_LABEL);

            this.Id   = deployment.Id;
            this.Name = deployment.Labels[ConfigurationsHelper.DEPLOYMENT_NAME_LABEL];
            this.CreatedDateTimeUtc = deployment.CreatedTimeUtc;
            this.DeviceGroupId      = deployment.Labels[ConfigurationsHelper.DEPLOYMENT_GROUP_ID_LABEL];

            if (deployment.Labels.ContainsKey(ConfigurationsHelper.DEPLOYMENT_GROUP_NAME_LABEL))
            {
                this.DeviceGroupName = deployment.Labels[ConfigurationsHelper.DEPLOYMENT_GROUP_NAME_LABEL];
            }

            if (deployment.Labels.ContainsKey(ConfigurationsHelper.DEPLOYMENT_PACKAGE_NAME_LABEL))
            {
                this.PackageName = deployment.Labels[ConfigurationsHelper.DEPLOYMENT_PACKAGE_NAME_LABEL];
            }

            this.Priority = deployment.Priority;

            if (ConfigurationsHelper.IsEdgeDeployment(deployment))
            {
                this.PackageType = PackageType.EdgeManifest;
            }
            else
            {
                this.PackageType = PackageType.DeviceConfiguration;
            }

            if (deployment.Labels.ContainsKey(ConfigurationsHelper.CONFIG_TYPE_LABEL))
            {
                this.ConfigType = deployment.Labels[ConfigurationsHelper.CONFIG_TYPE_LABEL];
            }
            else
            {
                this.ConfigType = PackageType.EdgeManifest.ToString();
            }

            this.DeploymentMetrics = new DeploymentMetricsServiceModel(deployment.SystemMetrics, deployment.Metrics);
        }
        public async Task <DeploymentServiceModel> CreateAsync(DeploymentServiceModel model)
        {
            if (string.IsNullOrEmpty(model.DeviceGroupId))
            {
                throw new ArgumentNullException(DeviceGroupIdParameter);
            }

            if (string.IsNullOrEmpty(model.DeviceGroupQuery))
            {
                throw new ArgumentNullException(DeviceGroupQueryParameter);
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                throw new ArgumentNullException(NameParameter);
            }

            if (string.IsNullOrEmpty(model.PackageContent))
            {
                throw new ArgumentNullException(PackageContentParameter);
            }

            if (model.PackageType.Equals(PackageType.DeviceConfiguration) &&
                string.IsNullOrEmpty(model.ConfigType))
            {
                throw new ArgumentNullException(ConfigurationTypeParameter);
            }

            if (model.Priority < 0)
            {
                throw new ArgumentOutOfRangeException(
                          PriorityParameter,
                          model.Priority,
                          "The priority provided should be 0 or greater");
            }

            var configuration = ConfigurationsHelper.ToHubConfiguration(model);

            // TODO: Add specific exception handling when exception types are exposed
            // https://github.com/Azure/azure-iot-sdk-csharp/issues/649
            return(new DeploymentServiceModel(await this.tenantHelper.GetRegistry().AddConfigurationAsync(configuration)));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Schedules a deployment of the provided package, to the given group.
        /// </summary>
        /// <returns>Scheduled deployment</returns>
        public async Task <DeploymentServiceModel> CreateAsync(DeploymentServiceModel model)
        {
            if (string.IsNullOrEmpty(model.DeviceGroupId))
            {
                throw new ArgumentNullException(DEVICE_GROUP_ID_PARAM);
            }

            if (string.IsNullOrEmpty(model.DeviceGroupQuery))
            {
                throw new ArgumentNullException(DEVICE_GROUP_QUERY_PARAM);
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                throw new ArgumentNullException(NAME_PARAM);
            }

            if (string.IsNullOrEmpty(model.PackageContent))
            {
                throw new ArgumentNullException(PACKAGE_CONTENT_PARAM);
            }

            if (model.PackageType.Equals(PackageType.DeviceConfiguration) &&
                string.IsNullOrEmpty(model.ConfigType))
            {
                throw new ArgumentNullException(CONFIG_TYPE_PARAM);
            }

            if (model.Priority < 0)
            {
                throw new ArgumentOutOfRangeException(PRIORITY_PARAM,
                                                      model.Priority,
                                                      "The priority provided should be 0 or greater");
            }

            var configuration = ConfigurationsHelper.ToHubConfiguration(model);

            // TODO: Add specific exception handling when exception types are exposed
            // https://github.com/Azure/azure-iot-sdk-csharp/issues/649
            return(new DeploymentServiceModel(await this.registry.AddConfigurationAsync(configuration)));
        }
        public async Task <DeploymentServiceModel> CreateAsync(DeploymentServiceModel model, string userId, string tenantId)
        {
            if (string.IsNullOrEmpty(model.DeviceGroupId))
            {
                throw new ArgumentNullException(DeviceGroupIdParameter);
            }

            if (string.IsNullOrEmpty(model.DeviceGroupQuery) && (model.DeviceIds == null || (model.DeviceIds != null && model.DeviceIds.Count() == 0)))
            {
                throw new ArgumentNullException(DeviceGroupQueryParameter);
            }

            if (string.IsNullOrEmpty(model.Name))
            {
                throw new ArgumentNullException(NameParameter);
            }

            if (string.IsNullOrEmpty(model.PackageContent))
            {
                throw new ArgumentNullException(PackageContentParameter);
            }

            if (model.PackageType.Equals(PackageType.DeviceConfiguration) &&
                string.IsNullOrEmpty(model.ConfigType))
            {
                throw new ArgumentNullException(ConfigurationTypeParameter);
            }

            if (model.Priority < 0)
            {
                throw new ArgumentOutOfRangeException(
                          PriorityParameter,
                          model.Priority,
                          "The priority provided should be 0 or greater");
            }

            var configuration = ConfigurationsHelper.ToHubConfiguration(model);

            // Update the Metrics related to previous deployment which targets the same device group as the metrics
            // will be overriden once the new deployment gets applied to the devices.
            bool shouldMarkAsLatest = await this.UpdateMetricsOfCurrentDeployment(model.DeviceGroupId, model.Priority);

            // TODO: Add specific exception handling when exception types are exposed
            // https://github.com/Azure/azure-iot-sdk-csharp/issues/649
            var result = new DeploymentServiceModel(await this.tenantHelper.GetRegistry().AddConfigurationAsync(configuration));

            // Setting the id so that deployment id is populated
            model.Id = result.Id;
            model.CreatedDateTimeUtc = result.CreatedDateTimeUtc;

            // Add latest tag to deployment if deployment has highest priority for the device group.
            if (shouldMarkAsLatest)
            {
                if (model.Tags == null)
                {
                    model.Tags = new List <string>();
                }

                model.Tags.Add(LatestTag);
            }
            else
            {
                // Update the Device Statuses for the DeploymentId for future references.
                model.DeploymentMetrics = result.DeploymentMetrics;
            }

            // Store the deployment details in Cosmos DB
            await this.StoreDeploymentInSecondaryStorage(model, userId);

            // Log a custom event to Application Insights
            // this.deploymentLog.LogDeploymentCreate(model, tenantId, userId);
            return(model);
        }
Exemplo n.º 10
0
        private async Task <bool> UpdateMetricsOfCurrentDeployment(string deviceGroupId, int priority)
        {
            var deploymentsFromHub = await this.ListAsync();

            var deploymentsOfDeviceGroup = deploymentsFromHub.Items.Where(i => i.DeviceGroupId == deviceGroupId).OrderByDescending(p => p.Priority).ThenByDescending(q => q.CreatedDateTimeUtc);

            if (deploymentsOfDeviceGroup != null && deploymentsOfDeviceGroup.Count() > 0)
            {
                var deployment = deploymentsOfDeviceGroup.First();

                if (priority >= deployment.Priority)
                {
                    var deploymentDetails = await this.GetDeploymentAsync(deployment.Id);

                    DeploymentServiceModel currentDeployment = await this.GetDeploymentFromStorageAsync(deployment.Id);

                    // Update the Device Statuses for the DeploymentId for future references.
                    currentDeployment.DeploymentMetrics = new DeploymentMetricsServiceModel(deploymentDetails.SystemMetrics, deploymentDetails.Metrics);

                    currentDeployment.DeploymentMetrics.DeviceStatuses = this.GetDeviceStatuses(deploymentDetails);

                    var deviceTwins = await this.GetDeviceProperties(currentDeployment.DeploymentMetrics.DeviceStatuses.Keys);

                    // Since the deployment that will be created have highest priority, remove latest tag on current deployment
                    if (currentDeployment?.Tags != null)
                    {
                        var existingTag = currentDeployment.Tags.FirstOrDefault(t => t.Equals(LatestTag, StringComparison.OrdinalIgnoreCase));
                        if (existingTag != null)
                        {
                            currentDeployment.Tags.Remove(existingTag);
                        }
                    }

                    var value = JsonConvert.SerializeObject(
                        currentDeployment,
                        Formatting.Indented,
                        new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                    });

                    await this.client.UpdateAsync(DeploymentsCollection, currentDeployment.Id, value, currentDeployment.ETag);

                    await this.StoreDevicePropertiesInStorage(deviceTwins, currentDeployment.Id);

                    if (ConfigurationsHelper.IsEdgeDeployment(deploymentDetails))
                    {
                        var moduleTwins = await this.GetDeviceProperties(currentDeployment.DeploymentMetrics.DeviceStatuses.Keys, PackageType.EdgeManifest);

                        await this.StoreModuleTwinsInStorage(moduleTwins, currentDeployment.Id);
                    }

                    // Since the deployment that will be created have highest priority, mark it as the latest
                    return(true);
                }
                else
                {
                    return(false);
                }
            }

            return(true);
        }