publish.ts 8.3 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
	size: number;
J
Joao Moreno 已提交
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
}

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 已提交
107
					console.log('Build successfully updated.');
J
Joao Moreno 已提交
108 109 110 111 112 113 114 115 116 117 118
					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 已提交
119
			console.log('Build successfully published.');
J
Joao Moreno 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
			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> {
135 136 137 138 139
	const blobOptions: azure.BlobService.CreateBlockBlobRequestOptions = {
		contentSettings: {
			contentType: mime.lookup(file),
			cacheControl: 'max-age=31536000, public'
		}
J
Joao Moreno 已提交
140 141 142 143 144
	};

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

J
Joao Moreno 已提交
145 146 147 148 149
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 已提交
150 151 152 153 154 155 156 157
	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 已提交
158 159 160 161 162 163 164 165 166 167
	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 已提交
168

J
Joao Moreno 已提交
169 170 171 172 173
	const stat = await new Promise<fs.Stats>((c, e) => fs.stat(file, (err, stat) => err ? e(err) : c(stat)));
	const size = stat.size;

	console.log('Size:', size);

174 175 176 177
	const stream = fs.createReadStream(file);
	const [sha1hash, sha256hash] = await Promise.all([hashStream('sha1', stream), hashStream('sha256', stream)]);

	console.log('SHA1:', sha1hash);
J
Joao Moreno 已提交
178
	console.log('SHA256:', sha256hash);
J
Joao Moreno 已提交
179 180 181 182 183

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

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

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

189 190 191
	// mooncake is fussy and far away, this is needed!
	mooncakeBlobService.defaultClientRequestTimeoutInMs = 10 * 60 * 1000;

J
Joao Moreno 已提交
192 193 194 195 196 197 198 199 200 201
	await Promise.all([
		assertContainer(blobService, quality),
		assertContainer(mooncakeBlobService, quality)
	]);

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

202 203 204 205 206 207 208 209 210 211 212
	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 已提交
213
		console.log(`Blob ${quality}, ${blobName} already exists, not publishing again.`);
J
Joao Moreno 已提交
214 215 216
		return;
	}

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

219
	await Promise.all(promises);
J
Joao Moreno 已提交
220

J
Joao Moreno 已提交
221
	console.log('Blobs successfully uploaded.');
J
Joao Moreno 已提交
222 223 224

	const config = await getConfig(quality);

J
Joao Moreno 已提交
225
	console.log('Quality config:', config);
J
Joao Moreno 已提交
226 227 228 229 230 231

	const asset: Asset = {
		platform: platform,
		type: type,
		url: `${process.env['AZURE_CDN_URL']}/${quality}/${blobName}`,
		mooncakeUrl: `${process.env['MOONCAKE_CDN_URL']}/${quality}/${blobName}`,
232
		hash: sha1hash,
J
Joao Moreno 已提交
233 234
		sha256hash,
		size
J
Joao Moreno 已提交
235 236 237 238 239 240 241 242 243
	};

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

248 249 250 251 252 253
	if (!opts['upload-only']) {
		release.assets.push(asset);

		if (isUpdate) {
			release.updates[platform] = type;
		}
J
Joao Moreno 已提交
254 255 256 257 258 259
	}

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

function main(): void {
J
Joao Moreno 已提交
260 261 262 263 264
	const opts = minimist<PublishOptions>(process.argv.slice(2), {
		boolean: ['upload-only']
	});

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

J
Joao Moreno 已提交
267
	publish(commit, quality, platform, type, name, version, _isUpdate, file, opts).catch(err => {
J
Joao Moreno 已提交
268 269 270 271 272 273
		console.error(err);
		process.exit(1);
	});
}

main();