public ApplicationDatabaseTestFixture()
        {
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("testsettings.json", optional: false, reloadOnChange: true)
                          .AddJsonFile("testsettings.Development.json", optional: true, reloadOnChange: true)
                          .AddEnvironmentVariables();

            _configuration = builder.Build();
            _configuration.Bind("OpcVault", _serviceConfig);
            _configuration.Bind("Auth", _clientConfig);
            _logger = SerilogTestLogger.Create <ApplicationDatabaseTestFixture>();
            if (!InvalidConfiguration())
            {
                RandomGenerator       = new ApplicationTestDataGenerator(_randomStart);
                _documentDBRepository = new OpcVaultDocumentDbRepository(_serviceConfig);
                ApplicationsDatabase  = CosmosDBApplicationsDatabaseFactory.Create(null, _serviceConfig, _documentDBRepository, _logger);
                // create test set
                ApplicationTestSet = new List <ApplicationTestData>();
                for (int i = 0; i < _testSetSize; i++)
                {
                    var randomApp = RandomGenerator.RandomApplicationTestData();
                    ApplicationTestSet.Add(randomApp);
                }
                // try initialize DB
                ApplicationsDatabase.Initialize().Wait();
            }
            RegistrationOk = false;
        }
示例#2
0
 public void Start()
 {
     Task.Run(async() =>
     {
         try
         {
             await _repository.CreateRepositoryIfNotExistsAsync();
             await _applicationDatabase.Initialize();
             await _certificateRequest.Initialize();
             _logger.Information("Database warm start successful.");
         }
         catch (Exception ex)
         {
             _logger.Error("Failed to warm start databases.", ex);
         }
     });
 }
        public CertificateRequestTestFixture()
        {
            RandomGenerator = new ApplicationTestDataGenerator(_randomStart);
            var builder = new ConfigurationBuilder()
                          .SetBasePath(Directory.GetCurrentDirectory())
                          .AddJsonFile("testsettings.json", optional: false, reloadOnChange: true)
                          .AddJsonFile("testsettings.Development.json", optional: true, reloadOnChange: true)
                          .AddEnvironmentVariables();
            IConfigurationRoot configuration = builder.Build();

            configuration.Bind("OpcVault", _serviceConfig);
            configuration.Bind("Auth", _clientConfig);
            _logger = SerilogTestLogger.Create <CertificateRequestTestFixture>();
            if (!InvalidConfiguration())
            {
                _documentDBRepository = new OpcVaultDocumentDbRepository(_serviceConfig);
                ApplicationsDatabase  = CosmosDBApplicationsDatabaseFactory.Create(null, _serviceConfig, _documentDBRepository, _logger);

                var timeid = (DateTime.UtcNow.ToFileTimeUtc() / 1000) % 10000;
                _groupId  = "CertReqIssuerCA" + timeid.ToString();
                _configId = "CertReqConfig" + timeid.ToString();
                var keyVaultServiceClient = KeyVaultServiceClient.Get(_configId, _serviceConfig, _clientConfig, _logger);
                _keyVaultCertificateGroup = new KeyVaultCertificateGroup(keyVaultServiceClient, _serviceConfig, _clientConfig, _logger);
                _keyVaultCertificateGroup.PurgeAsync(_configId, _groupId).Wait();
                CertificateGroup = _keyVaultCertificateGroup;
                CertificateGroup = new KeyVaultCertificateGroup(keyVaultServiceClient, _serviceConfig, _clientConfig, _logger);
                CertificateGroup.CreateCertificateGroupConfiguration(_groupId, "CN=OPC Vault Cert Request Test CA, O=Microsoft, OU=Azure IoT", null).Wait();
                CertificateRequest = CosmosDBCertificateRequestFactory.Create(ApplicationsDatabase, CertificateGroup, _serviceConfig, _documentDBRepository, _logger);

                // create test set
                ApplicationTestSet = new List <ApplicationTestData>();
                for (int i = 0; i < _testSetSize; i++)
                {
                    var randomApp = RandomGenerator.RandomApplicationTestData();
                    ApplicationTestSet.Add(randomApp);
                }
                // try initialize DB
                ApplicationsDatabase.Initialize().Wait();
            }
            RegistrationOk = false;
        }
