Exemplo n.º 1
0
        public async Task ValidateMetrics()
        {
            CancellationToken token = this.TestToken;

            await this.DeployAsync(token);

            var agent = new EdgeAgent(this.runtime.DeviceId, this.IotHub);
            await agent.PingAsync(token);

            // This method can take a long time to process in the nested case.
            // So have a long response timeout but short connection timeout.
            var result = await this.IotHub.InvokeMethodAsync(
                this.runtime.DeviceId,
                ModuleName,
                new CloudToDeviceMethod("ValidateMetrics", TimeSpan.FromSeconds(120), TimeSpan.FromSeconds(60)),
                token);

            Assert.AreEqual(result.Status, (int)HttpStatusCode.OK);

            string body   = result.GetPayloadAsJson();
            Report report = JsonConvert.DeserializeObject <Report>(body, new JsonSerializerSettings()
            {
                DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate
            });

            Assert.Zero(report.Failed, report.ToString());
        }
Exemplo n.º 2
0
        public async Task ManuallyProvisionEdgeAsync()
        {
            await Profiler.Run(
                async() =>
            {
                using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout))
                {
                    // NUnit's [Timeout] attribute isn't supported in .NET Standard
                    // and even if it were, it doesn't run the teardown method when
                    // a test times out. We need teardown to run, to remove the
                    // device registration from IoT Hub and stop the daemon. So
                    // we have our own timeout mechanism.
                    DateTime startTime      = DateTime.Now;
                    CancellationToken token = cts.Token;

                    EdgeDevice device = await EdgeDevice.GetOrCreateIdentityAsync(
                        Context.Current.DeviceId,
                        this.iotHub,
                        token);
                    Context.Current.DeleteList.TryAdd(device.Id, device);

                    IotHubConnectionStringBuilder builder =
                        IotHubConnectionStringBuilder.Create(device.ConnectionString);

                    await this.daemon.ConfigureAsync(
                        config =>
                    {
                        config.SetDeviceConnectionString(device.ConnectionString);
                        config.Update();
                        return(Task.FromResult((
                                                   "with connection string for device '{Identity}'",
                                                   new object[] { builder.DeviceId })));
                    },
                        token);

                    try
                    {
                        await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token);

                        var agent = new EdgeAgent(device.Id, this.iotHub);
                        await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token);
                        await agent.PingAsync(token);
                    }

                    // ReSharper disable once RedundantCatchClause
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        await NUnitLogs.CollectAsync(startTime, token);
                    }
                }
            },
                "Completed edge manual provisioning");
        }
