Example #1
0
        public override void ExecuteCmdlet()
        {
            IotHubDescription iotHubDescription;

            if (ParameterSetName.Equals(InputObjectParameterSet))
            {
                this.ResourceGroupName = this.InputObject.Resourcegroup;
                this.IotHubName        = this.InputObject.Name;
                iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
            }
            else
            {
                if (ParameterSetName.Equals(ResourceIdParameterSet))
                {
                    this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                    this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                }

                iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
            }

            IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
            SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
            PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
            RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

            if (this.Name != null)
            {
                this.WriteObject(IotHubDataPlaneUtils.ToPSDeployment(registryManager.GetConfigurationAsync(this.Name).GetAwaiter().GetResult()));
            }
            else
            {
                this.WriteObject(IotHubDataPlaneUtils.ToPSDeployments(registryManager.GetConfigurationsAsync(Int32.MaxValue).GetAwaiter().GetResult()), true);
            }
        }
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.IotHubName, Properties.Resources.SetIotHubConfiguration))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                Configuration config = registryManager.GetConfigurationAsync(this.Name).GetAwaiter().GetResult();
                if (config != null && config.Content.ModulesContent != null)
                {
                    PSDeployment psDeployment = IotHubDataPlaneUtils.ToPSDeployment(config);

                    if (this.IsParameterBound(c => c.Priority))
                    {
                        psDeployment.Priority = this.Priority;
                    }

                    if (this.IsParameterBound(c => c.TargetCondition))
                    {
                        psDeployment.TargetCondition = this.TargetCondition;
                    }

                    if (this.IsParameterBound(c => c.Label))
                    {
                        psDeployment.Labels = this.Label;
                    }

                    if (this.IsParameterBound(c => c.Metric))
                    {
                        psDeployment.Metrics.Queries = this.Metric;
                    }

                    this.WriteObject(IotHubDataPlaneUtils.ToPSDeployment(registryManager.UpdateConfigurationAsync(IotHubDataPlaneUtils.ToConfiguration(psDeployment), this.Force.IsPresent).GetAwaiter().GetResult()));
                }
                else
                {
                    throw new ArgumentException("The deployment doesn't exist.");
                }
            }
        }
