Esempio n. 1
0
        public async void FileBackupSuccessCallsEncrypt()
        {
            if (File.Exists(this.tempFileName))
            {
                File.Delete(this.tempFileName);
            }

            var underlying = new Mock <IConfigSource>();

            underlying.SetupSequence(t => t.GetDeploymentConfigInfoAsync())
            .ReturnsAsync(ValidConfigInfo1);

            ISerde <DeploymentConfigInfo> serde = this.GetSerde();
            var encryptionProvider = new Mock <IEncryptionProvider>();

            encryptionProvider.Setup(ep => ep.EncryptAsync(It.IsAny <string>()))
            .ReturnsAsync(serde.Serialize(ValidConfigInfo1));
            using (IConfigSource configSource = new FileBackupConfigSource(this.tempFileName, underlying.Object, serde, encryptionProvider.Object))
            {
                DeploymentConfigInfo config1 = await configSource.GetDeploymentConfigInfoAsync();

                Assert.NotNull(config1);

                Assert.True(File.Exists(this.tempFileName));
                string backupJson = await DiskFile.ReadAllAsync(this.tempFileName);

                string returnedJson = serde.Serialize(config1);

                Assert.Equal(backupJson, returnedJson, true);
                encryptionProvider.Verify(ep => ep.EncryptAsync(It.IsAny <string>()));
            }
        }
Esempio n. 2
0
        public async void FileBackupDoesNotThrowWhenBackupFileDoesNotExist()
        {
            if (File.Exists(this.tempFileName))
            {
                File.Delete(this.tempFileName);
            }

            // Arrange
            var underlying = new Mock <IConfigSource>();

            underlying.Setup(cs => cs.GetDeploymentConfigInfoAsync())
            .ReturnsAsync(DeploymentConfigInfo.Empty);

            ISerde <DeploymentConfigInfo> serde = this.GetSerde();

            // Act
            using (IConfigSource configSource = new FileBackupConfigSource(this.tempFileName, underlying.Object, serde, NullEncryptionProvider.Instance))
            {
                // this call should fetch the config properly
                DeploymentConfigInfo config1 = await configSource.GetDeploymentConfigInfoAsync();

                Assert.NotNull(config1);
                Assert.Equal(DeploymentConfigInfo.Empty, config1);
            }
        }
        public async void ReadDeploymentConfigFromSecret()
        {
            ISerde <DeploymentConfigInfo> serde = this.GetSerde();

            var secretData = new Dictionary <string, byte[]>
            {
                ["backup.json"] = System.Text.Encoding.UTF8.GetBytes(serde.Serialize(ValidConfigInfo1))
            };
            var secret   = new V1Secret(data: secretData);
            var response = new HttpOperationResponse <V1Secret>()
            {
                Body     = secret,
                Response = new HttpResponseMessage(HttpStatusCode.OK)
            };

            var client = new Mock <IKubernetes>(MockBehavior.Strict);

            client.Setup(c => c.ReadNamespacedSecretWithHttpMessagesAsync(DefaultSecretName, DefaultNamespace, It.IsAny <bool?>(), It.IsAny <bool?>(), null, null, It.IsAny <CancellationToken>()))
            .ReturnsAsync(response);

            var backupSource         = new DeploymentSecretBackup(DefaultSecretName, DefaultNamespace, DefaultOwner, serde, client.Object);
            var deploymentConfigInfo = await backupSource.ReadFromBackupAsync();

            string returnedJson = serde.Serialize(deploymentConfigInfo);
            string expectedJson = serde.Serialize(ValidConfigInfo1);

            Assert.Equal(expectedJson, returnedJson, ignoreCase: true);
            client.VerifyAll();
        }
Esempio n. 4
0
        public async void FileBackupDoesNotThrowWhenEncryptFails()
        {
            if (File.Exists(this.tempFileName))
            {
                File.Delete(this.tempFileName);
            }

            var underlying = new Mock <IConfigSource>();

            underlying.SetupSequence(t => t.GetDeploymentConfigInfoAsync())
            .ReturnsAsync(ValidConfigInfo1);

            ISerde <DeploymentConfigInfo> serde = this.GetSerde();
            var encryptionProvider = new Mock <IEncryptionProvider>();

            encryptionProvider.Setup(ep => ep.EncryptAsync(It.IsAny <string>()))
            .ThrowsAsync(new IoTEdgedException("failed", 404, "", null, null));
            using (IConfigSource configSource = new FileBackupConfigSource(this.tempFileName, underlying.Object, serde, encryptionProvider.Object))
            {
                DeploymentConfigInfo config1 = await configSource.GetDeploymentConfigInfoAsync();

                Assert.NotNull(config1);

                Assert.Equal(ValidConfigInfo1, config1);

                encryptionProvider.Verify(ep => ep.EncryptAsync(It.IsAny <string>()));
            }
        }