Exemplo n.º 3
0
        public async Task DpsX509()
        {
            (string, string, string)rootCa =
                Context.Current.RootCaKeys.Expect(() => new InvalidOperationException("Missing root CA keys"));
            string caCertScriptPath =
                Context.Current.CaCertScriptPath.Expect(() => new InvalidOperationException("Missing CA cert script path"));
            string idScope        = Context.Current.DpsIdScope.Expect(() => new InvalidOperationException("Missing DPS ID scope"));
            string registrationId = DeviceId.Current.Generate();

            CancellationToken token = this.TestToken;

            CertificateAuthority ca = await CertificateAuthority.CreateAsync(
                registrationId,
                rootCa,
                caCertScriptPath,
                token);

            IdCertificates idCert = await ca.GenerateIdentityCertificatesAsync(registrationId, token);

            // The trust bundle for this test isn't used. It can be any arbitrary existing certificate.
            string trustBundle = Path.Combine(
                caCertScriptPath,
                "certs",
                "azure-iot-test-only.intermediate-full-chain.cert.pem");

            await this.daemon.ConfigureAsync(
                config =>
            {
                config.SetDpsX509(idScope, registrationId, idCert, trustBundle);
                config.Update();
                return(Task.FromResult((
                                           "with DPS X509 attestation for '{Identity}'",
                                           new object[] { registrationId })));
            },
                token);

            await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token);

            var agent = new EdgeAgent(registrationId, this.iotHub);
            await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token);

            await agent.PingAsync(token);

            Option <EdgeDevice> device = await EdgeDevice.GetIdentityAsync(
                registrationId,
                Context.Current.ParentDeviceId,
                this.iotHub,
                token,
                takeOwnership : true);

            Context.Current.DeleteList.TryAdd(
                registrationId,
                device.Expect(() => new InvalidOperationException(
                                  $"Device '{registrationId}' should have been created by DPS, but was not found in '{this.iotHub.Hostname}'")));
        }
        private void buttonDisconnect_Click(object sender, EventArgs e)
        {
            if (_edgeAgent == null)
            {
                return;
            }

            _edgeAgent.Disconnect();

            _edgeAgent = null;
        }
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtNodeId.Text))
            {
                MessageBox.Show("Node ID can not be null !");
                return;
            }

            if (_edgeAgent == null)
            {
                EdgeAgentOptions options = new EdgeAgentOptions()
                {
                    DCCS = new DCCSOptions()
                    {
                        CredentialKey = txtDCCSKey.Text.Trim(),
                        APIUrl        = txtDCCSAPIUrl.Text.Trim()
                    },

                    AutoReconnect     = true,
                    ReconnectInterval = 1000,
                    NodeId            = txtNodeId.Text.Trim(),
                    Heartbeat         = 60000, // default is 60 seconds
                    DataRecover       = true,
                    UseSecure         = ckbSecure.Checked
                };

                _edgeAgent = new EdgeAgent(options);

                _edgeAgent.Connected       += _edgeAgent_Connected;
                _edgeAgent.Disconnected    += _edgeAgent_Disconnected;
                _edgeAgent.MessageReceived += _edgeAgent_MessageReceived;
            }
            else
            {
                _edgeAgent.Options.NodeId    = txtNodeId.Text.Trim();
                _edgeAgent.Options.UseSecure = ckbSecure.Checked;

                _edgeAgent.Options.DCCS = new DCCSOptions()
                {
                    CredentialKey = txtDCCSKey.Text.Trim(),
                    APIUrl        = txtDCCSAPIUrl.Text.Trim()
                };
            }

            _edgeAgent.Connect();
        }
        private void buttonConnect_Click(object sender, EventArgs e)
        {
            if (_edgeAgent == null)
            {
                EdgeAgentOptions options = new EdgeAgentOptions()
                {
                    AutoReconnect = true,

                    ReconnectInterval = 1000,

                    ScadaId = textBoxGroupId.Text,

                    Type = EdgeType.Gateway,

                    Heartbeat = 60000,   // default is 60 seconds,

                    DataRecover = true,

                    ConnectType = ConnectType.MQTT,

                    UseSecure = checkBoxSSL.Checked
                };

                switch (options.ConnectType)
                {
                case ConnectType.MQTT:
                    options.MQTT = new MQTTOptions()
                    {
                        HostName     = textBoxIp.Text,
                        Port         = Convert.ToInt32(textBoxPort.Text),
                        Username     = textBoxUser.Text,
                        Password     = textBoxPwd.Text,
                        ProtocolType = Protocol.TCP
                    };
                    break;
                }

                _edgeAgent = new EdgeAgent(options);

                _edgeAgent.Connected       += _edgeAgent_Connected;
                _edgeAgent.Disconnected    += _edgeAgent_Disconnected;
                _edgeAgent.MessageReceived += _edgeAgent_MessageReceived;
            }
            _edgeAgent.Connect();
        }
