// POST: api/Cameras/Deactivate/1
        public async Task <IHttpActionResult> Deactivate(int id)
        {
            using (var db = new VideoAnalyticContext())
            {
                Camera camera = db.Cameras.Find(id);
                if (camera == null)
                {
                    return(NotFound());
                }

                var        deviceId = camera.HostingDevice;
                EdgeDevice device   = db.EdgeDevices.Find(deviceId);
                if (device == null)
                {
                    return(NotFound());
                }

                var configStr = device.Configurations;
                if (string.IsNullOrEmpty(configStr))
                {
                    return(InternalServerError());
                }

                var moduleName   = camera.Name;
                var resultConfig = await IoTEdgeManager.DeleteModuleOnDeviceAsync(moduleName, device.Name, camera.Pipeline, JObject.Parse(configStr));

                device.Configurations = resultConfig;
                camera.Status         = "NotActive";

                db.SaveChanges();

                return(Ok());
            }
        }
        public async Task X509ProvisionEdgeAsync()
        {
            await Profiler.Run(
                async() =>
            {
                using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout))
                {
                    CancellationToken token = cts.Token;
                    DateTime startTime      = DateTime.Now;

                    IdCertificates certs;
                    (this.Thumbprint, certs) = await this.CreateDeviceIdCertAsync(Context.Current.DeviceId + "-x509", token);

                    EdgeDevice device = await EdgeDevice.GetOrCreateIdentityAsync(
                        Context.Current.DeviceId + "-x509",
                        this.iotHub,
                        AuthenticationType.SelfSigned,
                        this.Thumbprint,
                        token);

                    Context.Current.DeleteList.TryAdd(device.Id, device);

                    this.Device = device;

                    await this.ManuallyProvisionEdgeX509Async(device, certs.CertificatePath, certs.KeyPath, startTime, token);
                }
            },
                "Completed edge manual provisioning with self-signed certificate");
        }
        public async Task X509ProvisionEdgeAsync()
        {
            await Profiler.Run(
                async() =>
            {
                using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout))
                {
                    CancellationToken token = cts.Token;
                    DateTime startTime      = DateTime.Now;
                    string deviceId         = DeviceId.Current.Generate();

                    (X509Thumbprint thumbprint, string certPath, string keyPath) = await this.CreateIdentityCertAsync(
                        deviceId, token);

                    EdgeDevice device = await EdgeDevice.GetOrCreateIdentityAsync(
                        deviceId,
                        this.GetNestedEdgeConfig(this.IotHub),
                        this.IotHub,
                        AuthenticationType.SelfSigned,
                        thumbprint,
                        token);

                    Context.Current.DeleteList.TryAdd(device.Id, device);

                    this.runtime = new EdgeRuntime(
                        device.Id,
                        Context.Current.EdgeAgentImage,
                        Context.Current.EdgeHubImage,
                        Context.Current.EdgeProxy,
                        Context.Current.Registries,
                        Context.Current.OptimizeForPerformance,
                        this.IotHub);

                    TestCertificates testCerts;
                    (testCerts, this.ca) = await TestCertificates.GenerateCertsAsync(device.Id, token);

                    await this.ConfigureDaemonAsync(
                        config =>
                    {
                        testCerts.AddCertsToConfig(config);
                        config.SetDeviceManualX509(
                            this.IotHub.Hostname,
                            Context.Current.ParentHostname,
                            device.Id,
                            certPath,
                            keyPath);
                        config.Update();
                        return(Task.FromResult((
                                                   "with x509 certificate for device '{Identity}'",
                                                   new object[] { device.Id })));
                    },
                        device,
                        startTime,
                        token);
                }
            },
                "Completed edge manual provisioning with self-signed certificate");
        }
