Exemplo n.º 1
0
        public void AddsVolumesFromCreateOptionsToContainerSpecEvenIfTheyOverrideExistingOnes()
        {
            var identity = new ModuleIdentity("hostname", "gatewayhost", "deviceid", "Module1", Mock.Of <ICredentials>());
            var docker   = new DockerModule("module1", "v1", ModuleStatus.Running, RestartPolicy.Always, Config1, ImagePullPolicy.OnCreate, Constants.DefaultPriority, DefaultConfigurationInfo, EnvVarsDict);
            var volumes  = new[]
            {
                new KubernetesModuleVolumeSpec(
                    new V1Volume("homeblah", configMap: new V1ConfigMapVolumeSource(name: "additional-config-map")),
                    new[] { new V1VolumeMount(name: "homeblah", mountPath: "/home/blah") })
            };
            var hostConfig = new HostConfig {
                Binds = new List <string> {
                    "/home/blah:/home/blah2:ro"
                }
            };
            var config = new KubernetesConfig("image", CreatePodParameters.Create(volumes: volumes, hostConfig: hostConfig), Option.None <AuthConfig>());
            var module = new KubernetesModule(docker, config, EdgeletModuleOwner);
            var labels = new Dictionary <string, string>();
            var mapper = CreateMapper();

            var deployment = mapper.CreateDeployment(identity, module, labels);

            // Validate module volume mounts
            var moduleContainer = deployment.Spec.Template.Spec.Containers.Single(container => container.Name == "module1");

            Assert.Equal(2, moduleContainer.VolumeMounts.Count(vm => vm.Name.Equals("homeblah")));

            // Validate proxy volume mounts
            var proxyContainer = deployment.Spec.Template.Spec.Containers.Single(p => p.Name == "proxy");

            Assert.Equal(2, proxyContainer.VolumeMounts.Count);
            Assert.Contains(proxyContainer.VolumeMounts, vm => vm.Name.Equals("configVolumeName"));
            Assert.Contains(proxyContainer.VolumeMounts, vm => vm.Name.Equals("trustBundleVolumeName"));

            // Validate pod volumes
            Assert.Equal(4, deployment.Spec.Template.Spec.Volumes.Count);
            Assert.Equal(2, deployment.Spec.Template.Spec.Volumes.Count(v => v.Name.Equals("homeblah")));
            Assert.Contains(deployment.Spec.Template.Spec.Volumes, v => v.Name.Equals("configVolumeName"));
            Assert.Contains(deployment.Spec.Template.Spec.Volumes, v => v.Name.Equals("trustBundleVolumeName"));
        }
        public async Task DoesNotSendToModule()
        {
            var connector          = GetConnector();
            var connectionRegistry = GetConnectionRegistry();
            var identity           = new ModuleIdentity("hub", "device_id", "module_id");
            var message            = new EdgeMessage
                                     .Builder(new byte[] { 0x01, 0x02, 0x03 })
                                     .SetSystemProperties(new Dictionary <string, string>()
            {
                [SystemProperties.LockToken] = "12345"
            })
                                     .Build();

            var sut = new Cloud2DeviceMessageHandler(connectionRegistry);

            sut.SetConnector(connector);

            await sut.SendC2DMessageAsync(message, identity, true);

            Mock.Get(connector)
            .Verify(c => c.SendAsync(It.IsAny <string>(), It.IsAny <byte[]>(), It.IsAny <bool>()), Times.Never());
        }
        public async Task SendsMessageDataAsPayload()
        {
            var capture            = new SendCapture();
            var connector          = GetConnector(capture);
            var connectionRegistry = GetConnectionRegistry();
            var identityProvider   = new IdentityProvider("hub");
            var identity           = new ModuleIdentity("hub", "device_id", "module_id");
            var message            = new EdgeMessage
                                     .Builder(new byte[] { 0x01, 0x02, 0x03 })
                                     .SetSystemProperties(new Dictionary <string, string>()
            {
                [SystemProperties.LockToken] = "12345"
            })
                                     .Build();

            using var sut = new ModuleToModuleMessageHandler(connectionRegistry, identityProvider, GetAckTimeout());
            sut.SetConnector(connector);

            await sut.SendModuleToModuleMessageAsync(message, "some_input", identity, true);

            Assert.Equal(new byte[] { 0x01, 0x02, 0x03 }, capture.Content);
        }
