blueprint-shared-templates 0.2.0 → 0.3.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/base/.github/ISSUE_TEMPLATE/bug.yml +2 -2
- package/base/.github/ISSUE_TEMPLATE/hotfix.yml +1 -1
- package/base/.github/actions/setup-workspace/action.yml +2 -2
- package/base/.github/workflows/auto-merge.yml +4 -0
- package/base/.github/workflows/ci.yml +21 -1
- package/base/scripts/ci/run-affected.sh +6 -0
- package/base/scripts/lib/common.sh +1 -1
- package/base/scripts/lib/retry.mjs +36 -6
- package/base/scripts/merge/decide.mjs +30 -15
- package/deploy/.github/workflows/deploy-prerelease.yml +6 -50
- package/deploy/.github/workflows/deploy-prod.yml +103 -0
- package/deploy/scripts/deploy/plan-prod.sh +57 -0
- package/deploy/scripts/deploy/promote.sh +23 -7
- package/deploy/scripts/deploy/publish-bundle.sh +10 -1
- package/deploy/scripts/deploy/route-tag.sh +10 -12
- package/deploy/scripts/deploy/run-prerelease.sh +4 -7
- package/deploy/scripts/deploy/{run-production.sh → run-prod.sh} +15 -17
- package/deploy/scripts/deploy/writeback-ops.sh +71 -40
- package/hub/scripts/release/dispatch-release-lines.sh +25 -2
- package/hub/scripts/release/snapshot-members.sh +1 -1
- package/ops/.github/workflows/ops-deploy.yml +92 -11
- package/ops/schemas/targets.schema.json +209 -0
- package/ops/scripts/ci/check-targets.mjs +291 -0
- package/ops/scripts/deploy/apply-iac.sh +89 -0
- package/ops/scripts/deploy/apply-ops.sh +101 -48
- package/ops/scripts/deploy/ops-run.sh +50 -12
- package/ops/scripts/deploy/smoke.sh +35 -16
- package/ops/scripts/lib/ops-steps.sh +75 -0
- package/org/scripts/ci/check-org-values.mjs +91 -0
- package/package.json +2 -2
- package/publish/.github/workflows/publish.yml +12 -3
- package/publish/scripts/release/mirror-units.sh +45 -5
- package/publish/scripts/release/publish-units.sh +28 -4
- package/release/.github/workflows/advance-release.yml +107 -0
- package/release/.github/workflows/close-release.yml +133 -0
- package/release/.github/workflows/merge-back.yml +82 -0
- package/release/.github/workflows/merge-release-pr.yml +82 -0
- package/release/.github/workflows/open-release-line.yml +14 -5
- package/release/.github/workflows/release-line-finalize.yml +5 -3
- package/release/.github/workflows/release-please.yml +99 -15
- package/release/.github/workflows/sync-release-tools.yml +91 -0
- package/release/release-policy.json +1 -1
- package/release/schemas/release-policy.schema.json +13 -3
- package/release/scripts/ci/branch-exists.sh +27 -0
- package/release/scripts/ci/check-release-policy.sh +13 -2
- package/release/scripts/ci/pin-train.sh +5 -3
- package/release/scripts/ci/release-train.sh +22 -3
- package/release/scripts/lib/release-plan.sh +3 -1
- package/release/scripts/lib/release-pr.sh +275 -11
- package/release/scripts/lib/release-stages.sh +245 -27
- package/release/scripts/release/check-trigger-actor.sh +32 -0
- package/release/scripts/release/close-ready.mjs +72 -0
- package/release/scripts/release/close-ready.sh +70 -0
- package/release/scripts/release/cut-release.sh +34 -3
- package/release/scripts/release/ensure-stage-deploys.sh +3 -3
- package/release/scripts/release/finalize-release.sh +47 -15
- package/release/scripts/release/merge-back-ready.sh +27 -0
- package/release/scripts/release/merge-release-pr.sh +34 -107
- package/release/scripts/release/open-release-line.sh +28 -8
- package/release/scripts/release/pin-release-pr.sh +53 -0
- package/release/scripts/release/product-release-notes.sh +28 -0
- package/release/scripts/release/sync-release-tools.sh +137 -0
- package/release/scripts/release/{verify-production.sh → verify-prod.sh} +11 -10
- package/transform.mjs +2 -3
- package/verify/.github/workflows/{verify-production.yml → verify-prod.yml} +7 -7
- package/verify/scripts/release/verify-ops.sh +4 -4
- package/deploy/.github/workflows/deploy-production.yml +0 -173
- package/deploy/scripts/deploy/plan-production.sh +0 -43
- package/infra/.github/workflows/deploy-prerelease.yml +0 -157
- package/infra/.github/workflows/deploy-production.yml +0 -173
- package/infra/scripts/deploy/apply-infra.sh +0 -46
- package/infra/scripts/deploy/apply-prerelease.sh +0 -22
- package/infra/scripts/deploy/apply-production.sh +0 -33
- package/infra/scripts/deploy/route-tag.sh +0 -65
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
{
|
|
2
|
+
"description": "`ops/targets.json` 的格式,組織層與產品層共用。`hosts` 宣告位置與它的能力,`instances` 宣告實例。實例的位置二選一:自己寫 `host`(放在母叢集或租戶裡時加 `cluster`),或用 `ref` 指向別的倉宣告的實例。`host` 指向別的倉宣告的位置時加 `<RepoName>:` 前綴。只有 `shared` 實例必寫 `serves`。這份 schema 驗證鍵的格式、`host` 與 `ref` 二選一、`serves` 只在 `shared` 實例、`provider` 是 `orbstack` 時只能有一個母叢集。三項由程式檢查:`ref` 指到的實例 `kind` 相同、`host` 與 `cluster` 指到的位置與母叢集存在、帶環境後綴的上層裡實例環境相同。",
|
|
3
|
+
"type": "object",
|
|
4
|
+
"additionalProperties": false,
|
|
5
|
+
"properties": {
|
|
6
|
+
"hosts": {
|
|
7
|
+
"type": "object",
|
|
8
|
+
"description": "鍵是位置名,`hosts` 與 `clusters` 是保留名",
|
|
9
|
+
"propertyNames": {
|
|
10
|
+
"pattern": "^[a-z0-9][a-z0-9-]*$",
|
|
11
|
+
"not": {
|
|
12
|
+
"enum": [
|
|
13
|
+
"hosts",
|
|
14
|
+
"clusters"
|
|
15
|
+
]
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"additionalProperties": {
|
|
19
|
+
"type": "object",
|
|
20
|
+
"required": [
|
|
21
|
+
"provider"
|
|
22
|
+
],
|
|
23
|
+
"additionalProperties": false,
|
|
24
|
+
"properties": {
|
|
25
|
+
"provider": {
|
|
26
|
+
"type": "string",
|
|
27
|
+
"minLength": 1,
|
|
28
|
+
"description": "供應商,例如 `gcp`、`cloudflare`、`orbstack`"
|
|
29
|
+
},
|
|
30
|
+
"machine": {
|
|
31
|
+
"enum": [
|
|
32
|
+
"macos",
|
|
33
|
+
"linux"
|
|
34
|
+
],
|
|
35
|
+
"description": "實體機器才寫"
|
|
36
|
+
},
|
|
37
|
+
"project": {
|
|
38
|
+
"type": "string",
|
|
39
|
+
"pattern": "^[a-z][a-z0-9-]{4,28}[a-z0-9]$",
|
|
40
|
+
"description": "雲端專案 ID,GCP 與 AWS 才寫。專案 ID 全域唯一、建立後不能改,所以和位置名分開記"
|
|
41
|
+
},
|
|
42
|
+
"region": {
|
|
43
|
+
"type": "string",
|
|
44
|
+
"minLength": 1
|
|
45
|
+
},
|
|
46
|
+
"vm": {
|
|
47
|
+
"type": "boolean",
|
|
48
|
+
"description": "能開 VM"
|
|
49
|
+
},
|
|
50
|
+
"serverless": {
|
|
51
|
+
"type": "boolean",
|
|
52
|
+
"description": "能跑 serverless"
|
|
53
|
+
},
|
|
54
|
+
"clusters": {
|
|
55
|
+
"type": "object",
|
|
56
|
+
"description": "鍵是母叢集名,值是那個母叢集提供的層",
|
|
57
|
+
"propertyNames": {
|
|
58
|
+
"pattern": "^[a-z0-9][a-z0-9-]*$"
|
|
59
|
+
},
|
|
60
|
+
"additionalProperties": {
|
|
61
|
+
"type": "array",
|
|
62
|
+
"uniqueItems": true,
|
|
63
|
+
"minItems": 1,
|
|
64
|
+
"items": {
|
|
65
|
+
"enum": [
|
|
66
|
+
"namespace",
|
|
67
|
+
"vcluster",
|
|
68
|
+
"node"
|
|
69
|
+
]
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
"if": {
|
|
75
|
+
"properties": {
|
|
76
|
+
"provider": {
|
|
77
|
+
"const": "orbstack"
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
"required": [
|
|
81
|
+
"provider"
|
|
82
|
+
]
|
|
83
|
+
},
|
|
84
|
+
"then": {
|
|
85
|
+
"properties": {
|
|
86
|
+
"clusters": {
|
|
87
|
+
"maxProperties": 1
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
"instances": {
|
|
94
|
+
"type": "object",
|
|
95
|
+
"description": "鍵是 `<用途>/<環境>`",
|
|
96
|
+
"propertyNames": {
|
|
97
|
+
"pattern": "^[a-z0-9][a-z0-9-]*/(dev|stg|prod|shared)$",
|
|
98
|
+
"not": {
|
|
99
|
+
"pattern": "^(hosts|clusters)/"
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
"patternProperties": {
|
|
103
|
+
"^[a-z0-9][a-z0-9-]*/shared$": {
|
|
104
|
+
"allOf": [
|
|
105
|
+
{
|
|
106
|
+
"$ref": "#/$defs/instance"
|
|
107
|
+
}
|
|
108
|
+
],
|
|
109
|
+
"required": [
|
|
110
|
+
"serves"
|
|
111
|
+
]
|
|
112
|
+
},
|
|
113
|
+
"^[a-z0-9][a-z0-9-]*/(dev|stg|prod)$": {
|
|
114
|
+
"allOf": [
|
|
115
|
+
{
|
|
116
|
+
"$ref": "#/$defs/instance"
|
|
117
|
+
}
|
|
118
|
+
],
|
|
119
|
+
"not": {
|
|
120
|
+
"required": [
|
|
121
|
+
"serves"
|
|
122
|
+
]
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
"additionalProperties": false
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
"$defs": {
|
|
130
|
+
"instance": {
|
|
131
|
+
"type": "object",
|
|
132
|
+
"required": [
|
|
133
|
+
"kind"
|
|
134
|
+
],
|
|
135
|
+
"additionalProperties": false,
|
|
136
|
+
"properties": {
|
|
137
|
+
"kind": {
|
|
138
|
+
"enum": [
|
|
139
|
+
"vm",
|
|
140
|
+
"cluster",
|
|
141
|
+
"vcluster",
|
|
142
|
+
"namespace",
|
|
143
|
+
"serverless",
|
|
144
|
+
"cloud"
|
|
145
|
+
]
|
|
146
|
+
},
|
|
147
|
+
"host": {
|
|
148
|
+
"type": "string",
|
|
149
|
+
"pattern": "^([A-Za-z0-9_.-]+:)?[a-z0-9][a-z0-9-]*$",
|
|
150
|
+
"description": "位置,別的倉宣告的位置寫 `<RepoName>:<位置>`"
|
|
151
|
+
},
|
|
152
|
+
"cluster": {
|
|
153
|
+
"type": "string",
|
|
154
|
+
"pattern": "^[a-z0-9][a-z0-9-]*$",
|
|
155
|
+
"description": "放在母叢集或租戶裡時寫母叢集名"
|
|
156
|
+
},
|
|
157
|
+
"ref": {
|
|
158
|
+
"type": "string",
|
|
159
|
+
"pattern": "^[A-Za-z0-9_.-]+:[a-z0-9][a-z0-9-]*/(dev|stg|prod|shared)$",
|
|
160
|
+
"description": "別的倉宣告的實例 `<RepoName>:<用途>/<環境>`"
|
|
161
|
+
},
|
|
162
|
+
"serves": {
|
|
163
|
+
"type": "array",
|
|
164
|
+
"minItems": 1,
|
|
165
|
+
"uniqueItems": true,
|
|
166
|
+
"items": {
|
|
167
|
+
"enum": [
|
|
168
|
+
"dev",
|
|
169
|
+
"stg",
|
|
170
|
+
"prod"
|
|
171
|
+
]
|
|
172
|
+
},
|
|
173
|
+
"description": "`shared` 實例服務的環境"
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
"oneOf": [
|
|
177
|
+
{
|
|
178
|
+
"required": [
|
|
179
|
+
"host"
|
|
180
|
+
],
|
|
181
|
+
"not": {
|
|
182
|
+
"required": [
|
|
183
|
+
"ref"
|
|
184
|
+
]
|
|
185
|
+
}
|
|
186
|
+
},
|
|
187
|
+
{
|
|
188
|
+
"required": [
|
|
189
|
+
"ref"
|
|
190
|
+
],
|
|
191
|
+
"not": {
|
|
192
|
+
"anyOf": [
|
|
193
|
+
{
|
|
194
|
+
"required": [
|
|
195
|
+
"host"
|
|
196
|
+
]
|
|
197
|
+
},
|
|
198
|
+
{
|
|
199
|
+
"required": [
|
|
200
|
+
"cluster"
|
|
201
|
+
]
|
|
202
|
+
}
|
|
203
|
+
]
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
]
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
// Checks ops/targets.json for what its JSON Schema cannot: the three cross-field rules of targets.json and the naming of the clusters
|
|
2
|
+
// and tenants. No dependency except ajv 8 from the root devDependencies, which validates the schema first.
|
|
3
|
+
//
|
|
4
|
+
// 1. ref An instance that points at an instance of another repository with `ref` has the same kind as the instance it points at.
|
|
5
|
+
// 2. host The location in `host` and the parent cluster in `cluster` exist in the targets.json that declares them.
|
|
6
|
+
// 3. env A location or parent cluster whose name ends in an environment suffix (-dev, -stg, -prod, -shared) holds the instances of that
|
|
7
|
+
// environment only.
|
|
8
|
+
// + naming A parent cluster is named after the environments it serves, and a tenant (the cluster of a virtual cluster, the namespace of
|
|
9
|
+
// an instance) is worked out from the instance path and its parents, by the rule of cluster-naming (clusterName below).
|
|
10
|
+
// + dirs Every iac/hosts/<location>/clusters/<cluster> and workloads/hosts/<location>/clusters/<cluster> directory names a parent
|
|
11
|
+
// cluster that targets.json declares.
|
|
12
|
+
//
|
|
13
|
+
// Across repositories. A `host` of the form <RepoName>:<location> and a `ref` of the form <RepoName>:<purpose>/<environment> point at another
|
|
14
|
+
// repository. <RepoName> has to be in the list of repositories of ONE organization (--repos): two organizations may each have a repository of the same
|
|
15
|
+
// name, so a list that mixes them could not tell which one a name means. A name outside the list fails, which catches a mistyped name. When the
|
|
16
|
+
// repository named is in the list but its targets.json was not given (--targets <RepoName>=<file>), the check prints "未核對" with the instance and
|
|
17
|
+
// the host and does not fail. A repository checked alone, as in its own CI, therefore cannot check what points elsewhere, and a run
|
|
18
|
+
// that is given the targets.json of all the repositories of the organization checks all of it. The environments a parent cluster serves are
|
|
19
|
+
// worked out from the instances of every targets.json given.
|
|
20
|
+
//
|
|
21
|
+
// usage: node scripts/ci/check-targets.mjs [--repo <RepoName>] [--repos <file>] [--root <dir>] [--targets <RepoName>=<file>]...
|
|
22
|
+
// --repo the repository this runs in (default: the name in package.json of --root)
|
|
23
|
+
// --repos JSON array of the repository names of the organization (default: scripts/ci/org-repos.json)
|
|
24
|
+
// --root the repository root (default: the current directory); its ops/targets.json and ops/{iac,workloads}/hosts/ are checked
|
|
25
|
+
// --targets the targets.json of another repository of the organization, as <RepoName>=<file>; repeatable
|
|
26
|
+
// Exit status: 0 everything checked passes ("未核對" does not fail), 1 a rule is broken or a file is unreadable, 2 wrong arguments.
|
|
27
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
28
|
+
import { dirname, join, resolve } from "node:path";
|
|
29
|
+
import { fileURLToPath } from "node:url";
|
|
30
|
+
|
|
31
|
+
// The environment suffixes of cluster-naming (blueprint-shared.infra-layout.cluster-naming, environmentSuffixes), and the three cases of its
|
|
32
|
+
// `decide` in the order they are tried. tests/targets-check.test.mjs compares both with the fact.
|
|
33
|
+
export const ENVIRONMENT_SUFFIXES = ["-dev", "-stg", "-prod", "-shared"];
|
|
34
|
+
export const DECIDE = [
|
|
35
|
+
{ name: "<purpose>", applies: ({ parentEnv }) => parentEnv !== undefined },
|
|
36
|
+
{ name: "<purpose>-<environment>", applies: ({ serves }) => serves.length === 1 },
|
|
37
|
+
{ name: "<purpose>", applies: () => true },
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
// the environment a name ends in (dev, stg, prod or shared), or undefined
|
|
41
|
+
export const suffixEnvOf = (name) => ENVIRONMENT_SUFFIXES.find((s) => name.endsWith(s))?.slice(1);
|
|
42
|
+
export const withoutSuffix = (name) => {
|
|
43
|
+
const s = ENVIRONMENT_SUFFIXES.find((x) => name.endsWith(x));
|
|
44
|
+
return s ? name.slice(0, -s.length) : name;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// The name of a cluster or tenant from its purpose, the names of its parents (outside in) and the environments it serves. Throws when a parent
|
|
48
|
+
// ends in an environment suffix and an environment served is another one.
|
|
49
|
+
export function clusterName({ purpose, parents, serves, region, sequence }) {
|
|
50
|
+
const parentEnv = parents.map(suffixEnvOf).find((e) => e !== undefined);
|
|
51
|
+
const wrong = parentEnv === undefined ? [] : serves.filter((env) => env !== parentEnv);
|
|
52
|
+
if (wrong.length > 0) throw new Error(`a parent ends in -${parentEnv} but ${wrong.join(", ")} is served inside it`);
|
|
53
|
+
const picked = DECIDE.find((d) => d.applies({ parentEnv, serves })).name;
|
|
54
|
+
const name = picked.replace("<purpose>", purpose).replace("<environment>", serves[0]);
|
|
55
|
+
if (region) return `${name}-${region}`;
|
|
56
|
+
if (sequence) return `${name}-${sequence}`;
|
|
57
|
+
return name;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const split = (ref) => {
|
|
61
|
+
const at = ref.indexOf(":");
|
|
62
|
+
return at === -1 ? { repo: undefined, rest: ref } : { repo: ref.slice(0, at), rest: ref.slice(at + 1) };
|
|
63
|
+
};
|
|
64
|
+
const envOfKey = (key) => key.slice(key.lastIndexOf("/") + 1);
|
|
65
|
+
const purposeOfKey = (key) => key.slice(0, key.lastIndexOf("/"));
|
|
66
|
+
|
|
67
|
+
const subdirs = (p) => (existsSync(p) ? readdirSync(p).filter((n) => statSync(join(p, n)).isDirectory()).toSorted() : []);
|
|
68
|
+
|
|
69
|
+
// The directories iac/hosts/<location>/clusters/<cluster> and workloads/hosts/<location>/clusters/<cluster> under an ops directory.
|
|
70
|
+
export function scanClusterDirs(opsDir) {
|
|
71
|
+
return ["iac", "workloads"].flatMap((tree) =>
|
|
72
|
+
subdirs(join(opsDir, tree, "hosts")).flatMap((host) => subdirs(join(opsDir, tree, "hosts", host, "clusters")).map((cluster) => ({ tree, host, cluster }))),
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const instancesOf = (e) => Object.entries(e.targets.instances ?? {});
|
|
77
|
+
|
|
78
|
+
// entries: [{ repo, targets, dirs }], one per targets.json given. repos: the repository names of the organization.
|
|
79
|
+
// Returns { errors, unchecked, ok, counts }: lines to print, and how many of each check ran.
|
|
80
|
+
export function checkTargets({ repos, entries }) {
|
|
81
|
+
const errors = [];
|
|
82
|
+
const unchecked = [];
|
|
83
|
+
const ok = [];
|
|
84
|
+
const counts = { ref: 0, host: 0, cluster: 0, environment: 0, parentCluster: 0, tenant: 0, dir: 0 };
|
|
85
|
+
const byRepo = new Map(entries.map((e) => [e.repo, e]));
|
|
86
|
+
const listed = new Set(repos);
|
|
87
|
+
|
|
88
|
+
// where an instance sits: the repository that declares the location, the location and the parent cluster
|
|
89
|
+
const placeOf = (e, inst) => {
|
|
90
|
+
const { repo, rest } = split(inst.host);
|
|
91
|
+
return { repo: repo ?? e.repo, host: rest, cluster: inst.cluster };
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// the environments served by each parent cluster, from the instances of every targets.json given
|
|
95
|
+
const served = new Map();
|
|
96
|
+
const tenants = new Map();
|
|
97
|
+
for (const e of entries) {
|
|
98
|
+
for (const [key, inst] of instancesOf(e)) {
|
|
99
|
+
if (inst.host === undefined || inst.cluster === undefined) continue;
|
|
100
|
+
const p = placeOf(e, inst);
|
|
101
|
+
const at = `${p.repo}/${p.host}/${p.cluster}`;
|
|
102
|
+
if (!served.has(at)) served.set(at, new Set());
|
|
103
|
+
served.get(at).add(envOfKey(key));
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
for (const e of entries) {
|
|
108
|
+
const hosts = e.targets.hosts ?? {};
|
|
109
|
+
for (const [key, inst] of instancesOf(e)) {
|
|
110
|
+
const who = `${e.repo} ${key}`;
|
|
111
|
+
const env = envOfKey(key);
|
|
112
|
+
if (inst.ref !== undefined) {
|
|
113
|
+
const { repo, rest } = split(inst.ref);
|
|
114
|
+
if (!listed.has(repo)) {
|
|
115
|
+
errors.push(`✗ ${who}: ref ${inst.ref} 指到的倉 ${repo} 不在這個組織的倉清單(${[...listed].join(", ")})`);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
const target = byRepo.get(repo);
|
|
119
|
+
if (!target) {
|
|
120
|
+
unchecked.push(`未核對 ${who}: ref ${inst.ref},倉 ${repo} 沒有提供 targets.json`);
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
counts.ref += 1;
|
|
124
|
+
const found = target.targets.instances?.[rest];
|
|
125
|
+
if (!found) errors.push(`✗ ${who}: ref ${inst.ref} 指到的實例 ${rest} 不在 ${repo} 的 targets.json`);
|
|
126
|
+
else if (found.kind !== inst.kind) errors.push(`✗ ${who}: kind 是 ${inst.kind},但 ref ${inst.ref} 指到的實例 kind 是 ${found.kind}`);
|
|
127
|
+
else ok.push(`✓ ${who}: ref ${inst.ref} 的 kind 相同(${inst.kind})`);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const place = placeOf(e, inst);
|
|
132
|
+
const parents = [place.host, ...(place.cluster ? [place.cluster] : [])];
|
|
133
|
+
for (const parent of parents) {
|
|
134
|
+
const parentEnv = suffixEnvOf(parent);
|
|
135
|
+
if (parentEnv !== undefined && parentEnv !== env) {
|
|
136
|
+
errors.push(`✗ ${who}: ${parent} 帶 -${parentEnv} 後綴,只放 ${parentEnv} 的實例,但這個實例的環境是 ${env}(位置 ${place.host})`);
|
|
137
|
+
} else if (parentEnv !== undefined) {
|
|
138
|
+
counts.environment += 1;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
if (!listed.has(place.repo)) {
|
|
143
|
+
errors.push(`✗ ${who}: host ${inst.host} 的倉 ${place.repo} 不在這個組織的倉清單(${[...listed].join(", ")})`);
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
const declaring = place.repo === e.repo ? e : byRepo.get(place.repo);
|
|
147
|
+
if (!declaring) {
|
|
148
|
+
unchecked.push(`未核對 ${who}: host ${inst.host}${inst.cluster ? ` cluster ${inst.cluster}` : ""},倉 ${place.repo} 沒有提供 targets.json`);
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
counts.host += 1;
|
|
152
|
+
const host = declaring.targets.hosts?.[place.host];
|
|
153
|
+
if (!host) {
|
|
154
|
+
errors.push(`✗ ${who}: host ${place.host} 不在 ${place.repo} 的 targets.json 的 hosts`);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
if (place.cluster !== undefined) {
|
|
158
|
+
counts.cluster += 1;
|
|
159
|
+
if (!host.clusters?.[place.cluster]) {
|
|
160
|
+
errors.push(`✗ ${who}: 位置 ${place.host} 沒有母叢集 ${place.cluster}(${place.repo} 的 targets.json 宣告的是 ${Object.keys(host.clusters ?? {}).join(", ") || "沒有"})`);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (["vcluster", "namespace"].includes(inst.kind)) {
|
|
164
|
+
let name;
|
|
165
|
+
try {
|
|
166
|
+
name = clusterName({ purpose: purposeOfKey(key), parents, serves: [env] });
|
|
167
|
+
} catch {
|
|
168
|
+
continue; // a parent of another environment is reported above, and it has no name to work out
|
|
169
|
+
}
|
|
170
|
+
counts.tenant += 1;
|
|
171
|
+
const tenantAt = `${place.repo}/${place.host}/${place.cluster}/${name}`;
|
|
172
|
+
if (tenants.has(tenantAt)) errors.push(`✗ ${who}: 租戶名 ${name} 和 ${tenants.get(tenantAt)} 相同,都在 ${place.host}/${place.cluster}`);
|
|
173
|
+
else tenants.set(tenantAt, who);
|
|
174
|
+
ok.push(`✓ ${who}: 租戶名 ${name}(${parents.join("/")})`);
|
|
175
|
+
}
|
|
176
|
+
} else {
|
|
177
|
+
ok.push(`✓ ${who}: 位置 ${place.host} 存在`);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// the names of the parent clusters, from the environments the instances put in them
|
|
182
|
+
for (const [location, host] of Object.entries(hosts)) {
|
|
183
|
+
for (const cluster of Object.keys(host.clusters ?? {})) {
|
|
184
|
+
const envs = [...(served.get(`${e.repo}/${location}/${cluster}`) ?? [])].toSorted();
|
|
185
|
+
if (envs.length === 0) continue;
|
|
186
|
+
counts.parentCluster += 1;
|
|
187
|
+
const purpose = withoutSuffix(cluster);
|
|
188
|
+
let expected;
|
|
189
|
+
try {
|
|
190
|
+
expected = clusterName({ purpose, parents: [location], serves: envs });
|
|
191
|
+
} catch {
|
|
192
|
+
continue; // an instance of another environment under a location with a suffix is reported above
|
|
193
|
+
}
|
|
194
|
+
const why = suffixEnvOf(location) !== undefined
|
|
195
|
+
? `位置 ${location} 已帶環境後綴,母叢集名不再加環境`
|
|
196
|
+
: envs.length === 1 ? `位置 ${location} 沒有環境後綴,只服務 ${envs[0]}` : `位置 ${location} 沒有環境後綴,服務 ${envs.join("、")},沒有單一環境可寫`;
|
|
197
|
+
if (cluster !== expected) errors.push(`✗ ${e.repo} 母叢集 ${location}/${cluster}: ${why},應改成 ${expected}`);
|
|
198
|
+
else ok.push(`✓ ${e.repo} 母叢集 ${location}/${cluster}: 服務 ${envs.join("、")},名稱符合`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
for (const d of e.dirs ?? []) {
|
|
203
|
+
counts.dir += 1;
|
|
204
|
+
if (!hosts[d.host]?.clusters?.[d.cluster]) errors.push(`✗ ${e.repo} ops/${d.tree}/hosts/${d.host}/clusters/${d.cluster}: targets.json 沒有宣告位置 ${d.host} 的母叢集 ${d.cluster}`);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
return { errors, unchecked, ok, counts };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// The schema of targets.json (schemas/targets.schema.json, the same JSON Schema as the fact blueprint-shared.infra-layout.targets).
|
|
211
|
+
export async function schemaErrors(targets, schema) {
|
|
212
|
+
const { default: Ajv } = await import("ajv");
|
|
213
|
+
const validate = new Ajv({ allErrors: true, strict: false }).compile(schema);
|
|
214
|
+
return validate(targets) ? [] : validate.errors.map((x) => `${x.instancePath || "/"} ${x.message}`);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
export const SCHEMA_FILE = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "schemas", "targets.schema.json");
|
|
218
|
+
|
|
219
|
+
// Reads, validates, checks and prints. `inputs` is [{ repo, file, opsDir? }]; opsDir is the ops directory whose cluster directories are checked.
|
|
220
|
+
export async function runCheck({ repos, inputs, schemaFile = SCHEMA_FILE, out = console.log, err = console.error }) {
|
|
221
|
+
const schema = JSON.parse(readFileSync(schemaFile, "utf8"));
|
|
222
|
+
const entries = [];
|
|
223
|
+
let failed = false;
|
|
224
|
+
for (const input of inputs) {
|
|
225
|
+
let targets;
|
|
226
|
+
try {
|
|
227
|
+
targets = JSON.parse(readFileSync(input.file, "utf8"));
|
|
228
|
+
} catch (e) {
|
|
229
|
+
err(`✗ ${input.repo}: 讀不到 ${input.file}(${e.message})`);
|
|
230
|
+
failed = true;
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
const bad = await schemaErrors(targets, schema);
|
|
234
|
+
if (bad.length > 0) {
|
|
235
|
+
for (const b of bad) err(`✗ ${input.repo} ${input.file} 不符合 schema: ${b}`);
|
|
236
|
+
failed = true;
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
out(`✓ ${input.repo} ${input.file} 符合 schema`);
|
|
240
|
+
entries.push({ repo: input.repo, targets, dirs: input.opsDir ? scanClusterDirs(input.opsDir) : [] });
|
|
241
|
+
}
|
|
242
|
+
const result = checkTargets({ repos, entries });
|
|
243
|
+
for (const line of result.ok) out(line);
|
|
244
|
+
for (const line of result.unchecked) out(line);
|
|
245
|
+
for (const line of result.errors) err(line);
|
|
246
|
+
const c = result.counts;
|
|
247
|
+
const tail = result.unchecked.length > 0 ? `;${result.unchecked.length} 筆未核對` : "";
|
|
248
|
+
const summary = `${entries.length} 個 targets.json(${entries.map((e) => e.repo).join(", ")}):ref ${c.ref} 筆、host ${c.host} 筆、母叢集 ${c.cluster} 筆、環境後綴 ${c.environment} 筆、母叢集命名 ${c.parentCluster} 筆、租戶命名 ${c.tenant} 筆、叢集目錄 ${c.dir} 筆${tail}`;
|
|
249
|
+
if (failed || result.errors.length > 0) {
|
|
250
|
+
err(`✗ ${summary}`);
|
|
251
|
+
return 1;
|
|
252
|
+
}
|
|
253
|
+
out(`✓ ${summary}`);
|
|
254
|
+
return 0;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export async function main(argv) {
|
|
258
|
+
const opts = { targets: [] };
|
|
259
|
+
for (let i = 0; i < argv.length; i += 2) {
|
|
260
|
+
const k = argv[i];
|
|
261
|
+
if (!["--repo", "--repos", "--root", "--targets"].includes(k) || argv[i + 1] === undefined) {
|
|
262
|
+
console.error(`✗ 不認得的參數 ${k}\nusage: check-targets.mjs [--repo <RepoName>] [--repos <file>] [--root <dir>] [--targets <RepoName>=<file>]...`);
|
|
263
|
+
return 2;
|
|
264
|
+
}
|
|
265
|
+
if (k === "--targets") opts.targets.push(argv[i + 1]);
|
|
266
|
+
else opts[k.slice(2)] = argv[i + 1];
|
|
267
|
+
}
|
|
268
|
+
const root = resolve(opts.root ?? ".");
|
|
269
|
+
const reposFile = opts.repos ?? join(root, "scripts/ci/org-repos.json");
|
|
270
|
+
let repos;
|
|
271
|
+
let repo = opts.repo;
|
|
272
|
+
try {
|
|
273
|
+
repos = JSON.parse(readFileSync(reposFile, "utf8")).map((r) => (typeof r === "string" ? r : r.repoName));
|
|
274
|
+
repo ??= JSON.parse(readFileSync(join(root, "package.json"), "utf8")).name;
|
|
275
|
+
} catch (e) {
|
|
276
|
+
console.error(`✗ ${e.message}`);
|
|
277
|
+
return 1;
|
|
278
|
+
}
|
|
279
|
+
const inputs = [{ repo, file: join(root, "ops/targets.json"), opsDir: join(root, "ops") }];
|
|
280
|
+
for (const spec of opts.targets) {
|
|
281
|
+
const at = spec.indexOf("=");
|
|
282
|
+
if (at <= 0) {
|
|
283
|
+
console.error(`✗ --targets 要寫成 <RepoName>=<file>:${spec}`);
|
|
284
|
+
return 2;
|
|
285
|
+
}
|
|
286
|
+
inputs.push({ repo: spec.slice(0, at), file: spec.slice(at + 1) });
|
|
287
|
+
}
|
|
288
|
+
return runCheck({ repos, inputs });
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (process.argv[1] === fileURLToPath(import.meta.url)) process.exitCode = await main(process.argv.slice(2));
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# Create the cloud resources that the iac steps of an environment declare. A step is a directory ops/iac/<purpose>/<env>/<name>/ with an
|
|
3
|
+
# OpenTofu root module: main.tf and terraform.tfvars.json. Per step, in the order of ops/needs.json (scripts/lib/ops-steps.sh):
|
|
4
|
+
# `tofu init` with the state backend settings, then `tofu apply`. The apply is idempotent, so a step whose resources are in place changes
|
|
5
|
+
# nothing, and every run of ops-deploy.yml can apply the steps again.
|
|
6
|
+
#
|
|
7
|
+
# The state is kept in an S3-compatible bucket (R2) that the organization provides, one state per step. The runner of the iac job is
|
|
8
|
+
# GitHub-hosted and starts empty, so without a backend the second apply would try to create what exists. When a setting is missing the
|
|
9
|
+
# script prints which ones and ends 1 before it calls tofu at all, so nothing is created without a state to remember it.
|
|
10
|
+
#
|
|
11
|
+
# With --only the steps are those that the workloads steps of the given units need, directly or not, and nothing else: a run that
|
|
12
|
+
# deploys one unit creates what that unit binds and leaves the other resources alone.
|
|
13
|
+
#
|
|
14
|
+
# usage: apply-iac.sh <env> [--only unit1,unit2]
|
|
15
|
+
# env: TOFU the command that runs OpenTofu (default `tofu`; local mode: the stand-in, scripts/lib/tofu-sim.mjs)
|
|
16
|
+
# TOFU_STATE_BUCKET, TOFU_STATE_ENDPOINT the bucket and the S3 endpoint of the state backend
|
|
17
|
+
# TOFU_STATE_ACCESS_KEY_ID, TOFU_STATE_SECRET_ACCESS_KEY the access key of that bucket
|
|
18
|
+
# CLOUDFLARE_API_TOKEN, CLOUDFLARE_ACCOUNT_ID read by the cloudflare provider; set only by the workflow step that deploys
|
|
19
|
+
# DEPLOY_LOG_DIR where <env>.iac.log is appended (default tmp/deploy-log)
|
|
20
|
+
set -euo pipefail
|
|
21
|
+
env_name="${1:?usage: apply-iac.sh <env> [--only u1,u2]}"
|
|
22
|
+
shift
|
|
23
|
+
only=""
|
|
24
|
+
while [[ $# -gt 0 ]]; do
|
|
25
|
+
case "$1" in --only) only="$2"; shift 2 ;; *) printf '%s\n' >&2 "unknown argument: $1"; exit 2 ;; esac
|
|
26
|
+
done
|
|
27
|
+
[[ "$env_name" =~ ^[a-z][a-z0-9-]*$ ]] || { printf '%s\n' >&2 "env 需為小寫英數與連字號(環境名由 release-policy.json 的 targets 決定)"; exit 2; }
|
|
28
|
+
root="$(git rev-parse --show-toplevel)"
|
|
29
|
+
here="$(dirname "$0")"
|
|
30
|
+
source "$here/../lib/ops-steps.sh"
|
|
31
|
+
decl="$root/ops/versions.json"
|
|
32
|
+
|
|
33
|
+
# the workloads steps of the units to deploy: <purpose>/<env> instances of versions.json, not hosts/...
|
|
34
|
+
workloads=()
|
|
35
|
+
if [[ -n "$only" && -f "$decl" ]]; then
|
|
36
|
+
while read -r instance unit; do
|
|
37
|
+
[[ -n "$instance" ]] || continue
|
|
38
|
+
[[ ",$only," == *",$unit,"* ]] && workloads+=("workloads/$instance/$unit")
|
|
39
|
+
done < <(jq -r --arg e "$env_name" 'to_entries[] | select((.key | startswith("hosts/") | not) and (.key | endswith("/" + $e))) | .key as $k | (.value // {}) | keys[] | "\($k) \(.)"' "$decl")
|
|
40
|
+
fi
|
|
41
|
+
order_text="$(ops_order "$env_name" "${workloads[@]:-}")" || exit 1
|
|
42
|
+
wanted=""
|
|
43
|
+
if [[ -n "$only" ]]; then wanted="$( (( ${#workloads[@]} )) && ops_needs_closure "${workloads[@]}" || true )"; fi
|
|
44
|
+
steps=()
|
|
45
|
+
while IFS= read -r r; do
|
|
46
|
+
[[ "$r" == iac/* ]] || continue
|
|
47
|
+
[[ -d "$root/ops/$r" ]] || continue
|
|
48
|
+
if [[ -n "$only" ]]; then grep -qxF "$r" <<<"$wanted" || continue; fi
|
|
49
|
+
steps+=("$r")
|
|
50
|
+
done <<<"$order_text"
|
|
51
|
+
printf '%s\n' "[apply-iac] $env_name 套用順序:${steps[*]:-(無)}"
|
|
52
|
+
if (( ${#steps[@]} == 0 )); then printf '%s\n' "[apply-iac] $env_name 沒有要套用的 iac 步驟"; exit 0; fi
|
|
53
|
+
|
|
54
|
+
# the settings the apply needs, checked before tofu is called
|
|
55
|
+
missing=()
|
|
56
|
+
for v in TOFU_STATE_BUCKET TOFU_STATE_ENDPOINT TOFU_STATE_ACCESS_KEY_ID TOFU_STATE_SECRET_ACCESS_KEY; do [[ -n "${!v:-}" ]] || missing+=("$v"); done
|
|
57
|
+
if (( ${#missing[@]} )); then
|
|
58
|
+
printf '%s\n' >&2 "✗ 沒有設定 state backend:缺 ${missing[*]}。GitHub-hosted runner 每次都是空的,沒有 state 會在第二次套用時重建已存在的資源,所以不呼叫 tofu。請在倉設定這些 variable 與 secret"
|
|
59
|
+
exit 1
|
|
60
|
+
fi
|
|
61
|
+
provider_missing=()
|
|
62
|
+
for v in CLOUDFLARE_API_TOKEN CLOUDFLARE_ACCOUNT_ID; do [[ -n "${!v:-}" ]] || provider_missing+=("$v"); done
|
|
63
|
+
if (( ${#provider_missing[@]} )); then
|
|
64
|
+
printf '%s\n' >&2 "✗ 缺 Cloudflare 設定:${provider_missing[*]},不呼叫 tofu"
|
|
65
|
+
exit 1
|
|
66
|
+
fi
|
|
67
|
+
|
|
68
|
+
read -r -a tofu <<<"${TOFU:-tofu}"
|
|
69
|
+
log_dir="${DEPLOY_LOG_DIR:-$root/tmp/deploy-log}"
|
|
70
|
+
mkdir -p "$log_dir"
|
|
71
|
+
work="$(mktemp -d)"; trap 'rm -rf "$work"' EXIT
|
|
72
|
+
export AWS_ACCESS_KEY_ID="$TOFU_STATE_ACCESS_KEY_ID" AWS_SECRET_ACCESS_KEY="$TOFU_STATE_SECRET_ACCESS_KEY"
|
|
73
|
+
export TF_VAR_account_id="$CLOUDFLARE_ACCOUNT_ID" TF_IN_AUTOMATION=1
|
|
74
|
+
n=0
|
|
75
|
+
for step in "${steps[@]}"; do
|
|
76
|
+
[[ -f "$root/ops/$step/main.tf" ]] || { printf '%s\n' >&2 "✗ ${step}:找不到 main.tf"; exit 1; }
|
|
77
|
+
key="${step}.tfstate"
|
|
78
|
+
cfg="$work/${step//\//_}.hcl"
|
|
79
|
+
printf 'bucket = "%s"\nkey = "%s"\nendpoints = { s3 = "%s" }\n' "$TOFU_STATE_BUCKET" "$key" "$TOFU_STATE_ENDPOINT" > "$cfg"
|
|
80
|
+
(
|
|
81
|
+
cd "$root/ops/$step"
|
|
82
|
+
"${tofu[@]}" init -input=false -no-color -reconfigure "-backend-config=$cfg"
|
|
83
|
+
"${tofu[@]}" apply -input=false -no-color -auto-approve
|
|
84
|
+
)
|
|
85
|
+
n=$(( n + 1 ))
|
|
86
|
+
printf '%s\n' "$(date -u '+%Y-%m-%d %H:%M') | $env_name | $step | apply" >> "$log_dir/$env_name.iac.log"
|
|
87
|
+
printf '%s\n' " [$n] $step 已套用(state ${key})"
|
|
88
|
+
done
|
|
89
|
+
printf '%s\n' "[apply-iac] $env_name 完成,套用 $n 個 iac 步驟"
|