Esempio n. 4
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");
        }
        public IActionResult Post([FromBody] EdgeDeviceDTO item)
        {
            var edgeDeviceItem = new EdgeDevice()
            {
                EdgeDeviceName = item.EdgeDeviceName
            };

            _repository.Add(edgeDeviceItem);
            return(Ok(EdgeDeviceDTO.FromEdgeDevice(edgeDeviceItem)));
        }
        public static EdgeDeviceDTO FromEdgeDevice(EdgeDevice item)
        {
            EdgeDeviceDTO edgeDeviceDTO = new EdgeDeviceDTO
            {
                Id             = item.Id,
                EdgeDeviceName = item.EdgeDeviceName
            };

            return(edgeDeviceDTO);
        }
        public async Task<HttpResponseMessage> AddEdgeDevice(JObject body)
        {
            try
            {
                var deviceName = body?.GetValue("deviceName")?.Value<string>();
                var deviceDescription = body?.GetValue("deviceDescription")?.Value<string>() ?? "";
                var osType = body?.GetValue("osType")?.Value<string>();
                var capacity = body?.GetValue("capacity")?.Value<int>() ?? 0;

                if (string.IsNullOrEmpty(deviceName) || string.IsNullOrEmpty(osType))
                {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid body. deviceName,osType is required");
                }


                using (var db = new VideoAnalyticContext())
                {
                    var device = await db.EdgeDevices.SingleOrDefaultAsync(d => d.Name.Equals(deviceName));
                    if (device != null)
                    {
                        return Request.CreateErrorResponse(HttpStatusCode.Conflict, $"Device with name: {deviceName} already exits.");
                    }

                    var connectString = await IoTEdgeManager.AddDeviceAsync(deviceName);

                    if (string.IsNullOrEmpty(connectString))
                    {
                        return Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, $"Create Device with name: {deviceName} failed!.");
                    }

                    EdgeDevice edgeDevice = new EdgeDevice()
                    {
                        Name = deviceName,
                        Description = deviceDescription,
                        OSType = osType,
                        Capacity = capacity,
                        ConnectString = connectString,
                        Status = EdgeDeviceStatus.Create.ToString(),
                        CreatedOn = DateTime.UtcNow
                    };

                    db.EdgeDevices.Add(edgeDevice);
                    db.SaveChanges();

                    return Request.CreateResponse(HttpStatusCode.OK, edgeDevice);
                }

            }
            catch (Exception e)
            {
                LogUtil.LogException(e);
                return Request.CreateResponse(HttpStatusCode.InternalServerError, e.Message);
            }

        }
Esempio n. 8
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}'")));
        }