示例#4
0
        /// <summary>
        /// Initializes the node manager.
        /// </summary>
        public GlobalDiscoveryServiceNodeManager(IServerInternal server, ApplicationConfiguration applicationConfiguration,
                                                 IApplicationsDatabase database, ICertificateRequest request, ICertificateGroup certificateGroup, bool autoApprove = false)
            : base(server, applicationConfiguration)
        {
            NamespaceUris = new List <string> {
                $"http://{Dns.GetHostName()}/GDS/Default", Namespaces.OpcUaGds
            };
            _nextNodeId = 0;
            SystemContext.NodeIdFactory = this;
            _defaultSubjectNameContext  = "CN=" + applicationConfiguration.ApplicationName + ", DC=" + Dns.GetHostName();
            _certificateGroupConfigurationCollection = new CertificateGroupConfigurationCollection();

            //Authorities Certificates Store Path
            string directoryName = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location);

            if (string.IsNullOrEmpty(directoryName))
            {
                return;
            }
            string authoritiesStorePathDirectory = Path.Combine(directoryName, "pki\\authoritie");

            if (!Directory.Exists(authoritiesStorePathDirectory))
            {
                Directory.CreateDirectory(authoritiesStorePathDirectory);
            }
            _authoritiesStorePath = authoritiesStorePathDirectory;
            //Application Certificates Store Path
            string applicationCertificatesStorePathDirectory = Path.Combine(directoryName, "pki\\applications");

            if (!Directory.Exists(applicationCertificatesStorePathDirectory))
            {
                Directory.CreateDirectory(applicationCertificatesStorePathDirectory);
            }
            _applicationCertificatesStorePath = applicationCertificatesStorePathDirectory;
            //Base Certificates Store Path
            string baseCertificateGroupStorePathDirectory = Path.Combine(directoryName, "pki\\CA\\default");

            if (!Directory.Exists(baseCertificateGroupStorePathDirectory))
            {
                Directory.CreateDirectory(baseCertificateGroupStorePathDirectory);
            }
            _certificateGroupConfigurationCollection.Add(new CertificateGroupConfiguration {
                Id = "Default",
                CertificateType            = "RsaSha256ApplicationCertificateType",
                SubjectName                = _defaultSubjectNameContext,
                BaseStorePath              = baseCertificateGroupStorePathDirectory,
                DefaultCertificateLifetime = 12,
                DefaultCertificateKeySize  = 2048,
                DefaultCertificateHashSize = 256,
                CACertificateLifetime      = 60,
                CACertificateKeySize       = 2048,
                CACertificateHashSize      = 256
            });
            _knownHostNames = new StringCollection();

            _defaultApplicationGroupId = ExpandedNodeId.ToNodeId(ObjectIds.Directory_CertificateGroups_DefaultApplicationGroup, Server.NamespaceUris);
            _defaultHttpsGroupId       = ExpandedNodeId.ToNodeId(ObjectIds.Directory_CertificateGroups_DefaultHttpsGroup, Server.NamespaceUris);
            _defaultUserTokenGroupId   = ExpandedNodeId.ToNodeId(ObjectIds.Directory_CertificateGroups_DefaultUserTokenGroup, Server.NamespaceUris);

            _autoApprove             = autoApprove;
            _database                = database;
            _request                 = request;
            _certificateGroupFactory = certificateGroup;
            _certificateGroups       = new Dictionary <NodeId, CertificateGroup>();

            try
            {
                ServerOnNetwork[] results = _database.QueryServers(0, 5, null, null, null, null, out DateTime _);
                Utils.Trace($"QueryServers Returned: {results.Length} records");
                foreach (ServerOnNetwork result in results)
                {
                    Utils.Trace($"Server Found at {result.DiscoveryUrl}");
                }
            }
            catch (Exception e)
            {
                Utils.Trace($"Could not connect to the Database! Exception:\r\n{e.InnerException}");
                Utils.Trace("Initialize Database tables!");
                _database.Initialize();
                Utils.Trace("Database Initialized!");
            }
            Server.MessageContext.Factory.AddEncodeableTypes(typeof(ObjectIds).GetTypeInfo().Assembly);
        }
示例#5
0
        /// <summary>
        /// Initializes the node manager.
        /// </summary>
        public ApplicationsNodeManager(
            IServerInternal server,
            ApplicationConfiguration configuration,
            IApplicationsDatabase database,
            ICertificateGroupProvider certificateGroupProvider
            )
            : base(server, configuration)
        {
            List <string> namespaceUris = new List <string>
            {
                "http://opcfoundation.org/UA/GDS/applications/",
                Opc.Ua.Gds.Namespaces.OpcUaGds
            };

            NamespaceUris = namespaceUris;

            SystemContext.NodeIdFactory = this;

            // get the configuration for the node manager.
            m_configuration = configuration.ParseExtension <GlobalDiscoveryServerConfiguration>();

            // use suitable defaults if no configuration exists.
            if (m_configuration == null)
            {
                m_configuration = new GlobalDiscoveryServerConfiguration();
            }

            if (!String.IsNullOrEmpty(m_configuration.DefaultSubjectNameContext))
            {
                if (m_configuration.DefaultSubjectNameContext[0] != ',')
                {
                    m_configuration.DefaultSubjectNameContext = "," + m_configuration.DefaultSubjectNameContext;
                }
            }

            DefaultApplicationGroupId = ExpandedNodeId.ToNodeId(Opc.Ua.Gds.ObjectIds.Directory_CertificateGroups_DefaultApplicationGroup, Server.NamespaceUris);
            DefaultHttpsGroupId       = ExpandedNodeId.ToNodeId(Opc.Ua.Gds.ObjectIds.Directory_CertificateGroups_DefaultHttpsGroup, Server.NamespaceUris);
            DefaultUserTokenGroupId   = ExpandedNodeId.ToNodeId(Opc.Ua.Gds.ObjectIds.Directory_CertificateGroups_DefaultUserTokenGroup, Server.NamespaceUris);

            m_autoApprove = true;
            m_database    = database;
            m_certificateGroupProvider = certificateGroupProvider;
            m_certificateGroups        = new Dictionary <NodeId, CertificateGroup>();

            try
            {
                var results = m_database.QueryServers(0, 5, null, null, null, null, out DateTime lastResetTime);
                Utils.Trace("QueryServers Returned: {0} records", results.Length);

                foreach (var result in results)
                {
                    Utils.Trace("Server Found at {0}", result.DiscoveryUrl);
                }
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Could not connect to the Database!");

                var ie = e.InnerException;

                while (ie != null)
                {
                    Utils.Trace(ie, "");
                    ie = ie.InnerException;
                }

                Utils.Trace("Initialize Database tables!");
                m_database.Initialize();

                Utils.Trace("Database Initialized!");
            }

            Server.MessageContext.Factory.AddEncodeableTypes(typeof(Opc.Ua.Gds.ObjectIds).GetTypeInfo().Assembly);
        }