publish.ts 8.1 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5 6 7 8
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

import * as fs from 'fs';
J
Joao Moreno 已提交
9
import { execSync } from 'child_process';
10
import { Readable } from 'stream';
J
Joao Moreno 已提交
11 12 13
import * as crypto from 'crypto';
import * as azure from 'azure-storage';
import * as mime from 'mime';
J
Joao Moreno 已提交
14
import * as minimist from 'minimist';
J
Joao Moreno 已提交
15 16 17 18 19 20 21
import { DocumentClient, NewDocument } from 'documentdb';

if (process.argv.length < 6) {
	console.error('Usage: node publish.js <product> <platform> <type> <name> <version> <commit> <is_update> <file>');
	process.exit(-1);
}

22
function hashStream(hashName: string, stream: Readable): Promise<string> {
J
Joao Moreno 已提交
23
	return new Promise<string>((c, e) => {
24
		const shasum = crypto.createHash(hashName);
J
Joao Moreno 已提交
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

		stream
			.on('data', shasum.update.bind(shasum))
			.on('error', e)
			.on('close', () => c(shasum.digest('hex')));
	});
}

interface Config {
	id: string;
	frozen: boolean;
}

function createDefaultConfig(quality: string): Config {
	return {
		id: quality,
		frozen: false
	};
}

function getConfig(quality: string): Promise<Config> {
	const client = new DocumentClient(process.env['AZURE_DOCUMENTDB_ENDPOINT'], { masterKey: process.env['AZURE_DOCUMENTDB_MASTERKEY'] });
	const collection = 'dbs/builds/colls/config';
	const query = {
		query: `SELECT TOP 1 * FROM c WHERE c.id = @quality`,
		parameters: [
			{ name: '@quality', value: quality }
		]
	};

	return new Promise<Config>((c, e) => {
		client.queryDocuments(collection, query).toArray((err, results) => {
			if (err && err.code !== 409) { return e(err); }

			c(!results || results.length === 0 ? createDefaultConfig(quality) : results[0] as any as Config);
		});
	});
}

interface Asset {
	platform: string;
	type: string;
	url: string;
	mooncakeUrl: string;
	hash: string;
70
	sha256hash: string;
J
Joao Moreno 已提交
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
}

function createOrUpdate(commit: string, quality: string, platform: string, type: string, release: NewDocument, asset: Asset, isUpdate: boolean): Promise<void> {
	const client = new DocumentClient(process.env['AZURE_DOCUMENTDB_ENDPOINT'], { masterKey: process.env['AZURE_DOCUMENTDB_MASTERKEY'] });
	const collection = 'dbs/builds/colls/' + quality;
	const updateQuery = {
		query: 'SELECT TOP 1 * FROM c WHERE c.id = @id',
		parameters: [{ name: '@id', value: commit }]
	};

	let updateTries = 0;

	function update(): Promise<void> {
		updateTries++;

		return new Promise<void>((c, e) => {
			client.queryDocuments(collection, updateQuery).toArray((err, results) => {
				if (err) { return e(err); }
				if (results.length !== 1) { return e(new Error('No documents')); }

				const release = results[0];

				release.assets = [
					...release.assets.filter((a: any) => !(a.platform === platform && a.type === type)),
					asset
				];

				if (isUpdate) {
					release.updates[platform] = type;
				}

				client.replaceDocument(release._self, release, err => {
					if (err && err.code === 409 && updateTries < 5) { return c(update()); }
					if (err) { return e(err); }

J
Joao Moreno 已提交
106
					console.log('Build successfully updated.');
J
Joao Moreno 已提交
107 108 109 110 111 112 113 114 115 116 117
					c();
				});
			});
		});
	}

	return new Promise<void>((c, e) => {
		client.createDocument(collection, release, err => {
			if (err && err.code === 409) { return c(update()); }
			if (err) { return e(err); }

J
Joao Moreno 已提交
118
			console.log('Build successfully published.');
J
Joao Moreno 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
			c();
		});
	});
}

async function assertContainer(blobService: azure.BlobService, quality: string): Promise<void> {
	await new Promise((c, e) => blobService.createContainerIfNotExists(quality, { publicAccessLevel: 'blob' }, err => err ? e(err) : c()));
}

async function doesAssetExist(blobService: azure.BlobService, quality: string, blobName: string): Promise<boolean> {
	const existsResult = await new Promise<azure.BlobService.BlobResult>((c, e) => blobService.doesBlobExist(quality, blobName, (err, r) => err ? e(err) : c(r)));
	return existsResult.exists;
}

async function uploadBlob(blobService: azure.BlobService, quality: string, blobName: string, file: string): Promise<void> {
134 135 136 137 138
	const blobOptions: azure.BlobService.CreateBlockBlobRequestOptions = {
		contentSettings: {
			contentType: mime.lookup(file),
			cacheControl: 'max-age=31536000, public'
		}
J
Joao Moreno 已提交
139 140 141 142 143
	};

	await new Promise((c, e) => blobService.createBlockBlobFromLocalFile(quality, blobName, file, blobOptions, err => err ? e(err) : c()));
}

J
Joao Moreno 已提交
144 145 146 147 148
interface PublishOptions {
	'upload-only': boolean;
}