Exemplo n.º 7
0
        public async Task DpsSymmetricKey()
        {
            string idScope        = Context.Current.DpsIdScope.Expect(() => new InvalidOperationException("Missing DPS ID scope"));
            string groupKey       = Context.Current.DpsGroupKey.Expect(() => new InvalidOperationException("Missing DPS enrollment group key"));
            string registrationId = DeviceId.Current.Generate();

            string deviceKey = this.DeriveDeviceKey(Convert.FromBase64String(groupKey), registrationId);

            CancellationToken token = this.TestToken;

            (TestCertificates testCerts, _) = await TestCertificates.GenerateCertsAsync(registrationId, token);

            await this.daemon.ConfigureAsync(
                config =>
            {
                testCerts.AddCertsToConfig(config);
                config.SetDpsSymmetricKey(idScope, registrationId, deviceKey);
                config.Update();
                return(Task.FromResult((
                                           "with DPS symmetric key attestation for '{Identity}'",
                                           new object[] { registrationId })));
            },
                token);

            await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token);

            var agent = new EdgeAgent(registrationId, this.iotHub);
            await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token);

            await agent.PingAsync(token);

            Option <EdgeDevice> device = await EdgeDevice.GetIdentityAsync(
                registrationId,
                Context.Current.ParentDeviceId,
                this.iotHub,
                token,
                takeOwnership : true);

            Context.Current.DeleteList.TryAdd(
                registrationId,
                device.Expect(() => new InvalidOperationException(
                                  $"Device '{registrationId}' should have been created by DPS, but was not found in '{this.iotHub.Hostname}'")));
        }
Exemplo n.º 8
0
        private async Task WaitForConfiguredStatusAsync(EdgeDevice device, DateTime startTime, CancellationToken token)
        {
            try
            {
                await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token);

                var agent = new EdgeAgent(device.Id, this.iotHub);
                await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token);

                await agent.PingAsync(token);
            }

            // ReSharper disable once RedundantCatchClause
            catch
            {
                throw;
            }
            finally
            {
                await NUnitLogs.CollectAsync(startTime, token);
            }
        }
Exemplo n.º 9
0
        public Task VerifyAsync(IotHub iotHub, CancellationToken token)
        {
            EdgeAgent agent = new EdgeAgent(this.deviceId, iotHub);

            return(agent.WaitForReportedConfigurationAsync(this.expectedConfig, token));
        }
Exemplo n.º 10
0
        public async Task BeforeAllAsync()
        {
            await Profiler.Run(
                async() =>
            {
                // Set up logging
                LogEventLevel consoleLevel = Context.Current.Verbose
                        ? LogEventLevel.Verbose
                        : LogEventLevel.Information;
                var loggerConfig = new LoggerConfiguration()
                                   .MinimumLevel.Verbose()
                                   .WriteTo.NUnit(consoleLevel);
                Context.Current.LogFile.ForEach(f => loggerConfig.WriteTo.File(f));
                Log.Logger = loggerConfig.CreateLogger();

                // Install IoT Edge
                using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout))
                {
                    // NUnit's [Timeout] attribute isn't supported in .NET Standard
                    // and even if it were, it doesn't run the teardown method when
                    // a test times out. We need teardown to run, to remove the
                    // device registration from IoT Hub and stop the daemon. So
                    // we have our own timeout mechanism.
                    DateTime startTime      = DateTime.Now;
                    CancellationToken token = cts.Token;

                    Assert.IsNull(this.device);
                    this.device = await EdgeDevice.GetOrCreateIdentityAsync(
                        Context.Current.DeviceId,
                        this.iotHub,
                        token);

                    await this.daemon.UninstallAsync(token);
                    await this.daemon.InstallAsync(
                        this.device.ConnectionString,
                        Context.Current.PackagePath,
                        Context.Current.Proxy,
                        token);

                    try
                    {
                        await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token);

                        var agent = new EdgeAgent(this.device.Id, this.iotHub);
                        await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token);
                        await agent.PingAsync(token);
                    }

                    // ReSharper disable once RedundantCatchClause
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        await NUnitLogs.CollectAsync(startTime, token);
                    }
                }
            },
                "Completed end-to-end test setup");
        }