Esempio n. 9
0
        public async Task ModuleToModuleDirectMethod(
            [Values] Protocol protocol)
        {
            if (Platform.IsWindows() && (protocol == Protocol.AmqpWs || protocol == Protocol.MqttWs))
            {
                Assert.Ignore("Module-to-module direct methods don't work over WebSocket on Windows");
            }

            string       agentImage             = Context.Current.EdgeAgentImage.Expect(() => new ArgumentException());
            string       hubImage               = Context.Current.EdgeHubImage.Expect(() => new ArgumentException());
            string       senderImage            = Context.Current.MethodSenderImage.Expect(() => new ArgumentException());
            string       receiverImage          = Context.Current.MethodReceiverImage.Expect(() => new ArgumentException());
            bool         optimizeForPerformance = Context.Current.OptimizeForPerformance;
            Option <Uri> proxy = Context.Current.Proxy;

            CancellationToken token = this.cts.Token;

            string name = $"module-to-module direct method ({protocol.ToString()})";

            Log.Information("Running test '{Name}'", name);
            await Profiler.Run(
                async() =>
            {
                var iotHub = new IotHub(
                    Context.Current.ConnectionString,
                    Context.Current.EventHubEndpoint,
                    proxy);

                EdgeDevice device = (await EdgeDevice.GetIdentityAsync(
                                         Context.Current.DeviceId,
                                         iotHub,
                                         token)).Expect(() => new Exception("Device should have already been created in setup fixture"));

                string methodSender    = $"methodSender-{protocol.ToString()}";
                string methodReceiver  = $"methodReceiver-{protocol.ToString()}";
                string clientTransport = protocol.ToTransportType().ToString();

                var builder = new EdgeConfigBuilder(device.Id);
                foreach ((string address, string username, string password) in Context.Current.Registries)
                {
                    builder.AddRegistryCredentials(address, username, password);
                }

                builder.AddEdgeAgent(agentImage).WithProxy(proxy);
                builder.AddEdgeHub(hubImage, optimizeForPerformance).WithProxy(proxy);
                builder.AddModule(methodSender, senderImage)
                .WithEnvironment(
                    new[]
                {
                    ("ClientTransportType", clientTransport),
                    ("TargetModuleId", methodReceiver)
                });
Esempio n. 10
0
        protected virtual async Task SasProvisionEdgeAsync(bool withCerts = false)
        {
            using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout))
            {
                CancellationToken token     = cts.Token;
                DateTime          startTime = DateTime.Now;

                this.device = await EdgeDevice.GetOrCreateIdentityAsync(
                    Context.Current.DeviceId.GetOrElse(DeviceId.Current.Generate()),
                    this.GetNestedEdgeConfig(this.IotHub),
                    this.IotHub,
                    AuthenticationType.Sas,
                    null,
                    token);

                Log.Information($"Device ID {this.device.Id}");

                Context.Current.DeleteList.TryAdd(this.device.Id, this.device);

                this.runtime = new EdgeRuntime(
                    this.device.Id,
                    Context.Current.EdgeAgentImage,
                    Context.Current.EdgeHubImage,
                    Context.Current.EdgeProxy,
                    Context.Current.Registries,
                    Context.Current.OptimizeForPerformance,
                    this.IotHub);

                // This is a temporary solution see ticket: 9288683
                if (!Context.Current.ISA95Tag)
                {
                    TestCertificates testCerts;
                    (testCerts, this.ca) = await TestCertificates.GenerateCertsAsync(this.device.Id, token);

                    await this.ConfigureDaemonAsync(
                        config =>
                    {
                        testCerts.AddCertsToConfig(config);

                        config.SetManualSasProvisioning(Context.Current.ParentHostname.GetOrElse(this.device.HubHostname), this.device.Id, this.device.SharedAccessKey);

                        config.Update();
                        return(Task.FromResult((
                                                   "with connection string for device '{Identity}'",
                                                   new object[] { this.device.Id })));
                    },
                        this.device,
                        startTime,
                        token);
                }
            }
        }
Esempio n. 11
0
        public async Task ManuallyProvisionEdgeX509Async(EdgeDevice device, string certPath, string keyPath, DateTime startTime, CancellationToken token)
        {
            await this.daemon.ConfigureAsync(
                config =>
            {
                config.SetDeviceManualX509(device.HubHostname, device.Id, certPath, keyPath);
                config.Update();
                return(Task.FromResult((
                                           "with x509 certificate for device '{Identity}'",
                                           new object[] { device.Id })));
            },
                token);

            await this.WaitForConfiguredStatusAsync(device, startTime, token);
        }
Esempio n. 12
0
        public async Task ManuallyProvisionEdgeSasAsync(EdgeDevice device, DateTime startTime, CancellationToken token)
        {
            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);

            await this.WaitForConfiguredStatusAsync(device, startTime, token);
        }
Esempio n. 13
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}'")));
        }
        public virtual async Task SasProvisionEdgeAsync()
        {
            using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout))
            {
                CancellationToken token     = cts.Token;
                DateTime          startTime = DateTime.Now;

                EdgeDevice device = await EdgeDevice.GetOrCreateIdentityAsync(
                    DeviceId.Current.Generate(),
                    this.iotHub,
                    AuthenticationType.Sas,
                    null,
                    token);

                Context.Current.DeleteList.TryAdd(device.Id, device);

                this.runtime = new EdgeRuntime(
                    device.Id,
                    Context.Current.EdgeAgentImage,
                    Context.Current.EdgeHubImage,
                    Context.Current.Proxy,
                    Context.Current.Registries,
                    Context.Current.OptimizeForPerformance,
                    this.iotHub);

                await this.ConfigureDaemonAsync(
                    config =>
                {
                    config.SetDeviceConnectionString(device.ConnectionString);
                    config.Update();
                    return(Task.FromResult((
                                               "with connection string for device '{Identity}'",
                                               new object[] { device.Id })));
                },
                    device,
                    startTime,
                    token);
            }
        }