async function publish(commit: string, quality: string, platform: string, type: string, name: string, version: string, _isUpdate: string, file: string, opts: PublishOptions): Promise<void> {
J
Joao Moreno 已提交
149 150 151 152 153 154 155 156
	const isUpdate = _isUpdate === 'true';

	const queuedBy = process.env['BUILD_QUEUEDBY'];
	const sourceBranch = process.env['BUILD_SOURCEBRANCH'];
	const isReleased = quality === 'insider'
		&& /^master$|^refs\/heads\/master$/.test(sourceBranch)
		&& /Project Collection Service Accounts|Microsoft.VisualStudio.Services.TFS/.test(queuedBy);

J
Joao Moreno 已提交
157 158 159 160 161 162 163 164 165 166
	console.log('Publishing...');
	console.log('Quality:', quality);
	console.log('Platforn:', platform);
	console.log('Type:', type);
	console.log('Name:', name);
	console.log('Version:', version);
	console.log('Commit:', commit);
	console.log('Is Update:', isUpdate);
	console.log('Is Released:', isReleased);
	console.log('File:', file);
J
Joao Moreno 已提交
167

168 169 170 171
	const stream = fs.createReadStream(file);
	const [sha1hash, sha256hash] = await Promise.all([hashStream('sha1', stream), hashStream('sha256', stream)]);

	console.log('SHA1:', sha1hash);
J
Joao Moreno 已提交
172
	console.log('SHA256:', sha256hash);
J
Joao Moreno 已提交
173 174 175 176 177

	const blobName = commit + '/' + name;
	const storageAccount = process.env['AZURE_STORAGE_ACCOUNT_2'];

	const blobService = azure.createBlobService(storageAccount, process.env['AZURE_STORAGE_ACCESS_KEY_2'])
178
		.withFilter(new azure.ExponentialRetryPolicyFilter(20));
J
Joao Moreno 已提交
179 180

	const mooncakeBlobService = azure.createBlobService(storageAccount, process.env['MOONCAKE_STORAGE_ACCESS_KEY'], `${storageAccount}.blob.core.chinacloudapi.cn`)
181
		.withFilter(new azure.ExponentialRetryPolicyFilter(20));
J
Joao Moreno 已提交
182

183 184 185
	// mooncake is fussy and far away, this is needed!
	mooncakeBlobService.defaultClientRequestTimeoutInMs = 10 * 60 * 1000;

J
Joao Moreno 已提交
186 187 188 189 190 191 192 193 194 195
	await Promise.all([
		assertContainer(blobService, quality),
		assertContainer(mooncakeBlobService, quality)
	]);

	const [blobExists, moooncakeBlobExists] = await Promise.all([
		doesAssetExist(blobService, quality, blobName),
		doesAssetExist(mooncakeBlobService, quality, blobName)
	]);

196 197 198 199 200 201 202 203 204 205 206
	const promises = [];

	if (!blobExists) {
		promises.push(uploadBlob(blobService, quality, blobName, file));
	}

	if (!moooncakeBlobExists) {
		promises.push(uploadBlob(mooncakeBlobService, quality, blobName, file));
	}

	if (promises.length === 0) {
J
Joao Moreno 已提交
207
		console.log(`Blob ${quality}, ${blobName} already exists, not publishing again.`);
J
Joao Moreno 已提交
208 209 210
		return;
	}

J
Joao Moreno 已提交
211
	console.log('Uploading blobs to Azure storage...');
J
Joao Moreno 已提交
212

213
	await Promise.all(promises);
J
Joao Moreno 已提交
214

J
Joao Moreno 已提交
215
	console.log('Blobs successfully uploaded.');
J
Joao Moreno 已提交
216 217 218

	const config = await getConfig(quality);

J
Joao Moreno 已提交
219
	console.log('Quality config:', config);
J
Joao Moreno 已提交
220 221 222 223 224 225

	const asset: Asset = {
		platform: platform,
		type: type,
		url: `${process.env['AZURE_CDN_URL']}/${quality}/${blobName}`,
		mooncakeUrl: `${process.env['MOONCAKE_CDN_URL']}/${quality}/${blobName}`,
226 227
		hash: sha1hash,
		sha256hash
J
Joao Moreno 已提交
228 229 230 231 232 233 234 235 236
	};

	const release = {
		id: commit,
		timestamp: (new Date()).getTime(),
		version,
		isReleased: config.frozen ? false : isReleased,
		sourceBranch,
		queuedBy,
237
		assets: [],
J
Joao Moreno 已提交
238 239 240
		updates: {} as any
	};

241 242 243 244 245 246
	if (!opts['upload-only']) {
		release.assets.push(asset);

		if (isUpdate) {
			release.updates[platform] = type;
		}
J
Joao Moreno 已提交
247 248 249 250 251 252
	}

	await createOrUpdate(commit, quality, platform, type, release, asset, isUpdate);
}

function main(): void {
J
Joao Moreno 已提交
253 254 255 256 257
	const opts = minimist<PublishOptions>(process.argv.slice(2), {
		boolean: ['upload-only']
	});

	const [quality, platform, type, name, version, _isUpdate, file] = opts._;
J
Joao Moreno 已提交
258
	const commit = execSync('git rev-parse HEAD', { encoding: 'utf8' }).trim();
J
Joao Moreno 已提交
259

J
Joao Moreno 已提交
260
	publish(commit, quality, platform, type, name, version, _isUpdate, file, opts).catch(err => {
J
Joao Moreno 已提交
261 262 263 264 265 266
		console.error(err);
		process.exit(1);
	});
}

main();