Esempio n. 5
0
        public async void FileBackupSuccessWhenFileNotExists()
        {
            if (File.Exists(this.tempFileName))
            {
                File.Delete(this.tempFileName);
            }

            var underlying = new Mock <IConfigSource>();

            underlying.SetupSequence(t => t.GetDeploymentConfigInfoAsync())
            .ReturnsAsync(ValidConfigInfo1)
            .ThrowsAsync(new InvalidOperationException());
            ISerde <DeploymentConfigInfo> serde = this.GetSerde();

            using (IConfigSource configSource = new FileBackupConfigSource(this.tempFileName, underlying.Object, serde, NullEncryptionProvider.Instance))
            {
                DeploymentConfigInfo config1 = await configSource.GetDeploymentConfigInfoAsync();

                Assert.NotNull(config1);

                Assert.True(File.Exists(this.tempFileName));
                string backupJson = await DiskFile.ReadAllAsync(this.tempFileName);

                string returnedJson = serde.Serialize(config1);

                Assert.True(string.Equals(backupJson, returnedJson, StringComparison.OrdinalIgnoreCase));

                DeploymentConfigInfo config2 = await configSource.GetDeploymentConfigInfoAsync();

                Assert.NotNull(config2);

                Assert.Equal(serde.Serialize(config1), serde.Serialize(config2));
            }
        }
        public async void BackupDeploymentDoesNotThrowOnFailure()
        {
            ISerde <DeploymentConfigInfo> serde = this.GetSerde();

            string expectedJson   = serde.Serialize(ValidConfigInfo1);
            var    readSecretData = new Dictionary <string, byte[]>
            {
                ["backup.json"] = System.Text.Encoding.UTF8.GetBytes(serde.Serialize(ValidConfigInfo2))
            };
            var readSecret        = new V1Secret(data: readSecretData);
            var replaceSecretData = new Dictionary <string, byte[]>
            {
                ["backup.json"] = System.Text.Encoding.UTF8.GetBytes(expectedJson)
            };
            var replaceSecret = new V1Secret(data: readSecretData);
            var readResponse  = new HttpOperationResponse <V1Secret>()
            {
                Body     = readSecret,
                Response = new HttpResponseMessage(HttpStatusCode.OK)
            };

            var client = new Mock <IKubernetes>(MockBehavior.Strict);

            client.Setup(c => c.ReadNamespacedSecretWithHttpMessagesAsync(DefaultSecretName, DefaultNamespace, It.IsAny <bool?>(), It.IsAny <bool?>(), null, null, It.IsAny <CancellationToken>()))
            .ReturnsAsync(readResponse);
            client.Setup(c => c.ReplaceNamespacedSecretWithHttpMessagesAsync(It.IsAny <V1Secret>(), DefaultSecretName, DefaultNamespace, null, null, null, null, It.IsAny <CancellationToken>()))
            .ThrowsAsync(new HttpOperationException("Not Permitted"));

            var backupSource = new DeploymentSecretBackup(DefaultSecretName, DefaultNamespace, DefaultOwner, serde, client.Object);
            await backupSource.BackupDeploymentConfigAsync(ValidConfigInfo1);

            client.VerifyAll();
        }
Esempio n. 7
0
 public EdgeAgentConnection(
     IModuleClientProvider moduleClientProvider,
     ISerde <DeploymentConfig> desiredPropertiesSerDe,
     IRequestManager requestManager)
     : this(moduleClientProvider, desiredPropertiesSerDe, requestManager, true, DefaultConfigRefreshFrequency, TransientRetryStrategy)
 {
 }
