Пример #1
0
 public DeviceType[] Get()
 {
     using (var connection = _connectionFactory.CreateAndOpen())
     {
         return(connection
                .Query <DeviceType>("select Id, Name, CreatedUtc from DeviceTypes order by Name")
                .ToArray());
     }
 }
Пример #2
0
        public ApplicationEnvironmentVariable[] Get()
        {
            var queryBuilder = new SelectQueryBuilder <ApplicationEnvironmentVariable>("select * from ApplicationEnvironmentVariables", Request.Query);

            queryBuilder.TryAddGuidParameter("applicationId", "ApplicationId");

            using (var connection = _connectionFactory.CreateAndOpen())
            {
                return(queryBuilder.Execute(connection)
                       .ToArray());
            }
        }
Пример #3
0
        public void Post([FromBody] SubmitApplicationLogsRequest request)
        {
            using (var connection = _connectionFactory.CreateAndOpen())
                using (var transaction = connection.BeginTransaction())
                {
                    //If this is the first batch, we'll go ahead and kill the existing entries.
                    if (request.IsFirst)
                    {
                        const string deleteSql = "delete from ApplicationLogs where DeviceId = @deviceId";

                        connection.Execute(deleteSql, new { deviceId = DeviceId }, transaction);
                    }

                    //Transform the request into something we can insert.
                    var entries = request.Events
                                  .Select(e => new ApplicationLog
                    {
                        Id           = Guid.NewGuid(),
                        Type         = e.Type,
                        Message      = e.Content,
                        DeviceId     = DeviceId,
                        CreatedLocal = e.TimestampLocal,
                        CreatedUtc   = e.TimestampUtc
                    });

                    //Insert these guys
                    foreach (var entry in entries)
                    {
                        connection.Insert(entry, transaction);
                    }

                    transaction.Commit();
                }
        }
        public IActionResult Get(Guid id)
        {
            using (var connection = _connectionFactory.CreateAndOpen())
            {
                //Get the device
                var device = connection.Get <Device>(id);

                if (device == null)
                {
                    return(NotFound());
                }

                var configuration = new DeviceConfiguration()
                {
                    DeviceKey    = device.DeviceKey,
                    DeviceId     = device.Id,
                    DeviceApiUrl = _provisioningConfig.DeviceApiUrl,
                    PollSeconds  = 60,
                };

                //Craft the response
                var response = new GetDeviceConfigurationResponse()
                {
                    DeviceConfiguration = JsonConvert.SerializeObject(configuration)
                };

                //Put together the configuration
                return(Ok(response));
            }
        }
        public ApplicationVersion[] Get()
        {
            var queryBuilder = new SelectQueryBuilder <ApplicationVersion>(
                "select * from ApplicationVersions",
                Request.Query,
                new []
            {
                new SortableColumn("applicationId", "ApplicationId"),
                new SortableColumn("createdUtc", "CreatedUtc", true, SortDirection.Descending),
            });

            queryBuilder.TryAddGuidParameter("applicationId", "ApplicationId");

            using (var connection = _connectionFactory.CreateAndOpen())
            {
                return(queryBuilder.Execute(connection)
                       .ToArray());
            }
        }
Пример #6
0
        public AgentVersion[] Get()
        {
            var queryBuilder = new SelectQueryBuilder <AgentVersion>(
                "select * from AgentVersions",
                Request.Query,
                new[]
            {
                new SortableColumn("name", "Name", true),
                new SortableColumn("createdUtc", "CreatedUtc"),
            });

            queryBuilder.TryAddGuidParameter("deviceTypeId", "DeviceTypeId");

            using (var connection = _connectionFactory.CreateAndOpen())
            {
                return(queryBuilder.Execute(connection)
                       .ToArray());
            }
        }
