Remove resinApiEndpoint meta-endpoint and use config.json entry instead

The resinApiEndpoint config option existed for legacy reasons, where the
apiEndpoint was passed in via env vars, but this is no longer the case,
and the current supervisor wouldn't run on these older versions of
resinOS anymore anyway, so I've removed the references to this legacy
endpoint, as it made reasoning about offline mode weird.

Change-type: minor
Signed-off-by: Cameron Diver <cameron@resin.io>
This commit is contained in:
Cameron Diver 2018-07-12 13:27:47 +01:00
parent 0ec7b829b9
commit c61b16655e
No known key found for this signature in database
GPG Key ID: 69264F9C923F55C1
7 changed files with 33 additions and 45 deletions

View File

@ -63,47 +63,47 @@ module.exports = class APIBinder
release() release()
initClient: => initClient: =>
@config.getMany([ 'offlineMode', 'resinApiEndpoint', 'currentApiKey' ]) @config.getMany([ 'offlineMode', 'apiEndpoint', 'currentApiKey' ])
.then ({ offlineMode, resinApiEndpoint, currentApiKey }) => .then ({ offlineMode, apiEndpoint, currentApiKey }) =>
if offlineMode if offlineMode
console.log('Offline Mode is set, skipping API client initialization') console.log('Offline Mode is set, skipping API client initialization')
return return
baseUrl = url.resolve(resinApiEndpoint, '/v4/') baseUrl = url.resolve(apiEndpoint, '/v4/')
passthrough = _.cloneDeep(requestOpts) passthrough = _.cloneDeep(requestOpts)
passthrough.headers ?= {} passthrough.headers ?= {}
passthrough.headers.Authorization = "Bearer #{currentApiKey}" passthrough.headers.Authorization = "Bearer #{currentApiKey}"
@resinApi = new PinejsClient @resinApi = new PinejsClient
apiPrefix: baseUrl apiPrefix: baseUrl
passthrough: passthrough passthrough: passthrough
baseUrlLegacy = url.resolve(resinApiEndpoint, '/v2/') baseUrlLegacy = url.resolve(apiEndpoint, '/v2/')
@resinApiLegacy = new PinejsClient @resinApiLegacy = new PinejsClient
apiPrefix: baseUrlLegacy apiPrefix: baseUrlLegacy
passthrough: passthrough passthrough: passthrough
@cachedResinApi = @resinApi.clone({}, cache: {}) @cachedResinApi = @resinApi.clone({}, cache: {})
start: => start: =>
@config.getMany([ 'resinApiEndpoint', 'offlineMode', 'bootstrapRetryDelay' ]) @config.getMany([ 'apiEndpoint', 'offlineMode', 'bootstrapRetryDelay' ])
.then ({ resinApiEndpoint, offlineMode, bootstrapRetryDelay }) => .then ({ apiEndpoint, offlineMode, bootstrapRetryDelay }) =>
if offlineMode if offlineMode
console.log('Offline Mode is set, skipping API binder initialization') console.log('Offline Mode is set, skipping API binder initialization')
# If we are offline because there is no apiEndpoint, there's a chance # If we are offline because there is no apiEndpoint, there's a chance
# we've went through a deprovision. We need to set the initialConfigReported # we've went through a deprovision. We need to set the initialConfigReported
# value to '', to ensure that when we do re-provision, we'll report # value to '', to ensure that when we do re-provision, we'll report
# the config and hardward-specific options won't be lost # the config and hardward-specific options won't be lost
if !Boolean(resinApiEndpoint) if !Boolean(apiEndpoint)
return @config.set({ initialConfigReported: '' }) return @config.set({ initialConfigReported: '' })
return return
console.log('Ensuring device is provisioned') console.log('Ensuring device is provisioned')
@provisionDevice() @provisionDevice()
.then => .then =>
@config.getMany([ 'initialConfigReported', 'resinApiEndpoint' ]) @config.getMany([ 'initialConfigReported', 'apiEndpoint' ])
.then ({ initialConfigReported, resinApiEndpoint }) => .then ({ initialConfigReported, apiEndpoint }) =>
# Either we haven't reported our initial config or we've # Either we haven't reported our initial config or we've
# been re-provisioned # been re-provisioned
if resinApiEndpoint != initialConfigReported if apiEndpoint != initialConfigReported
console.log('Reporting initial configuration') console.log('Reporting initial configuration')
@reportInitialConfig(resinApiEndpoint, bootstrapRetryDelay) @reportInitialConfig(apiEndpoint, bootstrapRetryDelay)
.then => .then =>
console.log('Starting current state report') console.log('Starting current state report')
@startCurrentStateReport() @startCurrentStateReport()
@ -308,7 +308,7 @@ module.exports = class APIBinder
_sendLogsRequest: (uuid, data) => _sendLogsRequest: (uuid, data) =>
reqBody = _.map(data, (msg) -> _.mapKeys(msg, (v, k) -> _.snakeCase(k))) reqBody = _.map(data, (msg) -> _.mapKeys(msg, (v, k) -> _.snakeCase(k)))
@config.get('resinApiEndpoint') @config.get('apiEndpoint')
.then (resinApiEndpoint) => .then (resinApiEndpoint) =>
endpoint = url.resolve(resinApiEndpoint, "/device/v2/#{uuid}/logs") endpoint = url.resolve(resinApiEndpoint, "/device/v2/#{uuid}/logs")
requestParams = _.extend requestParams = _.extend
@ -364,9 +364,9 @@ module.exports = class APIBinder
@reportInitialConfig(apiEndpoint, retryDelay) @reportInitialConfig(apiEndpoint, retryDelay)
getTargetState: => getTargetState: =>
@config.getMany([ 'uuid', 'resinApiEndpoint', 'apiTimeout' ]) @config.getMany([ 'uuid', 'apiEndpoint', 'apiTimeout' ])
.then ({ uuid, resinApiEndpoint, apiTimeout }) => .then ({ uuid, apiEndpoint, apiTimeout }) =>
endpoint = url.resolve(resinApiEndpoint, "/device/v2/#{uuid}/state") endpoint = url.resolve(apiEndpoint, "/device/v2/#{uuid}/state")
requestParams = _.extend requestParams = _.extend
method: 'GET' method: 'GET'
@ -422,7 +422,7 @@ module.exports = class APIBinder
return _.pickBy(diff, _.negate(_.isEmpty)) return _.pickBy(diff, _.negate(_.isEmpty))
_sendReportPatch: (stateDiff, conf) => _sendReportPatch: (stateDiff, conf) =>
endpoint = url.resolve(conf.resinApiEndpoint, "/device/v2/#{conf.uuid}/state") endpoint = url.resolve(conf.apiEndpoint, "/device/v2/#{conf.uuid}/state")
requestParams = _.extend requestParams = _.extend
method: 'PATCH' method: 'PATCH'
url: "#{endpoint}" url: "#{endpoint}"
@ -432,7 +432,7 @@ module.exports = class APIBinder
@cachedResinApi._request(requestParams) @cachedResinApi._request(requestParams)
_report: => _report: =>
@config.getMany([ 'deviceId', 'apiTimeout', 'resinApiEndpoint', 'uuid' ]) @config.getMany([ 'deviceId', 'apiTimeout', 'apiEndpoint', 'uuid' ])
.then (conf) => .then (conf) =>
stateDiff = @_getStateDiff() stateDiff = @_getStateDiff()
if _.size(stateDiff) is 0 if _.size(stateDiff) is 0

