-
Notifications
You must be signed in to change notification settings - Fork 215
/
promote.ts
231 lines (188 loc) · 7.87 KB
/
promote.ts
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
import color from '@heroku-cli/color'
import {APIClient, Command, flags} from '@heroku-cli/command'
import Heroku from '@heroku-cli/schema'
import assert from 'assert'
import cli from 'cli-ux'
import got from 'got'
import {listPipelineApps} from '../../api'
import keyBy from '../../key-by'
function assertNotPromotingToSelf(source: string, target: string) {
assert.notStrictEqual(source, target, `Cannot promote from an app to itself: ${target}. Specify a different target app.`)
}
function findAppInPipeline(apps: Array<Heroku.App>, target: string) {
const found = apps.find(app => (app.name === target) || (app.id === target))
assert(found, `Cannot find app ${color.app(target)}`)
return found
}
const PROMOTION_ORDER = ['development', 'staging', 'production']
// tslint:disable-next-line: no-string-based-set-timeout
const wait = (ms = 100) => new Promise(resolve => setTimeout(resolve, ms))
function isComplete(promotionTarget: Heroku.PipelinePromotionTarget) {
return promotionTarget.status !== 'pending'
}
function isSucceeded(promotionTarget: Heroku.PipelinePromotionTarget) {
return promotionTarget.status === 'succeeded'
}
function isFailed(promotionTarget: Heroku.PipelinePromotionTarget) {
return promotionTarget.status === 'failed'
}
function pollPromotionStatus(heroku: APIClient, id: string, needsReleaseCommand: boolean): Promise<Array<Heroku.PipelinePromotionTarget>> {
return heroku.get<Array<Heroku.PipelinePromotionTarget>>(`/pipeline-promotions/${id}/promotion-targets`).then(function ({body: targets}) {
if (targets.every(isComplete)) {
return targets
}
//
// With only one target, we can return as soon as the release is created.
// The command will then read the release phase output
//
// `needsReleaseCommand` allows us to keep polling, as it can take a few
// seconds to get the release to succeeded after the release command
// finished.
//
if (needsReleaseCommand && targets.length === 1 && targets[0].release !== null) {
return targets
}
return wait(1000).then(pollPromotionStatus.bind(null, heroku, id, needsReleaseCommand))
})
}
async function getCoupling(heroku: APIClient, app: string): Promise<Heroku.PipelineCoupling> {
cli.log('Fetching app info...')
const {body: coupling} = await heroku.get<Heroku.PipelineCoupling>(`/apps/${app}/pipeline-couplings`)
return coupling
}
async function promote(heroku: APIClient, label: string, id: string, sourceAppId: string, targetApps: Array<Heroku.App>, secondFactor?: string): Promise<Heroku.PipelinePromotion> {
const options = {
headers: {},
body: {
pipeline: {id},
source: {app: {id: sourceAppId}},
targets: targetApps.map(app => ({app: {id: app.id}})),
},
}
if (secondFactor) {
options.headers = {'Heroku-Two-Factor-Code': secondFactor}
}
try {
cli.log(`${label}...`)
const {body: promotions} = await heroku.post<Heroku.PipelinePromotion>('/pipeline-promotions', options)
return promotions
} catch (error) {
if (!error.body || error.body.id !== 'two_factor') {
throw error
}
const secondFactor = await heroku.twoFactorPrompt()
return promote(heroku, label, id, sourceAppId, targetApps, secondFactor)
}
}
function assertValidPromotion(app: string, source: string, target?: string) {
if (!target || PROMOTION_ORDER.indexOf(source) < 0) {
throw new Error(`Cannot promote ${app} from '${source}' stage`)
}
}
function assertApps(app: string, targetApps: Array<Heroku.App>, targetStage: string) {
if (targetApps.length === 0) {
throw new Error(`Cannot promote from ${color.app(app)} as there are no downstream apps in ${targetStage} stage`)
}
}
async function getRelease(heroku: APIClient, app: string, releaseId: string): Promise<Heroku.Release> {
cli.log('Fetching release info...')
const {body: release} = await heroku.get<Heroku.Release>(`/apps/${app}/releases/${releaseId}`)
return release
}
async function streamReleaseCommand(heroku: APIClient, targets: Array<Heroku.App>, promotion: any) {
if (targets.length !== 1 || targets.every(isComplete)) {
return pollPromotionStatus(heroku, promotion.id, false)
}
const target = targets[0]
const release = await getRelease(heroku, target.app.id, target.release.id)
if (!release.output_stream_url) {
return pollPromotionStatus(heroku, promotion.id, false)
}
cli.log('Running release command...')
const fetch = (retry = 100) => new Promise((resolve, reject) => {
const stream = got.stream(release.output_stream_url!)
stream.on('error', async err => {
await wait(100)
if (retry && err.code === '404') {
fetch(retry - 1).then(resolve).catch(reject)
} else reject(err)
})
stream.on('end', resolve)
const piped = stream.pipe(process.stdout)
piped.on('error', reject)
})
await fetch()
return pollPromotionStatus(heroku, promotion.id, false)
}
export default class Promote extends Command {
static description = 'promote the latest release of this app to its downstream app(s)'
static examples = [
'$ heroku pipelines:promote -a my-app-staging',
]
static flags = {
app: flags.app({
required: true,
}),
remote: flags.remote(),
to: flags.string({
char: 't',
description: 'comma separated list of apps to promote to',
}),
}
async run() {
const {flags} = this.parse(Promote)
const appNameOrId = flags.app
const coupling = await getCoupling(this.heroku, appNameOrId)
cli.log(`Fetching apps from ${color.pipeline(coupling.pipeline!.name)}...`)
const allApps = await listPipelineApps(this.heroku, coupling.pipeline!.id!)
const sourceStage = coupling.stage
let promotionActionName = ''
let targetApps: Array<Heroku.App> = []
if (flags.to) {
// The user specified a specific set of apps they want to target
// We don't have to infer the apps or the stage they want to promote to
// Strip out any empty app names due to something like a trailing comma
const targetAppNames = flags.to.split(',').filter(appName => appName.length >= 1)
// Now let's make sure that we can find every target app they specified
// The only requirement is that the app be in this pipeline. They can be at any stage.
targetApps = targetAppNames.reduce((acc: Array<Heroku.App>, targetAppNameOrId) => {
assertNotPromotingToSelf(appNameOrId, targetAppNameOrId)
const app = findAppInPipeline(allApps, targetAppNameOrId)
if (app) {
acc.push(app)
}
return acc
}, [])
promotionActionName = `Starting promotion to apps: ${targetAppNames.toString()}`
} else {
const targetStage = PROMOTION_ORDER[PROMOTION_ORDER.indexOf(sourceStage!) + 1]
assertValidPromotion(appNameOrId, sourceStage!, targetStage)
targetApps = allApps.filter(app => app.coupling.stage === targetStage)
assertApps(appNameOrId, targetApps, targetStage)
promotionActionName = `Starting promotion to ${targetStage}`
}
const promotion = await promote(
this.heroku, promotionActionName, coupling.pipeline!.id!, coupling.app!.id!, targetApps,
)
const pollLoop = pollPromotionStatus(this.heroku, promotion.id!, true)
cli.log('Waiting for promotion to complete...')
let promotionTargets = await pollLoop
promotionTargets = await streamReleaseCommand(this.heroku, promotionTargets, promotion)
const appsByID = keyBy(allApps, 'id')
const styledTargets = promotionTargets.reduce(function (memo: Heroku.App, target: Heroku.App) {
const app = appsByID[target.app.id]
const details = [target.status]
if (isFailed(target)) {
details.push(target.error_message)
}
memo[app.name] = details
return memo
}, {})
if (promotionTargets.every(isSucceeded)) {
cli.log('\nPromotion successful')
} else {
cli.warn('\nPromotion to some apps failed')
}
cli.styledObject(styledTargets)
}
}