Пример #7
0
        public Device[] Get()
        {
            var queryBuilder = new SelectQueryBuilder <Device>("select * from Devices", Request.Query);

            queryBuilder.TryAddGuidParameter("applicationId", "ApplicationId");
            queryBuilder.TryAddBitParameter("isDisabled", "IsDisabled");

            //Ignore deleted devices, unless the caller specifically asks for them.
            if (!queryBuilder.TryAddBitParameter("isDeleted", "IsDeleted"))
            {
                queryBuilder.AddCondition("IsDeleted", false);
            }

            using (var connection = _connectionFactory.CreateAndOpen())
            {
                return(queryBuilder.Execute(connection)
                       .ToArray());
            }
        }
Пример #8
0
        public IActionResult Get([FromQuery] Guid deviceId)
        {
            using (var connection = _connectionFactory.CreateAndOpen())
            {
                const string sql = "select * from [ApplicationLogs] where deviceId = @deviceId order by CreatedUtc";

                var entities = connection.Query <ApplicationLog>(sql, new { deviceId });

                return(Ok(entities));
            }
        }
Пример #9
0
        private GetHealthResponseItem GetDatabaseHealth()
        {
            return(Test("database", () =>
            {
                //Talk to the database
                using (var connection = _connectionFactory.CreateAndOpen())
                {
                    //Query something so we know whether it worked or not
                    connection.Query <DeviceType>("select * from DeviceTypes");
                }

                return "passed";
            }));
        }
Пример #10
0
        public IActionResult Post([FromBody] GetImageDownloadInfoRequest request)
        {
            //Ensure that the application version exists and that the device has access to it.
            using (var connection = _connectionFactory.CreateAndOpen())
            {
                var agentVersion = connection.Get <AgentVersion>(request.Id);

                if (agentVersion == null)
                {
                    return(NotFound(new Error($"Unable to find agent version {request.Id}")));
                }

                var device = connection.Get <Device>(DeviceId);

                if (device == null)
                {
                    return(NotFound(new Error("Unable to find device")));
                }

                var application = connection.Get <Application>(device.ApplicationId);

                if (application == null)
                {
                    return(NotFound(new Error($"Unable to find application '{device.ApplicationId}'.")));
                }

                var deviceType = connection.Get <DeviceType>(application.DeviceTypeId);

                if (deviceType == null)
                {
                    return(NotFound(new Error($"Unable to find device type '{application.DeviceTypeId}'.")));
                }

                var response = new ImageDownloadInfo()
                {
                    ImageId    = agentVersion.ImageId,
                    Registry   = _registryConfig.RegistryHost,
                    AuthToken  = null, //TODO: This is where the auth token will go
                    Repository = _repositoryNameFactory.Agent,
                    Name       = agentVersion.Name,
                };

                //TODO: Add a device event for getting this token

                return(Ok(response));
            }
        }
Пример #11
0
        public IActionResult Post([FromBody] GetImageDownloadInfoRequest request)
        {
            //Ensure that the application version exists and that the device has access to it.
            using (var connection = _connectionFactory.CreateAndOpen())
            {
                var applicationVersion = connection.Get <ApplicationVersion>(request.Id);

                if (applicationVersion == null)
                {
                    return(NotFound());
                }

                var device = connection.Get <Device>(DeviceId);

                if (device == null)
                {
                    return(NotFound());
                }

                if (device.ApplicationId != applicationVersion.ApplicationId)
                {
                    return(BadRequest());
                }

                //Verify that the device has access to this *specific* version.
                var application = connection.Get <Application>(device.ApplicationId);

                if (application.ApplicationVersionId != request.Id && device.ApplicationVersionId != request.Id)
                {
                    return(BadRequest());
                }

                var response = new ImageDownloadInfo()
                {
                    ImageId    = applicationVersion.ImageId,
                    Registry   = _registryConfig.RegistryHost,
                    AuthToken  = null, //TODO: This is where the auth token will go
                    Repository = _repositoryNameFactory.FromApplication(device.ApplicationId),
                    Name       = applicationVersion.Name,
                };

                //TODO: Add a device event for getting this token

                return(Ok(response));
            }
        }
        /// <summary>
        ///     This gets the correct key for the device.
        /// </summary>
        /// <param name="token"></param>
        /// <param name="securityToken"></param>
        /// <param name="kid"></param>
        /// <param name="validationParameters"></param>
        /// <returns></returns>
        private IEnumerable <SecurityKey> IssuerSigningKeyResolver(
            string token,
            SecurityToken securityToken,
            string kid,
            TokenValidationParameters validationParameters)
        {
            //TODO: implement multiple keys. That seems to be "good". MS does it. Other IoT identity providers do it.

            //Parse the token
            var parsed = new JwtSecurityToken(token);

            //Get the device id
            var deviceId = parsed.Claims
                           .FirstOrDefault(c => c.Type == TokenConstants.DeviceIdClaimName)?.Value?
                           .TryParseGuid();

            //Check to see if we got a deviceId.
            //TODO: Determin if there is a more informative exception that we could throw.
            if (deviceId == null)
            {
                return(_emptySecurityKeys);
            }

            using (var connection = _connectionFactory.CreateAndOpen())
            {
                //Get the device key
                var deviceKey = connection.GetDeviceKey(deviceId.Value);

                //Make sure we got it back.
                if (deviceKey == null)
                {
                    return(_emptySecurityKeys);
                }

                //Return the security key(s) for this device.
                return(new SecurityKey[]
                {
                    new SymmetricSecurityKey(deviceKey.Value.ToByteArray())
                    {
                        KeyId = $"DeviceId_{deviceId:D}"
                    }
                });
            }
        }