Esempio n. 8
0
        public async void FileBackupReadFromBackupCallsEncryptDecrypt()
        {
            if (File.Exists(this.tempFileName))
            {
                File.Delete(this.tempFileName);
            }

            ISerde <DeploymentConfigInfo> serde = this.GetSerde();
            var encryptionProvider = new Mock <IEncryptionProvider>();

            encryptionProvider.Setup(ep => ep.EncryptAsync(It.IsAny <string>()))
            .ReturnsAsync(serde.Serialize(ValidConfigInfo1));
            encryptionProvider.Setup(ep => ep.DecryptAsync(It.IsAny <string>()))
            .ReturnsAsync(serde.Serialize(ValidConfigInfo1));

            IDeploymentBackupSource fileBackup = new DeploymentFileBackup(this.tempFileName, serde, encryptionProvider.Object);

            await fileBackup.BackupDeploymentConfigAsync(ValidConfigInfo1);

            DeploymentConfigInfo config1 = await fileBackup.ReadFromBackupAsync();

            Assert.NotNull(config1);
            Assert.True(File.Exists(this.tempFileName));
            string backupJson = await DiskFile.ReadAllAsync(this.tempFileName);

            string returnedJson = serde.Serialize(config1);
            string expectedJson = serde.Serialize(ValidConfigInfo1);

            Assert.Equal(expectedJson, backupJson, ignoreCase: true);
            Assert.Equal(expectedJson, returnedJson, ignoreCase: true);

            encryptionProvider.Verify(ep => ep.EncryptAsync(It.IsAny <string>()));
            encryptionProvider.Verify(ep => ep.DecryptAsync(It.IsAny <string>()));
        }
Esempio n. 9
0
 public Agent(
     IConfigSource configSource,
     IEnvironmentProvider environmentProvider,
     IPlanner planner,
     IPlanRunner planRunner,
     IReporter reporter,
     IModuleIdentityLifecycleManager moduleIdentityLifecycleManager,
     IEntityStore <string, string> configStore,
     DeploymentConfigInfo initialDeployedConfigInfo,
     ISerde <DeploymentConfigInfo> deploymentConfigInfoSerde,
     IEncryptionProvider encryptionProvider,
     IAvailabilityMetric availabilityMetric)
 {
     this.configSource = Preconditions.CheckNotNull(configSource, nameof(configSource));
     this.planner      = Preconditions.CheckNotNull(planner, nameof(planner));
     this.planRunner   = Preconditions.CheckNotNull(planRunner, nameof(planRunner));
     this.reporter     = Preconditions.CheckNotNull(reporter, nameof(reporter));
     this.moduleIdentityLifecycleManager = Preconditions.CheckNotNull(moduleIdentityLifecycleManager, nameof(moduleIdentityLifecycleManager));
     this.configStore               = Preconditions.CheckNotNull(configStore, nameof(configStore));
     this.environmentProvider       = Preconditions.CheckNotNull(environmentProvider, nameof(environmentProvider));
     this.currentConfig             = Preconditions.CheckNotNull(initialDeployedConfigInfo);
     this.deploymentConfigInfoSerde = Preconditions.CheckNotNull(deploymentConfigInfoSerde, nameof(deploymentConfigInfoSerde));
     this.environment               = this.environmentProvider.Create(this.currentConfig.DeploymentConfig);
     this.encryptionProvider        = Preconditions.CheckNotNull(encryptionProvider, nameof(encryptionProvider));
     this.availabilityMetric        = Preconditions.CheckNotNull(availabilityMetric, nameof(availabilityMetric));
     this.status = DeploymentStatus.Unknown;
     Events.AgentCreated();
 }
Esempio n. 10
0
 internal EdgeAgentConnection(
     IModuleClientProvider moduleClientProvider,
     ISerde <DeploymentConfig> desiredPropertiesSerDe,
     IRequestManager requestManager,
     IDeviceManager deviceManager,
     bool enableSubscriptions,
     TimeSpan refreshConfigFrequency,
     RetryStrategy retryStrategy,
     IDeploymentMetrics deploymentMetrics,
     Option <X509Certificate2> manifestTrustBundle,
     TimeSpan twinPullOnConnectThrottleTime)
 {
     this.desiredPropertiesSerDe = Preconditions.CheckNotNull(desiredPropertiesSerDe, nameof(desiredPropertiesSerDe));
     this.deploymentConfigInfo   = Option.None <DeploymentConfigInfo>();
     this.reportedProperties     = Option.None <TwinCollection>();
     this.moduleConnection       = new ModuleConnection(moduleClientProvider, requestManager, this.OnConnectionStatusChanged, this.OnDesiredPropertiesUpdated, enableSubscriptions);
     this.retryStrategy          = Preconditions.CheckNotNull(retryStrategy, nameof(retryStrategy));
     this.refreshTwinTask        = new PeriodicTask(this.ForceRefreshTwin, refreshConfigFrequency, refreshConfigFrequency, Events.Log, "refresh twin config");
     this.pullOnReconnect        = enableSubscriptions;
     this.deviceManager          = Preconditions.CheckNotNull(deviceManager, nameof(deviceManager));
     Events.TwinRefreshInit(refreshConfigFrequency);
     this.deploymentMetrics             = Preconditions.CheckNotNull(deploymentMetrics, nameof(deploymentMetrics));
     this.initTask                      = this.ForceRefreshTwin();
     this.manifestTrustBundle           = manifestTrustBundle;
     this.twinPullOnConnectThrottleTime = twinPullOnConnectThrottleTime;
 }
