public async Task GetSystemInfoTest()
        {
            // Arrange
            var systemInfoResponse = new SystemInfoResponse
            {
                OSType       = OperatingSystemType,
                Architecture = Architecture
            };

            var dockerClient = Mock.Of <IDockerClient>(
                dc =>
                dc.System == Mock.Of <ISystemOperations>(so => so.GetSystemInfoAsync(default(CancellationToken)) == Task.FromResult(systemInfoResponse)));

            var inputRuntimeInfo = new DockerRuntimeInfo("docker", new DockerRuntimeConfig("1.13", string.Empty));

            // Act
            RuntimeInfoProvider runtimeInfoProvider = await RuntimeInfoProvider.CreateAsync(dockerClient);

            SystemInfo systemInfo = await runtimeInfoProvider.GetSystemInfo();

            // Assert
            Assert.NotNull(systemInfo);
            Assert.Equal(systemInfo.OperatingSystemType, systemInfoResponse.OSType);
            Assert.Equal(systemInfo.Architecture, systemInfoResponse.Architecture);
        }
Exemple #2
0
        internal override async Task <ExecutionResult> _RunAsync(CancellationToken cancellationToken)
        {
            try
            {
                var containers =
                    await _dockerClient.Containers.ListContainersAsync(new ContainersListParameters { All = true },
                                                                       cancellationToken);

                if (containers
                    .SingleOrDefault(e =>
                                     e.Image == (_moduleWithIdentity.Module as Devices.Edge.Agent.Docker.DockerModule)?.Config
                                     .Image) != null)
                {
                    Console.WriteLine($"Removing {_moduleWithIdentity.Module.Name}...");
                    await(await _dockerFactory.RemoveAsync(_moduleWithIdentity.Module))
                    .ExecuteAsync(cancellationToken);
                }
            }
            catch (Exception)
            {
                Console.WriteLine($"{_moduleWithIdentity.Module.Name} not found");
            }

            try
            {
                var runtimeConfig = new DockerRuntimeConfig("1.24.0", "{}");
                var runtimeInfo   = new DockerRuntimeInfo("docker", runtimeConfig);
                Console.WriteLine($"Creating {_moduleWithIdentity.Module.Name}...");
                //_dockerClient.Volumes.CreateAsync(new VolumesCreateParameters() { Name = "vol1", Driver = "local",  })
                await(await _dockerFactory.CreateAsync(_moduleWithIdentity, runtimeInfo)).ExecuteAsync(
                    cancellationToken);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            try
            {
                Console.WriteLine($"Starting {_moduleWithIdentity.Module.Name}...");

                await(await _dockerFactory.StartAsync(_moduleWithIdentity.Module)).ExecuteAsync(cancellationToken);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            return(await base._RunAsync(cancellationToken));
        }
Exemple #3
0
        public void TestAddNewRootKeyRegistryCredential()
        {
            var runtimeConfig = new DockerRuntimeConfig(
                "1.0",
                new Dictionary <string, RegistryCredentials>
            {
                ["r1"] = new RegistryCredentials("mcr.microsoft.com", "foo", "foo", "credential")
            });

            var runtimeInfo = new DockerRuntimeInfo("docker", runtimeConfig);

            var module = new Mock <IModule <DockerConfig> >();

            module.SetupGet(m => m.Config).Returns(new DockerConfig("mcr.microsoft.com/windows/nanoserver:1809"));
            module.SetupGet(m => m.Name).Returns(Constants.EdgeAgentModuleName);

            var unixUris = new Dictionary <string, string>
            {
                { Constants.EdgeletWorkloadUriVariableName, "unix:///path/to/workload.sock" },
                { Constants.EdgeletManagementUriVariableName, "unix:///path/to/mgmt.sock" }
            };

            var windowsUris = new Dictionary <string, string>
            {
                { Constants.EdgeletWorkloadUriVariableName, "unix:///C:/path/to/workload/sock" },
                { Constants.EdgeletManagementUriVariableName, "unix:///C:/path/to/mgmt/sock" }
            };

            IConfigurationRoot configRoot = new ConfigurationBuilder().AddInMemoryCollection(
                RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? windowsUris : unixUris).Build();
            var configSource = Mock.Of <IConfigSource>(s => s.Configuration == configRoot);
            var authConfig   = new AuthConfig {
                ServerAddress = "mcr.microsoft.com"
            };
            ICombinedConfigProvider <CombinedDockerConfig> provider = new CombinedEdgeletConfigProvider(new[] { authConfig }, configSource);

            var             systemInfoSample = new SystemInfo("linux", "x86", "1");
            var             moduleManager    = Mock.Of <IModuleManager>(m => m.GetSystemInfoAsync(CancellationToken.None) == Task.FromResult(systemInfoSample));
            ICommandFactory factory          = new EdgeletCommandFactory <CombinedDockerConfig>(moduleManager, configSource, provider);
            // Act
            CombinedDockerConfig config = provider.GetCombinedConfig(module.Object, runtimeInfo);

            // Assert
            Assert.Equal("credential", config.AuthConfig.OrDefault().RegistryToken);
        }
Exemple #4
0
        public void EqualityTest()
        {
            var dri1 = new DockerRuntimeInfo(
                "docker",
                new DockerRuntimeConfig(
                    "1.0",
                    new Dictionary <string, RegistryCredentials>
            {
                ["r1"] = new RegistryCredentials("foo.azurecr.io", "foo", "foo")
            }));

            var dri2 = new DockerRuntimeInfo(
                "docker",
                new DockerRuntimeConfig(
                    "1.0",
                    new Dictionary <string, RegistryCredentials>
            {
                ["r1"] = new RegistryCredentials("foo.azurecr.io", "foo", "foo")
            }));

            Assert.Equal(dri1, dri2);
        }
Exemple #5
0
        public async Task AgentStartsUpModules(TestConfig testConfig)
        {
            // Build the docker host URL.
            string       dockerHostUrl = ConfigHelper.TestConfig["dockerHostUrl"];
            DockerClient client        = new DockerClientConfiguration(new Uri(dockerHostUrl)).CreateClient();

            try
            {
                // Remove any running containers with the same name that may be a left-over
                // from previous test runs.
                await RemoveContainer(client, testConfig);

                // Initialize docker configuration for this module.
                DockerConfig dockerConfig = testConfig.ImageCreateOptions != null
                    ? new DockerConfig(testConfig.Image, testConfig.ImageCreateOptions)
                    : new DockerConfig(testConfig.Image);

                // Initialize an Edge Agent module object.
                var dockerModule = new DockerModule(
                    testConfig.Name,
                    testConfig.Version,
                    ModuleStatus.Running,
                    global::Microsoft.Azure.Devices.Edge.Agent.Core.RestartPolicy.OnUnhealthy,
                    dockerConfig,
                    null,
                    null);
                var modules = new Dictionary <string, IModule> {
                    [testConfig.Name] = dockerModule
                };
                var systemModules = new SystemModules(null, null);

                // Start up the agent and run a "reconcile".
                var dockerLoggingOptions = new Dictionary <string, string>
                {
                    { "max-size", "1m" },
                    { "max-file", "1" }
                };
                var loggingConfig = new DockerLoggingConfig("json-file", dockerLoggingOptions);

                string             sharedAccessKey = Convert.ToBase64String(Encoding.UTF8.GetBytes("test"));
                IConfigurationRoot configRoot      = new ConfigurationBuilder().AddInMemoryCollection(
                    new Dictionary <string, string>
                {
                    { "DeviceConnectionString", $"Hostname=fakeiothub;Deviceid=test;SharedAccessKey={sharedAccessKey}" }
                }).Build();

                var runtimeConfig        = new DockerRuntimeConfig("1.24.0", "{}");
                var runtimeInfo          = new DockerRuntimeInfo("docker", runtimeConfig);
                var deploymentConfigInfo = new DeploymentConfigInfo(1, new DeploymentConfig("1.0", runtimeInfo, systemModules, modules));

                var configSource = new Mock <IConfigSource>();
                configSource.Setup(cs => cs.Configuration).Returns(configRoot);
                configSource.Setup(cs => cs.GetDeploymentConfigInfoAsync()).ReturnsAsync(deploymentConfigInfo);

                // TODO: Fix this up with a real reporter. But before we can do that we need to use
                // the real configuration source that talks to IoT Hub above.
                NullReporter reporter = NullReporter.Instance;

                var restartStateStore                = Mock.Of <IEntityStore <string, ModuleState> >();
                var configStore                      = Mock.Of <IEntityStore <string, string> >();
                var deploymentConfigInfoSerde        = Mock.Of <ISerde <DeploymentConfigInfo> >();
                IRestartPolicyManager restartManager = new Mock <IRestartPolicyManager>().Object;

                var dockerCommandFactory = new DockerCommandFactory(client, loggingConfig, configSource.Object, new CombinedDockerConfigProvider(Enumerable.Empty <AuthConfig>()));
                IRuntimeInfoProvider runtimeInfoProvider = await RuntimeInfoProvider.CreateAsync(client);

                IEnvironmentProvider environmentProvider = await DockerEnvironmentProvider.CreateAsync(runtimeInfoProvider, restartStateStore, restartManager);

                var logFactoryMock = new Mock <ILoggerFactory>();
                var logMock        = new Mock <ILogger <LoggingCommandFactory> >();
                logFactoryMock.Setup(l => l.CreateLogger(It.IsAny <string>()))
                .Returns(logMock.Object);
                var commandFactory = new LoggingCommandFactory(dockerCommandFactory, logFactoryMock.Object);

                var credential = new ConnectionStringCredentials("fake");
                var identity   = new Mock <IModuleIdentity>();
                identity.Setup(id => id.Credentials).Returns(credential);
                identity.Setup(id => id.ModuleId).Returns(testConfig.Name);
                IImmutableDictionary <string, IModuleIdentity> identities = new Dictionary <string, IModuleIdentity>()
                {
                    [testConfig.Name] = identity.Object
                }.ToImmutableDictionary();
                var moduleIdentityLifecycleManager = new Mock <IModuleIdentityLifecycleManager>();
                moduleIdentityLifecycleManager.Setup(m => m.GetModuleIdentitiesAsync(It.IsAny <ModuleSet>(), It.IsAny <ModuleSet>())).Returns(Task.FromResult(identities));

                Agent agent = await Agent.Create(
                    configSource.Object,
                    new RestartPlanner(commandFactory),
                    new OrderedPlanRunner(),
                    reporter,
                    moduleIdentityLifecycleManager.Object,
                    environmentProvider,
                    configStore,
                    deploymentConfigInfoSerde,
                    NullEncryptionProvider.Instance);

                await agent.ReconcileAsync(CancellationToken.None);

                // Sometimes the container is still not ready by the time we run the validator.
                // So we attempt validation multiple times and bail only if all of them fail.
                bool      validated   = false;
                int       attempts    = 0;
                const int MaxAttempts = 5;
                while (!validated && attempts < MaxAttempts)
                {
                    validated = testConfig.Validator.Validate();
                    if (!validated)
                    {
                        Thread.Sleep(TimeSpan.FromSeconds(5));
                    }

                    ++attempts;
                }

                Assert.Equal(true, validated);
            }
            finally
            {
                await RemoveContainer(client, testConfig);
            }
        }