Exemplo n.º 11
0
        public async Task DpsX509()
        {
            (string, string, string)rootCa =
                Context.Current.RootCaKeys.Expect(() => new InvalidOperationException("Missing DPS ID scope (check rootCaPrivateKeyPath in context.json)"));
            string caCertScriptPath =
                Context.Current.CaCertScriptPath.Expect(() => new InvalidOperationException("Missing CA cert script path (check caCertScriptPath in context.json)"));
            string idScope        = Context.Current.DpsIdScope.Expect(() => new InvalidOperationException("Missing DPS ID scope (check dpsIdScope in context.json)"));
            string registrationId = DeviceId.Current.Generate();

            CancellationToken token = this.TestToken;

            CertificateAuthority ca = await CertificateAuthority.CreateAsync(
                registrationId,
                rootCa,
                caCertScriptPath,
                token);

            IdCertificates idCert = await ca.GenerateIdentityCertificatesAsync(registrationId, token);

            (TestCertificates testCerts, _) = await TestCertificates.GenerateCertsAsync(registrationId, token);

            // Generated credentials need to be copied out of the script path because future runs
            // of the script will overwrite them.
            string path     = Path.Combine(FixedPaths.E2E_TEST_DIR, registrationId);
            string certPath = Path.Combine(path, "device_id_cert.pem");
            string keyPath  = Path.Combine(path, "device_id_cert_key.pem");

            Directory.CreateDirectory(path);
            File.Copy(idCert.CertificatePath, certPath);
            OsPlatform.Current.SetOwner(certPath, "aziotcs", "644");
            File.Copy(idCert.KeyPath, keyPath);
            OsPlatform.Current.SetOwner(keyPath, "aziotks", "600");

            await this.daemon.ConfigureAsync(
                config =>
            {
                testCerts.AddCertsToConfig(config);
                config.SetDpsX509(idScope, registrationId, certPath, keyPath);
                config.Update();
                return(Task.FromResult((
                                           "with DPS X509 attestation for '{Identity}'",
                                           new object[] { registrationId })));
            },
                token);

            await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token);

            var agent = new EdgeAgent(registrationId, this.iotHub);
            await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token);

            await agent.PingAsync(token);

            Option <EdgeDevice> device = await EdgeDevice.GetIdentityAsync(
                registrationId,
                this.iotHub,
                token,
                takeOwnership : true);

            Context.Current.DeleteList.TryAdd(
                registrationId,
                device.Expect(() => new InvalidOperationException(
                                  $"Device '{registrationId}' should have been created by DPS, but was not found in '{this.iotHub.Hostname}'")));
        }
Exemplo n.º 12
0
        public async Task <int> RunAsync(Args args)
        {
            LogEventLevel consoleLevel = args.Verbose
                ? LogEventLevel.Verbose
                : LogEventLevel.Information;
            var loggerConfig = new LoggerConfiguration()
                               .MinimumLevel.Verbose()
                               .WriteTo.Console(consoleLevel);

            args.LogFile.ForEach(f => loggerConfig.WriteTo.File(f));
            Log.Logger = loggerConfig.CreateLogger();

            try
            {
                using (var cts = new CancellationTokenSource(args.Timeout))
                {
                    Log.Information("Running tempSensor test");
                    await Profiler.Run(
                        async() =>
                    {
                        CancellationToken token = cts.Token;

                        // ** setup
                        var iotHub        = new IotHub(args.ConnectionString, args.Endpoint, args.Proxy);
                        EdgeDevice device = await EdgeDevice.GetOrCreateIdentityAsync(
                            args.DeviceId,
                            iotHub,
                            token);

                        var daemon = Platform.CreateEdgeDaemon(args.InstallerPath);
                        await daemon.UninstallAsync(token);
                        await daemon.InstallAsync(
                            device.ConnectionString,
                            args.PackagesPath,
                            args.Proxy,
                            token);
                        await daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token);

                        var agent = new EdgeAgent(device.Id, iotHub);
                        await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token);
                        await agent.PingAsync(token);

                        // ** test
                        var config = new EdgeConfiguration(device.Id, args.AgentImage, iotHub);
                        args.Registry.ForEach(
                            r => config.AddRegistryCredentials(r.address, r.username, r.password));
                        config.AddEdgeHub(args.HubImage);
                        args.Proxy.ForEach(p => config.AddProxy(p));
                        config.AddTempSensor(args.SensorImage);
                        await config.DeployAsync(token);

                        var hub    = new EdgeModule("edgeHub", device.Id, iotHub);
                        var sensor = new EdgeModule("tempSensor", device.Id, iotHub);
                        await EdgeModule.WaitForStatusAsync(
                            new[] { hub, sensor },
                            EdgeModuleStatus.Running,
                            token);
                        await sensor.WaitForEventsReceivedAsync(token);

                        var sensorTwin = new ModuleTwin(sensor.Id, device.Id, iotHub);
                        await sensorTwin.UpdateDesiredPropertiesAsync(
                            new
                        {
                            properties = new
                            {
                                desired = new
                                {
                                    SendData     = true,
                                    SendInterval = 10
                                }
                            }
                        },
                            token);
                        await sensorTwin.WaitForReportedPropertyUpdatesAsync(
                            new
                        {
                            properties = new
                            {
                                reported = new
                                {
                                    SendData     = true,
                                    SendInterval = 10
                                }
                            }
                        },
                            token);

                        // ** teardown
                        await daemon.StopAsync(token);
                        await device.MaybeDeleteIdentityAsync(token);
                    },
                        "Completed tempSensor test");
                }
            }
            catch (OperationCanceledException e)
            {
                Log.Error(e, "Cancelled tempSensor test after {Timeout} minutes", args.Timeout.TotalMinutes);
            }
            catch (Exception e)
            {
                Log.Error(e, "Failed tempSensor test");
                return(1);
            }
            finally
            {
                Log.CloseAndFlush();
            }

            return(0);
        }