Esempio n. 11
0
 public EdgeAgentConnection(
     IModuleClientProvider moduleClientProvider,
     ISerde <DeploymentConfig> desiredPropertiesSerDe,
     TimeSpan configRefreshFrequency)
     : this(moduleClientProvider, desiredPropertiesSerDe, TransientRetryStrategy, configRefreshFrequency)
 {
 }
        public async void DeserializeFaillureReturnsEmptyConfig()
        {
            ISerde<DeploymentConfigInfo> serde = this.GetSerde();

            var secretData = new Dictionary<string, byte[]>
            {
                ["backup.json"] = System.Text.Encoding.UTF8.GetBytes("{}")
            };
            var secret = new V1Secret(data: secretData);
            var response = new HttpOperationResponse<V1Secret>()
            {
                Body = secret,
                Response = new HttpResponseMessage(HttpStatusCode.OK)
            };

            var client = new Mock<IKubernetes>(MockBehavior.Strict);
            client.Setup(c => c.ReadNamespacedSecretWithHttpMessagesAsync(
                    DefaultSecretName,
                    DefaultNamespace,
                    It.IsAny<string>(), // pretty
                    null, // customHeaders
                    It.IsAny<CancellationToken>()))
                .ReturnsAsync(response);

            var backupSource = new DeploymentSecretBackup(DefaultSecretName, DefaultNamespace, DefaultOwner, serde, client.Object);
            var deploymentConfigInfo = await backupSource.ReadFromBackupAsync();

            Assert.NotNull(deploymentConfigInfo);
            Assert.Equal(DeploymentConfigInfo.Empty, deploymentConfigInfo);
            client.VerifyAll();
        }
        public async void NullSecretreturnsEmptyConfig()
        {
            ISerde<DeploymentConfigInfo> serde = this.GetSerde();

            var response = new HttpOperationResponse<V1Secret>()
            {
                Body = null,
                Response = new HttpResponseMessage(HttpStatusCode.OK)
            };

            var client = new Mock<IKubernetes>(MockBehavior.Strict);
            client.Setup(c => c.ReadNamespacedSecretWithHttpMessagesAsync(
                    DefaultSecretName,
                    DefaultNamespace,
                    It.IsAny<string>(), // pretty
                    null, // customHeaders
                    It.IsAny<CancellationToken>()))
                .ReturnsAsync(response);

            var backupSource = new DeploymentSecretBackup(DefaultSecretName, DefaultNamespace, DefaultOwner, serde, client.Object);
            var deploymentConfigInfo = await backupSource.ReadFromBackupAsync();

            Assert.NotNull(deploymentConfigInfo);
            Assert.Equal(DeploymentConfigInfo.Empty, deploymentConfigInfo);
            client.VerifyAll();
        }
        public async void BackupDeploymentConfigReplacesSecret()
        {
            ISerde<DeploymentConfigInfo> serde = this.GetSerde();

            string expectedJson = serde.Serialize(ValidConfigInfo1);
            var readSecretData = new Dictionary<string, byte[]>
            {
                ["backup.json"] = System.Text.Encoding.UTF8.GetBytes(serde.Serialize(ValidConfigInfo2))
            };
            var readSecret = new V1Secret(data: readSecretData);
            var replaceSecretData = new Dictionary<string, byte[]>
            {
                ["backup.json"] = System.Text.Encoding.UTF8.GetBytes(expectedJson)
            };
            var replaceSecret = new V1Secret(data: readSecretData);
            var readResponse = new HttpOperationResponse<V1Secret>()
            {
                Body = readSecret,
                Response = new HttpResponseMessage(HttpStatusCode.OK)
            };
            var replaceResponse = new HttpOperationResponse<V1Secret>()
            {
                Body = replaceSecret,
                Response = new HttpResponseMessage(HttpStatusCode.OK)
            };

            byte[] receivedData = default(byte[]);
            var client = new Mock<IKubernetes>(MockBehavior.Strict);
            client.Setup(c => c.ReadNamespacedSecretWithHttpMessagesAsync(
                    DefaultSecretName,
                    DefaultNamespace,
                    It.IsAny<string>(), // pretty
                    null, // customHeaders
                    It.IsAny<CancellationToken>()))
                .ReturnsAsync(readResponse);
            client.Setup(c => c.ReplaceNamespacedSecretWithHttpMessagesAsync(
                    It.IsAny<V1Secret>(),
                    DefaultSecretName,
                    DefaultNamespace,
                    null, // dryRun
                    null, // fieldmanager
                    null, // pretty
                    null, // customHeaders
                    It.IsAny<CancellationToken>()))
                .Callback((V1Secret body, string name, string namespaceParameter, string dryRun, string fieldManager, string pretty, Dictionary<string, List<string>> customHeaders, CancellationToken cancellationToken) =>
                {
                    Assert.True(body.Data != null);
                    Assert.True(body.Data.TryGetValue("backup.json", out receivedData));
                })
                .ReturnsAsync(replaceResponse);

            var backupSource = new DeploymentSecretBackup(DefaultSecretName, DefaultNamespace, DefaultOwner, serde, client.Object);
            await backupSource.BackupDeploymentConfigAsync(ValidConfigInfo1);

            string backupJson = System.Text.Encoding.UTF8.GetString(receivedData);

            Assert.Equal(expectedJson, backupJson, ignoreCase: true);
            client.VerifyAll();
        }