Пример #13
0
        public IActionResult Post([FromBody] GetAgentUploadInfoRequest request)
        {
            //Make sure we can find the application
            using (var connection = _connectionFactory.CreateAndOpen())
            {
                var deviceType = connection.Get <DeviceType>(request.DeviceTypeId);

                if (deviceType == null)
                {
                    return(NotFound(new Error($"Unable to find device device type '{request.DeviceTypeId}'.")));
                }

                if (string.IsNullOrWhiteSpace(request.Name))
                {
                    return(BadRequest(new Error("No name was specified.")));
                }

                if (string.IsNullOrWhiteSpace(request.ImageId))
                {
                    return(BadRequest(new Error("No image id was specified.")));
                }

                //Check for duplicate name.
                if (connection.IsAgentVersionNameInUse(request.DeviceTypeId, request.Name))
                {
                    return(Ok(new GetUploadInfoResponse
                    {
                        Reason = $"Name '{request.Name}' is already in use for device architecture '{deviceType.Name}'. Specify a new name."
                    }));
                }

                //Craft the response
                var response = new GetUploadInfoResponse
                {
                    CanUpload    = true,
                    RegistryHost = _registryConfig.RegistryHost,
                    Repository   = _repositoryNameFactory.Agent
                };

                return(Ok(response));
            }
        }
Пример #14
0
        public DeviceEvent[] Get()
        {
            var queryBuilder = new SelectQueryBuilder <DeviceEvent>(
                "select * from DeviceEvents",
                Request.Query,
                new SortableColumn[]
            {
                new SortableColumn("deviceId", "DeviceId"),
                new SortableColumn("eventType", "EventType"),
                new SortableColumn("createdUtc", "CreatedUtc", true, SortDirection.Descending),
            });

            queryBuilder.TryAddGuidParameter("deviceId", "DeviceId");
            queryBuilder.TryAddIntParameter("eventType", "EventType");

            using (var connection = _connectionFactory.CreateAndOpen())
            {
                return(queryBuilder
                       .Execute(connection)
                       .ToArray());
            }
        }
