Merge pull request #760 from resin-io/balena-paths

Add /tmp/balena lock and handover paths and BALENA_ env vars
This commit is contained in:
Pablo Carranza Vélez 2018-10-18 11:33:44 +02:00 committed by GitHub
commit e2c7f1f2b3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 205 additions and 118 deletions

View File

@ -1,6 +1,6 @@
# Interacting with the Resin Supervisor
# Interacting with the balena Supervisor
The Resin Supervisor is resin.io's agent that runs on devices. Its main role is to ensure your app is running, and keep communications with the Resin API server.
The balena Supervisor is balena's agent that runs on devices. Its main role is to ensure your app is running, and keep communications with the balenaCloud API server.
The Supervisor itself has its own API, with means for user applications to communicate and execute some special actions that affect the host OS or the application itself. There are two main ways for the application to interact with the Supervisor: the update lockfile and the HTTP API.
@ -8,13 +8,13 @@ Only Supervisors after version 1.1.0 have this functionality, and some of the en
## HTTP API reference
The supervisor exposes an HTTP API on port 48484 (`RESIN_SUPERVISOR_PORT`).
The supervisor exposes an HTTP API on port 48484 (`BALENA_SUPERVISOR_PORT`).
**All endpoints require an apikey parameter, which is exposed to the application as `RESIN_SUPERVISOR_API_KEY`.**
**All endpoints require an apikey parameter, which is exposed to the application as `BALENA_SUPERVISOR_API_KEY`.**
The full address for the API, i.e. `"http://127.0.0.1:48484"`, is available as `RESIN_SUPERVISOR_ADDRESS`. **Always use these variables when communicating via the API, since address and port could change**.
The full address for the API, i.e. `"http://127.0.0.1:48484"`, is available as `BALENA_SUPERVISOR_ADDRESS`. **Always use these variables when communicating via the API, since address and port could change**.
Alternatively, the Resin API (api.resin.io) has a proxy endpoint at `POST /supervisor/<url>` (where `<url>` is one of the API URLs described below) from which you can send API commands to the supervisor remotely, using your Auth Token instead of your API key. Commands sent through the proxy can specify either an `appId` to send the request to all devices in an application, or a `deviceId` or `uuid` to send to a particular device. These requests default to POST unless you specify a `method` parameter (e.g. "GET"). In the examples below, we show how to use a uuid to specify a device, but in any of those you can replace `uuid` for a `deviceId` or `appId`.
Alternatively, the balena API (api.balena-cloud.com) has a proxy endpoint at `POST /supervisor/<url>` (where `<url>` is one of the API URLs described below) from which you can send API commands to the supervisor remotely, using your Auth Token instead of your API key. Commands sent through the proxy can specify either an `appId` to send the request to all devices in an application, or a `deviceId` or `uuid` to send to a particular device. These requests default to POST unless you specify a `method` parameter (e.g. "GET"). In the examples below, we show how to use a uuid to specify a device, but in any of those you can replace `uuid` for a `deviceId` or `appId`.
The API is versioned (currently at v1), except for `/ping`.
@ -32,7 +32,7 @@ Responds with a simple "OK", signaling that the supervisor is alive and well.
From the app on the device:
```bash
$ curl -X GET --header "Content-Type:application/json" \
"$RESIN_SUPERVISOR_ADDRESS/ping?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/ping?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:
```none
@ -44,7 +44,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>, "method": "GET"}' \
"https://api.resin.io/supervisor/ping"
"https://api.balena-cloud.com/supervisor/ping"
```
<hr>
@ -58,7 +58,7 @@ Responds with an empty 200 response. It implements the "identify device" feature
From the app on the device:
```bash
$ curl -X POST --header "Content-Type:application/json" \
"$RESIN_SUPERVISOR_ADDRESS/v1/blink?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/v1/blink?apikey=$BALENA_SUPERVISOR_API_KEY"
```
(Empty response)
@ -68,7 +68,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>}' \
"https://api.resin.io/supervisor/v1/blink"
"https://api.balena-cloud.com/supervisor/v1/blink"
```
<hr>
@ -92,7 +92,7 @@ From the app on the device:
```bash
$ curl -X POST --header "Content-Type:application/json" \
--data '{"force": true}' \
"$RESIN_SUPERVISOR_ADDRESS/v1/update?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/v1/update?apikey=$BALENA_SUPERVISOR_API_KEY"
```
(Empty response)
@ -101,7 +101,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>, "data": {"force": true}}' \
"https://api.resin.io/supervisor/v1/update"
"https://api.balena-cloud.com/supervisor/v1/update"
```
<hr>
@ -127,7 +127,7 @@ Can contain a `force` property, which if set to `true` will cause the update loc
From the app on the device:
```bash
$ curl -X POST --header "Content-Type:application/json" \
"$RESIN_SUPERVISOR_ADDRESS/v1/reboot?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/v1/reboot?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:
```json
@ -139,7 +139,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>}' \
"https://api.resin.io/supervisor/v1/reboot"
"https://api.balena-cloud.com/supervisor/v1/reboot"
```
<hr>
@ -165,7 +165,7 @@ Can contain a `force` property, which if set to `true` will cause the update loc
From the app on the device:
```bash
$ curl -X POST --header "Content-Type:application/json" \
"$RESIN_SUPERVISOR_ADDRESS/v1/shutdown?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/v1/shutdown?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:
@ -178,7 +178,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>}' \
"https://api.resin.io/supervisor/v1/shutdown"
"https://api.balena-cloud.com/supervisor/v1/shutdown"
```
<hr>
@ -211,7 +211,7 @@ From the app on the device:
```bash
$ curl -X POST --header "Content-Type:application/json" \
--data '{"appId": <appId>}' \
"$RESIN_SUPERVISOR_ADDRESS/v1/purge?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/v1/purge?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:
@ -224,7 +224,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>, "data": {"appId": <appId>}}' \
"https://api.resin.io/supervisor/v1/purge"
"https://api.balena-cloud.com/supervisor/v1/purge"
```
<hr>
@ -252,7 +252,7 @@ From the app on the device:
```bash
$ curl -X POST --header "Content-Type:application/json" \
--data '{"appId": <appId>}' \
"$RESIN_SUPERVISOR_ADDRESS/v1/restart?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/v1/restart?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:
@ -267,18 +267,18 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>, "data": {"appId": <appId>}}' \
"https://api.resin.io/supervisor/v1/restart"
"https://api.balena-cloud.com/supervisor/v1/restart"
```
### POST /v1/regenerate-api-key
Invalidates the current `RESIN_SUPERVISOR_API_KEY` and generates a new one. Responds with the new API key, but **the application will be restarted on the next update cycle** to update the API key environment variable.
Invalidates the current `BALENA_SUPERVISOR_API_KEY` and generates a new one. Responds with the new API key, but **the application will be restarted on the next update cycle** to update the API key environment variable.
#### Examples:
From the app on the device:
```bash
$ curl -X POST --header "Content-Type:application/json" \
"$RESIN_SUPERVISOR_ADDRESS/v1/regenerate-api-key?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/v1/regenerate-api-key?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:
@ -292,7 +292,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>}' \
"https://api.resin.io/supervisor/v1/regenerate-api-key"
"https://api.balena-cloud.com/supervisor/v1/regenerate-api-key"
```
<hr>
@ -300,7 +300,7 @@ $ curl -X POST --header "Content-Type:application/json" \
### GET /v1/device
Introduced in supervisor v1.6.
Returns the current device state, as reported to the Resin API and with some extra fields added to allow control over pending/locked updates.
Returns the current device state, as reported to the balenaCloud API and with some extra fields added to allow control over pending/locked updates.
The state is a JSON object that contains some or all of the following:
* `api_port`: Port on which the supervisor is listening.
* `commit`: Hash of the current commit of the application that is running.
@ -309,9 +309,9 @@ The state is a JSON object that contains some or all of the following:
* `download_progress`: Amount of the application image that has been downloaded, expressed as a percentage. If the update has already been downloaded, this will be `null`.
* `os_version`: Version of the host OS running on the device.
* `supervisor_version`: Version of the supervisor running on the device.
* `update_pending`: This one is not reported to the Resin API. It's a boolean that will be true if the supervisor has detected there is a pending update.
* `update_downloaded`: Not reported to the Resin API either. Boolean that will be true if a pending update has already been downloaded.
* `update_failed`: Not reported to the Resin API. Boolean that will be true if the supervisor has tried to apply a pending update but failed (i.e. if the app was locked, there was a network failure or anything else went wrong).
* `update_pending`: This one is not reported to the balenaCloud API. It's a boolean that will be true if the supervisor has detected there is a pending update.
* `update_downloaded`: Not reported to the balenaCloud API either. Boolean that will be true if a pending update has already been downloaded.
* `update_failed`: Not reported to the balenaCloud API. Boolean that will be true if the supervisor has tried to apply a pending update but failed (i.e. if the app was locked, there was a network failure or anything else went wrong).
Other attributes may be added in the future, and some may be missing or null if they haven't been set yet.
@ -319,7 +319,7 @@ Other attributes may be added in the future, and some may be missing or null if
From the app on the device:
```bash
$ curl -X GET --header "Content-Type:application/json" \
"$RESIN_SUPERVISOR_ADDRESS/v1/device?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/v1/device?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:
```json
@ -331,7 +331,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>, "method": "GET"}' \
"https://api.resin.io/supervisor/v1/device"
"https://api.balena-cloud.com/supervisor/v1/device"
```
<hr>
@ -356,7 +356,7 @@ From the app on the device:
```bash
$ curl -X POST --header "Content-Type:application/json" \
"$RESIN_SUPERVISOR_ADDRESS/v1/apps/<appId>/stop?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/v1/apps/<appId>/stop?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:
@ -371,7 +371,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>}' \
"https://api.resin.io/supervisor/v1/apps/<appId>/stop"
"https://api.balena-cloud.com/supervisor/v1/apps/<appId>/stop"
```
<hr>
@ -392,7 +392,7 @@ From the app on the device:
```bash
$ curl -X POST --header "Content-Type:application/json" \
"$RESIN_SUPERVISOR_ADDRESS/v1/apps/<appId>/start?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/v1/apps/<appId>/start?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:
@ -407,7 +407,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>}' \
"https://api.resin.io/supervisor/v1/apps/<appId>/start"
"https://api.balena-cloud.com/supervisor/v1/apps/<appId>/start"
```
<hr>
@ -417,7 +417,7 @@ $ curl -X POST --header "Content-Type:application/json" \
Introduced in supervisor v1.8.
Returns the application running on the device
The app is a JSON object that contains the following:
* `appId`: The id of the app as per the Resin API.
* `appId`: The id of the app as per the balenaCloud API.
* `commit`: Application commit that is running.
* `imageId`: The docker image of the current application build.
* `containerId`: ID of the docker container of the running app.
@ -431,11 +431,11 @@ This is only supported on single-container devices, and will return 400 on devic
From the app on the device:
```bash
$ curl -X GET --header "Content-Type:application/json" \
"$RESIN_SUPERVISOR_ADDRESS/v1/apps/<appId>?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/v1/apps/<appId>?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:
```json
{"appId": 3134,"commit":"414e65cd378a69a96f403b75f14b40b55856f860","imageId":"registry.resin.io/superapp/414e65cd378a69a96f403b75f14b40b55856f860","containerId":"e5c1eace8b4e","env":{"FOO":"bar"}}
{"appId": 3134,"commit":"414e65cd378a69a96f403b75f14b40b55856f860","imageId":"registry.balena-cloud.com/superapp/414e65cd378a69a96f403b75f14b40b55856f860","containerId":"e5c1eace8b4e","env":{"FOO":"bar"}}
```
Remotely via the API proxy:
@ -443,7 +443,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>, "method": "GET"}' \
"https://api.resin.io/supervisor/v1/apps/<appId>"
"https://api.balena-cloud.com/supervisor/v1/apps/<appId>"
```
<hr>
@ -453,7 +453,7 @@ $ curl -X POST --header "Content-Type:application/json" \
Added in supervisor v6.5.0.
Used internally to check whether the supervisor is running correctly, according to some heuristics that help determine
whether the internal components, application updates and reporting to the Resin API are functioning.
whether the internal components, application updates and reporting to the balenaCloud API are functioning.
Responds with an empty 200 response if the supervisor is healthy, or a 500 status code if something is not working
correctly.
@ -461,7 +461,7 @@ correctly.
#### Examples:
From the app on the device:
```bash
$ curl "$RESIN_SUPERVISOR_ADDRESS/v1/healthy"
$ curl "$BALENA_SUPERVISOR_ADDRESS/v1/healthy"
```
(Empty response)
@ -470,7 +470,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>, "method": "GET"}' \
"https://api.resin.io/supervisor/v1/healthy"
"https://api.balena-cloud.com/supervisor/v1/healthy"
```
<hr>
@ -508,9 +508,9 @@ without changing proxy settings and viceversa.
In the proxy settings, `type`, `ip`, `port`, `login` and `password` are the settings for the proxy redirector to
be able to connnect to the proxy, based on how [redsocks.conf](https://github.com/darkk/redsocks/blob/master/redsocks.conf.example) works. `type` can be `socks4`, `socks5`, `http-connect` or `http-relay` (not all proxies are
guaranteed to work, especially if they block connections that the resin services may require).
guaranteed to work, especially if they block connections that the balena services may require).
Keep in mind that, even if transparent proxy redirection will take effect immediately after the API call (i.e. all new connections will go through the proxy), open connections will not be closed. So, if for example, the device has managed to connect to the resin VPN without the proxy, it will stay connected directly without trying to reconnect through the proxy, unless the connection breaks - any reconnection attempts will then go through the proxy. To force *all* connections to go through the proxy, the best way is to reboot the device (see the /v1/reboot endpoint). In most networks were no connections to the Internet can be made if not through a proxy, this should not be necessary (as there will be no open connections before configuring the proxy settings).
Keep in mind that, even if transparent proxy redirection will take effect immediately after the API call (i.e. all new connections will go through the proxy), open connections will not be closed. So, if for example, the device has managed to connect to the balenaCloud VPN without the proxy, it will stay connected directly without trying to reconnect through the proxy, unless the connection breaks - any reconnection attempts will then go through the proxy. To force *all* connections to go through the proxy, the best way is to reboot the device (see the /v1/reboot endpoint). In most networks were no connections to the Internet can be made if not through a proxy, this should not be necessary (as there will be no open connections before configuring the proxy settings).
The "noProxy" setting for the proxy is an optional array of IP addresses/subnets that should not be routed through the
proxy. Keep in mind that local/reserved subnets are already [excluded by resinOS automatically](https://github.com/resin-os/meta-resin/blob/master/meta-resin-common/recipes-connectivity/resin-proxy-config/resin-proxy-config/resin-proxy-config#L48).
@ -522,7 +522,7 @@ From the app on the device:
```bash
$ curl -X PATCH --header "Content-Type:application/json" \
--data '{"network": {"hostname": "newhostname"}}' \
"$RESIN_SUPERVISOR_ADDRESS/v1/device/host-config?apikey=$RESIN_SUPERVISOR_API_KEY"
"$BALENA_SUPERVISOR_ADDRESS/v1/device/host-config?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:
@ -535,7 +535,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>, "method": "PATCH", "data": {"network": {"hostname": "newhostname"}}}' \
"https://api.resin.io/supervisor/v1/device/host-config"
"https://api.balena-cloud.com/supervisor/v1/device/host-config"
```
<hr>
@ -552,7 +552,7 @@ Please refer to the PATCH endpoint above for details on the behavior and meaning
#### Examples:
From the app on the device:
```bash
$ curl "$RESIN_SUPERVISOR_ADDRESS/v1/device/host-config?apikey=$RESIN_SUPERVISOR_API_KEY"
$ curl "$BALENA_SUPERVISOR_ADDRESS/v1/device/host-config?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:
@ -565,7 +565,7 @@ Remotely via the API proxy:
$ curl -X POST --header "Content-Type:application/json" \
--header "Authorization: Bearer <auth token>" \
--data '{"uuid": <uuid>, "method": "GET"}' \
"https://api.resin.io/supervisor/v1/device/host-config"
"https://api.balena-cloud.com/supervisor/v1/device/host-config"
```
### GET /v2/applications/state
@ -577,7 +577,7 @@ current state of the supervisor, and not the target state.
From the user container:
```bash
$ curl "$RESIN_SUPERVISOR_ADDRESS/v2/applications/state?apikey=$RESIN_SUPERVISOR_API_KEY"
$ curl "$BALENA_SUPERVISOR_ADDRESS/v2/applications/state?apikey=$BALENA_SUPERVISOR_API_KEY"
```
Response:

View File

@ -1,48 +1,47 @@
---
title: Application update locks
excerpt: Locking application updates on your resin.io devices
excerpt: Locking application updates on your balenaOS devices
---
# Application update locks
Locking updates means that the resin.io device supervisor will not be able to kill your application. This is meant to be used at critical sections of your code where you don't want to be interrupted, or to ensure that updates are only installed at certain times.
Locking updates means that the balena supervisor will not be able to kill your application. This is meant to be used at critical sections of your code where you don't want to be interrupted, or to ensure that updates are only installed at certain times.
In order to do this, users can create a lockfile called `resin-updates.lock` in a way that it has exclusive access, which will prevent the device supervisor from killing and restarting the app. As with any other lockfile, the supervisor itself will create such a file before killing the app, so you should only create it in exclusive mode. This means that the lockfile should only be created if it doesn't already exist. The exclusive access is achieved by opening the lockfile with the [O_EXCL and O_CREAT flags](https://linux.die.net/man/3/open), and several tools exist to simplify this process with examples given [below](#creating-the-lockfile).
In order to do this, users can create a lockfile in a way that it has exclusive access, which will prevent the device supervisor from killing and restarting the app. As with any other lockfile, the supervisor itself will create such a file before killing the app, so you should only create it in exclusive mode. This means that the lockfile should only be created if it doesn't already exist. The exclusive access is achieved by opening the lockfile with the [O_EXCL and O_CREAT flags](https://linux.die.net/man/3/open), and several tools exist to simplify this process with examples given [below](#creating-the-lockfile).
The presence of a lockfile will ensure that your application does not get killed, but updates will still be downloaded by the supervisor, ready to be applied once the lockfile no longer exists.
### Location of the lockfile
In supervisor v4.0.0 and higher, the lock is located at `/tmp/resin/resin-updates.lock`. This lock is cleared automatically when the device reboots, so the user app must take it every time it starts up.
On devices running supervisor 7.22.0 and higher, the lockfile is located at `/tmp/balena/updates.lock`. This lock is cleared automatically when the device reboots, so the user app must take it every time it starts up.
Older supervisors have the lock at `/data/resin-updates.lock`. This lock is still supported on devices running resinOS 1.X. In this case, newer supervisors will try to take *both* locks before killing the application.
On older devices (with v4.0.0 <= supervisor version < v7.22.0) the lock is located at `/tmp/resin/resin-updates.lock`. The latest supervisor versions still take the lock at this legacy path for backwards compatibility.
The old lock has the problem that the supervisor has to clear whenever it starts up to avoid deadlocks. If the user app
Legacy supervisors (< v4.0.0) have the lock at `/data/resin-updates.lock`. This lock is only supported on devices running resinOS 1.X.
This old lock has the problem that the supervisor has to clear whenever it starts up to avoid deadlocks. If the user app
has taken the lock before the supervisor starts up, the lock will be cleared and the app can operate under the false
assumption that updates are locked (see [issue #20](https://github.com/resin-io/resin-supervisor/issues/20)). We therefore strongly recommend switching to the new lock location as soon as possible.
For supervisors >= v4.0.0 and any OS that is not resinOS 1.x, the old lock location is completely ignored.
### Creating the lockfile
There are many different tools and libraries to provide proper lockfile functionality and a few common examples are shown below.
__Note:__ Just creating the lockfile, for example by using `touch /tmp/resin/resin-updates.lock`, is not adequate to prevent updates. A file created in this way won't have the exclusive access flag set, and thus does not provide reliable locking.
__Note:__ Just creating the lockfile, for example by using `touch /tmp/balena/updates.lock`, is not adequate to prevent updates. A file created in this way won't have the exclusive access flag set, and thus does not provide reliable locking.
#### Shell
One simple way to create a lockfile is using [lockfile](https://linux.die.net/man/1/lockfile) (available for example in Debian from the `procmail` package):
```shell
lockfile /tmp/resin/resin-updates.lock
lockfile /tmp/balena/updates.lock
# ... (do things)
rm -f /tmp/resin/resin-updates.lock
rm -f /tmp/balena/updates.lock
```
Another tool is [flock](https://linux.die.net/man/1/flock) (available for example in Debian from the `linux-utils` package):
```shell
flock /tmp/resin/resin-updates.lock -c '... (command to run while locked)'
flock /tmp/balena/updates.lock -c '... (command to run while locked)'
```
For more examples and explanation of the functionality, check the links to the specific tools above.
@ -53,7 +52,7 @@ Using the [`lockfile` library](https://www.npmjs.com/package/lockfile), the lock
```coffeescript
lockFile = require 'lockfile'
lockFile.lock '/tmp/resin/resin-updates.lock', (err) ->
lockFile.lock '/tmp/balena/updates.lock', (err) ->
# A non-null err probably means the supervisor is about to kill us
throw new Error('Could not acquire lock: ', err) if err?
@ -61,7 +60,7 @@ lockFile.lock '/tmp/resin/resin-updates.lock', (err) ->
doTheHarlemShake()
# Now we release the lock, and we can be killed again
lockFile.unlock '/tmp/resin/resin-updates.lock', (err) ->
lockFile.unlock '/tmp/balena/updates.lock', (err) ->
# If err is not null here, something went really wrong
throw err if err?
```
@ -71,7 +70,7 @@ lockFile.lock '/tmp/resin/resin-updates.lock', (err) ->
In Python you can use the [`lockfile` library](http://pythonhosted.org/lockfile/lockfile.html#examples)
```python
from lockfile import LockFile
lock = LockFile("/tmp/resin/resin-updates.lock")
lock = LockFile("/tmp/balena/updates.lock")
with lock:
print lock.path, 'is locked.'
```
@ -79,8 +78,8 @@ Check the link for more examples and other Python libraries that provide locking
### Overriding the lock
The update lock can be overriden in case you need to force an update, for instance, if your app has hung in a critical section.
The update lock can be overridden in case you need to force an update, for instance, if your app has hung in a critical section.
The way to do this is hitting the `/v1/update` endpoint of the [supervisor HTTP API](./API.md), with `{ "force": true }` as body.
The lock can also be overriden by setting the app's `RESIN_SUPERVISOR_OVERRIDE_LOCK` configuration variable to "1".
The lock can also be overridden by setting the app's `BALENA_SUPERVISOR_OVERRIDE_LOCK` configuration variable to "1".

View File

@ -8,8 +8,15 @@ rm -f /var/run/avahi-daemon/pid
/etc/init.d/dbus-1 start
/etc/init.d/avahi-daemon start
[ -d /mnt/root/tmp/resin-supervisor ] ||
mkdir -p /mnt/root/tmp/resin-supervisor
# If the legacy /tmp/resin-supervisor exists on the host, a container might
# already be using to take an update lock, so we symlink it to the new
# location so that the supervisor can see it
[ -d /mnt/root/tmp/resin-supervisor ] &&
( [ -d /mnt/root/tmp/balena-supervisor ] || ln ./resin-supervisor /mnt/root/tmp/balena-supervisor )
# Otherwise, if the lockfiles directory doesn't exist
[ -d /mnt/root/tmp/balena-supervisor ] ||
mkdir -p /mnt/root/tmp/balena-supervisor
# If DOCKER_ROOT isn't set then default it
if [ -z "${DOCKER_ROOT}" ]; then

View File

@ -227,16 +227,23 @@ module.exports = class ServiceManager extends EventEmitter
timeout = checkInt(timeout, positive: true) ? 60000
deadline = Date.now() + timeout
killmePath = service.killmeFullPathOnHost()
handoverCompletePaths = service.handoverCompleteFullPathsOnHost()
wait = ->
fs.statAsync(killmePath)
Promise.any _.map handoverCompletePaths, (file) ->
fs.statAsync(file)
.then ->
fs.unlinkAsync(killmePath).catch(_.noop)
.catch (err) ->
fs.unlinkAsync(file).catch(_.noop)
.catch ->
if Date.now() < deadline
Promise.delay(pollInterval).then(wait)
else
console.log('Handover timeout has passed, assuming handover was completed')
console.log('Waiting for handover to be completed')
wait()
.then ->
console.log('Handover complete')
prepareForHandover: (service) =>
@get(service)

View File

@ -19,6 +19,7 @@ import * as ComposeUtils from './utils';
import * as updateLock from '../lib/update-lock';
import { sanitiseComposeConfig } from './sanitise';
import * as constants from '../lib/constants';
export class Service {
@ -655,6 +656,17 @@ export class Service {
return _.reject(validVolumes, _.isNil);
}
public handoverCompleteFullPathsOnHost(): string[] {
return [
path.join(this.handoverCompletePathOnHost(), 'handover-complete'),
path.join(this.handoverCompletePathOnHost(), 'resin-kill-me'),
];
}
private handoverCompletePathOnHost(): string {
return path.join(constants.rootMountPoint, updateLock.lockPath(this.appId || 0, this.serviceName || ''));
}
private getBindsAndVolumes(): {
binds: string[],
volumes: { [volName: string]: { } }
@ -699,20 +711,25 @@ export class Service {
appId: number,
serviceName: string,
): { [envVarName: string]: string } {
let env = _.defaults(environment, {
RESIN_APP_ID: appId.toString(),
RESIN_APP_NAME: options.appName,
RESIN_SERVICE_NAME: serviceName,
RESIN_DEVICE_UUID: options.uuid,
RESIN_DEVICE_TYPE: options.deviceType,
RESIN_HOST_OS_VERSION: options.osVersion,
RESIN_SUPERVISOR_VERSION: options.version,
RESIN_APP_LOCK_PATH: '/tmp/resin/resin-updates.lock',
RESIN_SERVICE_KILL_ME_PATH: '/tmp/resin/resin-kill-me',
RESIN: '1',
USER: 'root',
});
let defaultEnv: { [ envVarName: string]: string } = {};
for(let namespace of [ 'BALENA', 'RESIN' ]){
_.assign(defaultEnv, _.mapKeys({
APP_ID: appId.toString(),
APP_NAME: options.appName,
SERVICE_NAME: serviceName,
DEVICE_UUID: options.uuid,
DEVICE_TYPE: options.deviceType,
HOST_OS_VERSION: options.osVersion,
SUPERVISOR_VERSION: options.version,
APP_LOCK_PATH: '/tmp/balena/updates.lock',
}, (_val, key) => `${namespace}_${key}`));
defaultEnv[namespace] = '1';
}
defaultEnv['RESIN_SERVICE_KILL_ME_PATH'] = '/tmp/balena/handover-complete';
defaultEnv['BALENA_SERVICE_HANDOVER_COMPLETE_PATH'] = '/tmp/balena/handover-complete';
defaultEnv['USER'] = 'root';
let env = _.defaults(environment, defaultEnv);
const imageInfoEnv = _.get(options.imageInfo, 'Config.Env', []);
env = _.defaults(env, conversions.envArrayToObject(imageInfoEnv));
return env;
@ -819,6 +836,7 @@ export class Service {
private static defaultBinds(appId: number, serviceName: string): string[] {
return [
`${updateLock.lockPath(appId, serviceName)}:/tmp/resin`,
`${updateLock.lockPath(appId, serviceName)}:/tmp/balena`,
];
}

View File

@ -18,13 +18,13 @@ const constants = {
privateAppEnvVars: [
'RESIN_SUPERVISOR_API_KEY',
'RESIN_API_KEY',
'BALENA_SUPERVISOR_API_KEY',
'BALENA_API_KEY',
],
dataPath: checkString(process.env.RESIN_DATA_PATH) || '/resin-data',
bootMountPointFromEnv,
bootMountPoint: bootMountPointFromEnv || '/boot',
configJsonPathOnHost: checkString(process.env.CONFIG_JSON_PATH),
proxyvisorHookReceiver:
checkString(process.env.RESIN_PROXYVISOR_HOOK_RECEIVER) || 'http://0.0.0.0:1337',
proxyvisorHookReceiver: 'http://0.0.0.0:1337',
configJsonNonAtomicPath: '/boot/config.json',
defaultMixpanelToken: process.env.DEFAULT_MIXPANEL_TOKEN,
supervisorNetworkInterface: supervisorNetworkInterface,

View File

@ -11,13 +11,14 @@ constants = require './constants'
{ ENOENT } = require './errors'
baseLockPath = (appId) ->
return path.join('/tmp/resin-supervisor/services', appId.toString())
return path.join('/tmp/balena-supervisor/services', appId.toString())
exports.lockPath = (appId, serviceName) ->
return path.join(baseLockPath(appId), serviceName)
lockFileOnHost = (appId, serviceName) ->
return path.join(constants.rootMountPoint, exports.lockPath(appId, serviceName), 'resin-updates.lock')
lockFilesOnHost = (appId, serviceName) ->
return _.map [ 'updates.lock', 'resin-updates.lock' ], (fileName) ->
path.join(constants.rootMountPoint, exports.lockPath(appId, serviceName), fileName)
exports.UpdatesLockedError = class UpdatesLockedError extends TypedError
locksTaken = {}
@ -46,7 +47,7 @@ exports.lock = do ->
fs.readdirAsync(theLockDir)
.catchReturn(ENOENT, [])
.mapSeries (serviceName) ->
tmpLockName = lockFileOnHost(appId, serviceName)
Promise.mapSeries lockFilesOnHost(appId, serviceName), (tmpLockName) ->
Promise.try ->
lockFile.unlockAsync(tmpLockName) if force == true
.then ->

View File

@ -18,7 +18,7 @@ configs = {
}
}
describe 'compose/service.coffee', ->
describe 'compose/service', ->
it 'extends environment variables properly', ->
extendEnvVarsOpts = {
@ -52,9 +52,19 @@ describe 'compose/service.coffee', ->
RESIN_HOST_OS_VERSION: 'Resin OS 2.0.2'
RESIN_SERVICE_NAME: 'serviceName'
RESIN_SUPERVISOR_VERSION: 'v1.0.0'
RESIN_APP_LOCK_PATH: '/tmp/resin/resin-updates.lock'
RESIN_SERVICE_KILL_ME_PATH: '/tmp/resin/resin-kill-me'
RESIN_APP_LOCK_PATH: '/tmp/balena/updates.lock'
RESIN_SERVICE_KILL_ME_PATH: '/tmp/balena/handover-complete'
RESIN: '1'
BALENA_APP_ID: '23'
BALENA_APP_NAME: 'awesomeApp'
BALENA_DEVICE_UUID: '1234'
BALENA_DEVICE_TYPE: 'raspberry-pi'
BALENA_HOST_OS_VERSION: 'Resin OS 2.0.2'
BALENA_SERVICE_NAME: 'serviceName'
BALENA_SUPERVISOR_VERSION: 'v1.0.0'
BALENA_APP_LOCK_PATH: '/tmp/balena/updates.lock'
BALENA_SERVICE_HANDOVER_COMPLETE_PATH: '/tmp/balena/handover-complete'
BALENA: '1'
USER: 'root'
})
@ -68,7 +78,8 @@ describe 'compose/service.coffee', ->
}, { appName: 'foo' })
binds = Service.defaultBinds(s.appId, s.serviceName)
expect(binds).to.deep.equal([
'/tmp/resin-supervisor/services/1234/foo:/tmp/resin'
'/tmp/balena-supervisor/services/1234/foo:/tmp/resin'
'/tmp/balena-supervisor/services/1234/foo:/tmp/balena'
])
it 'produces the correct port bindings and exposed ports', ->

View File

@ -34,7 +34,8 @@
"ExecIDs": null,
"HostConfig": {
"Binds": [
"/tmp/resin-supervisor/services/1011165/main:/tmp/resin"
"/tmp/balena-supervisor/services/1011165/main:/tmp/resin",
"/tmp/balena-supervisor/services/1011165/main:/tmp/balena"
],
"ContainerIDFile": "",
"LogConfig": {
@ -114,11 +115,19 @@
"Mounts": [
{
"Type": "bind",
"Source": "/tmp/resin-supervisor/services/1011165/main",
"Source": "/tmp/balena-supervisor/services/1011165/main",
"Destination": "/tmp/resin",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
},
{
"Type": "bind",
"Source": "/tmp/balena-supervisor/services/1011165/main",
"Destination": "/tmp/balena",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
],
"Config": {
@ -139,9 +148,19 @@
"RESIN_DEVICE_TYPE=raspberrypi3",
"RESIN_HOST_OS_VERSION=Resin OS 2.13.6+rev1",
"RESIN_SUPERVISOR_VERSION=7.18.0",
"RESIN_APP_LOCK_PATH=/tmp/resin/resin-updates.lock",
"RESIN_SERVICE_KILL_ME_PATH=/tmp/resin/resin-kill-me",
"RESIN_APP_LOCK_PATH=/tmp/balena/updates.lock",
"RESIN_SERVICE_KILL_ME_PATH=/tmp/balena/handover-complete",
"RESIN=1",
"BALENA_APP_ID=1011165",
"BALENA_APP_NAME=supervisortest",
"BALENA_SERVICE_NAME=main",
"BALENA_DEVICE_UUID=a7feb967fac7f559ccf2a006a36bcf5d",
"BALENA_DEVICE_TYPE=raspberrypi3",
"BALENA_HOST_OS_VERSION=Resin OS 2.13.6+rev1",
"BALENA_SUPERVISOR_VERSION=7.18.0",
"BALENA_APP_LOCK_PATH=/tmp/balena/updates.lock",
"BALENA_SERVICE_HANDOVER_COMPLETE_PATH=/tmp/balena/handover-complete",
"BALENA=1",
"USER=root",
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],

View File

@ -35,7 +35,8 @@
"ExecIDs": null,
"HostConfig": {
"Binds": [
"/tmp/resin-supervisor/services/1011165/main:/tmp/resin"
"/tmp/balena-supervisor/services/1011165/main:/tmp/resin",
"/tmp/balena-supervisor/services/1011165/main:/tmp/balena"
],
"ContainerIDFile": "",
"LogConfig": {
@ -114,11 +115,19 @@
"Mounts": [
{
"Type": "bind",
"Source": "/tmp/resin-supervisor/services/1011165/main",
"Source": "/tmp/balena-supervisor/services/1011165/main",
"Destination": "/tmp/resin",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
},
{
"Type": "bind",
"Source": "/tmp/balena-supervisor/services/1011165/main",
"Destination": "/tmp/balena",
"Mode": "",
"RW": true,
"Propagation": "rprivate"
}
],
"Config": {
@ -139,9 +148,19 @@
"RESIN_DEVICE_TYPE=raspberrypi3",
"RESIN_HOST_OS_VERSION=Resin OS 2.13.6+rev1",
"RESIN_SUPERVISOR_VERSION=7.16.6",
"RESIN_APP_LOCK_PATH=/tmp/resin/resin-updates.lock",
"RESIN_SERVICE_KILL_ME_PATH=/tmp/resin/resin-kill-me",
"RESIN_APP_LOCK_PATH=/tmp/balena/updates.lock",
"RESIN_SERVICE_KILL_ME_PATH=/tmp/balena/handover-complete",
"RESIN=1",
"BALENA_APP_ID=1011165",
"BALENA_APP_NAME=supervisortest",
"BALENA_SERVICE_NAME=main",
"BALENA_DEVICE_UUID=7dadabd4edec3067948d5952c2f2f26f",
"BALENA_DEVICE_TYPE=raspberrypi3",
"BALENA_HOST_OS_VERSION=Resin OS 2.13.6+rev1",
"BALENA_SUPERVISOR_VERSION=7.16.6",
"BALENA_APP_LOCK_PATH=/tmp/balena/updates.lock",
"BALENA_SERVICE_HANDOVER_COMPLETE_PATH=/tmp/balena/handover-complete",
"BALENA=1",
"USER=root",
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"UDEV=on"

View File

@ -336,7 +336,8 @@ currentState[0] = {
privileged: false
restart: 'always'
volumes: [
'/tmp/resin-supervisor/services/1234/aservice:/tmp/resin'
'/tmp/balena-supervisor/services/1234/aservice:/tmp/resin',
'/tmp/balena-supervisor/services/1234/aservice:/tmp/balena'
]
labels: {
'io.resin.app-id': '1234'
@ -365,7 +366,8 @@ currentState[0] = {
'ADDITIONAL_ENV_VAR': 'foo'
}
volumes: [
'/tmp/resin-supervisor/services/1234/anotherService:/tmp/resin'
'/tmp/balena-supervisor/services/1234/anotherService:/tmp/resin',
'/tmp/balena-supervisor/services/1234/anotherService:/tmp/balena'
]
privileged: false
restart: 'always'
@ -445,7 +447,8 @@ currentState[2] = {
privileged: false
restart: 'always'
volumes: [
'/tmp/resin-supervisor/services/1234/aservice:/tmp/resin'
'/tmp/balena-supervisor/services/1234/aservice:/tmp/resin',
'/tmp/balena-supervisor/services/1234/aservice:/tmp/balena'
]
labels: {
'io.resin.app-id': '1234'
@ -501,7 +504,8 @@ currentState[3] = {
privileged: false
restart: 'always'
volumes: [
'/tmp/resin-supervisor/services/1234/aservice:/tmp/resin'
'/tmp/balena-supervisor/services/1234/aservice:/tmp/resin',
'/tmp/balena-supervisor/services/1234/aservice:/tmp/balena'
]
labels: {
'io.resin.app-id': '1234'
@ -534,7 +538,8 @@ currentState[3] = {
privileged: false
restart: 'always'
volumes: [
'/tmp/resin-supervisor/services/1234/aservice:/tmp/resin'
'/tmp/balena-supervisor/services/1234/aservice:/tmp/resin',
'/tmp/balena-supervisor/services/1234/aservice:/tmp/balena'
]
labels: {
'io.resin.app-id': '1234'
@ -586,7 +591,8 @@ currentState[4] = {
'ADDITIONAL_ENV_VAR': 'foo'
}
volumes: [
'/tmp/resin-supervisor/services/1234/anotherService:/tmp/resin'
'/tmp/balena-supervisor/services/1234/anotherService:/tmp/resin',
'/tmp/balena-supervisor/services/1234/anotherService:/tmp/balena'
]
privileged: false
restart: 'always'