Esempio n. 15
0
 public DeploymentSecretBackup(string secretName, string deviceNamespace, KubernetesModuleOwner moduleOwner, ISerde <DeploymentConfigInfo> serde, IKubernetes client)
 {
     this.Name            = Preconditions.CheckNonWhiteSpace(secretName, nameof(secretName));
     this.deviceNamespace = Preconditions.CheckNonWhiteSpace(deviceNamespace, nameof(deviceNamespace));
     this.moduleOwner     = Preconditions.CheckNotNull(moduleOwner, nameof(moduleOwner));
     this.serde           = Preconditions.CheckNotNull(serde, nameof(serde));
     this.client          = Preconditions.CheckNotNull(client, nameof(client));
 }
Esempio n. 16
0
 public FileBackupConfigSource(string path, IConfigSource underlying, ISerde <DeploymentConfigInfo> serde, IEncryptionProvider encryptionProvider)
 {
     this.configFilePath     = Preconditions.CheckNonWhiteSpace(path, nameof(path));
     this.underlying         = Preconditions.CheckNotNull(underlying, nameof(underlying));
     this.serde              = Preconditions.CheckNotNull(serde, nameof(serde));
     this.encryptionProvider = Preconditions.CheckNotNull(encryptionProvider, nameof(IEncryptionProvider));
     Events.Created(this.configFilePath);
 }
Esempio n. 17
0
        static async Task <DeploymentConfigInfo> ReadFromDisk(string path, ISerde <DeploymentConfigInfo> serde)
        {
            string json = await DiskFile.ReadAllAsync(path);

            DeploymentConfigInfo deploymentConfig = serde.Deserialize(json);

            return(deploymentConfig);
        }
Esempio n. 18
0
 public EdgeAgentConnection(
     IModuleClientProvider moduleClientProvider,
     ISerde <DeploymentConfig> desiredPropertiesSerDe,
     IRequestManager requestManager,
     bool enableSubscriptions,
     TimeSpan configRefreshFrequency)
     : this(moduleClientProvider, desiredPropertiesSerDe, requestManager, enableSubscriptions, configRefreshFrequency, TransientRetryStrategy)
 {
 }
Esempio n. 19
0
 public EdgeAgentConnection(
     IModuleClientProvider moduleClientProvider,
     ISerde <DeploymentConfig> desiredPropertiesSerDe,
     IRequestManager requestManager,
     IStreamRequestListener streamRequestListener,
     TimeSpan configRefreshFrequency)
     : this(moduleClientProvider, desiredPropertiesSerDe, requestManager, streamRequestListener, TransientRetryStrategy, configRefreshFrequency)
 {
 }