Exemplo n.º 13
0
        public Task <int> RunAsync(Args args) => Profiler.Run(
            "Running tempSensor test",
            async() =>
        {
            using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5)))
            {
                CancellationToken token = cts.Token;

                // ** setup
                var iotHub = new IotHub(args.ConnectionString, args.Endpoint, args.Proxy);
                var device = await EdgeDevice.GetOrCreateIdentityAsync(
                    args.DeviceId,
                    iotHub,
                    token);

                var daemon = new EdgeDaemon(args.InstallerPath);
                await daemon.UninstallAsync(token);
                await daemon.InstallAsync(
                    device.ConnectionString,
                    args.PackagesPath,
                    args.Proxy,
                    token);

                await args.Proxy.Match(
                    async p =>
                {
                    await daemon.StopAsync(token);
                    var yaml = new DaemonConfiguration();
                    yaml.AddHttpsProxy(p);
                    yaml.Update();
                    await daemon.StartAsync(token);
                },
                    () => daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token));

                var agent = new EdgeAgent(device.Id, iotHub);
                await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token);
                await agent.PingAsync(token);

                // ** test
                var config = new EdgeConfiguration(device.Id, args.AgentImage, iotHub);
                args.Registry.ForEach(
                    r => config.AddRegistryCredentials(r.address, r.username, r.password));
                config.AddEdgeHub(args.HubImage);
                args.Proxy.ForEach(p => config.AddProxy(p));
                config.AddTempSensor(args.SensorImage);
                await config.DeployAsync(token);

                var hub    = new EdgeModule("edgeHub", device.Id, iotHub);
                var sensor = new EdgeModule("tempSensor", device.Id, iotHub);
                await EdgeModule.WaitForStatusAsync(
                    new[] { hub, sensor },
                    EdgeModuleStatus.Running,
                    token);
                await sensor.WaitForEventsReceivedAsync(token);

                var sensorTwin = new ModuleTwin(sensor.Id, device.Id, iotHub);
                await sensorTwin.UpdateDesiredPropertiesAsync(
                    new
                {
                    properties = new
                    {
                        desired = new
                        {
                            SendData     = true,
                            SendInterval = 10
                        }
                    }
                },
                    token);
                await sensorTwin.WaitForReportedPropertyUpdatesAsync(
                    new
                {
                    properties = new
                    {
                        reported = new
                        {
                            SendData     = true,
                            SendInterval = 10
                        }
                    }
                },
                    token);

                // ** teardown
                await daemon.StopAsync(token);
                await device.MaybeDeleteIdentityAsync(token);
            }

            return(0);
        },
            "Completed tempSensor test");