-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy pathprovision-platform-host.js
More file actions
350 lines (306 loc) · 12.1 KB
/
Copy pathprovision-platform-host.js
File metadata and controls
350 lines (306 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#!/usr/bin/env node
// Provisions a Power Platform Pipelines Platform Host (PE) via the BAP
// `getOrCreate` endpoint. The endpoint is idempotent: a tenant that already
// has a PE gets the existing one back (200 + provisioningState=Succeeded);
// a tenant without a PE gets one provisioned (202 + lifecycle op). Same call
// `make.powerapps.com → Pipelines` makes when a user clicks "Get started".
// Used by ensure-pipelines-host Phase 4.0.
//
// POST {bapBase}/providers/Microsoft.BusinessAppPlatform/getOrCreate?api-version=2021-04-01
// Headers:
// Authorization: Bearer {bapToken}
// Content-Type: application/json
// x-ms-correlation-id: {uuid v4}
// Body:
// {
// "properties": {
// "environmentSku": "Platform",
// "linkedEnvironmentMetadata": { "templates": ["D365_1stPartyAdminApps"] }
// }
// }
//
// Response handling:
// - 200 + provisioningState=Succeeded — tenant already had a PE; return it
// with alreadyExisted=true. This is the idempotent path, not an error.
// - 202 — Location header points to a lifecycle op; Retry-After is the poll
// interval (seconds). Body usually includes the env record with
// provisioningState: 'Creating'. Return alreadyExisted=false on success.
// - 401 — BAP token invalid; refresh and retry.
// - 403 — tenant policy or token-audience mismatch (PE provisioning does NOT
// require admin role). Surface body verbatim and recommend re-auth.
// - 4xx other — throw with body.
//
// Polling: identical to provision-custom-host.js. We GET the Location URL,
// read provisioningState, honor Retry-After, terminate on Succeeded/Failed/
// Canceled or after --timeoutSec.
//
// Usage: node provision-platform-host.js --bapToken <token>
// [--correlationId <uuid>] [--timeoutSec 600]
// [--apiVersion 2021-04-01] [--bapBase <url>]
//
// Output (JSON to stdout):
// {
// status: 'Succeeded',
// alreadyExisted: true | false, // 200 idempotent vs. 202 newly provisioned
// envId: '<guid>',
// instanceUrl: 'https://...',
// instanceApiUrl: 'https://...',
// displayName: '...',
// environmentSku: 'Platform',
// provisioningState: 'Succeeded',
// durationSec: <number>,
// correlationId: '<uuid>',
// pollAttempts: <number>,
// locationHeader: '<url>' | null
// }
//
// Exit 0 on success, exit 1 on error (stderr includes status + body).
'use strict';
const crypto = require('crypto');
const helpers = require('./validation-helpers');
const DEFAULT_API_VERSION = '2021-04-01';
const DEFAULT_BAP_BASE = 'https://api.bap.microsoft.com';
const DEFAULT_TIMEOUT_SEC = 600;
const DEFAULT_RETRY_AFTER_SEC = 10;
const POST_TIMEOUT_MS = 60000;
const POLL_TIMEOUT_MS = 30000;
const TEMPLATE_NAME = 'D365_1stPartyAdminApps';
const ENVIRONMENT_SKU = 'Platform';
function parseArgs(argv) {
const args = argv.slice(2);
const opts = {
bapToken: null,
correlationId: null,
timeoutSec: DEFAULT_TIMEOUT_SEC,
apiVersion: DEFAULT_API_VERSION,
bapBase: DEFAULT_BAP_BASE,
};
for (let i = 0; i < args.length; i++) {
const a = args[i];
const next = args[i + 1];
if (a === '--bapToken' && next) opts.bapToken = args[++i];
else if (a === '--correlationId' && next) opts.correlationId = args[++i];
else if (a === '--timeoutSec' && next) opts.timeoutSec = Number(args[++i]) || DEFAULT_TIMEOUT_SEC;
else if (a === '--apiVersion' && next) opts.apiVersion = args[++i];
else if (a === '--bapBase' && next) opts.bapBase = args[++i];
}
return opts;
}
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function extractProvisioningState(data) {
if (!data || typeof data !== 'object') return null;
if (data.properties && typeof data.properties.provisioningState === 'string') {
return data.properties.provisioningState;
}
if (typeof data.state === 'string') return data.state;
if (data.status && typeof data.status === 'object' && typeof data.status.code === 'string') {
return data.status.code;
}
if (typeof data.status === 'string') return data.status;
return null;
}
function isTerminalSucceeded(state) {
if (!state) return false;
const s = String(state).toLowerCase();
return s === 'succeeded' || s === 'succeeded.';
}
function isTerminalFailed(state) {
if (!state) return false;
const s = String(state).toLowerCase();
return s === 'failed' || s === 'canceled' || s === 'cancelled';
}
function readRetryAfterSec(headers) {
if (!headers) return null;
const v = headers['retry-after'] || headers['Retry-After'];
if (!v) return null;
const n = Number(v);
return isFinite(n) && n > 0 ? n : null;
}
async function provisionPlatformHost(opts = {}) {
const {
bapToken,
correlationId,
timeoutSec = DEFAULT_TIMEOUT_SEC,
apiVersion = DEFAULT_API_VERSION,
bapBase = DEFAULT_BAP_BASE,
sleepImpl = null,
nowImpl = null,
} = opts;
if (!bapToken) throw new Error('--bapToken is required');
const sleep = sleepImpl || defaultSleep;
const now = nowImpl || (() => Date.now());
const cleanBase = bapBase.replace(/\/+$/, '');
const cid = correlationId || crypto.randomUUID();
const startedAt = now();
const requestBody = JSON.stringify({
properties: {
environmentSku: ENVIRONMENT_SKU,
linkedEnvironmentMetadata: { templates: [TEMPLATE_NAME] },
},
});
const postUrl = `${cleanBase}/providers/Microsoft.BusinessAppPlatform/getOrCreate?api-version=${encodeURIComponent(apiVersion)}`;
const postHeaders = {
Authorization: `Bearer ${bapToken}`,
'Content-Type': 'application/json',
Accept: 'application/json',
'x-ms-correlation-id': cid,
};
const postRes = await helpers.makeRequest({
url: postUrl,
method: 'POST',
headers: postHeaders,
body: requestBody,
timeout: POST_TIMEOUT_MS,
includeHeaders: true,
});
if (postRes.error) {
throw new Error(`BAP getOrCreate POST failed: ${postRes.error}`);
}
if (postRes.statusCode === 401) {
throw new Error('BAP getOrCreate returned 401 — caller not authenticated; refresh BAP token and retry.');
}
if (postRes.statusCode === 403) {
throw new Error(`BAP getOrCreate returned 403 — tenant policy may have disabled Platform Host provisioning, or the BAP token audience is mismatched. Try re-authenticating ('az logout && az login') and retry. Body: ${(postRes.body || '').slice(0, 500)}`);
}
if (postRes.statusCode !== 200 && postRes.statusCode !== 202) {
throw new Error(`BAP getOrCreate returned unexpected status ${postRes.statusCode}: ${(postRes.body || '').slice(0, 500)}`);
}
let envBody = null;
if (postRes.body) {
try { envBody = JSON.parse(postRes.body); } catch { envBody = null; }
}
let envId = envBody?.name || null;
let instanceUrl = envBody?.properties?.linkedEnvironmentMetadata?.instanceUrl || null;
let instanceApiUrl = envBody?.properties?.linkedEnvironmentMetadata?.instanceApiUrl || null;
let displayName = envBody?.properties?.displayName || null;
let resolvedSku = envBody?.properties?.environmentSku || ENVIRONMENT_SKU;
let provisioningState = extractProvisioningState(envBody) || 'Creating';
const locationHeader = postRes.headers?.location || postRes.headers?.Location || null;
let retryAfterSec = readRetryAfterSec(postRes.headers) || DEFAULT_RETRY_AFTER_SEC;
// Idempotent existing-PE path: 200 + Succeeded means the tenant already had
// a PE; getOrCreate is returning it. Distinguish with alreadyExisted=true so
// the caller can write the right telemetry.
if (postRes.statusCode === 200 && isTerminalSucceeded(provisioningState)) {
return {
status: 'Succeeded',
alreadyExisted: true,
envId,
instanceUrl,
instanceApiUrl,
displayName,
environmentSku: resolvedSku,
provisioningState,
durationSec: (now() - startedAt) / 1000,
correlationId: cid,
pollAttempts: 0,
locationHeader,
};
}
// 202 path — we just kicked off a new provision. Poll until terminal.
if (!locationHeader && !envId) {
throw new Error('BAP getOrCreate returned 202 but neither Location header nor env id is available; cannot poll for completion.');
}
const envGetUrl = envId
? `${cleanBase}/providers/Microsoft.BusinessAppPlatform/environments/${encodeURIComponent(envId)}?api-version=${encodeURIComponent(apiVersion)}&$expand=${encodeURIComponent('properties.linkedEnvironmentMetadata')}`
: null;
let pollAttempts = 0;
const deadline = startedAt + timeoutSec * 1000;
while (now() < deadline) {
if (isTerminalSucceeded(provisioningState) || isTerminalFailed(provisioningState)) break;
await sleep(retryAfterSec * 1000);
pollAttempts++;
const pollUrl = locationHeader || envGetUrl;
const pollRes = await helpers.makeRequest({
url: pollUrl,
method: 'GET',
headers: {
Authorization: `Bearer ${bapToken}`,
Accept: 'application/json',
'x-ms-correlation-id': cid,
},
timeout: POLL_TIMEOUT_MS,
includeHeaders: true,
});
if (pollRes.error) {
continue;
}
if (pollRes.statusCode === 401) {
throw new Error('Polling returned 401 mid-provision — token expired. The PE may still finish; re-run detect after a few minutes.');
}
if (pollRes.statusCode >= 500) {
continue;
}
if (pollRes.statusCode !== 200 && pollRes.statusCode !== 202) {
throw new Error(`Polling returned unexpected status ${pollRes.statusCode}: ${(pollRes.body || '').slice(0, 500)}`);
}
let pollData = null;
try { pollData = JSON.parse(pollRes.body || '{}'); } catch { pollData = null; }
const newState = extractProvisioningState(pollData);
if (newState) provisioningState = newState;
const linked = pollData?.properties?.linkedEnvironmentMetadata;
if (linked?.instanceUrl) instanceUrl = linked.instanceUrl;
if (linked?.instanceApiUrl) instanceApiUrl = linked.instanceApiUrl;
if (pollData?.properties?.displayName) displayName = pollData.properties.displayName;
if (pollData?.name && !envId) envId = pollData.name;
const newRetryAfter = readRetryAfterSec(pollRes.headers);
if (newRetryAfter) retryAfterSec = newRetryAfter;
}
if (isTerminalSucceeded(provisioningState)) {
if ((!instanceApiUrl || !instanceUrl) && envId && envGetUrl) {
const envFinalRes = await helpers.makeRequest({
url: envGetUrl,
method: 'GET',
headers: { Authorization: `Bearer ${bapToken}`, Accept: 'application/json', 'x-ms-correlation-id': cid },
timeout: POLL_TIMEOUT_MS,
});
if (envFinalRes.statusCode === 200) {
try {
const final = JSON.parse(envFinalRes.body);
instanceApiUrl = final?.properties?.linkedEnvironmentMetadata?.instanceApiUrl || instanceApiUrl;
instanceUrl = final?.properties?.linkedEnvironmentMetadata?.instanceUrl || instanceUrl;
displayName = final?.properties?.displayName || displayName;
resolvedSku = final?.properties?.environmentSku || resolvedSku;
} catch {}
}
}
return {
status: 'Succeeded',
alreadyExisted: false,
envId,
instanceUrl,
instanceApiUrl,
displayName,
environmentSku: resolvedSku,
provisioningState,
durationSec: (now() - startedAt) / 1000,
correlationId: cid,
pollAttempts,
locationHeader,
};
}
if (isTerminalFailed(provisioningState)) {
throw new Error(`Platform Host provisioning ended with state "${provisioningState}" after ${pollAttempts} poll(s). Inspect lifecycle op ${locationHeader || envGetUrl} for details.`);
}
throw new Error(`Platform Host provisioning timed out after ${timeoutSec}s (${pollAttempts} polls); last state: ${provisioningState}.`);
}
if (require.main === module) {
const opts = parseArgs(process.argv);
provisionPlatformHost(opts)
.then((result) => {
console.log(JSON.stringify(result));
process.exit(0);
})
.catch((err) => {
process.stderr.write(`${err.message}\n`);
process.exit(1);
});
}
module.exports = {
provisionPlatformHost,
extractProvisioningState,
isTerminalSucceeded,
isTerminalFailed,
readRetryAfterSec,
TEMPLATE_NAME,
ENVIRONMENT_SKU,
};