Esempio n. 20
0
 public EdgeAgentConnection(
     IModuleClientProvider moduleClientProvider,
     ISerde <DeploymentConfig> desiredPropertiesSerDe,
     IRequestManager requestManager,
     IDeviceManager deviceManager,
     IDeploymentMetrics deploymentMetrics,
     Option <X509Certificate2> manifestTrustBundle)
     : this(moduleClientProvider, desiredPropertiesSerDe, requestManager, deviceManager, true, DefaultConfigRefreshFrequency, TransientRetryStrategy, deploymentMetrics, manifestTrustBundle)
 {
 }
Esempio n. 21
0
 public EdgeAgentConnection(
     IModuleClientProvider moduleClientProvider,
     ISerde <DeploymentConfig> desiredPropertiesSerDe,
     IRequestManager requestManager,
     IDeviceManager deviceManager,
     bool enableSubscriptions,
     TimeSpan configRefreshFrequency,
     IDeploymentMetrics deploymentMetrics,
     Option <X509Certificate2> manifestTrustBundle)
     : this(moduleClientProvider, desiredPropertiesSerDe, requestManager, deviceManager, enableSubscriptions, configRefreshFrequency, TransientRetryStrategy, deploymentMetrics, manifestTrustBundle, DefaultTwinPullOnConnectThrottleTime)
 {
 }
Esempio n. 22
0
        public IoTHubReporter(
            IEdgeAgentConnection edgeAgentConnection,
            ISerde <AgentState> agentStateSerde,
            VersionInfo versionInfo)
        {
            this.edgeAgentConnection = Preconditions.CheckNotNull(edgeAgentConnection, nameof(edgeAgentConnection));
            this.agentStateSerde     = Preconditions.CheckNotNull(agentStateSerde, nameof(agentStateSerde));
            this.versionInfo         = Preconditions.CheckNotNull(versionInfo, nameof(versionInfo));

            this.sync          = new AsyncLock();
            this.reportedState = Option.None <AgentState>();
        }
Esempio n. 23
0
 internal EdgeAgentConnection(IModuleClientProvider moduleClientProvider,
                              ISerde <DeploymentConfig> desiredPropertiesSerDe,
                              RetryStrategy retryStrategy,
                              TimeSpan refreshConfigFrequency)
 {
     this.desiredPropertiesSerDe = Preconditions.CheckNotNull(desiredPropertiesSerDe, nameof(desiredPropertiesSerDe));
     this.deploymentConfigInfo   = Option.None <DeploymentConfigInfo>();
     this.reportedProperties     = Option.None <TwinCollection>();
     this.deviceClient           = Option.None <IModuleClient>();
     this.retryStrategy          = Preconditions.CheckNotNull(retryStrategy, nameof(retryStrategy));
     this.refreshTimer           = new Timer(refreshConfigFrequency.TotalMilliseconds);
     this.refreshTimer.Elapsed  += (_, __) => this.RefreshTimerElapsed();
     this.initTask = this.CreateAndInitDeviceClient(Preconditions.CheckNotNull(moduleClientProvider, nameof(moduleClientProvider)));
 }
Esempio n. 24
0
        public static async Task <Agent> Create(
            IConfigSource configSource,
            IPlanner planner,
            IPlanRunner planRunner,
            IReporter reporter,
            IModuleIdentityLifecycleManager moduleIdentityLifecycleManager,
            IEnvironmentProvider environmentProvider,
            IEntityStore <string, string> configStore,
            ISerde <DeploymentConfigInfo> deploymentConfigInfoSerde,
            IEncryptionProvider encryptionProvider,
            IAvailabilityMetric availabilityMetric)
        {
            Preconditions.CheckNotNull(deploymentConfigInfoSerde, nameof(deploymentConfigInfoSerde));
            Preconditions.CheckNotNull(configStore, nameof(configStore));

            Option <DeploymentConfigInfo> deploymentConfigInfo = Option.None <DeploymentConfigInfo>();

            try
            {
                Option <string> deploymentConfigInfoJson = await Preconditions.CheckNotNull(configStore, nameof(configStore)).Get(StoreConfigKey);

                await deploymentConfigInfoJson.ForEachAsync(
                    async json =>
                {
                    string decryptedJson = await encryptionProvider.DecryptAsync(json);
                    deploymentConfigInfo = Option.Some(deploymentConfigInfoSerde.Deserialize(decryptedJson));
                });
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                Events.ErrorDeserializingConfig(ex);
            }

            var agent = new Agent(
                configSource,
                environmentProvider,
                planner,
                planRunner,
                reporter,
                moduleIdentityLifecycleManager,
                configStore,
                deploymentConfigInfo.GetOrElse(DeploymentConfigInfo.Empty),
                deploymentConfigInfoSerde,
                encryptionProvider,
                availabilityMetric);

            return(agent);
        }