Example #3
0
        /// <summary>
        /// Wait until one successful deployment is reported.
        /// </summary>
        public async Task WaitForSuccessfulDeploymentAsync(
            Configuration deploymentConfiguration,
            CancellationToken ct)
        {
            try {
                while (true)
                {
                    ct.ThrowIfCancellationRequested();

                    var activeConfiguration = await RegistryManager
                                              .GetConfigurationAsync(deploymentConfiguration.Id, ct)
                                              .ConfigureAwait(false);

                    if (activeConfiguration != null &&
                        Equals(activeConfiguration, deploymentConfiguration) &&
                        activeConfiguration.SystemMetrics.Results.ContainsKey("reportedSuccessfulCount") &&
                        activeConfiguration.SystemMetrics.Results["reportedSuccessfulCount"] == 1)
                    {
                        _context.OutputHelper?.WriteLine("All required IoT Edge modules are loaded!");
                        return;
                    }

                    await Task.Delay(TestConstants.DefaultDelayMilliseconds, ct).ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException) {
                _context.OutputHelper?.WriteLine("Waiting for IoT Edge modules to be loaded timeout - please check iot edge device for details");
                throw;
            }
            catch (Exception e) {
                _context.OutputHelper?.WriteLine("Error occurred while waiting for edge Modules");
                _context.OutputHelper?.WriteLine(e.Message);
                throw;
            }
        }
Example #4
0
        /// <summary>
        /// Create or update deployment configuration
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="forceUpdate"></param>
        /// <param name="deploymentId"></param>
        /// <param name="ct"> Cancellation token </param>
        public async Task <Configuration> CreateOrUpdateConfigurationAsync(
            Configuration configuration,
            bool forceUpdate,
            string deploymentId,
            CancellationToken ct = default
            )
        {
            try {
                var getConfig = await RegistryManager.GetConfigurationAsync(deploymentId, ct);

                if (getConfig == null)
                {
                    // First try create configuration
                    try {
                        _context.OutputHelper?.WriteLine("Add new IoT Hub device configuration");
                        var added = await RegistryManager.AddConfigurationAsync(
                            configuration, ct);

                        return(added);
                    }
                    catch (DeviceAlreadyExistsException) when(forceUpdate)
                    {
                        //
                        // Technically update below should now work but for
                        // some reason it does not.
                        // Remove and re-add in case we are forcing updates.
                        //
                        _context.OutputHelper?.WriteLine("IoT Hub device configuration already existed, remove and recreate it");
                        await RegistryManager.RemoveConfigurationAsync(configuration.Id, ct);

                        var added = await RegistryManager.AddConfigurationAsync(
                            configuration, ct);

                        return(added);
                    }
                }

                _context.OutputHelper?.WriteLine("IoT Hub device configuration will be updated");
                // Try update existing configuration
                var result = await RegistryManager.UpdateConfigurationAsync(
                    configuration, forceUpdate, ct);

                return(result);
            }
            catch (Exception e) {
                _context.OutputHelper?.WriteLine("Error while creating or updating IoT Hub device configuration! {0}", e.Message);
                throw;
            }
        }
Example #5
0
        /// <summary>
        /// Create or update deployment configuration
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="deploymentId"></param>
        /// <param name="ct"> Cancellation token </param>
        public async Task <Configuration> CreateOrUpdateConfigurationAsync(
            Configuration configuration,
            CancellationToken ct = default
            )
        {
            try {
                var getConfig = await RegistryManager.GetConfigurationAsync(configuration.Id, ct).ConfigureAwait(false);

                if (getConfig == null)
                {
                    // First try create configuration
                    try {
                        _context.OutputHelper?.WriteLine("Add new IoT Hub device configuration");
                        return(await RegistryManager.AddConfigurationAsync(configuration, ct).ConfigureAwait(false));
                    }
                    catch (DeviceAlreadyExistsException) {
                        // Technically update below should now work but for some reason it does not.
                        // Remove and re-add in case we are forcing updates.
                        _context.OutputHelper?.WriteLine("IoT Hub device configuration already existed, remove and recreate it");
                        await RegistryManager.RemoveConfigurationAsync(configuration.Id, ct).ConfigureAwait(false);

                        return(await RegistryManager.AddConfigurationAsync(configuration, ct).ConfigureAwait(false));
                    }
                }

                if (Equals(configuration, getConfig))
                {
                    return(getConfig);
                }

                _context.OutputHelper?.WriteLine("Existing IoT Hub device configuration is different, remove and recreate it");
                await RegistryManager.RemoveConfigurationAsync(configuration.Id, ct).ConfigureAwait(false);

                return(await RegistryManager.AddConfigurationAsync(configuration, ct).ConfigureAwait(false));
            }
            catch (Exception e) {
                _context.OutputHelper?.WriteLine("Error while creating or updating IoT Hub device configuration! {0}", e.Message);
                throw;
            }
        }
Example #6
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.IotHubName, Properties.Resources.InvokeIotHubConfigurationMetricsQuery))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                Configuration config = registryManager.GetConfigurationAsync(this.Name).GetAwaiter().GetResult();
                if (config != null && config.Content.ModulesContent != null)
                {
                    PSDeployment psDeployment = IotHubDataPlaneUtils.ToPSDeployment(config);
                    Hashtable    queries;
                    string       metricKey = this.MetricName;
                    if (this.MetricType.Equals(PSConfigurationMetricType.System))
                    {
                        if (this.MetricName.Equals("targeted", StringComparison.OrdinalIgnoreCase))
                        {
                            metricKey = "targetedCount";
                        }

                        if (this.MetricName.Equals("applied", StringComparison.OrdinalIgnoreCase))
                        {
                            metricKey = "appliedCount";
                        }

                        if (this.MetricName.Equals("reporting success", StringComparison.OrdinalIgnoreCase))
                        {
                            metricKey = "reportedSuccessfulCount";
                        }

                        if (this.MetricName.Equals("reporting failure", StringComparison.OrdinalIgnoreCase))
                        {
                            metricKey = "reportedFailedCount";
                        }

                        queries = psDeployment.SystemMetrics.Queries;
                    }
                    else
                    {
                        queries = psDeployment.Metrics.Queries;
                    }

                    if (queries.ContainsKey(metricKey))
                    {
                        PSConfigurationMetricsResult psConfigurationMetricsResult = new PSConfigurationMetricsResult();
                        psConfigurationMetricsResult.Name     = this.MetricName;
                        psConfigurationMetricsResult.Criteria = queries[metricKey].ToString();
                        IQuery metricQuery = registryManager.CreateQuery(queries[metricKey].ToString());
                        psConfigurationMetricsResult.Result = metricQuery.GetNextAsJsonAsync().GetAwaiter().GetResult().ToList();
                        this.WriteObject(psConfigurationMetricsResult);
                    }
                    else
                    {
                        throw new ArgumentException(string.Format("The metric '{0}' is not defined in the deployment '{1}'", this.MetricName, this.Name));
                    }
                }
                else
                {
                    throw new ArgumentException("The deployment doesn't exist.");
                }
            }
        }
        public async Task RegistryManager_ImportDevices(StorageAuthenticationType storageAuthenticationType, bool isUserAssignedMsi)
        {
            // arrange

            const string idPrefix = nameof(RegistryManager_ImportDevices);

            string deviceId = $"{idPrefix}-device-{StorageContainer.GetRandomSuffix(4)}";
            string configId = $"{idPrefix}-config-{StorageContainer.GetRandomSuffix(4)}".ToLower(); // Configuration Id characters must be all lower-case.

            Logger.Trace($"Using Ids {deviceId} and {configId}.");

            string devicesFileName = $"{idPrefix}-devices-{StorageContainer.GetRandomSuffix(4)}.txt";
            string configsFileName = $"{idPrefix}-configs-{StorageContainer.GetRandomSuffix(4)}.txt";

            using RegistryManager registryManager = RegistryManager.CreateFromConnectionString(TestConfiguration.IoTHub.ConnectionString);

            try
            {
                string containerName = StorageContainer.BuildContainerName(nameof(RegistryManager_ImportDevices));
                using StorageContainer storageContainer = await StorageContainer.GetInstanceAsync(containerName).ConfigureAwait(false);

                Logger.Trace($"Using devices container {storageContainer.Uri}");

                Uri containerUri = storageAuthenticationType == StorageAuthenticationType.KeyBased
                    ? storageContainer.SasUri
                    : storageContainer.Uri;

                using Stream devicesStream = ImportExportHelpers.BuildImportStream(
                          new List <ExportImportDevice>
                {
                    new ExportImportDevice(
                        new Device(deviceId)
                    {
                        Authentication = new AuthenticationMechanism { Type = AuthenticationType.Sas }
                    },
                        ImportMode.Create),
                });
                await UploadFileAndConfirmAsync(storageContainer, devicesStream, devicesFileName).ConfigureAwait(false);

                using Stream configsStream = ImportExportHelpers.BuildImportStream(
                          new List <ImportConfiguration>
                {
                    new ImportConfiguration(configId)
                    {
                        ImportMode      = ConfigurationImportMode.CreateOrUpdateIfMatchETag,
                        Priority        = 3,
                        Labels          = { { "labelName", "labelValue" } },
                        TargetCondition = "*",
                        Content         =
                        {
                            DeviceContent = { { "properties.desired.x", 5L } },
                        },
                        Metrics =
                        {
                            Queries = { { "successfullyConfigured", "select deviceId from devices where properties.reported.x = 5" } }
                        },
                    },
                });
                await UploadFileAndConfirmAsync(storageContainer, configsStream, configsFileName).ConfigureAwait(false);

                ManagedIdentity identity = isUserAssignedMsi
                    ? new ManagedIdentity
                {
                    UserAssignedIdentity = TestConfiguration.IoTHub.UserAssignedMsiResourceId
                }
                    : null;

                // act

                JobProperties importJobResponse = await CreateAndWaitForJobAsync(
                    storageAuthenticationType,
                    devicesFileName,
                    configsFileName,
                    registryManager,
                    containerUri,
                    identity)
                                                  .ConfigureAwait(false);

                // assert

                importJobResponse.Status.Should().Be(JobStatus.Completed, "Otherwise import failed");
                importJobResponse.FailureReason.Should().BeNullOrEmpty("Otherwise import failed");

                // should not throw due to 404, but device may not immediately appear in registry
                Device        device = null;
                Configuration config = null;
                for (int i = 0; i < MaxIterationWait; ++i)
                {
                    await Task.Delay(s_waitDuration).ConfigureAwait(false);

                    try
                    {
                        device = await registryManager.GetDeviceAsync(deviceId).ConfigureAwait(false);

                        config = await registryManager.GetConfigurationAsync(configId).ConfigureAwait(false);

                        break;
                    }
                    catch (Exception ex)
                    {
                        Logger.Trace($"Could not find device/config on iteration {i} due to [{ex.Message}]");
                    }
                }
                if (device == null)
                {
                    Assert.Fail($"Device {deviceId} not found in registry manager");
                }
                if (config == null)
                {
                    Assert.Fail($"Config {configId} not found in registry manager");
                }
            }
            finally
            {
                try
                {
                    await registryManager.RemoveDeviceAsync(deviceId).ConfigureAwait(false);

                    await registryManager.RemoveConfigurationAsync(configId).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Logger.Trace($"Failed to clean up device/config due to {ex}");
                }
            }
        }
