@hivemagnus/magnus 0.0.0-stage → 1.1.1
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/LICENSE +202 -0
- package/README.md +85 -2
- package/dist/adopt.d.ts +15 -0
- package/dist/adopt.js +98 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +14 -0
- package/dist/database.d.ts +15 -0
- package/dist/database.js +72 -0
- package/dist/env-file.d.ts +14 -0
- package/dist/env-file.js +42 -0
- package/dist/health.d.ts +23 -0
- package/dist/health.js +71 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +10 -0
- package/dist/init.d.ts +29 -0
- package/dist/init.js +187 -0
- package/dist/install.d.ts +38 -0
- package/dist/install.js +127 -0
- package/dist/io.d.ts +42 -0
- package/dist/io.js +78 -0
- package/dist/main.d.ts +12 -0
- package/dist/main.js +183 -0
- package/dist/project.d.ts +63 -0
- package/dist/project.js +133 -0
- package/dist/release.d.ts +36 -0
- package/dist/release.js +114 -0
- package/dist/rollback.d.ts +8 -0
- package/dist/rollback.js +60 -0
- package/dist/status.d.ts +8 -0
- package/dist/status.js +58 -0
- package/dist/supervisor.d.ts +9 -0
- package/dist/supervisor.js +53 -0
- package/dist/templates.d.ts +53 -0
- package/dist/templates.js +187 -0
- package/dist/upgrade.d.ts +26 -0
- package/dist/upgrade.js +225 -0
- package/package.json +81 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,86 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @hivemagnus/magnus
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Install, upgrade and roll back a [Magnus](https://github.com/ChefTaco/magnus) server and console
|
|
4
|
+
with one command.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npx @hivemagnus/magnus init # create and start a project in ~/.magnus
|
|
8
|
+
magnus upgrade # newest release of the current major, with backup and auto-revert
|
|
9
|
+
magnus rollback # back to the previous version
|
|
10
|
+
magnus status # versions, health, history, available updates
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Each release of this package pins exact, tested versions of `@hivemagnus/magnus-server`,
|
|
14
|
+
`@hivemagnus/magnus-ui` and `@hivemagnus/magnus-contracts`, together with the matching agent
|
|
15
|
+
version. The pins and release notes ship as `magnusRelease` in `package.json`.
|
|
16
|
+
|
|
17
|
+
## `magnus init`
|
|
18
|
+
|
|
19
|
+
`init` creates a managed project: the configuration, the installed versions and the units that run
|
|
20
|
+
them.
|
|
21
|
+
|
|
22
|
+
```
|
|
23
|
+
~/.magnus/
|
|
24
|
+
magnus-project.json project state and history
|
|
25
|
+
package.json, package-lock.json exact pins of the serving release
|
|
26
|
+
config/magnus-server.env generated secrets (0600)
|
|
27
|
+
config/magnus-ui.env
|
|
28
|
+
config/tls/ self-signed certificate (unless --tls-cert/--tls-key)
|
|
29
|
+
data/ server data (MAGNUS_HOME: audit logs, rotation state)
|
|
30
|
+
versions/1.1.0/ one npm install per release
|
|
31
|
+
current -> versions/1.1.0 what the services run
|
|
32
|
+
backups/ pre-migration database dumps
|
|
33
|
+
units/ the generated systemd units
|
|
34
|
+
deps.compose.yml PostgreSQL and Redis, when no --database-url/--redis-url is given
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
| Option | Meaning |
|
|
38
|
+
|---|---|
|
|
39
|
+
| `--system --service-user NAME` | System units in `/opt/magnus` (run as root) instead of user units |
|
|
40
|
+
| `--database-url URL --redis-url URL` | Use your own PostgreSQL and Redis instead of the bundled compose file |
|
|
41
|
+
| `--version X.Y.Z` | Install a specific release |
|
|
42
|
+
| `--public-host NAME` | Host name for URLs and the certificate |
|
|
43
|
+
| `--admin-user`, `--admin-password` | Console login (the password is generated and printed once by default) |
|
|
44
|
+
| `--no-ui`, `--no-start`, `--no-auto-migrate` | Server only; configure without starting; keep `MAGNUS_AUTO_MIGRATE=false` |
|
|
45
|
+
| `--supervisor none` | Write everything, but start the processes yourself |
|
|
46
|
+
|
|
47
|
+
User services start at boot only with lingering enabled (`loginctl enable-linger $USER`).
|
|
48
|
+
|
|
49
|
+
## `magnus upgrade`
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
magnus upgrade --dry-run # releases, notes, new settings and migrations, without changing anything
|
|
53
|
+
magnus upgrade [--to X.Y.Z] [--yes] [--generate-secrets] [--allow-major] [--source DIR]
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
An upgrade:
|
|
57
|
+
|
|
58
|
+
1. Checks the registry and the Node.js engines.
|
|
59
|
+
2. Refuses a downgrade or a major-version change (unless `--allow-major`).
|
|
60
|
+
3. Checks for new required settings.
|
|
61
|
+
4. Installs the release into `versions/<X>`.
|
|
62
|
+
5. Dumps PostgreSQL, migrates and checks.
|
|
63
|
+
6. Switches `./current`, restarts and waits for the new version to serve.
|
|
64
|
+
7. If the new version is unhealthy, switches back and prints the database restore command.
|
|
65
|
+
|
|
66
|
+
Slow or one-way migrations need `--yes`.
|
|
67
|
+
|
|
68
|
+
`magnus-server upgrade` hands the same command to the project it was installed into.
|
|
69
|
+
|
|
70
|
+
## `magnus adopt`
|
|
71
|
+
|
|
72
|
+
Turns an existing npm install into a managed project without touching what runs:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
npx @hivemagnus/magnus adopt --server-env-file /etc/magnus/server.env --ui-env-file /etc/magnus/ui.env
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
See [UPGRADING.md](https://github.com/ChefTaco/magnus/blob/main/UPGRADING.md) for every upgrade
|
|
79
|
+
path, agent upgrades and the switches that turn automation off.
|
|
80
|
+
|
|
81
|
+
Requires Node.js `^24.22.1` or `^26.13.0`, npm, systemd (or `--supervisor none`), and `openssl` for
|
|
82
|
+
the self-signed certificate.
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
Apache-2.0
|
package/dist/adopt.d.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Io } from './io.js';
|
|
2
|
+
import { type Supervisor } from './project.js';
|
|
3
|
+
export interface AdoptOptions {
|
|
4
|
+
dir?: string;
|
|
5
|
+
serverEnvFile: string;
|
|
6
|
+
uiEnvFile?: string;
|
|
7
|
+
version?: string;
|
|
8
|
+
system: boolean;
|
|
9
|
+
serviceUser?: string;
|
|
10
|
+
supervisor: Supervisor;
|
|
11
|
+
installUnits: boolean;
|
|
12
|
+
source?: string;
|
|
13
|
+
registry: string;
|
|
14
|
+
}
|
|
15
|
+
export declare function adopt(io: Io, options: AdoptOptions): Promise<number>;
|
package/dist/adopt.js
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `magnus adopt`: turn an existing npm install (1.0.x or later) into a
|
|
3
|
+
* managed project so `magnus upgrade` can take over. The env files stay where
|
|
4
|
+
* they are; the same version is installed under versions/ and new units point
|
|
5
|
+
* at ./current. Nothing running is touched unless --install-units is given.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { join, resolve } from 'node:path';
|
|
9
|
+
import { isVersion } from '@hivemagnus/magnus-contracts';
|
|
10
|
+
import { readEnvFile } from './env-file.js';
|
|
11
|
+
import { installVersion, publishPins } from './install.js';
|
|
12
|
+
import { acquireLock, Project } from './project.js';
|
|
13
|
+
import { releaseFor } from './release.js';
|
|
14
|
+
import { enableServices, unitDirectory } from './supervisor.js';
|
|
15
|
+
import { serverUnit, uiUnit } from './templates.js';
|
|
16
|
+
import { loadCatalog, UpgradeError } from './upgrade.js';
|
|
17
|
+
import { defaultProjectDir } from './init.js';
|
|
18
|
+
async function detectVersion(io) {
|
|
19
|
+
const result = await io.run('magnus-server', ['--version'], { capture: true }).catch(() => null);
|
|
20
|
+
const version = result?.code === 0 ? result.stdout.trim() : '';
|
|
21
|
+
return isVersion(version) ? version : null;
|
|
22
|
+
}
|
|
23
|
+
export async function adopt(io, options) {
|
|
24
|
+
if (options.system && !options.serviceUser)
|
|
25
|
+
throw new UpgradeError('--system needs --service-user <account the services run as>.');
|
|
26
|
+
const serverEnvFile = resolve(options.serverEnvFile);
|
|
27
|
+
if (!existsSync(serverEnvFile))
|
|
28
|
+
throw new UpgradeError(`--server-env-file ${serverEnvFile} does not exist`);
|
|
29
|
+
const uiEnvFile = options.uiEnvFile ? resolve(options.uiEnvFile) : undefined;
|
|
30
|
+
if (uiEnvFile && !existsSync(uiEnvFile))
|
|
31
|
+
throw new UpgradeError(`--ui-env-file ${uiEnvFile} does not exist`);
|
|
32
|
+
const dir = resolve(options.dir ?? defaultProjectDir(io, options.system));
|
|
33
|
+
if (Project.exists(dir))
|
|
34
|
+
throw new UpgradeError(`${dir} already holds a Magnus project.`);
|
|
35
|
+
const version = options.version ?? await detectVersion(io);
|
|
36
|
+
if (!version)
|
|
37
|
+
throw new UpgradeError('Could not detect the installed version; pass --version X.Y.Z (the output of `magnus-server --version`).');
|
|
38
|
+
const serverEnv = readEnvFile(serverEnvFile);
|
|
39
|
+
const uiEnv = uiEnvFile ? readEnvFile(uiEnvFile) : {};
|
|
40
|
+
const components = uiEnvFile ? ['server', 'ui'] : ['server'];
|
|
41
|
+
const state = {
|
|
42
|
+
schema: 1,
|
|
43
|
+
createdAt: io.now().toISOString(),
|
|
44
|
+
supervisor: options.supervisor,
|
|
45
|
+
scope: options.system ? 'system' : 'user',
|
|
46
|
+
components,
|
|
47
|
+
units: { server: 'magnus-server', ui: 'magnus-ui' },
|
|
48
|
+
envFiles: { server: serverEnvFile, ui: uiEnvFile ?? join('config', 'magnus-ui.env') },
|
|
49
|
+
database: { kind: 'external' },
|
|
50
|
+
ports: { server: Number(serverEnv['CONTROL_API_PORT'] ?? 4000), ui: Number(uiEnv['PORT'] ?? 3000) },
|
|
51
|
+
current: null,
|
|
52
|
+
previous: null,
|
|
53
|
+
keepVersions: 3,
|
|
54
|
+
history: [],
|
|
55
|
+
};
|
|
56
|
+
mkdirSync(dir, { recursive: true });
|
|
57
|
+
const project = new Project(dir, state);
|
|
58
|
+
const release = acquireLock(project.path('run', 'upgrade.lock'));
|
|
59
|
+
try {
|
|
60
|
+
for (const sub of ['backups', 'run', 'versions', 'units', 'ui-data'])
|
|
61
|
+
mkdirSync(project.path(sub), { recursive: true, mode: 0o750 });
|
|
62
|
+
const catalog = await loadCatalog(io, options);
|
|
63
|
+
io.log(`Adopting Magnus ${version} into ${dir} (env files stay in place)`);
|
|
64
|
+
await installVersion(io, project, releaseFor(catalog, version), catalog);
|
|
65
|
+
project.switchCurrent(version);
|
|
66
|
+
project.state.current = version;
|
|
67
|
+
project.record({ action: 'adopt', from: null, to: version, at: io.now().toISOString(), result: 'ok', migrations: [] });
|
|
68
|
+
publishPins(project, version);
|
|
69
|
+
project.save();
|
|
70
|
+
const unitOptions = { project, nodePath: process.execPath, serviceUser: options.serviceUser, afterUnits: [] };
|
|
71
|
+
const units = { 'magnus-server.service': serverUnit(unitOptions) };
|
|
72
|
+
if (uiEnvFile)
|
|
73
|
+
units['magnus-ui.service'] = uiUnit(unitOptions);
|
|
74
|
+
for (const [name, content] of Object.entries(units))
|
|
75
|
+
writeFileSync(project.path('units', name), content);
|
|
76
|
+
const target = unitDirectory(project, io.env);
|
|
77
|
+
if (options.installUnits && options.supervisor === 'systemd') {
|
|
78
|
+
mkdirSync(target, { recursive: true });
|
|
79
|
+
for (const [name, content] of Object.entries(units))
|
|
80
|
+
writeFileSync(join(target, name), content);
|
|
81
|
+
await enableServices(io, project);
|
|
82
|
+
io.log(`Installed ${Object.keys(units).join(', ')} into ${target}. Stop and disable your old units, then: systemctl ${options.system ? '' : '--user '}restart ${Object.keys(units).join(' ')}`);
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
io.log([
|
|
86
|
+
`Generated units in ${project.path('units')}. To switch over:`,
|
|
87
|
+
' 1. stop and disable the units that run your current install',
|
|
88
|
+
` 2. copy ${project.path('units')}/*.service to ${target}/ and run: systemctl ${options.system ? '' : '--user '}daemon-reload`,
|
|
89
|
+
` 3. systemctl ${options.system ? '' : '--user '}enable --now ${Object.keys(units).join(' ')}`,
|
|
90
|
+
`Then upgrade with: magnus upgrade --dir ${dir}`,
|
|
91
|
+
].join('\n'));
|
|
92
|
+
}
|
|
93
|
+
return 0;
|
|
94
|
+
}
|
|
95
|
+
finally {
|
|
96
|
+
release();
|
|
97
|
+
}
|
|
98
|
+
}
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** Entry point of the `magnus` command; see main.ts for the commands. */
|
|
3
|
+
import { systemIo } from './io.js';
|
|
4
|
+
import { ArgsError, run } from './main.js';
|
|
5
|
+
run(systemIo(), process.argv.slice(2)).then((code) => process.exit(code), (error) => {
|
|
6
|
+
if (error instanceof ArgsError) {
|
|
7
|
+
console.error(`magnus: ${error.message}. Run \`magnus --help\` for usage.`);
|
|
8
|
+
process.exit(2);
|
|
9
|
+
}
|
|
10
|
+
console.error(`magnus: ${error instanceof Error ? error.message : String(error)}`);
|
|
11
|
+
if (process.env['MAGNUS_DEBUG'] && error instanceof Error)
|
|
12
|
+
console.error(error.stack);
|
|
13
|
+
process.exit(1);
|
|
14
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type Io } from './io.js';
|
|
2
|
+
import type { Project } from './project.js';
|
|
3
|
+
export interface Backup {
|
|
4
|
+
file: string;
|
|
5
|
+
restoreCommand: string;
|
|
6
|
+
}
|
|
7
|
+
export declare function restoreCommandFor(project: Project, file: string): string;
|
|
8
|
+
/**
|
|
9
|
+
* Dump before migrating. Compose databases are dumped with the container's own
|
|
10
|
+
* pg_dump (always the server's version); external ones through the target
|
|
11
|
+
* server's `magnus-server backup`, which checks the pg_dump version.
|
|
12
|
+
*/
|
|
13
|
+
export declare function backupDatabase(io: Io, project: Project, version: string, label: string): Promise<Backup>;
|
|
14
|
+
/** Restore a dump. The services must be stopped first. */
|
|
15
|
+
export declare function restoreDatabase(io: Io, project: Project, file: string): Promise<void>;
|
package/dist/database.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** Pre-migration dumps and restores for both database kinds a project can use. */
|
|
2
|
+
import { closeSync, chmodSync, mkdirSync, openSync, statSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { readEnvFile } from './env-file.js';
|
|
5
|
+
import { mustRun } from './io.js';
|
|
6
|
+
import { serverCli } from './install.js';
|
|
7
|
+
function shellQuote(value) {
|
|
8
|
+
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
9
|
+
}
|
|
10
|
+
function composeArgs(project) {
|
|
11
|
+
const db = project.state.database;
|
|
12
|
+
if (db.kind !== 'compose')
|
|
13
|
+
throw new Error('not a compose database');
|
|
14
|
+
return ['compose', '-f', project.path(db.composeFile), '--env-file', project.path('config', 'deps.env')];
|
|
15
|
+
}
|
|
16
|
+
export function restoreCommandFor(project, file) {
|
|
17
|
+
const db = project.state.database;
|
|
18
|
+
if (db.kind === 'compose') {
|
|
19
|
+
return `docker ${composeArgs(project).map(shellQuote).join(' ')} exec -T ${db.service} pg_restore --clean --if-exists --no-owner -U ${db.user} -d ${db.database} < ${shellQuote(file)}`;
|
|
20
|
+
}
|
|
21
|
+
return `pg_restore --clean --if-exists --no-owner -d "$DATABASE_URL" ${shellQuote(file)}`;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Dump before migrating. Compose databases are dumped with the container's own
|
|
25
|
+
* pg_dump (always the server's version); external ones through the target
|
|
26
|
+
* server's `magnus-server backup`, which checks the pg_dump version.
|
|
27
|
+
*/
|
|
28
|
+
export async function backupDatabase(io, project, version, label) {
|
|
29
|
+
const db = project.state.database;
|
|
30
|
+
if (db.kind === 'external') {
|
|
31
|
+
const { stdout } = await serverCli(io, project, version, ['backup', '--label', label], { capture: true });
|
|
32
|
+
const result = JSON.parse(stdout.trim().split('\n').pop() ?? '{}');
|
|
33
|
+
if (!result.file)
|
|
34
|
+
throw new Error('magnus-server backup did not report a dump file');
|
|
35
|
+
return { file: result.file, restoreCommand: restoreCommandFor(project, result.file) };
|
|
36
|
+
}
|
|
37
|
+
const dir = project.path('backups');
|
|
38
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
39
|
+
const file = join(dir, `${io.now().toISOString().replace(/[:.]/g, '-')}-${label.replace(/[^A-Za-z0-9._-]+/g, '_')}.dump`);
|
|
40
|
+
const fd = openSync(file, 'w', 0o600);
|
|
41
|
+
try {
|
|
42
|
+
await mustRun(io, 'docker', [...composeArgs(project), 'exec', '-T', db.service, 'pg_dump', '--format=custom', '--no-owner', '-U', db.user, '-d', db.database], { stdoutFd: fd, capture: false });
|
|
43
|
+
}
|
|
44
|
+
finally {
|
|
45
|
+
closeSync(fd);
|
|
46
|
+
}
|
|
47
|
+
if (statSync(file).size === 0)
|
|
48
|
+
throw new Error(`pg_dump wrote nothing to ${file}`);
|
|
49
|
+
chmodSync(file, 0o600);
|
|
50
|
+
const restoreCommand = restoreCommandFor(project, file);
|
|
51
|
+
writeFileSync(`${file}.json`, `${JSON.stringify({ createdAt: io.now().toISOString(), label, restoreCommand }, null, 2)}\n`, { mode: 0o600 });
|
|
52
|
+
return { file, restoreCommand };
|
|
53
|
+
}
|
|
54
|
+
/** Restore a dump. The services must be stopped first. */
|
|
55
|
+
export async function restoreDatabase(io, project, file) {
|
|
56
|
+
const db = project.state.database;
|
|
57
|
+
if (db.kind === 'compose') {
|
|
58
|
+
const fd = openSync(file, 'r');
|
|
59
|
+
try {
|
|
60
|
+
await mustRun(io, 'docker', [...composeArgs(project), 'exec', '-T', db.service, 'pg_restore', '--clean', '--if-exists', '--no-owner', '-U', db.user, '-d', db.database], { stdinFd: fd });
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
closeSync(fd);
|
|
64
|
+
}
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const url = new URL(readEnvFile(project.envFile('server'))['DATABASE_URL'] ?? '');
|
|
68
|
+
// Keep the password out of the process list.
|
|
69
|
+
const password = decodeURIComponent(url.password);
|
|
70
|
+
url.password = '';
|
|
71
|
+
await mustRun(io, 'pg_restore', ['--clean', '--if-exists', '--no-owner', '-d', url.toString(), file], { env: { ...io.env, ...(password ? { PGPASSWORD: password } : {}) } });
|
|
72
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export declare function readEnvFile(path: string): Record<string, string>;
|
|
2
|
+
/** 64 hex characters: comfortably above every 32-character secret minimum. */
|
|
3
|
+
export declare function generateSecret(): string;
|
|
4
|
+
export interface EnvEntry {
|
|
5
|
+
name: string;
|
|
6
|
+
value: string;
|
|
7
|
+
comment?: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function renderEnv(header: string, sections: Array<{
|
|
10
|
+
title: string;
|
|
11
|
+
entries: EnvEntry[];
|
|
12
|
+
}>): string;
|
|
13
|
+
/** Append entries whose names are not already present; existing values are never changed. */
|
|
14
|
+
export declare function appendMissing(path: string, entries: EnvEntry[], note: string): string[];
|
package/dist/env-file.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/** Minimal env-file handling: read, append missing keys, generate secrets. */
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { parseEnv } from 'node:util';
|
|
5
|
+
export function readEnvFile(path) {
|
|
6
|
+
if (!existsSync(path))
|
|
7
|
+
return {};
|
|
8
|
+
return parseEnv(readFileSync(path, 'utf8'));
|
|
9
|
+
}
|
|
10
|
+
/** 64 hex characters: comfortably above every 32-character secret minimum. */
|
|
11
|
+
export function generateSecret() {
|
|
12
|
+
return randomBytes(32).toString('hex');
|
|
13
|
+
}
|
|
14
|
+
function quote(value) {
|
|
15
|
+
return /^[A-Za-z0-9_./:@%+,=-]*$/.test(value) ? value : `'${value.replace(/'/g, '')}'`;
|
|
16
|
+
}
|
|
17
|
+
export function renderEnv(header, sections) {
|
|
18
|
+
const lines = header.split('\n').map((line) => `# ${line}`.trimEnd());
|
|
19
|
+
for (const section of sections) {
|
|
20
|
+
lines.push('', `# ── ${section.title} ──`);
|
|
21
|
+
for (const entry of section.entries) {
|
|
22
|
+
if (entry.comment)
|
|
23
|
+
lines.push(`# ${entry.comment}`);
|
|
24
|
+
lines.push(`${entry.name}=${quote(entry.value)}`);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return `${lines.join('\n')}\n`;
|
|
28
|
+
}
|
|
29
|
+
/** Append entries whose names are not already present; existing values are never changed. */
|
|
30
|
+
export function appendMissing(path, entries, note) {
|
|
31
|
+
const existing = readEnvFile(path);
|
|
32
|
+
const missing = entries.filter((entry) => existing[entry.name] === undefined);
|
|
33
|
+
if (missing.length === 0)
|
|
34
|
+
return [];
|
|
35
|
+
const block = [`\n# ${note}`, ...missing.flatMap((entry) => [
|
|
36
|
+
...(entry.comment ? [`# ${entry.comment}`] : []),
|
|
37
|
+
`${entry.name}=${quote(entry.value)}`,
|
|
38
|
+
])].join('\n');
|
|
39
|
+
const current = existsSync(path) ? readFileSync(path, 'utf8') : '';
|
|
40
|
+
writeFileSync(path, `${current.replace(/\n*$/, '\n')}${block}\n`, { mode: 0o600 });
|
|
41
|
+
return missing.map((entry) => entry.name);
|
|
42
|
+
}
|
package/dist/health.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Io } from './io.js';
|
|
2
|
+
import type { Project } from './project.js';
|
|
3
|
+
export interface RuntimeInfo {
|
|
4
|
+
version: string;
|
|
5
|
+
pid: number;
|
|
6
|
+
port: number;
|
|
7
|
+
startedAt: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function runtimeFile(project: Project): string;
|
|
10
|
+
export declare function readRuntime(project: Project): RuntimeInfo | null;
|
|
11
|
+
export interface WaitOptions {
|
|
12
|
+
version: string;
|
|
13
|
+
/** The runtime file must name a process started after this instant. */
|
|
14
|
+
startedAfter: Date;
|
|
15
|
+
timeoutMs: number;
|
|
16
|
+
}
|
|
17
|
+
export interface HealthResult {
|
|
18
|
+
ok: boolean;
|
|
19
|
+
detail: string;
|
|
20
|
+
}
|
|
21
|
+
/** First server release that writes run/server-runtime.json. */
|
|
22
|
+
export declare const RUNTIME_FILE_SINCE = "1.1.0";
|
|
23
|
+
export declare function waitForHealthy(io: Io, project: Project, options: WaitOptions): Promise<HealthResult>;
|