private bool TryToRegister()
        {
            // Get the base url of the service directory host; this is where we send the registration info
            var baseUrl = config.Keyword(Keys.SERVICE_DIRECTORY__BASE_URI);

            // Get the parameters of the service we are registering
            var serviceUri         = config.Keyword(Keys.SERVICE_DIRECTORY__HOST_URI);
            var serviceLabel       = config.Keyword(Keys.SERVICE_DIRECTORY__LABEL);
            var serviceScopes      = config.Keyword(Keys.SERVICE_DIRECTORY__SCOPES);
            var serviceName        = config.Keyword(Keys.SERVICE_DIRECTORY__NAME);
            var serviceType        = (ServiceRegistrationType)config.Keyword(Keys.SERVICE_DIRECTORY__TYPE);
            var servicePriority    = config.Keyword <int>(Keys.SERVICE_DIRECTORY__PRIORITY);
            var serviceFormat      = config.Keyword(Keys.SERVICE_DIRECTORY__FORMAT);
            var serviceDescription = config.Keyword(Keys.SERVICE_DIRECTORY__DESCRIPTION);
            var serviceOAuth       = config.Keyword(Keys.SERVICE_DIRECTORY__OAUTH);
            var serviceToken       = config.Keyword(Keys.SERVICE_DIRECTORY__TOKEN);
            var serviceAuthority   = config.Keyword(AppKeys.UPP_AUTHORITY);

            // Make sure there are actual values passed in
            if (String.IsNullOrEmpty(baseUrl))
            {
                logger.Warn("No service directory URL set in the configuration file. Keyword '{0}'", Keys.SERVICE_DIRECTORY__BASE_URI);
                return(false);
            }

            if (String.IsNullOrEmpty(serviceUri))
            {
                logger.Warn("No service URI is set in the configuration file. Keyword '{0}'", Keys.SERVICE_DIRECTORY__HOST_URI);
                return(false);
            }

            if (String.IsNullOrEmpty(serviceScopes))
            {
                logger.Warn("No service scopes are set in the configuration file. Keyword '{0}'", Keys.SERVICE_DIRECTORY__SCOPES);
                return(false);
            }

            // Split the service URI into a host and a path
            var _serviceUri = new Uri(serviceUri);
            var serviceHost = String.Format("{0}://{1}", _serviceUri.Scheme, _serviceUri.Authority);
            var servicePath = _serviceUri.AbsolutePath;

            // Construct and serialize the JSON document for registering the service
            var body = new ServiceRegistrationRecord
            {
                Kind       = "Service",
                ApiVersion = "v1",
                Metadata   = new ServiceRegistrationMetadata
                {
                    Name = serviceName,                // Unique DNS-style service name, e.g. esri.routing, mndot.bridges, upp.data, etc.
                    Uid  = hostIdentity,               // RFC 4122 UUID assigned to the UPP Systems, e.g. 123e4567-e89b-12d3-a456-426655440000

                    Labels = new ServiceRegistrationLabels
                    {
                        FriendlyName = serviceLabel,     // Human-readable service name, e.g. "Clearwater County UPP Service"
                        Scopes       = serviceScopes,    // space-delimited list of scopes supported by this service
                        Authority    = serviceAuthority, // Assigned name of the UPP authority, e.g. "clearwater_co_mn",
                        Type         = serviceType.Key,  // What service is offered? geometry, routing, data, permit, etc.
                        Format       = serviceFormat     // Everything using this API provides data services
                    },
                    Annotations = new ServiceRegistrationAnnotations
                    {
                        Description = serviceDescription,
                        Priority    = servicePriority, // Priority of this service
                        OAuthId     = serviceOAuth,    // If this service uses one of the OAuth backend providers
                        TokenId     = serviceToken     // If this service uses one of the token backend providers
                    }
                },
                Spec = new ServiceRegistrationSpec
                {
                    Type         = "ExternalName",
                    ExternalName = serviceHost,
                    Path         = servicePath
                }
            };

            // Get just the host name for the services directory REST endpoint
            var _servicesDirectoryUri = new Uri(baseUrl);

            // Try to POST our registration information to the service directory
            var client  = new RestClient(String.Format("{0}://{1}", _servicesDirectoryUri.Scheme, _servicesDirectoryUri.Authority));
            var request = new RestRequest(String.Format("{0}/{1}", _servicesDirectoryUri.AbsolutePath, "services"), Method.POST);

            request.RequestFormat = DataFormat.Json;
            request.AddBody(body);

            logger.Debug("Attempting to register with service directory at {0}{1}", client.BaseUrl, request.Resource);
            logger.Debug("POST {0}", request.Resource);

            // Sending the request now....
            lastRequest = DateTime.Now;

            // Get the response and see if we were able to register outselves
            var response = client.Execute(request);

            logger.Debug(request.Parameters.Find(param => param.Type == ParameterType.RequestBody).Value.ToString());
            logger.Debug("Service Directory Response: {0}", response.Content);

            // Parse the response
            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                return(false);
            }

            // Success!!
            return(true);
        }
Ejemplo n.º 2
0
        public object RegisterService(ServiceRegistrationRecord record)
        {
            using (var conn = SimpleDbConnection())
            {
                // Get a reference to the metadata labels
                var labels      = record.Metadata.Labels;
                var annotations = record.Metadata.Annotations;

                // Cast the type to a registered value
                var type = (ServiceRegistrationType)labels.Type;

                // Extract the table values from the record
                var name        = record.Metadata.Name;
                var description = annotations.Description;
                var format      = labels.Format;
                var displayName = labels.FriendlyName;
                var url         = record.Spec.ExternalName + record.Spec.Path;
                var authority   = labels.Authority;
                var priority    = annotations.Priority;
                var oauth       = annotations.OAuthId;
                var token       = annotations.TokenId;
                var scopes      = labels.Scopes;

                logger.Debug("Registering new service:");
                logger.Debug("  Display     = {0}", displayName);
                logger.Debug("  Description = {0}", description);
                logger.Debug("  Url         = {0}", url);
                logger.Debug("  Type        = {0}", type.Key);
                logger.Debug("  Format      = {0}", format);
                logger.Debug("  Authority   = {0}", authority);
                logger.Debug("  Priority    = {0}", priority);
                logger.Debug("  Scopes      = {0}", scopes);
                logger.Debug("  OAuth       = {0}", oauth);
                logger.Debug("  Token       = {0}", token);

                // Insert the new values
                logger.Debug("Inserting new services");
                conn.Execute(@"
                    INSERT INTO MicroServiceProviders (
                      name,
                      oauth_provider_id,
                      token_provider_id,
                      display_name,
                      uri,
                      type,
                      format,
                      description,
                      priority,
                      authority,
                      active,
                      scopes
                    )
                    VALUES (@Name, @OAuth, @Token, @DisplayName, @Uri, @Type, @Format, @Description, @Priority, @Authority, @Active, @Scopes)
                    ",
                             new
                {
                    Name        = name,
                    OAuth       = oauth,
                    Token       = token,
                    DisplayName = displayName,
                    Uri         = url,
                    Type        = type.Key,
                    Format      = format,
                    Description = description,
                    Priority    = priority,
                    Authority   = authority,
                    Active      = 1,
                    Scopes      = scopes
                }
                             );

                // Return a response that enumerates that services were registers, which ones were updates and what failed
                return(new
                {
                    Added = new List <string>(),
                    Updated = new List <string>(),
                    Removed = new List <string>(),
                    Failed = new List <string>()
                });
            }
        }