Exemplo n.º 4
0
        public async void TestAuthSucceeds()
        {
            var          authenticator            = Mock.Of <IAuthenticator>();
            var          clientCredentialsFactory = Mock.Of <IClientCredentialsFactory>();
            var          saslAuthenticator        = new EdgeHubSaslPlainAuthenticator(authenticator, clientCredentialsFactory, "hub1");
            var          identity          = new ModuleIdentity("hub1", "dev1", "mod1");
            var          clientCredentials = Mock.Of <IClientCredentials>(c => c.Identity == identity);
            const string UserId            = "dev1/modules/[email protected]";
            const string Password          = "******";

            Mock.Get(clientCredentialsFactory).Setup(f => f.GetWithSasToken("dev1", "mod1", string.Empty, Password))
            .Returns(clientCredentials);
            Mock.Get(authenticator).Setup(a => a.AuthenticateAsync(clientCredentials))
            .ReturnsAsync(true);

            var principal = await saslAuthenticator.AuthenticateAsync(UserId, Password) as SaslPrincipal;

            Assert.NotNull(principal);
            Assert.NotNull(principal.Identity);
            Assert.NotNull(principal.AmqpAuthentication);
            Assert.Equal(identity, principal.AmqpAuthentication.ClientCredentials.OrDefault().Identity);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Get a module identity.
        /// </summary>
        /// <param name="deviceId">Unique identifier of the device the module belongs to.</param>
        /// <param name="moduleId">Unique identifier of the module to get.</param>
        public async Task <ModuleIdentity> GetModuleIdentityAsync(string deviceId, string moduleId)
        {
            SampleLogger.PrintHeader("GET A MODULE");

            try
            {
                Console.WriteLine($"Getting module identity with Id: '{moduleId}'\n");

                Response <ModuleIdentity> response = await IoTHubServiceClient.Modules.GetIdentityAsync(deviceId, moduleId);

                ModuleIdentity moduleIdentity = response.Value;

                SampleLogger.PrintSuccess($"\t- Device Id: '{moduleIdentity.DeviceId}', Module Id: '{moduleIdentity.ModuleId}', ETag: '{moduleIdentity.Etag}'");

                return(moduleIdentity);
            }
            catch (Exception ex)
            {
                SampleLogger.FatalError($"Failed to get a module identity due to:\n{ex}");
                throw;
            }
        }
Exemplo n.º 6
0
        public void EmptyDirMappingForVolume()
        {
            var identity   = new ModuleIdentity("hostname", "gatewayhost", "deviceid", "ModuleId", Mock.Of <ICredentials>());
            var labels     = new Dictionary <string, string>();
            var hostConfig = VolumeMountHostConfig;
            var config     = new KubernetesConfig("image", CreatePodParameters.Create(labels: labels, hostConfig: hostConfig), Option.None <AuthConfig>());
            var docker     = new DockerModule("module1", "v1", ModuleStatus.Running, RestartPolicy.Always, Config1, ImagePullPolicy.OnCreate, DefaultConfigurationInfo, EnvVarsDict);
            var module     = new KubernetesModule(docker, config);
            var mapper     = new KubernetesDeploymentMapper("namespace", "edgehub", "proxy", "configPath", "configVolumeName", "configMapName", "trustBundlePAth", "trustBundleVolumeName", "trustBundleConfigMapName", string.Empty, null, "apiVersion", new Uri("http://workload"), new Uri("http://management"));

            var deployment = mapper.CreateDeployment(identity, module, labels);
            var pod        = deployment.Spec.Template;

            Assert.True(pod != null);
            var podVolume = pod.Spec.Volumes.Single(v => v.Name == "a-volume");

            Assert.NotNull(podVolume.EmptyDir);
            var podVolumeMount = pod.Spec.Containers.Single(p => p.Name != "proxy").VolumeMounts.Single(vm => vm.Name == "a-volume");

            Assert.Equal("/tmp/volume", podVolumeMount.MountPath);
            Assert.True(podVolumeMount.ReadOnlyProperty);
        }
Exemplo n.º 7
0
        public void SimpleServiceCreationHappyPath()
        {
            var exposedPorts = new Dictionary <string, EmptyStruct> {
                ["10/TCP"] = default(EmptyStruct)
            };
            var createOptions = CreatePodParameters.Create(exposedPorts: exposedPorts);
            var config        = new KubernetesConfig("image", createOptions, Option.None <AuthConfig>());
            var docker        = new DockerModule("module1", "v1", ModuleStatus.Running, RestartPolicy.Always, Config1, ImagePullPolicy.OnCreate, Constants.DefaultPriority, DefaultConfigurationInfo, EnvVars);
            var module        = new KubernetesModule(docker, config, EdgeletModuleOwner);
            var moduleLabels  = new Dictionary <string, string>();
            var mapper        = new KubernetesServiceMapper(PortMapServiceType.ClusterIP);
            var moduleId      = new ModuleIdentity("hostname", "gatewayhost", "deviceid", "moduleid", Mock.Of <ICredentials>());

            var service = mapper.CreateService(moduleId, module, moduleLabels).OrDefault();

            Assert.NotNull(service);
            Assert.Equal(1, service.Metadata.OwnerReferences.Count);
            Assert.Equal(V1Deployment.KubeKind, service.Metadata.OwnerReferences[0].Kind);
            Assert.Equal(EdgeletModuleOwner.Name, service.Metadata.OwnerReferences[0].Name);
            Assert.Equal(1, service.Spec.Ports.Count);
            Assert.Equal(0, service.Spec.Selector.Count);
        }
        public void ExposingPortsCreatesAServiceWithPorts()
        {
            var createOptions = new Docker.Models.CreateContainerParameters
            {
                // Add a port to be exposed
                ExposedPorts = new Dictionary <string, EmptyStruct>
                {
                    ["10/TCP"] = default(EmptyStruct)
                }
            };
            var config       = new CombinedDockerConfig("image", createOptions, Option.None <AuthConfig>());
            var docker       = new DockerModule("module1", "v1", ModuleStatus.Running, Core.RestartPolicy.Always, Config1, ImagePullPolicy.OnCreate, DefaultConfigurationInfo, EnvVars);
            var module       = new KubernetesModule(docker, config);
            var moduleLabels = new Dictionary <string, string>();
            var mapper       = new KubernetesServiceMapper(PortMapServiceType.ClusterIP);
            var moduleId     = new ModuleIdentity("hostname", "gatewayhost", "deviceid", "moduleid", Mock.Of <ICredentials>());

            var service = mapper.CreateService(moduleId, module, moduleLabels).OrDefault();

            Assert.Equal(1, service.Spec.Ports.Count);
            AssertPort(new V1ServicePort(10, "exposedport-10-tcp", null, "TCP"), service.Spec.Ports.First());
            Assert.Equal("ClusterIP", service.Spec.Type);
        }
Exemplo n.º 9
0
        public void PvcMappingByDefault()
        {
            var identity   = new ModuleIdentity("hostname", "gatewayhost", "deviceid", "ModuleId", Mock.Of <ICredentials>());
            var labels     = new Dictionary <string, string>();
            var hostConfig = VolumeMountHostConfig;
            var config     = new KubernetesConfig("image", CreatePodParameters.Create(labels: labels, hostConfig: hostConfig), Option.None <AuthConfig>());
            var docker     = new DockerModule("module1", "v1", ModuleStatus.Running, RestartPolicy.Always, Config1, ImagePullPolicy.OnCreate, Constants.DefaultPriority, DefaultConfigurationInfo, EnvVarsDict);
            var module     = new KubernetesModule(docker, config, EdgeletModuleOwner);
            var mapper     = CreateMapper(storageClassName: null);
            var deployment = mapper.CreateDeployment(identity, module, labels);
            var pod        = deployment.Spec.Template;

            Assert.True(pod != null);
            var podVolume = pod.Spec.Volumes.Single(v => v.Name == "a-volume");

            Assert.NotNull(podVolume.PersistentVolumeClaim);
            Assert.Equal("a-volume", podVolume.PersistentVolumeClaim.ClaimName);
            Assert.True(podVolume.PersistentVolumeClaim.ReadOnlyProperty);
            var podVolumeMount = pod.Spec.Containers.Single(p => p.Name != "proxy").VolumeMounts.Single(vm => vm.Name == "a-volume");

            Assert.Equal("/tmp/volume", podVolumeMount.MountPath);
            Assert.True(podVolumeMount.ReadOnlyProperty);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Deletes a module identity.
        /// </summary>
        /// <param name="deviceId">Unique identifier of the device the module belongs to.</param>
        /// <param name="moduleId">Unique identifier of the module to be updated.</param>
        public async Task DeleteModuleIdentityAsync(string deviceId, string moduleId)
        {
            SampleLogger.PrintHeader("DELETE MODULE IDENTITY");

            try
            {
                // Get the module identity first.
                Response <ModuleIdentity> getResponse = await IoTHubServiceClient.Modules.GetIdentityAsync(deviceId, moduleId);

                ModuleIdentity moduleIdentity = getResponse.Value;

                Console.WriteLine($"Deleting module identity: DeviceId: '{moduleIdentity.DeviceId}', ModuleId: '{moduleIdentity.ModuleId}', ETag: '{moduleIdentity.Etag}'");

                // We use UnconditionalIfMatch to force delete the Module Identity (disregard the IfMatch ETag).
                Response response = await IoTHubServiceClient.Modules.DeleteIdentityAsync(moduleIdentity);

                SampleLogger.PrintSuccess($"Successfully deleted module identity: DeviceId: '{deviceId}', ModuleId: '{moduleId}'");
            }
            catch (Exception ex)
            {
                SampleLogger.FatalError($"Failed to delete module identity due to:\n{ex}");
            }
        }
        public async Task EncodesModuleNameInTopic()
        {
            var capture            = new SendCapture();
            var connector          = GetConnector(capture);
            var connectionRegistry = GetConnectionRegistry();
            var identityProvider   = new IdentityProvider("hub");
            var identity           = new ModuleIdentity("hub", "device_id", "module_id");
            var message            = new EdgeMessage
                                     .Builder(new byte[] { 0x01, 0x02, 0x03 })
                                     .SetSystemProperties(new Dictionary <string, string>()
            {
                [SystemProperties.LockToken] = "12345"
            })
                                     .Build();

            var sut = new ModuleToModuleMessageHandler(connectionRegistry, identityProvider);

            sut.SetConnector(connector);

            await sut.SendModuleToModuleMessageAsync(message, "some_input", identity, true);

            Assert.Equal("$edgehub/device_id/module_id/inputs/some_input/", capture.Topic);
        }
Exemplo n.º 12
0
        public void TestHandleEdgeHubServiceIdentityUpdateSuccess()
        {
            // Arrange
            var      connectionManager          = new Mock <IConnectionManager>(MockBehavior.Strict);
            var      authenticator              = new Mock <IAuthenticator>(MockBehavior.Strict);
            var      credentialsStore           = new Mock <ICredentialsCache>(MockBehavior.Strict);
            var      deviceScopeIdentitiesCache = new Mock <IDeviceScopeIdentitiesCache>(MockBehavior.Strict);
            TimeSpan reauthFrequency            = TimeSpan.FromSeconds(3);

            var edgeHubIdentity    = new ModuleIdentity(IoTHubHostName, "d1", "$edgeHub");
            var edgeHubCredentials = Mock.Of <IClientCredentials>(c => c.Identity == edgeHubIdentity && c.AuthenticationType == AuthenticationType.SasKey);

            credentialsStore.Setup(c => c.Get(edgeHubIdentity)).ReturnsAsync(Option.Some(edgeHubCredentials));

            var edgeHubProxy = Mock.Of <IDeviceProxy>(d => d.IsActive && d.Identity == edgeHubIdentity);

            connectionManager.Setup(c => c.GetDeviceConnection("d1/$edgeHub")).Returns(Option.Some(edgeHubProxy));
            connectionManager.Setup(c => c.RemoveDeviceConnection("d1/$edgeHub")).Returns(Task.CompletedTask);
            authenticator.Setup(a => a.ReauthenticateAsync(edgeHubCredentials)).ReturnsAsync(true);

            var serviceAuthentication  = new ServiceAuthentication(ServiceAuthenticationType.None);
            var edgeHubServiceIdentity = new ServiceIdentity("d1/$edgeHub", "1234", Enumerable.Empty <string>(), serviceAuthentication, ServiceIdentityStatus.Enabled);

            // Act
            var connectionReauthenticator = new ConnectionReauthenticator(connectionManager.Object, authenticator.Object, credentialsStore.Object, deviceScopeIdentitiesCache.Object, reauthFrequency, Mock.Of <IIdentity>(i => i.Id == "d1/$edgeHub"));

            deviceScopeIdentitiesCache.Raise(d => d.ServiceIdentityUpdated += null, null, edgeHubServiceIdentity);

            // Assert
            Assert.NotNull(connectionReauthenticator);
            connectionManager.Verify(c => c.RemoveDeviceConnection("d1"), Times.Never);
            connectionManager.Verify(c => c.RemoveDeviceConnection("d1/$edgeHub"), Times.Never);
            connectionManager.Verify(c => c.GetDeviceConnection("d1/$edgeHub"), Times.Never);
            authenticator.Verify(a => a.ReauthenticateAsync(edgeHubCredentials), Times.Never);
            credentialsStore.Verify(c => c.Get(edgeHubIdentity), Times.Never);
            deviceScopeIdentitiesCache.VerifyAll();
        }
Exemplo n.º 13
0
        public void AppliesVolumesFromCreateOptionsToContainerSpec()
        {
            var identity = new ModuleIdentity("hostname", "deviceid", "Module1", Mock.Of <ICredentials>());
            var docker   = new DockerModule("module1", "v1", ModuleStatus.Running, Core.RestartPolicy.Always, Config1, ImagePullPolicy.OnCreate, Constants.DefaultStartupOrder, DefaultConfigurationInfo, EnvVarsDict);
            var volumes  = new[]
            {
                new KubernetesModuleVolumeSpec(
                    new V1Volume("additional-volume", configMap: new V1ConfigMapVolumeSource(name: "additional-config-map")),
                    new[] { new V1VolumeMount(name: "additional-volume", mountPath: "/etc") })
            };
            var config = new KubernetesConfig("image", CreatePodParameters.Create(volumes: volumes), Option.None <AuthConfig>());
            var module = new KubernetesModule(docker, config, EdgeletModuleOwner);
            var labels = new Dictionary <string, string>();
            var mapper = CreateMapper();

            var deployment = mapper.CreateDeployment(identity, module, labels);

            // Validate module volume mounts
            var moduleContainer = deployment.Spec.Template.Spec.Containers.Single(container => container.Name == "module1");

            Assert.Equal(1, moduleContainer.VolumeMounts.Count);
            Assert.Contains(moduleContainer.VolumeMounts, vm => vm.Name.Equals("additional-volume"));

            // Validate proxy volume mounts
            var proxyContainer = deployment.Spec.Template.Spec.Containers.Single(p => p.Name == "proxy");

            Assert.Equal(2, proxyContainer.VolumeMounts.Count);
            Assert.Contains(proxyContainer.VolumeMounts, vm => vm.Name.Equals("configVolumeName"));
            Assert.Contains(proxyContainer.VolumeMounts, vm => vm.Name.Equals("trustBundleVolumeName"));

            // Validate pod volumes
            Assert.Equal(3, deployment.Spec.Template.Spec.Volumes.Count);
            Assert.Contains(deployment.Spec.Template.Spec.Volumes, v => v.Name.Equals("additional-volume"));
            Assert.Contains(deployment.Spec.Template.Spec.Volumes, v => v.Name.Equals("configVolumeName"));
            Assert.Contains(deployment.Spec.Template.Spec.Volumes, v => v.Name.Equals("trustBundleVolumeName"));
        }
Exemplo n.º 14
0
    /*^
    #pragma warning disable 2666, 2669, 2677, 2674
    ^*/
    internal PEFileToObjectModel(
      PeReader peReader,
      PEFileReader peFileReader,
      ModuleIdentity moduleIdentity,
      Assembly/*?*/ containingAssembly,
      byte pointerSize
    )
      //^ requires peFileReader.IsAssembly ==> moduleIdentity.ContainingAssembly != null;
      //^ requires peFileReader.IsAssembly ==> containingAssembly == null;
      //^ requires !(moduleIdentity.Location != null && moduleIdentity.Location.Length != 0);
    {
      this.pointerSize = pointerSize;
      this.document = new MetadataObjectDocument(this);
      this.ModuleReader = peReader;
      this.PEFileReader = peFileReader;
      this.NameTable = peReader.metadataReaderHost.NameTable;
      this.InternFactory = peReader.metadataReaderHost.InternFactory;
      this.StringIndexToNameTable = new Hashtable<IName>();
      this.StringIndexToUnmangledNameTable = new Hashtable<IName>();
      this.typeCache = new TypeCache(this);
      uint moduleNameOffset = peFileReader.ModuleTable.GetName(1);
      IName moduleName = this.GetNameFromOffset(moduleNameOffset);
      AssemblyIdentity/*?*/ assemblyIdentity = moduleIdentity as AssemblyIdentity;
      if (peFileReader.IsAssembly) {
        //^ assert assemblyIdentity != null;
        AssemblyRow assemblyRow = peFileReader.AssemblyTable[1];
        IName assemblyName = this.GetNameFromOffset(assemblyRow.Name);
        byte[] publicKeyArray = TypeCache.EmptyByteArray;
        if (assemblyRow.PublicKey != 0) {
          publicKeyArray = peFileReader.BlobStream[assemblyRow.PublicKey];
        }
        uint internedModuleId = (uint)peReader.metadataReaderHost.InternFactory.GetAssemblyInternedKey(assemblyIdentity);
        Assembly assem = new Assembly(this, moduleName, peFileReader.COR20Header.COR20Flags, internedModuleId, assemblyIdentity, assemblyName, assemblyRow.Flags, publicKeyArray);
        this.ContainingAssembly = assem;
        this.Module = assem;
      } else {
        uint internedModuleId = (uint)peReader.metadataReaderHost.InternFactory.GetModuleInternedKey(moduleIdentity);
        this.ContainingAssembly = containingAssembly;
        this.Module = new Module(this, moduleName, peFileReader.COR20Header.COR20Flags, internedModuleId, moduleIdentity);
      }

      this.LoadAssemblyReferences();
      this.LoadModuleReferences();
      this.RootModuleNamespace = new RootNamespace(this);
      this.NamespaceINameHashtable = new Hashtable<Namespace>();
      this.LoadNamespaces();
      this.NamespaceReferenceINameHashtable = new DoubleHashtable<NamespaceReference>();
      this.NamespaceTypeTokenTable = new DoubleHashtable(peFileReader.TypeDefTable.NumberOfRows + peFileReader.ExportedTypeTable.NumberOfRows);
      this.NestedTypeTokenTable = new DoubleHashtable(peFileReader.NestedClassTable.NumberOfRows + peFileReader.ExportedTypeTable.NumberOfRows);
      this.PreLoadTypeDefTableLookup();
      this.ModuleTypeDefArray = new TypeBase/*?*/[peFileReader.TypeDefTable.NumberOfRows + 1];
      this.ModuleTypeDefLoadState = new LoadState[peFileReader.TypeDefTable.NumberOfRows + 1];
      this.RedirectedTypeDefArray = new INamedTypeReference/*?*/[peFileReader.TypeDefTable.NumberOfRows + 1];
      this.ModuleTypeDefLoadState[0] = LoadState.Loaded;

      this.ExportedTypeArray = new ExportedTypeAliasBase/*?*/[peFileReader.ExportedTypeTable.NumberOfRows + 1];
      this.ExportedTypeLoadState = new LoadState[peFileReader.ExportedTypeTable.NumberOfRows + 1];
      this.ExportedTypeLoadState[0] = LoadState.Loaded;

      this.ModuleGenericParamArray = new GenericParameter[peFileReader.GenericParamTable.NumberOfRows + 1];
      if (peFileReader.MethodSpecTable.NumberOfRows > 0) {
        this.ModuleMethodSpecHashtable = new DoubleHashtable<IGenericMethodInstanceReference>(peFileReader.MethodSpecTable.NumberOfRows + 1);
      }

      this.ModuleTypeRefReferenceArray = new INamedTypeReference[peFileReader.TypeRefTable.NumberOfRows + 1];
      this.ModuleTypeRefReferenceLoadState = new LoadState[peFileReader.TypeRefTable.NumberOfRows + 1];
      this.ModuleTypeRefReferenceLoadState[0] = LoadState.Loaded;
      if (peFileReader.TypeSpecTable.NumberOfRows > 0) {
        this.ModuleTypeSpecHashtable = new DoubleHashtable<TypeSpecReference>(peFileReader.TypeSpecTable.NumberOfRows + 1);
      }

      this.ModuleFieldArray = new FieldDefinition[peFileReader.FieldTable.NumberOfRows + 1];
      this.ModuleMethodArray = new IMethodDefinition[peFileReader.MethodTable.NumberOfRows + 1];
      this.ModuleEventArray = new EventDefinition[peFileReader.EventTable.NumberOfRows + 1];
      this.ModulePropertyArray = new PropertyDefinition[peFileReader.PropertyTable.NumberOfRows + 1];

      this.ModuleMemberReferenceArray = new MemberReference/*?*/[peFileReader.MemberRefTable.NumberOfRows + 1];
      this.UnspecializedMemberReferenceArray = new MemberReference/*?*/[peFileReader.MemberRefTable.NumberOfRows + 1];
      this.SpecializedFieldHashtable = new DoubleHashtable<ISpecializedFieldReference>();
      this.SpecializedMethodHashtable = new DoubleHashtable<ISpecializedMethodReference>();

      this.CustomAttributeArray = new ICustomAttribute/*?*/[peFileReader.CustomAttributeTable.NumberOfRows + 1];

      this.DeclSecurityArray = new ISecurityAttribute/*?*/[peFileReader.DeclSecurityTable.NumberOfRows + 1];

      this._Module_ = this.Create_Module_Type();
    }
Exemplo n.º 15
0
 /// <summary>
 /// Populates the list of module references.
 /// </summary>
 void LoadModuleReferences()
   //^ ensures this.ModuleReferenceArray != null;
 {
   uint numberOfModuleReferences = this.PEFileReader.ModuleRefTable.NumberOfRows;
   ModuleReference[] moduleRefList = new ModuleReference[numberOfModuleReferences + 1];
   for (uint i = 1; i <= numberOfModuleReferences; ++i) {
     ModuleRefRow moduleRefRow = this.PEFileReader.ModuleRefTable[i];
     IName moduleRefName = this.GetNameFromOffset(moduleRefRow.Name);
     ModuleIdentity moduleIdentity;
     if (this.ContainingAssembly == null) {
       moduleIdentity = new ModuleIdentity(moduleRefName, string.Empty);
     } else {
       moduleIdentity = new ModuleIdentity(moduleRefName, string.Empty, this.ContainingAssembly.AssemblyIdentity);
     }
     ModuleIdentity probedModuleIdentity = this.ModuleReader.metadataReaderHost.ProbeModuleReference(this.Module, moduleIdentity);
     uint internedModuleId = (uint)this.ModuleReader.metadataReaderHost.InternFactory.GetModuleInternedKey(probedModuleIdentity);
     ModuleReference moduleReference = new ModuleReference(this, i, internedModuleId, probedModuleIdentity);
     moduleRefList[i] = moduleReference;
   }
   //^ NonNullType.AssertInitialized(moduleRefList);
   this.ModuleReferenceArray = moduleRefList;
 }
 private bool IsModuleRegistered(ModuleIdentity moduleIdentity)
 {
     return(Directory.Exists(Path.Combine(BasePath, moduleIdentity.ToString())));
 }
        public async Task ModulesClient_BulkUpdate()
        {
            string testDevicePrefix = $"bulkDeviceUpdate";
            string testModulePrefix = $"bulkModuleUpdate";

            IotHubServiceClient client = GetClient();

            string deviceId       = $"{testDevicePrefix}{GetRandom()}";
            var    deviceIdentity = new DeviceIdentity()
            {
                DeviceId = deviceId
            };

            IList <ModuleIdentity> listOfModulesToUpdate = new List <ModuleIdentity>();

            try
            {
                // Create the device to house two modules
                await client.Devices.CreateOrUpdateIdentityAsync(deviceIdentity).ConfigureAwait(false);

                AuthenticationMechanismType initialAuthenticationType = AuthenticationMechanismType.Sas;
                AuthenticationMechanismType updatedAuthenticationType = AuthenticationMechanismType.SelfSigned;

                for (int moduleIndex = 0; moduleIndex < BULK_MODULE_COUNT; moduleIndex++)
                {
                    // Create modules on that device
                    ModuleIdentity createdModule = (await client.Modules.CreateOrUpdateIdentityAsync(
                                                        new ModuleIdentity
                    {
                        DeviceId = deviceId,
                        ModuleId = $"{testModulePrefix}{GetRandom()}",
                        Authentication = new AuthenticationMechanism()
                        {
                            Type = initialAuthenticationType
                        },
                    }).ConfigureAwait(false)).Value;

                    // Update the authentication field so that we can test updating this identity later
                    createdModule.Authentication = new AuthenticationMechanism()
                    {
                        Type = AuthenticationMechanismType.SelfSigned
                    };

                    listOfModulesToUpdate.Add(createdModule);
                }

                // Make the API call to update the modules.
                Response <BulkRegistryOperationResponse> updateResponse =
                    await client.Modules.UpdateIdentitiesAsync(listOfModulesToUpdate, BulkIfMatchPrecondition.Unconditional)
                    .ConfigureAwait(false);

                // TODO: (azabbasi) Once the issue with the error parsing is resolved, include the error message in the message of the assert statement.
                Assert.IsTrue(updateResponse.Value.IsSuccessful, "Bulk module update ended with errors");

                // Verify that each module successfully updated its authentication field
                foreach (ModuleIdentity module in listOfModulesToUpdate)
                {
                    var updatedModule = (await client.Modules.GetIdentityAsync(module.DeviceId, module.ModuleId).ConfigureAwait(false)).Value;
                    updatedModule.Authentication.Type.Should().Be(updatedAuthenticationType, "Module should have been updated");
                }
            }
            finally
            {
                await CleanupAsync(client, deviceIdentity).ConfigureAwait(false);
            }
        }
        public async Task ModulesClient_UpdateModuleTwin_EtagDoesNotMatch()
        {
            string testDeviceId = $"TwinLifecycleDevice{GetRandom()}";
            string testModuleId = $"TwinLifecycleModule{GetRandom()}";

            DeviceIdentity device = null;
            ModuleIdentity module = null;

            IotHubServiceClient client = GetClient();

            try
            {
                // Create a device
                device = (await client.Devices.CreateOrUpdateIdentityAsync(
                              new DeviceIdentity
                {
                    DeviceId = testDeviceId
                }).ConfigureAwait(false)).Value;

                // Create a module on that device. Note that this implicitly creates the module twin
                module = (await client.Modules.CreateOrUpdateIdentityAsync(
                              new ModuleIdentity
                {
                    DeviceId = testDeviceId,
                    ModuleId = testModuleId
                }).ConfigureAwait(false)).Value;

                // Get the module twin
                TwinData moduleTwin = (await client.Modules.GetTwinAsync(testDeviceId, testModuleId).ConfigureAwait(false)).Value;

                moduleTwin.ModuleId.Should().BeEquivalentTo(testModuleId, "ModuleId on the Twin should match that of the module identity.");

                // Update device twin
                string propName  = "username";
                string propValue = "userA";
                moduleTwin.Properties.Desired.Add(new KeyValuePair <string, object>(propName, propValue));

                // TODO: (azabbasi) We should leave the IfMatchPrecondition to be the default value once we know more about the fix.
                Response <TwinData> updateResponse = await client.Modules.UpdateTwinAsync(moduleTwin, IfMatchPrecondition.UnconditionalIfMatch).ConfigureAwait(false);

                updateResponse.Value.Properties.Desired.Where(p => p.Key == propName).First().Value.Should().Be(propValue, "Desired property value is incorrect.");

                // Perform another update using the old device object to verify precondition fails.
                try
                {
                    // Try to update the twin with the previously up-to-date twin
                    await client.Modules.UpdateTwinAsync(moduleTwin, IfMatchPrecondition.IfMatch).ConfigureAwait(false);

                    Assert.Fail($"Update call with outdated ETag should fail with 412 (PreconditionFailed)");
                }
                // We will catch the exception and verify status is 412 (PreconditionfFailed)
                catch (RequestFailedException ex)
                {
                    Assert.AreEqual(412, ex.Status, $"Expected the update to fail with http status code 412 (PreconditionFailed)");
                }

                // Delete the module
                // Deleting the module happens in the finally block as cleanup.
            }
            finally
            {
                await CleanupAsync(client, device).ConfigureAwait(false);
            }
        }
Exemplo n.º 19
0
 public HttpResponseMessage RemoveModule(ModuleIdentity module)
 {
     return(_proxy.RemoveModuleAsync(module.Wrap()).Result);
 }
Exemplo n.º 20
0
        private static void Remove(HttpModules modules, RemoveOptions opts)
        {
            var r = modules.RemoveModule(ModuleIdentity.Parse($"{opts.Name} {opts.Version} {opts.Type}"));

            Console.WriteLine(r.IsSuccessStatusCode ? "success" : $"error {r.StatusCode} : {r.Content.ReadAsStringAsync().Result}");
        }
Exemplo n.º 21
0
 public ModuleMissedException(ModuleIdentity module, string message) : base(message)
 {
     Missed = new[] { module };
 }
Exemplo n.º 22
0
 public ModuleMissedException(ModuleIdentity module) : base()
 {
     Missed = new[] { module };
 }
Exemplo n.º 23
0
 public ModuleInfo(ModuleIdentity identity, ModuleIdentity[] dependencies)
 {
     ModuleIdentity = identity;
     Dependencies   = dependencies;
 }
Exemplo n.º 24
0
 /// <summary>
 /// Allocates a reference to a .NET module.
 /// </summary>
 /// <param name="host">Provides a standard abstraction over the applications that host components that provide or consume objects from the metadata model.</param>
 /// <param name="moduleIdentity"></param>
 public ModuleReference(IMetadataHost host, ModuleIdentity moduleIdentity)
 {
     this.host = host;
       this.moduleIdentity = moduleIdentity;
 }
Exemplo n.º 25
0
 /// <summary>
 /// Returns module by it's identity
 /// </summary>
 public virtual IModule GetModule(ModuleIdentity moduleIdentity)
 {
     return(_modulesRepository.GetModule(moduleIdentity));
 }
Exemplo n.º 26
0
        //^ requires peFileReader.IsAssembly ==> moduleIdentity.ContainingAssembly != null;
        //^ requires peFileReader.IsAssembly ==> containingAssembly == null;
        //^ requires !(moduleIdentity.Location != null && moduleIdentity.Location.Length != 0);
        /*^
        #pragma warning disable 2666, 2669, 2677, 2674
        ^*/
        internal PEFileToObjectModel(
      PeReader peReader,
      PEFileReader peFileReader,
      ModuleIdentity moduleIdentity,
      Assembly/*?*/ containingAssembly,
      byte pointerSize
    )
        {
            this.pointerSize = pointerSize;
              this.ModuleReader = peReader;
              this.PEFileReader = peFileReader;
              this.NameTable = peReader.metadataReaderHost.NameTable;
              this.StringIndexToNameTable = new Hashtable<IName>();
              this.StringIndexToUnmangledNameTable = new Hashtable<IName>();
              this.typeCache = new TypeCache(this);
              uint moduleNameOffset = peFileReader.ModuleTable.GetName(1);
              IName moduleName = this.GetNameFromOffset(moduleNameOffset);
              AssemblyIdentity/*?*/ assemblyIdentity = moduleIdentity as AssemblyIdentity;
              if (peFileReader.IsAssembly) {
            //^ assert assemblyIdentity != null;
            AssemblyRow assemblyRow = peFileReader.AssemblyTable[1];
            IName assemblyName = this.GetNameFromOffset(assemblyRow.Name);
            byte[] publicKeyArray = TypeCache.EmptyByteArray;
            if (assemblyRow.PublicKey != 0) {
              publicKeyArray = peFileReader.BlobStream[assemblyRow.PublicKey];
            }
            uint internedModuleId = (uint)peReader.metadataReaderHost.InternFactory.GetAssemblyInternedKey(assemblyIdentity);
            Assembly assem = new Assembly(this, moduleName, peFileReader.COR20Header.COR20Flags, internedModuleId, assemblyIdentity, assemblyName, assemblyRow.Flags, publicKeyArray);
            this.ContainingAssembly = assem;
            this.Module = assem;
              } else {
            uint internedModuleId = (uint)peReader.metadataReaderHost.InternFactory.GetModuleInternedKey(moduleIdentity);
            this.ContainingAssembly = containingAssembly;
            this.Module = new Module(this, moduleName, peFileReader.COR20Header.COR20Flags, internedModuleId, moduleIdentity);
              }

              this.LoadAssemblyReferences();
              this.LoadModuleReferences();
              this.RootModuleNamespace = new RootNamespace(this);
              this.NamespaceINameHashtable = new Hashtable<Namespace>();
              this.LoadNamespaces();
              this.NamespaceReferenceINameHashtable = new DoubleHashtable<NamespaceReference>();
              this.NamespaceTypeTokenTable = new DoubleHashtable(peFileReader.TypeDefTable.NumberOfRows + peFileReader.ExportedTypeTable.NumberOfRows);
              this.NestedTypeTokenTable = new DoubleHashtable(peFileReader.NestedClassTable.NumberOfRows + peFileReader.ExportedTypeTable.NumberOfRows);
              this.PreLoadTypeDefTableLookup();
              this.ModuleTypeDefArray = new TypeBase/*?*/[peFileReader.TypeDefTable.NumberOfRows + 1];
              this.ModuleTypeDefLoadState = new LoadState[peFileReader.TypeDefTable.NumberOfRows + 1];
              this.ModuleTypeDefLoadState[0] = LoadState.Loaded;

              this.ExportedTypeArray = new ExportedTypeAliasBase/*?*/[peFileReader.ExportedTypeTable.NumberOfRows + 1];
              this.ExportedTypeLoadState = new LoadState[peFileReader.ExportedTypeTable.NumberOfRows + 1];
              this.ExportedTypeLoadState[0] = LoadState.Loaded;

              this.ModuleGenericParamArray = new GenericParameter[peFileReader.GenericParamTable.NumberOfRows + 1];
              if (peFileReader.MethodSpecTable.NumberOfRows > 0) {
            this.ModuleMethodSpecHashtable = new DoubleHashtable<GenericMethodInstanceReference>(peFileReader.MethodSpecTable.NumberOfRows + 1);
              }

              this.ModuleTypeRefReferenceArray = new TypeRefReference[peFileReader.TypeRefTable.NumberOfRows + 1];
              this.ModuleTypeRefReferenceLoadState = new LoadState[peFileReader.TypeRefTable.NumberOfRows + 1];
              this.ModuleTypeRefReferenceLoadState[0] = LoadState.Loaded;
              if (peFileReader.TypeSpecTable.NumberOfRows > 0) {
            this.ModuleTypeSpecHashtable = new DoubleHashtable<TypeSpecReference>(peFileReader.TypeSpecTable.NumberOfRows + 1);
              }

              this.ModuleFieldArray = new FieldDefinition[peFileReader.FieldTable.NumberOfRows + 1];
              this.ModuleMethodArray = new MethodDefinition[peFileReader.MethodTable.NumberOfRows + 1];
              this.ModuleEventArray = new EventDefinition[peFileReader.EventTable.NumberOfRows + 1];
              this.ModulePropertyArray = new PropertyDefinition[peFileReader.PropertyTable.NumberOfRows + 1];

              this.ModuleMemberReferenceArray = new MemberReference/*?*/[peFileReader.MemberRefTable.NumberOfRows + 1];

              this.CustomAttributeArray = new ICustomAttribute/*?*/[peFileReader.CustomAttributeTable.NumberOfRows + 1];

              this.DeclSecurityArray = new ISecurityAttribute/*?*/[peFileReader.DeclSecurityTable.NumberOfRows + 1];

              uint moduleClassTypeDefToken = this.NamespaceTypeTokenTable.Find((uint)this.NameTable.EmptyName.UniqueKey, (uint)peReader._Module_.UniqueKey);
              _Module_Type/*?*/ _module_ = null;
              if (moduleClassTypeDefToken != 0 && ((TokenTypeIds.TokenTypeMask & moduleClassTypeDefToken) == TokenTypeIds.TypeDef)) {
            _module_ = this.Create_Module_Type(moduleClassTypeDefToken & TokenTypeIds.RIDMask);
              }
              if (_module_ == null) {
            //  Error
            throw new MetadataReaderException("<Module> Type not present");
              }
              this._Module_ = _module_;
              //^ NonNullType.AssertInitialized(this.ModuleGenericParamArray);
              //^ NonNullType.AssertInitialized(this.ModuleTypeRefReferenceArray);
              //^ NonNullType.AssertInitialized(this.ModuleFieldArray);
              //^ NonNullType.AssertInitialized(this.ModuleMethodArray);
              //^ NonNullType.AssertInitialized(this.ModuleEventArray);
              //^ NonNullType.AssertInitialized(this.ModulePropertyArray);
        }
 public CheckDependenciesResult(ModuleIdentity sourceModule, Dictionary <ModuleIdentity, Exception> failedModules)
 {
     SourceModule   = sourceModule;
     _failedModules = failedModules;
 }
Exemplo n.º 28
0
        async Task <(IMessageConsumer, IMessageConsumer, NullBrokerConnector)> SetupEnvironment()
        {
            Routing.UserMetricLogger    = NullRoutingUserMetricLogger.Instance;
            Routing.PerfCounter         = NullRoutingPerfCounter.Instance;
            Routing.UserAnalyticsLogger = NullUserAnalyticsLogger.Instance;

            var defaultRetryStrategy   = new FixedInterval(5, TimeSpan.FromSeconds(5));
            var defaultRevivePeriod    = TimeSpan.FromHours(1);
            var defaultTimeout         = TimeSpan.FromSeconds(60);
            var endpointExecutorConfig = new EndpointExecutorConfig(defaultTimeout, defaultRetryStrategy, defaultRevivePeriod, true);

            var cloudProxyDispatcher    = new BrokeredCloudProxyDispatcher();
            var cloudConnectionProvider = new BrokeredCloudConnectionProvider(cloudProxyDispatcher);

            var identityProvider          = new IdentityProvider(iotHubName);
            var deviceConnectivityManager = new BrokeredDeviceConnectivityManager(cloudProxyDispatcher);

            var connectionManager = new ConnectionManager(cloudConnectionProvider, Mock.Of <ICredentialsCache>(), new IdentityProvider(iotHubName), deviceConnectivityManager);

            var routingMessageConverter = new RoutingMessageConverter();
            var routeFactory            = new EdgeRouteFactory(new EndpointFactory(connectionManager, routingMessageConverter, edgeDeviceId, 10, 10));
            var routesList   = new[] { routeFactory.Create("FROM /messages INTO $upstream") };
            var endpoints    = routesList.Select(r => r.Endpoint);
            var routerConfig = new RouterConfig(endpoints, routesList);

            var dbStoreProvider         = new InMemoryDbStoreProvider();
            var storeProvider           = new StoreProvider(dbStoreProvider);
            var messageStore            = new MessageStore(storeProvider, CheckpointStore.Create(storeProvider), TimeSpan.MaxValue, false, 1800);
            var endpointExecutorFactory = new StoringAsyncEndpointExecutorFactory(endpointExecutorConfig, new AsyncEndpointExecutorOptions(1, TimeSpan.FromMilliseconds(10)), messageStore);

            var router = await Router.CreateAsync(Guid.NewGuid().ToString(), iotHubName, routerConfig, endpointExecutorFactory);

            var messageConverterProvider = new MessageConverterProvider(
                new Dictionary <Type, IMessageConverter>()
            {
                { typeof(Twin), new TwinMessageConverter() },
                { typeof(TwinCollection), new TwinCollectionMessageConverter() }
            });

            var twinManager           = TwinManager.CreateTwinManager(connectionManager, messageConverterProvider, Option.None <IStoreProvider>());
            var invokeMethodHandler   = Mock.Of <IInvokeMethodHandler>();
            var subscriptionProcessor = new SubscriptionProcessor(connectionManager, invokeMethodHandler, deviceConnectivityManager);

            var edgeHub = new RoutingEdgeHub(router, routingMessageConverter, connectionManager, twinManager, edgeDeviceId, edgeModuleName, invokeMethodHandler, subscriptionProcessor, Mock.Of <IDeviceScopeIdentitiesCache>());

            var brokerConnector = new NullBrokerConnector(cloudProxyDispatcher);

            cloudProxyDispatcher.SetConnector(brokerConnector);
            cloudProxyDispatcher.BindEdgeHub(edgeHub);

            var connectionProvider = new ConnectionProvider(connectionManager, edgeHub, TimeSpan.FromSeconds(30));
            var authenticator      = new NullAuthenticator();

            var edgeHubIdentity         = new ModuleIdentity(iotHubName, edgeDeviceId, edgeModuleName);
            var tokenCredentials        = new TokenCredentials(edgeHubIdentity, "qwerty", "test-product", Option.Some("test-model"), Option.None <string>(), false);
            var systemComponentProvider = new SystemComponentIdProvider(tokenCredentials);

            var connectionHandler = default(ConnectionHandler);

            connectionHandler = new ConnectionHandler(
                Task.FromResult <IConnectionProvider>(connectionProvider),
                Task.FromResult <IAuthenticator>(authenticator),
                identityProvider,
                systemComponentProvider,
                DeviceProxyFactory);

            DeviceProxy DeviceProxyFactory(IIdentity identity, bool isDirectClient)
            {
                return(new DeviceProxy(identity, isDirectClient, connectionHandler, Mock.Of <ITwinHandler>(), Mock.Of <IModuleToModuleMessageHandler>(), Mock.Of <ICloud2DeviceMessageHandler>(), Mock.Of <IDirectMethodHandler>()));
            }

            var cloud2DeviceMessageHandler   = new Cloud2DeviceMessageHandler(connectionHandler);
            var moduleToModuleMessageHandler = new ModuleToModuleMessageHandler(connectionHandler, identityProvider, new ModuleToModuleResponseTimeout(TimeSpan.FromSeconds(10)));
            var directMethodHandler          = new DirectMethodHandler(connectionHandler, identityProvider);
            var twinHandler = new TwinHandler(connectionHandler, identityProvider);

            var subscriptionChangeHandler = new SubscriptionChangeHandler(
                cloud2DeviceMessageHandler,
                moduleToModuleMessageHandler,
                directMethodHandler,
                twinHandler,
                connectionHandler,
                identityProvider);

            return(subscriptionChangeHandler, cloudProxyDispatcher, brokerConnector);
        }
Exemplo n.º 29
0
 public void ModuleOpened(IModule module, ModuleIdentity moduleIdentity, uint size)
 {
     ModuleOpened(module.Name.Value, moduleIdentity == null ? "" : moduleIdentity.Location, module.GetHashCode(), (int)size);
 }
        public void ValidatePodPropertyTranslation()
        {
            var identity = new ModuleIdentity("hostname", "gatewayhost", "deviceid", "Module1", Mock.Of <ICredentials>());
            var labels   = new Dictionary <string, string>
            {
                // Add a label
                { "demo", "test" }
            };
            var hostConfig = new HostConfig
            {
                // Make container privileged
                Privileged = true,
                // Add a readonly mount
                Binds = new List <string> {
                    "/home/blah:/home/blah2:ro"
                }
            };
            var config       = new KubernetesConfig("image", CreatePodParameters.Create(labels: labels, hostConfig: hostConfig), Option.None <AuthConfig>());
            var docker       = new DockerModule("module1", "v1", ModuleStatus.Running, RestartPolicy.Always, Config1, ImagePullPolicy.OnCreate, DefaultConfigurationInfo, EnvVarsDict);
            var module       = new KubernetesModule(docker, config, EdgeletModuleOwner);
            var moduleLabels = new Dictionary <string, string>();
            var mapper       = CreateMapper();

            var deployment = mapper.CreateDeployment(identity, module, moduleLabels);
            var pod        = deployment.Spec.Template;

            Assert.NotNull(pod);
            // Validate annotation
            Assert.True(pod.Metadata.Annotations.ContainsKey("demo"));
            // Two containers should exist - proxy and the module
            Assert.Equal(2, pod.Spec.Containers.Count);

            // There should only be one module container
            var moduleContainer = pod.Spec.Containers.Single(p => p.Name != "proxy");

            // We made this container privileged
            Assert.True(moduleContainer.SecurityContext.Privileged);
            // Validate that there are 1 mounts for module container
            Assert.Equal(1, moduleContainer.VolumeMounts.Count);
            // Validate the custom mount that we added
            Assert.Contains(moduleContainer.VolumeMounts, vm => vm.Name.Equals("homeblah"));
            var mount = moduleContainer.VolumeMounts.Single(vm => vm.Name.Equals("homeblah"));

            // Lets make sure that it is read only
            Assert.True(mount.ReadOnlyProperty);

            // Validate proxy container
            var proxyContainer = pod.Spec.Containers.Single(p => p.Name == "proxy");

            // Validate that there are 2 mounts for proxy container: config and trust-bundle
            Assert.Equal(2, proxyContainer.VolumeMounts.Count);
            Assert.Contains(proxyContainer.VolumeMounts, vm => vm.Name.Equals("configVolumeName"));
            Assert.Contains(proxyContainer.VolumeMounts, vm => vm.Name.Equals("trustBundleVolumeName"));

            // Validate pod volumes
            Assert.Equal(3, pod.Spec.Volumes.Count);
            Assert.Contains(pod.Spec.Volumes, v => v.Name.Equals("homeblah"));
            Assert.Contains(pod.Spec.Volumes, v => v.Name.Equals("configVolumeName"));
            Assert.Contains(pod.Spec.Volumes, v => v.Name.Equals("trustBundleVolumeName"));

            // Validate no image pull secrets for public images
            Assert.Null(pod.Spec.ImagePullSecrets);

            // Validate null pod security context by default
            Assert.Null(pod.Spec.SecurityContext);
        }
        public async Task ModulesClient_InvokeMethodOnModule()
        {
            if (!this.IsAsync)
            {
                // TODO: Tim: The module client doesn't appear to open a connection to iothub or start
                // listening for method invocations when this test is run in Sync mode. Not sure why though.
                // calls to track 1 library don't throw, but seem to silently fail
                return;
            }

            string testDeviceId = $"InvokeMethodDevice{GetRandom()}";
            string testModuleId = $"InvokeMethodModule{GetRandom()}";

            DeviceIdentity      device        = null;
            ModuleIdentity      module        = null;
            ModuleClient        moduleClient  = null;
            IotHubServiceClient serviceClient = GetClient();

            try
            {
                // Create a device to house the modules
                device = (await serviceClient.Devices
                          .CreateOrUpdateIdentityAsync(
                              new DeviceIdentity
                {
                    DeviceId = testDeviceId
                })
                          .ConfigureAwait(false))
                         .Value;

                // Create the module on the device
                module = (await serviceClient.Modules.CreateOrUpdateIdentityAsync(
                              new ModuleIdentity
                {
                    DeviceId = testDeviceId,
                    ModuleId = testModuleId
                }).ConfigureAwait(false)).Value;

                // Method expectations
                string expectedMethodName     = "someMethodToInvoke";
                int    expectedStatus         = 222;
                object expectedRequestPayload = null;

                // Create module client instance to receive the method invocation
                string moduleClientConnectionString = $"HostName={GetHostName()};DeviceId={testDeviceId};ModuleId={testModuleId};SharedAccessKey={module.Authentication.SymmetricKey.PrimaryKey}";
                moduleClient = ModuleClient.CreateFromConnectionString(moduleClientConnectionString, TransportType.Mqtt_Tcp_Only);

                // These two methods are part of our track 1 device client. When the test fixture runs when isAsync = true,
                // these methods work. When isAsync = false, these methods silently don't work.
                await moduleClient.OpenAsync().ConfigureAwait(false);

                await moduleClient.SetMethodHandlerAsync(
                    expectedMethodName,
                    (methodRequest, userContext) =>
                {
                    return(Task.FromResult(new MethodResponse(expectedStatus)));
                },
                    null).ConfigureAwait(false);

                // Invoke the method on the module
                CloudToDeviceMethodRequest methodRequest = new CloudToDeviceMethodRequest()
                {
                    MethodName = expectedMethodName,
                    Payload    = expectedRequestPayload,
                    ConnectTimeoutInSeconds  = 5,
                    ResponseTimeoutInSeconds = 5
                };

                var methodResponse = (await serviceClient.Modules.InvokeMethodAsync(testDeviceId, testModuleId, methodRequest).ConfigureAwait(false)).Value;

                Assert.AreEqual(expectedStatus, methodResponse.Status);
            }
            finally
            {
                if (moduleClient != null)
                {
                    await moduleClient.CloseAsync().ConfigureAwait(false);
                }

                await CleanupAsync(serviceClient, device).ConfigureAwait(false);
            }
        }
Exemplo n.º 32
0
        internal override InitializationResult _Init(IConfigurationRoot configuration, IContainer container)
        {
            _dockerClient = new DockerClientConfiguration(new Uri(configuration.GetValue <string>("DockerUri")))
                            .CreateClient();

            var configSource = new EmulatorConfigSource(configuration);

            var dockerLoggingOptions = new Dictionary <string, string>
            {
                { "max-size", "1m" },
                { "max-file", "1" }
            };
            var loggingConfig = new DockerLoggingConfig("json-file", dockerLoggingOptions);

            var dockerAuthConfig = configuration.GetSection("DockerRegistryAuth").Get <List <AuthConfig> >() ??
                                   new List <AuthConfig>();
            var combinedDockerConfigProvider = new CombinedDockerConfigProvider(dockerAuthConfig);
            //var runtimeInfoProvider = RuntimeInfoProvider.CreateAsync(_dockerClient);

            var dockerModule = new Devices.Edge.Agent.Docker.DockerModule(
                Name,
                DockerHostingSettings.Version,
                DockerHostingSettings.DesiredStatus.Value,
                DockerHostingSettings.RestartPolicy.Value,
                DockerHostingSettings.Config,
                null,
                null
                );

            var connectionString =
                configuration.GetValue <string>(Devices.Edge.Agent.Core.Constants.EdgeHubConnectionStringKey);
            var connectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);

            var moduleIdentity = new ModuleIdentity(connectionStringBuilder.IotHubName,
                                                    Environment.MachineName,
                                                    connectionStringBuilder.DeviceId,
                                                    connectionStringBuilder.ModuleId,
                                                    new ConnectionStringCredentials(connectionString));

            _moduleWithIdentity = new ModuleWithIdentity(dockerModule, moduleIdentity);
            //var combinedDockerConfig = combinedDockerConfigProvider.GetCombinedConfig(dockerModule, runtimeInfo);

            _dockerFactory = new LoggingCommandFactory(new DockerCommandFactory(_dockerClient,
                                                                                loggingConfig,
                                                                                configSource,
                                                                                combinedDockerConfigProvider),
                                                       Devices.Edge.Util.Logger.Factory);

            //var updateCommand = new GroupCommand(
            //      new RemoveCommand(_dockerClient, dockerModule),
            //        new GroupCommand(
            //            new PullCommand(_dockerClient, combinedDockerConfig),
            //            CreateCommand.BuildAsync(_dockerClient,
            //            dockerModule,
            //            dockerModuleWithIdentity.ModuleIdentity,
            //            loggingConfig,
            //            configSource,
            //            false).Result));

            //_createCommand = new GroupCommand(
            //   new PullCommand(_dockerClient, combinedDockerConfig),
            //   CreateCommand.BuildAsync(_dockerClient,
            //   dockerModule,
            //   dockerModuleWithIdentity.ModuleIdentity,
            //   loggingConfig,
            //   configSource,
            //   false).Result);

            //_startCommand = dockerFactory.StartAsync(dockerModule).Result;
            return(base._Init(configuration, container));
        }
 public WrongModuleTypeException(ModuleIdentity module, IEnumerable <ModuleType> allowedTypes = null)
 {
     Module       = module;
     AllowedTypes = allowedTypes;
 }
 public ModuleIsRequiredException(ModuleIdentity module, IEnumerable <ModuleIdentity> dependentModules) :
     base($"Module {module} is required for {string.Concat(dependentModules.Select(x => x.ToString() + "; "))}.")
 {
     ModuleIdentity   = module;
     DependentModules = dependentModules;
 }