View File

@ -272,7 +272,7 @@ module.exports = class ApplicationManager extends EventEmitter
).get(appId) ).get(appId)
getTargetApp: (appId) => getTargetApp: (appId) =>
@config.get('resinApiEndpoint').then (endpoint = '') -> @config.get('apiEndpoint').then (endpoint = '') ->
@db.models('app').where({ appId, source: endpoint }).select() @db.models('app').where({ appId, source: endpoint }).select()
.then ([ app ]) => .then ([ app ]) =>
if !app? if !app?
@ -714,7 +714,7 @@ module.exports = class ApplicationManager extends EventEmitter
@_targetVolatilePerImageId[imageId] = {} @_targetVolatilePerImageId[imageId] = {}
getTargetApps: => getTargetApps: =>
@config.get('resinApiEndpoint'). then (source = '') => @config.get('apiEndpoint'). then (source = '') =>
Promise.map(@db.models('app').where({ source }), @normaliseAndExtendAppFromDB) Promise.map(@db.models('app').where({ source }), @normaliseAndExtendAppFromDB)
.map (app) => .map (app) =>
if !_.isEmpty(app.services) if !_.isEmpty(app.services)

View File

@ -49,7 +49,6 @@ class Config extends EventEmitter {
currentApiKey: { source: 'func' }, currentApiKey: { source: 'func' },
offlineMode: { source: 'func' }, offlineMode: { source: 'func' },
pubnub: { source: 'func' }, pubnub: { source: 'func' },
resinApiEndpoint: { source: 'func' },
provisioned: { source: 'func' }, provisioned: { source: 'func' },
osVersion: { source: 'func' }, osVersion: { source: 'func' },
osVariant: { source: 'func' }, osVariant: { source: 'func' },

View File

@ -75,9 +75,9 @@ export function createProviderFunctions(config: Config, db: DB): ConfigProviderF
}, },
offlineMode: { offlineMode: {
get: () => { get: () => {
return config.getMany([ 'resinApiEndpoint', 'supervisorOfflineMode' ]) return config.getMany([ 'apiEndpoint', 'supervisorOfflineMode' ])
.then(({ resinApiEndpoint, supervisorOfflineMode }) => { .then(({ apiEndpoint, supervisorOfflineMode }) => {
return Boolean(supervisorOfflineMode) || !Boolean(resinApiEndpoint); return Boolean(supervisorOfflineMode) || !Boolean(apiEndpoint);
}); });
}, },
}, },
@ -93,21 +93,11 @@ export function createProviderFunctions(config: Config, db: DB): ConfigProviderF
}); });
}, },
}, },
resinApiEndpoint: {
get: () => {
// Fallback to checking if an API endpoint was passed via env vars if there's none
// in config.json (legacy)
return config.get('apiEndpoint')
.then((apiEndpoint) => {
return apiEndpoint || (constants.apiEndpointFromEnv || '');
});
},
},
provisioned: { provisioned: {
get: () => { get: () => {
return config.getMany([ return config.getMany([
'uuid', 'uuid',
'resinApiEndpoint', 'apiEndpoint',
'registered_at', 'registered_at',
'deviceId', 'deviceId',
]) ])
@ -135,7 +125,7 @@ export function createProviderFunctions(config: Config, db: DB): ConfigProviderF
'apiKey', 'apiKey',
'deviceApiKey', 'deviceApiKey',
'deviceType', 'deviceType',
'resinApiEndpoint', 'apiEndpoint',
'apiTimeout', 'apiTimeout',
'registered_at', 'registered_at',
'deviceId', 'deviceId',
@ -147,7 +137,7 @@ export function createProviderFunctions(config: Config, db: DB): ConfigProviderF
deviceType: conf.deviceType, deviceType: conf.deviceType,
provisioningApiKey: conf.apiKey, provisioningApiKey: conf.apiKey,
deviceApiKey: conf.deviceApiKey, deviceApiKey: conf.deviceApiKey,
apiEndpoint: conf.resinApiEndpoint, apiEndpoint: conf.apiEndpoint,
apiTimeout: conf.apiTimeout, apiTimeout: conf.apiTimeout,
registered_at: conf.registered_at, registered_at: conf.registered_at,
deviceId: conf.deviceId, deviceId: conf.deviceId,
@ -157,7 +147,7 @@ export function createProviderFunctions(config: Config, db: DB): ConfigProviderF
}, },
mixpanelHost: { mixpanelHost: {
get: () => { get: () => {
return config.get('resinApiEndpoint') return config.get('apiEndpoint')
.then((apiEndpoint) => { .then((apiEndpoint) => {
return `${apiEndpoint}/mixpanel`; return `${apiEndpoint}/mixpanel`;
}); });
@ -182,7 +172,7 @@ export function createProviderFunctions(config: Config, db: DB): ConfigProviderF
return config.getMany([ return config.getMany([
'uuid', 'uuid',
'currentApiKey', 'currentApiKey',
'resinApiEndpoint', 'apiEndpoint',
'deltaEndpoint', 'deltaEndpoint',
'delta', 'delta',
'deltaRequestTimeout', 'deltaRequestTimeout',

View File

@ -166,7 +166,7 @@ module.exports = class DeviceState extends EventEmitter
@config.getMany([ @config.getMany([
'initialConfigSaved', 'listenPort', 'apiSecret', 'osVersion', 'osVariant', 'logsChannelSecret', 'initialConfigSaved', 'listenPort', 'apiSecret', 'osVersion', 'osVariant', 'logsChannelSecret',
'version', 'provisioned', 'resinApiEndpoint', 'connectivityCheckEnabled', 'legacyAppsPresent' 'version', 'provisioned', 'apiEndpoint', 'connectivityCheckEnabled', 'legacyAppsPresent'
]) ])
.then (conf) => .then (conf) =>
Promise.try => Promise.try =>
@ -200,8 +200,8 @@ module.exports = class DeviceState extends EventEmitter
.then => .then =>
@triggerApplyTarget({ initial: true }) @triggerApplyTarget({ initial: true })
initNetworkChecks: ({ resinApiEndpoint, connectivityCheckEnabled }) => initNetworkChecks: ({ apiEndpoint, connectivityCheckEnabled }) =>
network.startConnectivityCheck resinApiEndpoint, connectivityCheckEnabled, (connected) => network.startConnectivityCheck apiEndpoint, connectivityCheckEnabled, (connected) =>
@connected = connected @connected = connected
@config.on 'change', (changedConfig) -> @config.on 'change', (changedConfig) ->
if changedConfig.connectivityCheckEnabled? if changedConfig.connectivityCheckEnabled?
@ -242,7 +242,7 @@ module.exports = class DeviceState extends EventEmitter
setTarget: (target) -> setTarget: (target) ->
Promise.join( Promise.join(
@config.get('resinApiEndpoint'), @config.get('apiEndpoint'),
validateState(target), validateState(target),
(source) => (source) =>
@usingWriteLockTarget => @usingWriteLockTarget =>

View File

@ -25,7 +25,6 @@ const constants = {
configJsonPathOnHost: checkString(process.env.CONFIG_JSON_PATH), configJsonPathOnHost: checkString(process.env.CONFIG_JSON_PATH),
proxyvisorHookReceiver: proxyvisorHookReceiver:
checkString(process.env.RESIN_PROXYVISOR_HOOK_RECEIVER) || 'http://0.0.0.0:1337', checkString(process.env.RESIN_PROXYVISOR_HOOK_RECEIVER) || 'http://0.0.0.0:1337',
apiEndpointFromEnv: checkString(process.env.API_ENDPOINT),
configJsonNonAtomicPath: '/boot/config.json', configJsonNonAtomicPath: '/boot/config.json',
defaultPubnubSubscribeKey: process.env.DEFAULT_PUBNUB_SUBSCRIBE_KEY, defaultPubnubSubscribeKey: process.env.DEFAULT_PUBNUB_SUBSCRIBE_KEY,
defaultPubnubPublishKey: process.env.DEFAULT_PUBNUB_PUBLISH_KEY, defaultPubnubPublishKey: process.env.DEFAULT_PUBNUB_PUBLISH_KEY,

View File

@ -58,7 +58,7 @@ module.exports = class DockerUtils extends DockerToolbelt
fetchDeltaWithProgress: (imgDest, fullDeltaOpts, onProgress) => fetchDeltaWithProgress: (imgDest, fullDeltaOpts, onProgress) =>
{ {
deltaRequestTimeout, deltaApplyTimeout, deltaRetryCount, deltaRetryInterval, deltaRequestTimeout, deltaApplyTimeout, deltaRetryCount, deltaRetryInterval,
uuid, currentApiKey, deltaEndpoint, resinApiEndpoint, uuid, currentApiKey, deltaEndpoint, apiEndpoint,
deltaSource, deltaSourceId, deltaVersion, startFromEmpty = false deltaSource, deltaSourceId, deltaVersion, startFromEmpty = false
} = fullDeltaOpts } = fullDeltaOpts
retryCount = checkInt(deltaRetryCount) retryCount = checkInt(deltaRetryCount)
@ -80,7 +80,7 @@ module.exports = class DockerUtils extends DockerToolbelt
log("Starting delta to #{imgDest}") log("Starting delta to #{imgDest}")
Promise.join @getRegistryAndName(imgDest), @getRegistryAndName(deltaSource), (dstInfo, srcInfo) -> Promise.join @getRegistryAndName(imgDest), @getRegistryAndName(deltaSource), (dstInfo, srcInfo) ->
tokenEndpoint = "#{resinApiEndpoint}/auth/v1/token" tokenEndpoint = "#{apiEndpoint}/auth/v1/token"
opts = opts =
auth: auth:
user: 'd_' + uuid user: 'd_' + uuid