Esempio n. 25
0
        public async void FileBackupReadFromBackupCallsEncryptDecrypt()
        {
            if (File.Exists(this.tempFileName))
            {
                File.Delete(this.tempFileName);
            }

            var underlying = new Mock <IConfigSource>();

            underlying.SetupSequence(t => t.GetDeploymentConfigInfoAsync())
            .ReturnsAsync(ValidConfigInfo1)
            .ThrowsAsync(new InvalidOperationException());
            ISerde <DeploymentConfigInfo> serde = this.GetSerde();
            var encryptionProvider = new Mock <IEncryptionProvider>();

            encryptionProvider.Setup(ep => ep.EncryptAsync(It.IsAny <string>()))
            .ReturnsAsync(serde.Serialize(ValidConfigInfo1));
            encryptionProvider.Setup(ep => ep.DecryptAsync(It.IsAny <string>()))
            .ReturnsAsync(serde.Serialize(ValidConfigInfo1));

            DeploymentConfigInfo config1;
            DeploymentConfigInfo config2;

            using (IConfigSource configSource = new FileBackupConfigSource(this.tempFileName, underlying.Object, serde, encryptionProvider.Object))
            {
                config1 = await configSource.GetDeploymentConfigInfoAsync();

                Assert.NotNull(config1);

                Assert.True(File.Exists(this.tempFileName));
                string backupJson = await DiskFile.ReadAllAsync(this.tempFileName);

                string returnedJson = serde.Serialize(config1);

                Assert.True(string.Equals(backupJson, returnedJson, StringComparison.OrdinalIgnoreCase));
            }

            using (IConfigSource configSource = new FileBackupConfigSource(this.tempFileName, underlying.Object, serde, encryptionProvider.Object))
            {
                config2 = await configSource.GetDeploymentConfigInfoAsync();

                Assert.NotNull(config2);
            }

            Assert.Equal(serde.Serialize(config1), serde.Serialize(config2));
            encryptionProvider.Verify(ep => ep.EncryptAsync(It.IsAny <string>()));
            encryptionProvider.Verify(ep => ep.DecryptAsync(It.IsAny <string>()));
        }
Esempio n. 26
0
        internal EdgeAgentConnection(
            IModuleClientProvider moduleClientProvider,
            ISerde <DeploymentConfig> desiredPropertiesSerDe,
            RetryStrategy retryStrategy,
            TimeSpan refreshConfigFrequency)
        {
            this.desiredPropertiesSerDe = Preconditions.CheckNotNull(desiredPropertiesSerDe, nameof(desiredPropertiesSerDe));
            this.deploymentConfigInfo   = Option.None <DeploymentConfigInfo>();
            this.reportedProperties     = Option.None <TwinCollection>();
            this.deviceClient           = Option.None <IModuleClient>();
            this.retryStrategy          = Preconditions.CheckNotNull(retryStrategy, nameof(retryStrategy));
            this.refreshTwinTask        = new PeriodicTask(this.ForceRefreshTwin, refreshConfigFrequency, refreshConfigFrequency, Events.Log, "refresh twin config");
            this.initTask = this.CreateAndInitDeviceClient(Preconditions.CheckNotNull(moduleClientProvider, nameof(moduleClientProvider)));

            Events.TwinRefreshInit(refreshConfigFrequency);
        }