Example #8
0
        public override void ExecuteCmdlet()
        {
            if (ShouldProcess(this.IotHubName, Properties.Resources.RemoveIotHubConfiguration))
            {
                IotHubDescription iotHubDescription;
                if (ParameterSetName.Equals(InputObjectParameterSet))
                {
                    this.ResourceGroupName = this.InputObject.Resourcegroup;
                    this.IotHubName        = this.InputObject.Name;
                    iotHubDescription      = IotHubUtils.ConvertObject <PSIotHub, IotHubDescription>(this.InputObject);
                }
                else
                {
                    if (ParameterSetName.Equals(ResourceIdParameterSet))
                    {
                        this.ResourceGroupName = IotHubUtils.GetResourceGroupName(this.ResourceId);
                        this.IotHubName        = IotHubUtils.GetIotHubName(this.ResourceId);
                    }

                    iotHubDescription = this.IotHubClient.IotHubResource.Get(this.ResourceGroupName, this.IotHubName);
                }

                IEnumerable <SharedAccessSignatureAuthorizationRule> authPolicies = this.IotHubClient.IotHubResource.ListKeys(this.ResourceGroupName, this.IotHubName);
                SharedAccessSignatureAuthorizationRule policy     = IotHubUtils.GetPolicy(authPolicies, PSAccessRights.RegistryWrite);
                PSIotHubConnectionString psIotHubConnectionString = IotHubUtils.ToPSIotHubConnectionString(policy, iotHubDescription.Properties.HostName);
                RegistryManager          registryManager          = RegistryManager.CreateFromConnectionString(psIotHubConnectionString.PrimaryConnectionString);

                try
                {
                    if (this.Name != null)
                    {
                        Configuration config = registryManager.GetConfigurationAsync(this.Name).GetAwaiter().GetResult();
                        if (config != null && config.Content.ModulesContent == null)
                        {
                            registryManager.RemoveConfigurationAsync(this.Name).GetAwaiter().GetResult();
                        }
                        else
                        {
                            throw new ArgumentException("The configuration doesn't exist.");
                        }
                    }
                    else
                    {
                        IEnumerable <Configuration> configs = registryManager.GetConfigurationsAsync(Int32.MaxValue).GetAwaiter().GetResult();
                        foreach (Configuration config in configs)
                        {
                            if (config.Content.ModulesContent == null)
                            {
                                registryManager.RemoveConfigurationAsync(config).GetAwaiter().GetResult();
                            }
                        }
                    }

                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(true);
                    }
                }
                catch
                {
                    if (PassThru.IsPresent)
                    {
                        this.WriteObject(false);
                    }
                }
            }
        }