@flowfuse/driver-localfs 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,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,58 @@
1
+ name: Build and push package
2
+ on:
3
+ workflow_dispatch:
4
+ inputs:
5
+ nr_launcher_release_name:
6
+ description: 'flowfuse-nr-launcher package version'
7
+ required: false
8
+ default: 'nightly'
9
+ nr_launcher_ref:
10
+ description: 'flowfuse-nr-launcher package ref'
11
+ required: false
12
+ pull_request:
13
+ branches:
14
+ - main
15
+ push:
16
+ branches:
17
+ - main
18
+
19
+
20
+ jobs:
21
+ build:
22
+ uses: 'flowfuse/github-actions-workflows/.github/workflows/build_node_package.yml@v0.1.0'
23
+
24
+ publish:
25
+ needs: build
26
+ if: |
27
+ ( github.event_name == 'push' && github.ref == 'refs/heads/main' ) ||
28
+ ( github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' )
29
+ uses: 'flowfuse/github-actions-workflows/.github/workflows/publish_node_package.yml@v0.1.0'
30
+ with:
31
+ package_name: driver-localfs
32
+ publish_package: true
33
+ package_dependencies: |
34
+ @flowfuse/nr-launcher
35
+ secrets:
36
+ npm_registry_token: ${{ secrets.NPM_PUBLISH_TOKEN }}
37
+
38
+ dispatch:
39
+ name: Dispatch flowfuse package build
40
+ runs-on: ubuntu-latest
41
+ needs: publish
42
+ steps:
43
+ - name: Generate a token
44
+ id: generate_token
45
+ uses: tibdex/github-app-token@v1
46
+ with:
47
+ app_id: ${{ secrets.GH_BOT_APP_ID }}
48
+ private_key: ${{ secrets.GH_BOT_APP_KEY }}
49
+
50
+ - name: Trigger flowfuse package build
51
+ uses: benc-uk/workflow-dispatch@v1
52
+ with:
53
+ workflow: publish.yml
54
+ repo: flowfuse/flowfuse
55
+ ref: main
56
+ token: ${{ steps.generate_token.outputs.token }}
57
+ inputs: '{"localfs_ref": "${{ github.ref }}", "localfs_release_name": "${{ needs.package.outputs.release_name }}"}'
58
+
@@ -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,125 @@
1
+ #### 1.14.0: Release
2
+
3
+ - Update nr-launcher reference to new flowfuse scoped module (#103) @knolleary
4
+
5
+ #### 1.13.3: Release
6
+
7
+ - Bump to v1.13.3 release @hardillb
8
+
9
+ #### 1.13.0: Release
10
+
11
+ - Pin reusable workflows to v0.1.0 (#100) @ppawlowski
12
+ - Update ff references in package.json (#99) @knolleary
13
+ - Change repo references in workflows after github org rename (#97) @ppawlowski
14
+
15
+ #### 1.12.0: Release
16
+
17
+ - Publish nightly package to npmjs (#96) @ppawlowski
18
+
19
+ #### 1.11.1: Release
20
+
21
+ - Pin reusable workflow to commit SHA (#93) @ppawlowski
22
+ - Disable scheduled package build (#92) @ppawlowski
23
+ - Update to @flowforge/nr-launcher@1.11.1
24
+
25
+ #### 1.11.0: Release
26
+
27
+ - Enable flowforge package build dispatcher after package publish (#90) @ppawlowski
28
+ - Bump word-wrap from 1.2.3 to 1.2.5 (#89) @app/dependabot
29
+ - FIX: Allow publish only when changes are pushed to `main` branch (#88) @ppawlowski
30
+ - Introduce publish pipeline (#85) @ppawlowski
31
+
32
+ #### 1.10.0: Release
33
+
34
+
35
+ #### 1.9.2: Release
36
+
37
+ - Update to @flowforge/nr-launcher@01.9.2
38
+
39
+ #### 1.9.0: Release
40
+
41
+ - Add package-lock.json (#82) @Pezmc
42
+
43
+ #### 1.8.0: Release
44
+
45
+
46
+ #### 1.7.0: Release
47
+
48
+
49
+ #### 1.6.0: Release
50
+
51
+
52
+ #### 1.5.0: Release
53
+
54
+
55
+ #### 1.4.0: Release
56
+
57
+
58
+ #### 1.3.0: Release
59
+
60
+
61
+ #### 1.2.0: Release
62
+
63
+
64
+ #### 1.1.0: Release
65
+
66
+ - Change default start port (#72) @hardillb
67
+ - Fix detection of default stack (#71) @knolleary
68
+ - Add getDefaultStackProperties function (#70) @hardillb
69
+ - Add flags to permit TCP/UDP inbound connections (#69) @Steve-Mcl
70
+
71
+ #### 1.0.0: Release
72
+
73
+ - Update eslint and add default build action (#67) @knolleary
74
+ - Revert 64 (#66) @hardillb
75
+ - Install theme and project nodes into userDir (#64) @hardillb
76
+
77
+ #### 0.10.0: Release
78
+
79
+
80
+ #### 0.9.0: Release
81
+
82
+ - Prevent localfs crash when deleting project (#60) @Steve-Mcl
83
+
84
+ #### 0.8.0: Release
85
+
86
+ - Add licenseType to launcher env (#58) @knolleary
87
+ - Add env var FORGE_TEAM_ID (#57) @Steve-Mcl
88
+ - Add FORGE_BROKER_* credentials to launcher env (#54) @knolleary
89
+
90
+ #### 0.7.0: Release
91
+
92
+
93
+ #### 0.6.0: Release
94
+
95
+ - Map FlowForge logout to nodered auth/revoke (#48) @Steve-Mcl
96
+ - Handle actions on deleted project (#49) @knolleary
97
+ - Update dependencies (#50) @knolleary
98
+ - Pass credentialSecret to env (supports auto gen credential secret PRs) (#47) @Steve-Mcl
99
+ - Add description to stack memory value (#46) @hardillb
100
+ - Make sure DB has right values for port + URL (#45) @hardillb
101
+
102
+ #### 0.5.0: Release
103
+
104
+ - Modify nodered stack property regex to support beta releases (#43) @knolleary
105
+
106
+ #### 0.4.0: Release
107
+
108
+ - Move setting project URL to before launcher started (#39) @hardillb
109
+ - Update localfs to new driver api (#37) @knolleary
110
+ - Update project automation (#38) @knolleary
111
+
112
+ #### 0.3.0: Release
113
+
114
+ - Stop driver setting baseURL/forgeURL (#35) @knolleary
115
+ - Add basic stack support (#30) @knolleary
116
+ - Fix port allocation problem (main) (#32) @hardillb
117
+ - Stop opening cmd windows (#29) @hardillb
118
+ - Update package-lock.json (#28) @hardillb
119
+ - Automate npm publish on release (#27) @hardillb
120
+
121
+ #### 0.2.0: Release
122
+
123
+ - Add shutdown hook (#24) @hardillb
124
+ - Add lint rules (#22) @hardillb
125
+ - Add project workflow automation (#20) @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,24 @@
1
+ # FlowFuse LocalFS Driver
2
+
3
+ This will start/stop/monitor Node-RED instances and build separate useDirs for each instance
4
+
5
+ ## Configure
6
+
7
+ The following environment variables (in the `.env` file) configure this driver
8
+
9
+ - CONTAINER_DRIVER=localfs
10
+ - LOCALFS_ROOT=<path/to/store/project/userDirs>
11
+ - LOCALFS_START_PORT=12080
12
+ - LOCALFS_NODE_PATH=<path/to/node/binary> (not required, but useful with nvm)
13
+
14
+ ## Node-RED Versions for Stacks
15
+
16
+ To install copies of different versions of Node-RED for use by Project Stacks do the following:
17
+
18
+ Assuming you wish to install Node-RED v2.2.2
19
+
20
+ - In the `var` directory create a directory called `stacks`
21
+ - In the `var/stacks` directory create a directory called `2.2.2`
22
+ - in the `var/stacks/2.2.2` directory run `npm install --prefix . node-red@2.2.2`
23
+
24
+ In the FlowFuse Admin settings create a Stack with the Node-RED version `2.2.2`
package/localfs.js ADDED
@@ -0,0 +1,555 @@
1
+ /**
2
+ * Local Container driver
3
+ *
4
+ * Handles the creation and deletion of containers to back Projects
5
+ *
6
+ * This driver creates Projects backed by userDirectories on the local file system
7
+ *
8
+ * @module localfs
9
+ * @memberof forge.containers.drivers
10
+ *
11
+ */
12
+
13
+ const fs = require('fs/promises')
14
+ const { existsSync, openSync, close, readdirSync } = require('fs')
15
+ const got = require('got')
16
+ const path = require('path')
17
+ const semver = require('semver')
18
+ const childProcess = require('child_process')
19
+
20
+ let initialPortNumber
21
+
22
+ const fileHandles = {}
23
+
24
+ let logger
25
+
26
+ function getNextFreePort (ports) {
27
+ let port = initialPortNumber
28
+ while (ports.has(port)) {
29
+ port++
30
+ }
31
+ return port
32
+ }
33
+
34
+ async function createUserDirIfNeeded (userDir) {
35
+ if (!existsSync(userDir)) {
36
+ logger.info(`Creating settings directory: ${userDir}`)
37
+ await fs.mkdir(userDir)
38
+ await fs.mkdir(path.join(userDir, 'node_modules'))
39
+ const packageJSON = {
40
+ name: 'flowfuse-node-red-project',
41
+ description: 'A FlowFuse Node-RED Instance',
42
+ version: '0.0.1',
43
+ private: true
44
+ }
45
+ await fs.writeFile(path.join(userDir, 'package.json'),
46
+ JSON.stringify(packageJSON)
47
+ )
48
+ }
49
+ }
50
+
51
+ async function startProject (app, project, ProjectStack, userDir, port) {
52
+ const env = {} // JSON.parse(JSON.stringify(process.env))
53
+
54
+ const authTokens = await project.refreshAuthTokens()
55
+
56
+ env.FORGE_CLIENT_ID = authTokens.clientID
57
+ env.FORGE_CLIENT_SECRET = authTokens.clientSecret
58
+ env.FORGE_URL = app.config.api_url
59
+ env.FORGE_TEAM_ID = app.db.models.Team.encodeHashid(project.TeamId)
60
+ env.FORGE_PROJECT_ID = project.id
61
+ env.FORGE_PROJECT_TOKEN = authTokens.token
62
+ env.FORGE_NR_SECRET = await project.getSetting('credentialSecret')
63
+ // Inbound connections for localfs enabled by default
64
+ env.FORGE_NR_NO_TCP_IN = false // MVP. Future iteration could present this to YML or UI
65
+ env.FORGE_NR_NO_UDP_IN = false// MVP. Future iteration could present this to YML or UI
66
+ if (authTokens.broker) {
67
+ env.FORGE_BROKER_URL = authTokens.broker.url
68
+ env.FORGE_BROKER_USERNAME = authTokens.broker.username
69
+ env.FORGE_BROKER_PASSWORD = authTokens.broker.password
70
+ }
71
+ if (app.license.active()) {
72
+ env.FORGE_LICENSE_TYPE = 'ee'
73
+ }
74
+
75
+ if (app.config.node_path) {
76
+ env.PATH = process.env.PATH + path.delimiter + app.config.node_path
77
+ } else {
78
+ env.PATH = process.env.PATH
79
+ }
80
+
81
+ logger.debug(`Stack info ${JSON.stringify(ProjectStack?.properties)}`)
82
+ /*
83
+ * ProjectStack.properties will contain the stack properties for this project
84
+ *
85
+ * This driver specifices two properties:
86
+ * - memory : the value to apply to max-old-space-size
87
+ * This gets passed to the project instance via the /:projectId/settings
88
+ * endpoint - so this driver doesn't need to anything more with it
89
+ * - nodered : the version of node-red to use
90
+ * This driver needs to ensure the launcher is started using that
91
+ * version of Node-RED. We assume the admin has installed it to a well-known
92
+ * location using a set of instructions we provide (to be written)
93
+ */
94
+ if (ProjectStack?.properties.nodered) {
95
+ env.FORGE_NR_PATH = path.resolve(app.config.home, 'var/stacks', ProjectStack.properties.nodered)
96
+ logger.info(`Set FORGE_NR_PATH to ${env.FORGE_NR_PATH}`)
97
+ }
98
+
99
+ // logger.debug(`Project Environment Vars ${JSON.stringify(env)}`)
100
+
101
+ const out = openSync(path.join(userDir, '/out.log'), 'a')
102
+ const err = openSync(path.join(userDir, '/out.log'), 'a')
103
+
104
+ fileHandles[project.id] = {
105
+ out,
106
+ err
107
+ }
108
+
109
+ const processOptions = {
110
+ detached: true,
111
+ stdio: ['ignore', out, err],
112
+ windowsHide: true,
113
+ env,
114
+ cwd: userDir
115
+ }
116
+
117
+ // this needs work
118
+ // const ext = process.platform === 'win32' ? '.cmd' : ''
119
+
120
+ let execPath
121
+ for (let i = 0; i < module.paths.length; i++) {
122
+ // execPath = path.join(process.mainModule.paths[i], `.bin/flowforge-node-red${ext}`)
123
+ execPath = path.join(module.paths[i], '@flowfuse/nr-launcher/index.js')
124
+ if (existsSync(execPath)) {
125
+ break
126
+ }
127
+ execPath = null
128
+ }
129
+ if (!execPath) {
130
+ logger.info('Can not find flowfuse-node-red executable, no way to start projects')
131
+ process.exit(1)
132
+ }
133
+
134
+ logger.debug(`exec path ${execPath}`)
135
+
136
+ const args = [
137
+ execPath, // new
138
+ '-p',
139
+ port + 1000,
140
+ '--forgeURL',
141
+ app.config.base_url,
142
+ '--project',
143
+ project.id
144
+ // '--token',
145
+ // options.projectToken
146
+ ]
147
+
148
+ // const proc = childProcess.spawn(execPath, args, processOptions)
149
+ const proc = childProcess.spawn(process.execPath, args, processOptions)
150
+
151
+ proc.unref()
152
+
153
+ return proc.pid
154
+ }
155
+
156
+ function stopProject (app, project, projectSettings) {
157
+ try {
158
+ if (process.platform === 'win32') {
159
+ childProcess.exec(`taskkill /pid ${projectSettings.pid} /T /F`)
160
+ } else {
161
+ process.kill(projectSettings.pid, 'SIGTERM')
162
+ }
163
+ } catch (err) {
164
+ // probably means already stopped
165
+ }
166
+
167
+ if (fileHandles[project.id]) {
168
+ close(fileHandles[project.id].out)
169
+ close(fileHandles[project.id].err)
170
+ delete fileHandles[project.id]
171
+ }
172
+ }
173
+
174
+ async function getProjectList (driver) {
175
+ // Get a list of all projects - with the absolute minimum of fields returned
176
+ const projects = await driver._app.db.models.Project.findAll({
177
+ attributes: [
178
+ 'id',
179
+ 'state',
180
+ 'ProjectStackId',
181
+ 'TeamId'
182
+ ],
183
+ include: [
184
+ {
185
+ model: driver._app.db.models.ProjectSettings,
186
+ where: { key: driver._app.db.sequelize.or('port', 'path') }
187
+ }
188
+ ]
189
+ })
190
+ projects.forEach(async (project) => {
191
+ const projectSettings = {}
192
+ // Remap the project settings to make them accessible
193
+ project.ProjectSettings.forEach(ps => {
194
+ projectSettings[ps.key] = ps.value
195
+ })
196
+ driver._usedPorts.add(projectSettings.port)
197
+ if (driver._projects[project.id] === undefined) {
198
+ driver._projects[project.id] = {
199
+ state: 'unknown'
200
+ }
201
+ }
202
+ project._settings = projectSettings
203
+ })
204
+ return projects
205
+ }
206
+
207
+ async function checkExistingProjects (driver) {
208
+ logger.debug('[localfs] Checking project status')
209
+
210
+ const projects = await getProjectList(driver)
211
+ projects.forEach(async (project) => {
212
+ const projectSettings = project._settings
213
+ // Suspended projects don't get restarted
214
+ if (project.state === 'suspended') {
215
+ return
216
+ }
217
+
218
+ logger.debug(`[localfs] Project ${project.id} port ${projectSettings.port}`)
219
+
220
+ const directory = path.join(driver._rootDir, project.id)
221
+ await createUserDirIfNeeded(directory)
222
+
223
+ try {
224
+ const info = await got.get(`http://localhost:${projectSettings.port + 1000}/flowforge/info`, {
225
+ timeout: {
226
+ request: 1000
227
+ }
228
+ }).json()
229
+ if (project.id !== info.id) {
230
+ // Running project doesn't match db
231
+ logger.warn(`[localfs] Project ${project.id} expected on port ${projectSettings.port}. Found ${info.id}`)
232
+ // TODO should do something here...
233
+ } else {
234
+ driver._projects[project.id] = {
235
+ state: 'started'
236
+ }
237
+ }
238
+ } catch (err) {
239
+ logger.info(`Starting project ${project.id} on port ${projectSettings.port}`)
240
+
241
+ const projectStack = await project.getProjectStack()
242
+
243
+ const pid = await startProject(driver._app, project, projectStack, projectSettings.path, projectSettings.port)
244
+ await project.updateSetting('pid', pid)
245
+ driver._projects[project.id] = {
246
+ state: 'started'
247
+ }
248
+ }
249
+ })
250
+ }
251
+
252
+ module.exports = {
253
+ /**
254
+ * Initialises this driver
255
+ * @param {string} app - the Vue application
256
+ * @param {object} options - A set of configuration options for the driver
257
+ * @return {forge.containers.ProjectArguments}
258
+ */
259
+ init: async (app, options) => {
260
+ this._app = app
261
+ this._options = options
262
+ this._projects = {}
263
+ this._usedPorts = new Set()
264
+ // TODO need a better way to find this location?
265
+ this._rootDir = path.resolve(app.config.home, 'var/projects')
266
+ this._stackDir = path.resolve(app.config.home, 'var/stacks')
267
+
268
+ initialPortNumber = app.config.driver.options?.start_port || 12080
269
+
270
+ logger = app.log
271
+
272
+ if (!existsSync(this._rootDir)) {
273
+ await fs.mkdir(this._rootDir)
274
+ }
275
+
276
+ // Ensure we have our local list of projects up to date
277
+ await getProjectList(this)
278
+ this._initialCheckTimeout = setTimeout(() => {
279
+ app.log.debug('[localfs] Restarting projects')
280
+ checkExistingProjects(this)
281
+ }, 1000)
282
+ this._checkInterval = setInterval(() => {
283
+ checkExistingProjects(this)
284
+ }, 60000)
285
+ return {
286
+ stack: {
287
+ properties: {
288
+ nodered: {
289
+ label: 'Node-RED Version',
290
+ description: 'This must match a version installed on the platform. See the docs for how to setup stacks locally.',
291
+ validate: '^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(-.*)?$',
292
+ invalidMessage: 'Invalid version number - expected x.y.z'
293
+ },
294
+ memory: {
295
+ label: 'Memory (MB)',
296
+ description: 'This is the point at which the runtime will start garbage collecting unused memory. Recommended minimum: 256',
297
+ validate: '^[1-9]\\d+$',
298
+ invalidMessage: 'Invalid value - must be a number'
299
+ }
300
+ }
301
+ }
302
+ }
303
+ },
304
+ /**
305
+ * Start a Project
306
+ * @param {Project} project - the project model instance
307
+ */
308
+ start: async (project) => {
309
+ // Setup project directory
310
+ const directory = path.join(this._rootDir, project.id)
311
+ await createUserDirIfNeeded(directory)
312
+
313
+ // Check if the project has a port assigned already
314
+ let port = await project.getSetting('port')
315
+
316
+ if (port === undefined) {
317
+ // This project has never been run, so assign a new port to it
318
+ port = getNextFreePort(this._usedPorts)
319
+ this._usedPorts.add(port)
320
+ }
321
+
322
+ this._projects[project.id] = {
323
+ state: 'starting'
324
+ }
325
+
326
+ await project.updateSettings({
327
+ path: directory,
328
+ port
329
+ })
330
+
331
+ const baseURL = new URL(this._app.config.base_url)
332
+ baseURL.port = port
333
+ project.url = baseURL.href
334
+ await project.save()
335
+
336
+ // Kick-off the project start and return the promise to let it
337
+ // complete asynchronously
338
+ return startProject(this._app, project, project.ProjectStack, directory, port).then(async pid => {
339
+ return new Promise(resolve => {
340
+ // These is a race condition when running locally where the UI
341
+ // creates a project then immediate reloads it. That can hit
342
+ // a timing window where the project creation completes mid-request
343
+ setTimeout(async () => {
344
+ logger.debug(`PID ${pid}, port, ${port}, directory, ${directory}`)
345
+ await project.updateSetting('pid', pid)
346
+ this._projects[project.id].state = 'started'
347
+ resolve()
348
+ }, 1000)
349
+ })
350
+ })
351
+ },
352
+ /**
353
+ * Stops a project from running, but doesn't clear its state as it could
354
+ * get restarted and we want to preserve port number and user dir
355
+ * @param {*} project
356
+ */
357
+ stop: async (project) => {
358
+ const projectSettings = await project.getAllSettings()
359
+ this._projects[project.id].state = 'suspended'
360
+ stopProject(this._app, project, projectSettings)
361
+ },
362
+
363
+ /**
364
+ * Removes a Project
365
+ * @param {Project} project - the project model instance
366
+ * @return {Object}
367
+ */
368
+ remove: async (project) => {
369
+ const projectSettings = await project.getAllSettings()
370
+ stopProject(this._app, project, projectSettings)
371
+
372
+ setTimeout(async () => {
373
+ try {
374
+ await fs.rm(projectSettings.path, { recursive: true, force: true })
375
+ } catch (error) {
376
+ logger.warn(`Error removing project files: ${projectSettings.path}`)
377
+ }
378
+ }, 5000)
379
+
380
+ this._usedPorts.delete(projectSettings.port)
381
+ delete this._projects[project.id]
382
+ },
383
+ /**
384
+ * Retrieves details of a project's container
385
+ * @param {Project} project - the project model instance
386
+ * @return {Object}
387
+ */
388
+ details: async (project) => {
389
+ if (this._projects[project.id] === undefined) {
390
+ return { state: 'unknown' }
391
+ }
392
+ if (this._projects[project.id].state !== 'started') {
393
+ // We should only poll the launcher if we think it is running.
394
+ // Otherwise, return our cached state
395
+ return {
396
+ state: this._projects[project.id].state
397
+ }
398
+ }
399
+ const port = await project.getSetting('port')
400
+ const infoURL = 'http://localhost:' + (port + 1000) + '/flowforge/info'
401
+ try {
402
+ const info = JSON.parse((await got.get(infoURL)).body)
403
+ return info
404
+ } catch (err) {
405
+ console.log(err)
406
+ // TODO
407
+ }
408
+ },
409
+ /**
410
+ * Returns the settings for the project
411
+ * @param {Project} project - the project model instance
412
+ */
413
+ settings: async (project) => {
414
+ const settings = {}
415
+ if (project) {
416
+ settings.projectID = project.id
417
+ settings.rootDir = this._rootDir
418
+ settings.userDir = project.id
419
+ settings.port = await project.getSetting('port')
420
+ settings.env = {
421
+ NODE_PATH: path.join(this._app.config.home, 'app', 'node_modules')
422
+ }
423
+ }
424
+ // settings.state is set by the core forge app before this returns to
425
+ // the launcher
426
+
427
+ // settings.stack is set by the core forge app
428
+
429
+ return settings
430
+ },
431
+
432
+ /**
433
+ * Starts the flows
434
+ * @param {Project} project - the project model instance
435
+ */
436
+ startFlows: async (project) => {
437
+ if (this._projects[project.id] === undefined) {
438
+ throw new Error('Project cannot start flows')
439
+ }
440
+ const port = await project.getSetting('port')
441
+ await got.post('http://localhost:' + (port + 1000) + '/flowforge/command', {
442
+ json: {
443
+ cmd: 'start'
444
+ }
445
+ })
446
+ },
447
+ /**
448
+ * Stops the flows
449
+ * @param {Project} project - the project model instance
450
+ * @return {forge.Status}
451
+ */
452
+ stopFlows: async (project) => {
453
+ if (this._projects[project.id] === undefined) {
454
+ throw new Error('Project cannot stop flows')
455
+ }
456
+ const port = await project.getSetting('port')
457
+ await got.post('http://localhost:' + (port + 1000) + '/flowforge/command', {
458
+ json: {
459
+ cmd: 'stop'
460
+ }
461
+ })
462
+ },
463
+ /**
464
+ * Restarts the flows
465
+ * @param {Project} project - the project model instance
466
+ * @return {forge.Status}
467
+ */
468
+ restartFlows: async (project) => {
469
+ if (this._projects[project.id] === undefined) {
470
+ throw new Error('Project cannot restart flows')
471
+ }
472
+ const port = await project.getSetting('port')
473
+ await got.post('http://localhost:' + (port + 1000) + '/flowforge/command', {
474
+ json: {
475
+ cmd: 'restart'
476
+ }
477
+ })
478
+ },
479
+ /**
480
+ * Logout Node-RED instance
481
+ * @param {Project} project - the project model instance
482
+ * @param {string} token - the node-red token to revoke
483
+ * @return {forge.Status}
484
+ */
485
+ revokeUserToken: async (project, token) => { // logout:nodered(step-3)
486
+ const port = await project.getSetting('port')
487
+ try {
488
+ this._app.log.debug(`[localfs] Project ${project.id} - logging out node-red instance`)
489
+ await got.post('http://localhost:' + (port + 1000) + '/flowforge/command', { // logout:nodered(step-4)
490
+ json: {
491
+ cmd: 'logout',
492
+ token
493
+ }
494
+ })
495
+ } catch (error) {
496
+ logger.error(`[localfs] Project ${project.id} - error in 'revokeUserToken': ${error.stack}`)
497
+ }
498
+ },
499
+
500
+ /**
501
+ * Get a Project's logs
502
+ * @param {Project} project - the project model instance
503
+ * @return {array} logs
504
+ */
505
+ logs: async (project) => {
506
+ if (this._projects[project.id] === undefined) {
507
+ throw new Error('Cannot get project logs')
508
+ }
509
+ const port = await project.getSetting('port')
510
+ const result = await got.get('http://localhost:' + (port + 1000) + '/flowforge/logs').json()
511
+ return result
512
+ },
513
+ /**
514
+ * Shutdown driver
515
+ */
516
+ shutdown: async () => {
517
+ clearTimeout(this._initialCheckTimeout)
518
+ clearInterval(this._checkInterval)
519
+ },
520
+ /**
521
+ * getDefaultStackProperties
522
+ */
523
+ getDefaultStackProperties: () => {
524
+ const properties = {
525
+ memory: 256,
526
+ ...this._app.config.driver.options?.default_stack
527
+ }
528
+
529
+ // allow stack value to be passing in from config
530
+ if (!properties.nodered) {
531
+ const entries = readdirSync(this._stackDir, { withFileTypes: true })
532
+ const directories = entries.filter(dir => {
533
+ return dir.isDirectory() && semver.valid(dir.name)
534
+ }).map(dir => dir.name)
535
+ .sort((a, b) => {
536
+ if (semver.gt(a, b)) {
537
+ return -1
538
+ } else {
539
+ return 1
540
+ }
541
+ })
542
+ if (directories[0]) {
543
+ properties.nodered = directories[0]
544
+ } else {
545
+ throw new Error(`No Stacks found in ${this._stackDir}`)
546
+ }
547
+ } else {
548
+ const preconfiguredStack = path.join(this._stackDir, properties.nodered)
549
+ if (!fs.existsSync(preconfiguredStack)) {
550
+ throw new Error(`Stack not found: ${preconfiguredStack}`)
551
+ }
552
+ }
553
+ return properties
554
+ }
555
+ }
package/package.json ADDED
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "@flowfuse/driver-localfs",
3
+ "version": "1.14.0",
4
+ "description": "Local Filesystem FlowFuse Project driver",
5
+ "main": "localfs.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-localfs.git"
14
+ },
15
+ "bugs": {
16
+ "url": "https://github.com/FlowFuse/driver-localfs/issues"
17
+ },
18
+ "homepage": "https://github.com/FlowFuse/driver-localfs#readme",
19
+ "author": {
20
+ "name": "FlowFuse Inc."
21
+ },
22
+ "license": "Apache-2.0",
23
+ "dependencies": {
24
+ "@flowfuse/nr-launcher": "^1.14.0",
25
+ "got": "^11.8.5",
26
+ "semver": "^7.3.8"
27
+ },
28
+ "devDependencies": {
29
+ "eslint": "^8.25.0",
30
+ "eslint-config-standard": "^17.0.0"
31
+ }
32
+ }