Esempio n. 27
0
        FileConfigSource(FileSystemWatcher watcher, DeploymentConfigInfo initial, IConfiguration configuration, ISerde <DeploymentConfigInfo> serde)
        {
            this.watcher        = Preconditions.CheckNotNull(watcher, nameof(watcher));
            this.Configuration  = Preconditions.CheckNotNull(configuration, nameof(configuration));
            this.current        = new AtomicReference <DeploymentConfigInfo>(Preconditions.CheckNotNull(initial, nameof(initial)));
            this.serde          = Preconditions.CheckNotNull(serde, nameof(serde));
            this.configFilePath = Path.Combine(this.watcher.Path, this.watcher.Filter);

            this.sync = new AsyncLock();
            this.watcherSubscription = Observable
                                       .FromEventPattern <FileSystemEventArgs>(this.watcher, "Changed")
                                       // Rx.NET's "Throttle" is really "Debounce". An unfortunate naming mishap.
                                       .Throttle(TimeSpan.FromMilliseconds(FileChangeWatcherDebounceInterval))
                                       .Subscribe(this.WatcherOnChanged);
            this.watcher.EnableRaisingEvents = true;
            Events.Created(this.configFilePath);
        }
        public async void FileBackupShouldNotThrowWhenDecryptFails()
        {
            if (File.Exists(this.tempFileName))
            {
                File.Delete(this.tempFileName);
            }

            var underlying = new Mock <IConfigSource>();

            underlying.SetupSequence(t => t.GetDeploymentConfigInfoAsync())
            .ReturnsAsync(ValidConfigInfo1)
            .ThrowsAsync(new InvalidOperationException());
            ISerde <DeploymentConfigInfo> serde = this.GetSerde();
            var encryptionProvider = new Mock <IEncryptionProvider>();

            encryptionProvider.Setup(ep => ep.EncryptAsync(It.IsAny <string>()))
            .ReturnsAsync(serde.Serialize(ValidConfigInfo1));
            encryptionProvider.Setup(ep => ep.DecryptAsync(It.IsAny <string>()))
            .ThrowsAsync(new WorkloadCommunicationException("failed", 404));

            using (IConfigSource configSource = new FileBackupConfigSource(this.tempFileName, underlying.Object, serde, encryptionProvider.Object))
            {
                DeploymentConfigInfo config1 = await configSource.GetDeploymentConfigInfoAsync();

                Assert.NotNull(config1);

                Assert.True(File.Exists(this.tempFileName));
                string backupJson = await DiskFile.ReadAllAsync(this.tempFileName);

                string returnedJson = serde.Serialize(config1);

                Assert.Equal(backupJson, returnedJson, ignoreCase: true);
            }

            using (IConfigSource configSource = new FileBackupConfigSource(this.tempFileName, underlying.Object, serde, encryptionProvider.Object))
            {
                DeploymentConfigInfo config2 = await configSource.GetDeploymentConfigInfoAsync();

                Assert.NotNull(config2);

                Assert.Equal(DeploymentConfigInfo.Empty, config2);
                encryptionProvider.Verify(ep => ep.EncryptAsync(It.IsAny <string>()));
                encryptionProvider.Verify(ep => ep.DecryptAsync(It.IsAny <string>()));
            }
        }
Esempio n. 29
0
 internal EdgeAgentConnection(
     IModuleClientProvider moduleClientProvider,
     ISerde <DeploymentConfig> desiredPropertiesSerDe,
     IRequestManager requestManager,
     bool enableSubscriptions,
     TimeSpan refreshConfigFrequency,
     RetryStrategy retryStrategy)
 {
     this.desiredPropertiesSerDe = Preconditions.CheckNotNull(desiredPropertiesSerDe, nameof(desiredPropertiesSerDe));
     this.deploymentConfigInfo   = Option.None <DeploymentConfigInfo>();
     this.reportedProperties     = Option.None <TwinCollection>();
     this.moduleConnection       = new ModuleConnection(moduleClientProvider, requestManager, this.OnConnectionStatusChanged, this.OnDesiredPropertiesUpdated, enableSubscriptions);
     this.retryStrategy          = Preconditions.CheckNotNull(retryStrategy, nameof(retryStrategy));
     this.refreshTwinTask        = new PeriodicTask(this.ForceRefreshTwin, refreshConfigFrequency, refreshConfigFrequency, Events.Log, "refresh twin config");
     this.initTask        = this.ForceRefreshTwin();
     this.pullOnReconnect = enableSubscriptions;
     Events.TwinRefreshInit(refreshConfigFrequency);
 }
Esempio n. 30
0
        public async void FileBackupDoesNotHappenIfConfigSourceReportsException()
        {
            if (File.Exists(this.tempFileName))
            {
                File.Delete(this.tempFileName);
            }

            // Arrange
            var exceptionDeployment             = new DeploymentConfigInfo(10, new InvalidOperationException());
            ISerde <DeploymentConfigInfo> serde = this.GetSerde();

            // Act
            IDeploymentBackupSource fileBackup = new DeploymentFileBackup(this.tempFileName, serde, NullEncryptionProvider.Instance);

            await fileBackup.BackupDeploymentConfigAsync(exceptionDeployment);

            // Assert
            Assert.False(File.Exists(this.tempFileName));
        }