Esempio n. 15
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);
            }
        }
        // POST: api/Cameras/Activate/1
        public async Task <IHttpActionResult> Activate(int id)
        {
            using (var db = new VideoAnalyticContext())
            {
                Camera camera = db.Cameras.Find(id);
                if (camera == null)
                {
                    return(NotFound());
                }

                var        deviceId = camera.HostingDevice;
                EdgeDevice device   = db.EdgeDevices.Find(deviceId);
                if (device == null)
                {
                    return(NotFound());
                }

                var configStr = device.Configurations;
                if (string.IsNullOrEmpty(configStr))
                {
                    configStr = File.ReadAllText($"{WebApiConfig.DataPath}/moduleTemplate/default.json");
                }

                var properties = new JObject
                {
                    { "RTSP", camera.Stream }
                };

                var moduleName   = camera.Name;
                var resultConfig = await IoTEdgeManager.AddModuleOnDeviceAsync(moduleName, device.Name, camera.Pipeline, properties, JObject.Parse(configStr));

                device.Configurations = resultConfig;
                camera.Status         = "Active";
                db.SaveChanges();

                return(Ok());
            }
        }
        public async Task<IHttpActionResult> DeleteEdgeDevice(int id)
        {
            using (var db = new VideoAnalyticContext())
            {
                EdgeDevice edgeDevice = await db.EdgeDevices.SingleOrDefaultAsync(d => d.Id == id);
                if (edgeDevice == null)
                {
                    return NotFound();
                }

                var cameras = await db.Cameras.Where(d => d.HostingDevice == edgeDevice.Id).ToListAsync();
                if (cameras.Count > 0)
                {
                    return Content(HttpStatusCode.Forbidden, $"Cannot delete Edge Device {id}, since there are {cameras.Count} cameras connected. Delete all cameras connected to this device first. ");
                }

                await IoTEdgeManager.DeleteDeviceAsync(edgeDevice.Name);
                db.EdgeDevices.Remove(edgeDevice);
                db.SaveChanges();

                return Ok(edgeDevice);
            }
        }
        public async Task SasProvisionEdgeAsync()
        {
            await Profiler.Run(
                async() =>
            {
                using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout))
                {
                    CancellationToken token = cts.Token;
                    DateTime startTime      = DateTime.Now;

                    EdgeDevice device = await EdgeDevice.GetOrCreateIdentityAsync(
                        Context.Current.DeviceId,
                        this.iotHub,
                        AuthenticationType.Sas,
                        null,
                        token);

                    Context.Current.DeleteList.TryAdd(device.Id, device);

                    await this.ManuallyProvisionEdgeSasAsync(device, startTime, token);
                }
            },
                "Completed edge manual provisioning with SAS token");
        }
Esempio n. 19
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");
Esempio n. 20
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");
        }
Esempio n. 21
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}'")));
        }
Esempio n. 22
0
        public async Task TempSensor()
        {
            string       agentImage             = Context.Current.EdgeAgentImage.Expect(() => new ArgumentException());
            string       hubImage               = Context.Current.EdgeHubImage.Expect(() => new ArgumentException());
            string       sensorImage            = Context.Current.TempSensorImage.Expect(() => new ArgumentException());
            bool         optimizeForPerformance = Context.Current.OptimizeForPerformance;
            Option <Uri> proxy = Context.Current.Proxy;

            CancellationToken token = this.cts.Token;

            string name = "temp sensor";

            Log.Information("Running test '{Name}'", name);
            await Profiler.Run(
                async() =>
            {
                var iotHub = new IotHub(
                    Context.Current.ConnectionString,
                    Context.Current.EventHubEndpoint,
                    proxy);

                EdgeDevice device = (await EdgeDevice.GetIdentityAsync(
                                         Context.Current.DeviceId,
                                         iotHub,
                                         token)).Expect(() => new Exception("Device should have already been created in setup fixture"));

                var builder = new EdgeConfigBuilder(device.Id);
                foreach ((string address, string username, string password) in Context.Current.Registries)
                {
                    builder.AddRegistryCredentials(address, username, password);
                }

                builder.AddEdgeAgent(agentImage).WithProxy(proxy);
                builder.AddEdgeHub(hubImage, optimizeForPerformance).WithProxy(proxy);
                builder.AddModule("tempSensor", sensorImage);
                await builder.Build().DeployAsync(iotHub, 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);
            },
                "Completed test '{Name}'",
                name);
        }
Esempio n. 23
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);
        }