@flowfuse/driver-docker 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.eslintrc ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "root": true,
3
+ "env": {
4
+ "browser": true,
5
+ "commonjs": true,
6
+ "es2021": true,
7
+ "mocha": true
8
+ },
9
+ "extends": [
10
+ "standard"
11
+ ],
12
+ "parserOptions": {
13
+ "ecmaVersion": 12
14
+ },
15
+ "rules": {
16
+ "indent": ["error", 4],
17
+ "object-shorthand": ["error"]
18
+ }
19
+ }
@@ -0,0 +1,24 @@
1
+ name: Default Build & Test
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ build:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ node-version: [16.x]
15
+ steps:
16
+ - uses: actions/checkout@v3
17
+ - name: Use Node.js ${{ matrix.node-version }}
18
+ uses: actions/setup-node@v3
19
+ with:
20
+ node-version: ${{ matrix.node-version }}
21
+ - name: Install Dependencies
22
+ run: npm ci
23
+ - name: Run lint
24
+ run: npm run lint
@@ -0,0 +1,10 @@
1
+ name: Project automations
2
+ on:
3
+ issues:
4
+ types:
5
+ - opened
6
+ jobs:
7
+ add_to_product_board:
8
+ uses: flowfuse/.github/.github/workflows/project-automation.yml@main
9
+ secrets:
10
+ token: ${{ secrets.PROJECT_ACCESS_TOKEN }}
@@ -0,0 +1,18 @@
1
+ name: Release Published
2
+ on:
3
+ push:
4
+ tags:
5
+ - 'v*.*.*'
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v1
12
+ - uses: actions/setup-node@v1
13
+ with:
14
+ node-version: 16
15
+ - run: npm ci --omit dev
16
+ - uses: JS-DevTools/npm-publish@v1
17
+ with:
18
+ token: ${{ secrets.NPM_PUBLISH_TOKEN }}
package/CHANGELOG.md ADDED
@@ -0,0 +1,108 @@
1
+ #### 1.14.0: Release
2
+
3
+ - Add support for Private CA (#75) @hardillb
4
+
5
+ #### 1.13.0: Release
6
+
7
+ - Expose cpu/mem limits (#73) @hardillb
8
+ - Update ff references in package.json (#72) @knolleary
9
+ - Reusable workflow reference name change (#71) @ppawlowski
10
+
11
+ #### 1.12.0: Release
12
+
13
+
14
+ #### 1.11.0: Release
15
+
16
+ - Bump word-wrap from 1.2.3 to 1.2.5 (#68) @app/dependabot
17
+
18
+ #### 1.10.1: Release
19
+
20
+ - Fix editor path (#66) @hardillb
21
+
22
+ #### 1.10.0: Release
23
+
24
+ - Chore: Set root flag in eslint (#63) @Pezmc
25
+
26
+ #### 1.9.0: Release
27
+
28
+ - Allow hosting domain to be changed (#60) @hardillb
29
+ - Add package-lock.json (#61) @Pezmc
30
+
31
+ #### 1.8.0: Release
32
+
33
+ - Fix Delete suspended projects (#57) @hardillb
34
+
35
+ #### 1.7.0: Release
36
+
37
+
38
+ #### 1.6.0: Release
39
+
40
+
41
+ #### 1.5.0: Release
42
+
43
+
44
+ #### 1.4.0: Release
45
+
46
+
47
+ #### 1.3.0: Release
48
+
49
+
50
+ #### 1.2.0: Release
51
+
52
+
53
+ #### 1.1.0: Release
54
+
55
+ - Add getDefaultStackProperies (#46) @hardillb
56
+ - Add flags to inhibit TCP/UDP inbound connections (#45) @Steve-Mcl
57
+ - Add guard for deleting suspended projects (#44) @hardillb
58
+
59
+ #### 1.0.0: Release
60
+
61
+ - Add LetsEncypt env var if https enabled
62
+ - Update eslint (#42) @knolleary
63
+
64
+ #### 0.10.0: Release
65
+
66
+
67
+ #### 0.9.0: Release
68
+
69
+ - Use project.safeName (#37) @hardillb
70
+
71
+ #### 0.8.0: Release
72
+
73
+ - Add licenseType to launcher env (#34) @knolleary
74
+ - add env var FORGE_TEAM_ID (#33) @Steve-Mcl
75
+ - Better start up exp 586 (#32) @hardillb
76
+ - Add FORGE_BROKER_* credentials to launcher env (#30) @knolleary
77
+
78
+ #### 0.7.0: Release
79
+
80
+ - Fix log call when revoking Node-RED sessions (#29) @knolleary
81
+
82
+ #### 0.6.0: Release
83
+
84
+ - Map FlowForge logout to nodered auth/revoke (#24) @Steve-Mcl
85
+ - Throw proper errors when actions performed on unknown project (#25) @knolleary
86
+ - Add FORGE_NR_SECRET env if project has credSecret set (#23) @knolleary
87
+ - Add Stack Properties descriptions (#21) @hardillb
88
+
89
+ #### 0.5.0: Release
90
+
91
+ #### 0.4.0: Release
92
+
93
+ - Update to use new container driver API (#17) @knolleary
94
+ - Fix validator regex for CPU % (#16) @hardillb
95
+ - Update project automation (#18) @knolleary
96
+
97
+ #### 0.3.0: Release
98
+
99
+ - Stop driver setting baseURL/forgeURL (#14) @knolleary
100
+ - Add Stack support (#13) @hardillb
101
+ - Automate npm publish on release (#12) @hardillb
102
+
103
+ #### 0.2.0: Release
104
+
105
+ - Update deps for security issues (#10) @hardillb
106
+ - Add shutdown hook (#9) @hardillb
107
+ - Make project URL schema match base_url (#8) @hardillb
108
+ - Add project workflow automation (#6) @knolleary
package/LICENSE ADDED
@@ -0,0 +1,178 @@
1
+ Copyright FlowForge Inc, and other contributors, https://flowforge.com/
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
package/README.md ADDED
@@ -0,0 +1,25 @@
1
+ # FlowFuse Docker Container Driver
2
+
3
+ FlowFuse driver to create projects as docker containers
4
+
5
+ ## Configuration
6
+
7
+ In the `flowforge.yml` file
8
+
9
+ ```yaml
10
+ ...
11
+ driver:
12
+ type: docker
13
+ options:
14
+ socket: /var/run/docker.sock
15
+ registry: containers.flowforge.com
16
+ privateCA: /full/path/to/chain.pem
17
+ ```
18
+
19
+ - `registry` is the Docker Registry to load Stack Containers from (default: Docker Hub)
20
+ - `socket` is the path to the docker unix domain socket (default: /var/run/docker.sock)
21
+ - privateCA: is the fully qualified path to a pem file containing trusted CA cert chain (default: not set)
22
+
23
+ ### Configuration via environment variables
24
+
25
+ - `DOCKER_SOCKET` - Path to docker unix domain socket
package/docker.js ADDED
@@ -0,0 +1,446 @@
1
+ const fs = require('fs')
2
+ const got = require('got')
3
+ const Docker = require('dockerode')
4
+
5
+ const createContainer = async (project, domain) => {
6
+ const networks = await this._docker.listNetworks({ filters: { label: ['com.docker.compose.network=flowforge'] } })
7
+ const stack = project.ProjectStack.properties
8
+ const contOptions = {
9
+ Image: stack.container,
10
+ name: project.id, // options.name,
11
+ Env: [],
12
+ Labels: {
13
+ flowforge: 'project'
14
+ },
15
+ AttachStdin: false,
16
+ AttachStdout: false,
17
+ AttachStderr: false,
18
+ HostConfig: {
19
+ NetworkMode: networks[0].Name
20
+ }
21
+ }
22
+
23
+ if (stack) {
24
+ if (stack.cpu) {
25
+ contOptions.HostConfig.NanoCpus = ((Number(stack.cpu) / 100) * (10 ** 9))
26
+ }
27
+ if (stack.memory) {
28
+ contOptions.HostConfig.Memory = Number(stack.memory) * (1024 * 1024)
29
+ }
30
+ }
31
+
32
+ // TODO http/https needs to be dynamic (or we just enforce https?)
33
+ // and port number
34
+ const baseURL = new URL(this._app.config.base_url)
35
+ let projectURL
36
+ if (!project.url.startsWith('http')) {
37
+ projectURL = `${baseURL.protocol}//${project.safeName}.${this._options.domain}`
38
+ } else {
39
+ const temp = new URL(project.url)
40
+ projectURL = `${temp.protocol}//${temp.hostname}${temp.port ? ':' + temp.port : ''}`
41
+ }
42
+ const url = new URL(projectURL)
43
+ const hostname = url.hostname
44
+ const teamID = this._app.db.models.Team.encodeHashid(project.TeamId)
45
+ const authTokens = await project.refreshAuthTokens()
46
+
47
+ // AuthProvider
48
+ contOptions.Env.push('FORGE_CLIENT_ID=' + authTokens.clientID)
49
+ contOptions.Env.push('FORGE_CLIENT_SECRET=' + authTokens.clientSecret)
50
+ // TODO this needs to come from a central point
51
+ contOptions.Env.push('FORGE_URL=' + this._app.config.api_url)
52
+ contOptions.Env.push(`BASE_URL=${projectURL}`)
53
+ contOptions.Env.push(`VIRTUAL_HOST=${hostname}`)
54
+ if (baseURL.protocol === 'https:') {
55
+ contOptions.Env.push(`LETSENCRYPT_HOST=${hostname}`)
56
+ }
57
+ contOptions.Env.push('VIRTUAL_PORT=1880')
58
+ // httpStorage settings
59
+ contOptions.Env.push(`FORGE_PROJECT_ID=${project.id}`)
60
+ contOptions.Env.push(`FORGE_PROJECT_TOKEN=${authTokens.token}`)
61
+ // Inbound connections for docker disabled by default
62
+ contOptions.Env.push('FORGE_NR_NO_TCP_IN=true') // MVP. Future iteration could present this to YML or UI
63
+ contOptions.Env.push('FORGE_NR_NO_UDP_IN=true') // MVP. Future iteration could present this to YML or UI
64
+ // common
65
+ contOptions.Env.push(`FORGE_TEAM_ID=${teamID}`)
66
+ // broker settings
67
+ if (authTokens.broker) {
68
+ contOptions.Env.push(`FORGE_BROKER_URL=${authTokens.broker.url}`)
69
+ contOptions.Env.push(`FORGE_BROKER_USERNAME=${authTokens.broker.username}`)
70
+ contOptions.Env.push(`FORGE_BROKER_PASSWORD=${authTokens.broker.password}`)
71
+ }
72
+ if (this._app.license.active()) {
73
+ contOptions.Env.push('FORGE_LICENSE_TYPE=ee')
74
+ }
75
+
76
+ if (stack.memory) {
77
+ contOptions.Env.push(`FORGE_MEMORY_LIMIT=${stack.memory}`)
78
+ }
79
+
80
+ if (stack.cpu) {
81
+ contOptions.Env.push(`FORGE_CPU_LIMIT=${stack.cpu}`)
82
+ }
83
+
84
+ const credentialSecret = await project.getSetting('credentialSecret')
85
+ if (credentialSecret) {
86
+ contOptions.Env.push(`FORGE_NR_SECRET=${credentialSecret}`)
87
+ }
88
+
89
+ if (this._app.config.driver.options.privateCA && fs.existsSync(this._app.config.driver.options.privateCA)) {
90
+ contOptions.Binds = [
91
+ `${this._app.config.driver.options.privateCA}:/usr/local/ssl-certs/chain.pem`
92
+ ]
93
+ contOptions.Env.push('NODE_EXTRA_CA_CERTS=/usr/local/ssl-certs/chain.pem')
94
+ }
95
+
96
+ const container = await this._docker.createContainer(contOptions)
97
+ return container.start()
98
+ .then(async () => {
99
+ this._app.log.debug(`Container ${project.id} started [${container.id.substring(0, 12)}]`)
100
+ project.url = projectURL
101
+ project.state = 'running'
102
+ await project.save()
103
+ this._projects[project.id].state = 'starting'
104
+ })
105
+ }
106
+
107
+ /**
108
+ * Docker Container driver
109
+ *
110
+ * Handles the creation and deletation of containers to back Projects
111
+ *
112
+ * This driver creates Projects backed by Docker
113
+ *
114
+ * @module docker
115
+ * @memberof forge.containers.drivers
116
+ *
117
+ */
118
+ module.exports = {
119
+ /**
120
+ * Initialises this driver
121
+ * @param {string} app - the Vue application
122
+ * @param {object} options - A set of configuration options for the driver
123
+ * @return {forge.containers.ProjectArguments}
124
+ */
125
+ init: async (app, options) => {
126
+ this._app = app
127
+ this._projects = {}
128
+ this._docker = new Docker({
129
+ socketPath: app.config.driver.options?.socket || '/var/run/docker.sock'
130
+ })
131
+ this._options = options
132
+
133
+ if (!options.registry) {
134
+ options.registry = app.config.driver.options?.registry || '' // use docker hub
135
+ }
136
+
137
+ // Get a list of all projects - with the absolute minimum of fields returned
138
+ const projects = await app.db.models.Project.findAll({
139
+ attributes: [
140
+ 'id',
141
+ 'state',
142
+ 'ProjectStackId',
143
+ 'TeamId'
144
+ ]
145
+ })
146
+ projects.forEach(async (project) => {
147
+ if (this._projects[project.id] === undefined) {
148
+ this._projects[project.id] = {
149
+ state: 'unknown'
150
+ }
151
+ }
152
+ })
153
+
154
+ this._initialCheckTimeout = setTimeout(() => {
155
+ this._app.log.debug('[docker] Restarting projects')
156
+ projects.forEach(async (project) => {
157
+ try {
158
+ if (project.state === 'suspended') {
159
+ // Do not restart suspended projects
160
+ return
161
+ }
162
+ let container
163
+ try {
164
+ container = await this._docker.listContainers({
165
+ all: true,
166
+ filters: {
167
+ name: [project.id]
168
+ }
169
+ })
170
+ if (container[0]) {
171
+ container = await this._docker.getContainer(container[0].Id)
172
+ } else {
173
+ container = undefined
174
+ }
175
+ } catch (err) {
176
+ console.log(err)
177
+ }
178
+ if (container) {
179
+ const state = await container.inspect()
180
+ if (!state.State.Running) {
181
+ this._projects[project.id].state = 'starting'
182
+ this._app.log.debug(`[docker] Project ${project.id} - restarting container [${container.id.substring(0, 12)}]`)
183
+ // need to restart existing container
184
+ container.start().then(() => {
185
+ this._projects[project.id].state = 'started'
186
+ })
187
+ } else {
188
+ this._app.log.debug(`[docker] Project ${project.id} - already running container [${container.id.substring(0, 12)}]`)
189
+ this._projects[project.id].state = 'started'
190
+ }
191
+ } else {
192
+ this._app.log.debug(`[docker] Project ${project.id} - recreating container`)
193
+ const fullProject = await this._app.db.models.Project.byId(project.id)
194
+ // need to create
195
+ await createContainer(fullProject, this._options.domain)
196
+ }
197
+ } catch (err) {
198
+ this._app.log.error(`[docker] Project ${project.id} - error resuming project: ${err.stack}`)
199
+ }
200
+ })
201
+ }, 1000)
202
+
203
+ return {
204
+ stack: {
205
+ properties: {
206
+ cpu: {
207
+ label: 'CPU Cores (%)',
208
+ validate: '^([1-9][0-9]?|100)$',
209
+ invalidMessage: 'Invalid value - must be a number between 1 and 100',
210
+ description: 'How much of a single CPU core each Project should receive'
211
+ },
212
+ memory: {
213
+ label: 'Memory (MB)',
214
+ validate: '^[1-9]\\d+$',
215
+ invalidMessage: 'Invalid value - must be a number',
216
+ description: 'How much memory the container for each Project will be granted, recommended value 256'
217
+ },
218
+ container: {
219
+ label: 'Container Location',
220
+ // taken from https://stackoverflow.com/a/62964157
221
+ validate: '^(([a-z0-9]|[a-z0-9][a-z0-9\\-]*[a-z0-9])\\.)*([a-z0-9]|[a-z0-9][a-z0-9\\-]*[a-z0-9])(:[0-9]+\\/)?(?:[0-9a-z-]+[/@])(?:([0-9a-z-]+))[/@]?(?:([0-9a-z-]+))?(?::[a-z0-9\\.-]+)?$',
222
+ invalidMessage: 'Invalid value - must be a Docker image',
223
+ description: 'Container image location, can include a tag'
224
+ }
225
+ }
226
+ }
227
+ }
228
+ },
229
+ /**
230
+ * Start a Project
231
+ * @param {*} - id for the project
232
+ * @return {forge.containers.Project}
233
+ */
234
+ start: async (project) => {
235
+ this._projects[project.id] = {
236
+ state: 'starting'
237
+ }
238
+ const rs = createContainer(project, this._options.domain)
239
+ return rs
240
+ },
241
+ /**
242
+ * Stops the container and removes it
243
+ * @param {*} project
244
+ */
245
+ stop: async (project) => {
246
+ // There is no difference in docker between suspending and stopping the container
247
+ // as we have no additional state to maintain
248
+ const container = await this._docker.getContainer(project.id)
249
+ this._projects[project.id].state = 'suspended'
250
+ await container.stop()
251
+
252
+ // We remove the container even though this is only a stop, so that a
253
+ // restart can rebuild with a different container image if needed.
254
+ // An alternative would be to spot the required image had changed on
255
+ // start, and do the remove/create/start at that point in time.
256
+ await container.remove()
257
+ },
258
+ /**
259
+ * Removes a Project
260
+ * @param {string} id - id of project to remove
261
+ * @return {Object}
262
+ */
263
+ remove: async (project) => {
264
+ if (this._projects[project.id].state !== 'suspended') {
265
+ try {
266
+ const container = await this._docker.getContainer(project.id)
267
+ await container.stop()
268
+ await container.remove()
269
+ } catch (err) {}
270
+ }
271
+ delete this._projects[project.id]
272
+ },
273
+ /**
274
+ * Retrieves details of a project's container
275
+ * @param {string} id - id of project to query
276
+ * @return {Object}
277
+ */
278
+ details: async (project) => {
279
+ if (this._projects[project.id] === undefined) {
280
+ return { state: 'unknown' }
281
+ }
282
+ if (this._projects[project.id].state === 'suspended') {
283
+ // We should only poll the launcher if we think it is running.
284
+ // Otherwise, return our cached state
285
+ return {
286
+ state: this._projects[project.id].state
287
+ }
288
+ }
289
+ const containers = await this._docker.listContainers({})
290
+ let found = false
291
+ let response
292
+ for (let index = 0; index < containers.length; index++) {
293
+ const container = containers[index]
294
+ if (container.Names[0].endsWith(project.id)) {
295
+ found = true
296
+ const infoURL = 'http://' + project.id + ':2880/flowforge/info'
297
+ try {
298
+ response = await got.get(infoURL, {
299
+ timeout: {
300
+ request: 500
301
+ }
302
+ }).json()
303
+ this._projects[project.id].state = 'running'
304
+ break
305
+ } catch (err) {
306
+ response = {
307
+ id: project.id,
308
+ state: 'starting',
309
+ meta: {}
310
+ }
311
+ }
312
+ }
313
+ }
314
+ if (found) {
315
+ return response
316
+ } else {
317
+ return {
318
+ id: project.id,
319
+ state: 'starting',
320
+ meta: {}
321
+ }
322
+ }
323
+ // const infoURL = 'http://' + project.id + ':2880/flowforge/info'
324
+ // try {
325
+ // const info = JSON.parse((await got.get(infoURL),{
326
+ // timeout: {
327
+ // request: 500
328
+ // }
329
+ // }).body)
330
+ // this._projects[project.id].state = 'running'
331
+ // return info
332
+ // } catch (err) {
333
+ // // TODO
334
+ // // return
335
+ // return {
336
+ // id: project.id,
337
+ // state: 'starting'
338
+ // }
339
+ // }
340
+ },
341
+ /**
342
+ * Returns the settings for the project
343
+ */
344
+ settings: async (project) => {
345
+ // let project = await this._app.db.models.DockerProject.byId(id)
346
+ // const projectSettings = await project.getAllSettings()
347
+ // let options = JSON.parse(project.options)
348
+ const settings = {}
349
+ settings.projectID = project.id
350
+ settings.port = 1880
351
+ settings.rootDir = '/'
352
+ settings.userDir = 'data'
353
+
354
+ return settings
355
+ },
356
+ /**
357
+ * Starts the flows
358
+ * @param {string} id - id of project to start
359
+ * @return {forge.Status}
360
+ */
361
+ startFlows: async (project) => {
362
+ if (this._projects[project.id] === undefined) {
363
+ return { state: 'unknown' }
364
+ }
365
+ await got.post('http://' + project.id + ':2880/flowforge/command', {
366
+ json: {
367
+ cmd: 'start'
368
+ }
369
+ })
370
+ },
371
+ /**
372
+ * Stops the flows
373
+ * @param {string} id - id of project to stop
374
+ * @return {forge.Status}
375
+ */
376
+ stopFlows: async (project) => {
377
+ if (this._projects[project.id] === undefined) {
378
+ return { state: 'unknown' }
379
+ }
380
+ await got.post('http://' + project.id + ':2880/flowforge/command', {
381
+ json: {
382
+ cmd: 'stop'
383
+ }
384
+ })
385
+ },
386
+ /**
387
+ * Restarts the flows
388
+ * @param {string} id - id of project to restart
389
+ * @return {forge.Status}
390
+ */
391
+ restartFlows: async (project) => {
392
+ if (this._projects[project.id] === undefined) {
393
+ return { state: 'unknown' }
394
+ }
395
+ await got.post('http://' + project.id + ':2880/flowforge/command', {
396
+ json: {
397
+ cmd: 'restart'
398
+ }
399
+ })
400
+ },
401
+ /**
402
+ * Logout Node-RED instance
403
+ * @param {Project} project - the project model instance
404
+ * @param {string} token - the node-red token to revoke
405
+ * @return {forge.Status}
406
+ */
407
+ revokeUserToken: async (project, token) => { // logout:nodered(step-3)
408
+ try {
409
+ this._app.log.debug(`[docker] Project ${project.id} - logging out node-red instance`)
410
+ await got.post('http://' + project.id + ':2880/flowforge/command', { // logout:nodered(step-4)
411
+ json: {
412
+ cmd: 'logout',
413
+ token
414
+ }
415
+ })
416
+ } catch (error) {
417
+ this._app.log.error(`[docker] Project ${project.id} - error in 'revokeUserToken': ${error.stack}`)
418
+ }
419
+ },
420
+ logs: async (project) => {
421
+ if (this._projects[project.id] === undefined) {
422
+ return { state: 'unknown' }
423
+ }
424
+ return await got.get('http://' + project.id + ':2880/flowforge/logs').json()
425
+ },
426
+ /**
427
+ * Shutdown Driver
428
+ */
429
+ shutdown: async () => {
430
+ clearTimeout(this._initialCheckTimeout)
431
+ },
432
+ /**
433
+ * getDefaultStackProperties
434
+ */
435
+ getDefaultStackProperties: () => {
436
+ // need to work out what the right container tag is
437
+ const properties = {
438
+ cpu: 10,
439
+ memory: 256,
440
+ container: 'flowforge/node-red',
441
+ ...this._app.config.driver.options?.default_stack
442
+ }
443
+
444
+ return properties
445
+ }
446
+ }
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@flowfuse/driver-docker",
3
+ "version": "1.14.0",
4
+ "description": "Docker driver for FlowFuse",
5
+ "main": "docker.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1",
8
+ "lint": "eslint -c .eslintrc *.js",
9
+ "lint:fix": "eslint -c .eslintrc *.js --fix"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/FlowFuse/driver-docker.git"
14
+ },
15
+ "bugs": {
16
+ "url": "https://github.com/FlowFuse/driver-docker/issues"
17
+ },
18
+ "homepage": "https://github.com/FlowFuse/driver-docker#readme",
19
+ "author": {
20
+ "name": "FlowFuse Inc."
21
+ },
22
+ "license": "Apache-2.0",
23
+ "dependencies": {
24
+ "dockerode": "^3.3.1",
25
+ "got": "^11.8.0"
26
+ },
27
+ "devDependencies": {
28
+ "eslint": "^8.25.0",
29
+ "eslint-config-standard": "^17.0.0"
30
+ }
31
+ }