Пример #15
0
        public HeartbeatResponse Post([FromBody] HeartbeatRequest request)
        {
            using (var connection = _connectionFactory.CreateAndOpen())
            {
                const string updateSql = "update DeviceStatus " +
                                         "set " +
                                         "  AgentVersion = @AgentVersion, " +
                                         "  ApplicationVersion = @ApplicationVersion, " +
                                         "  UptimeSeconds = @UptimeSeconds, " +
                                         "  LastContactUtc = @Utc, " +
                                         "  State = @State " +
                                         "where " +
                                         "  DeviceId = @DeviceId";

                connection.Execute(updateSql, new
                {
                    request.UptimeSeconds,
                    Utc = DateTime.UtcNow,
                    DeviceId,
                    request.State,
                    request.AgentVersion,
                    request.ApplicationVersion
                });

                const string responseSql = "select ConfigurationVersion from Devices where Id = @Id";

                //Get the response
                var response = connection.QuerySingle <HeartbeatResponse>(responseSql, new { Id = DeviceId });

                _logger.LogTrace(
                    "Heartbeat receved for device {DeviceId}. Device has been up for {UptimeSeconds} seconds and is using ConfigurationVersion {ConfigurationVersion} sent.",
                    DeviceId, request.UptimeSeconds, response.ConfigurationVersion);

                return(response);
            }
        }
Пример #16
0
        public IActionResult Get()
        {
            using (var connection = _connectionFactory.CreateAndOpen())
            {
                //TODO: Consider executing a single command with multiple result sets.
                //      Might have to use some T-SQL to get the application given the device id.

                //Get the device
                var device = connection.Get <Device>(DeviceId);

                if (device == null)
                {
                    return(NotFound("Unable to find device."));
                }

                var application = connection.Get <Application>(device.ApplicationId);

                if (application == null)
                {
                    return(NotFound("Unable to find application."));
                }

                //Get the environment variables
                var deviceEnvironmentVariables      = connection.GetDeviceEnvironmentVariables(DeviceId);
                var applicationEnvironmentVariables = connection.GetApplicationEnvironmentVariables(application.Id);

                var applicationVersionId = application.ApplicationVersionId;
                var agentVersionId       = application.AgentVersionId;

                //Start out with the version information at the application level.
                var response = new GetDeviceConfigurationResponse
                {
                    RootFileSystemVersionId = application.RootFileSystemVersionId,
                    ConfigurationVersion    = device.ConfigurationVersion
                };

                //Override with device level version information (if available)
                if (device.AgentVersionId != null)
                {
                    agentVersionId = device.AgentVersionId.Value;
                }

                if (device.ApplicationVersionId != null)
                {
                    applicationVersionId = device.ApplicationVersionId.Value;
                }

                if (device.RootFileSystemVersionId != null)
                {
                    response.RootFileSystemVersionId = device.RootFileSystemVersionId.Value;
                }

                //Get the detailed application version information
                if (applicationVersionId != null)
                {
                    var applicationVersion = connection.Get <ApplicationVersion>(applicationVersionId.Value);

                    if (applicationVersion == null)
                    {
                        return(StatusCode(StatusCodes.Status500InternalServerError));
                    }

                    //Set thhe image reference
                    response.ApplicationVersion = new VersionReference
                    {
                        Id      = applicationVersion.Id,
                        ImageId = applicationVersion.ImageId,
                        Name    = applicationVersion.Name
                    };
                }

                //Get the detailed agent version id
                if (agentVersionId != null)
                {
                    var agentVersion = connection.Get <AgentVersion>(agentVersionId);

                    if (agentVersion == null)
                    {
                        return(StatusCode(StatusCodes.Status500InternalServerError));
                    }

                    response.AgentVersion = new VersionReference
                    {
                        Id      = agentVersion.Id,
                        ImageId = agentVersion.ImageId,
                        Name    = agentVersion.Name
                    };
                }

                //Once again, start out with the application level (this time environment variables)
                var effectiveEnvironmentVariables = new Dictionary <string, string>();

                foreach (var variable in applicationEnvironmentVariables)
                {
                    effectiveEnvironmentVariables[variable.Name] = variable.Value;
                }

                //Now add / override with the device level environment variables.
                foreach (var variable in deviceEnvironmentVariables)
                {
                    effectiveEnvironmentVariables[variable.Name] = variable.Value;
                }

                //Copy the effective variables to the response
                response.EnvironmentVariables = effectiveEnvironmentVariables.Select(v => new EnvironmentVariable
                {
                    Name  = v.Key,
                    Value = v.Value
                }).ToArray();

                //We're good
                return(Ok(response));
            }
        }