/
index.ts
442 lines (372 loc) · 13.6 KB
/
index.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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import * as crypto from 'crypto';
import {GoogleAuthOptions} from 'google-auth-library';
import * as retry from 'p-retry';
import * as path from 'path';
import * as zlib from 'zlib';
import {handler as dockerAuth} from './auth/dockerio';
import {handler as gcrAuth} from './auth/gcr';
import {DockerCredentialHelpers} from './credentials-helper';
import {ImageLocation, parse as parseSpecifier} from './image-specifier';
import * as packer from './packer';
import {pending, PendingTracker} from './pending';
import {ImageConfig, ManifestV2, RegistryClient} from './registry';
const tar = require('tar');
// expose plain registry client.
export {RegistryClient} from './registry';
export type ImageOptions = {
auth?: AuthConfig,
sync?: false|undefined
};
export type ImageData = {
manifest: ManifestV2,
config: ImageConfig
};
export class Image {
private options: ImageOptions;
private image: ImageLocation;
// where to save the image and where to upload blobs
private targetImage: ImageLocation;
// the manifest and config for the source image
private imageData: Promise<ImageData>;
private originalManifest?: ManifestV2;
private clients: {[k: string]: RegistryClient|Promise<RegistryClient>} = {};
private pending: PendingTracker;
private syncedBaseImage = false;
// convenience properties. these values get updated in the image config when
// saving. these overwrite values updated manually in ImageData.config.config
// tslint:disable-next-line:variable-name
WorkingDir?: string;
// tslint:disable-next-line:variable-name
Cmd?: string[];
// tslint:disable-next-line:variable-name
Env?: string[];
// queue all pending actions so i can Promise.all them in save before saving
// manifest
constructor(
imageSpecifier: string, targetImage?: string|ImageOptions,
options?: ImageOptions) {
this.options = options || {};
if (typeof targetImage !== 'string') {
this.options = this.options || targetImage;
targetImage = undefined;
}
this.image = parseSpecifier(imageSpecifier);
this.targetImage = parseSpecifier(targetImage || imageSpecifier);
this.pending = pending();
// setup default client.
// if the to and from match host and namespace we'll make one write client.
const readOnly =
this.authKey(this.image) !== this.authKey(this.targetImage);
this.client(this.image, !readOnly);
this.imageData = this.getImageData();
}
// returns the part of the config object you care about for things like
// entrypoint and env.
async getImageConfig() {
const imageData = await this.getImageData();
return imageData.config.config;
}
async addLayer(
digest: string, uncompressedDigest: string, size: number,
urls?: string[]) {
const imageData = await this.getImageData();
let layerMediaType = 'application/vnd.oci.image.layer.v1.tar+gzip';
if (imageData.manifest.mediaType.indexOf('docker') > -1) {
layerMediaType = 'application/vnd.docker.image.rootfs.diff.tar.gzip';
}
const layerResult = {mediaType: layerMediaType, digest, size, urls};
imageData.manifest.layers.push(layerResult);
imageData.config.rootfs.diff_ids.push(uncompressedDigest);
return Object.assign({}, layerResult, {uncompressedDigest});
}
async removeLayer(digest: string) {
// edit the config and manifest returned from getImageData
const imageData = await this.getImageData();
const layers = imageData.manifest.layers;
let found: number|undefined;
layers.forEach((layerData, i) => {
if (layerData.digest === digest) {
found = i;
}
});
if (found !== undefined) {
layers.splice(found, 1);
imageData.config.rootfs.diff_ids.splice(found, 1);
return true;
}
return false;
}
// "./myfiles", "/workspace"
// "localDirectory", "imageDirectory"
addFiles(
dir: string|{[dir: string]: string},
targetDir?: string|packer.PackOptions,
options?: packer.PackOptions): Promise<{
mediaType: string,
digest: string,
size: number,
uncompressedDigest: string
}> {
// dir,target,options
// dir,options
// {dir:target,....},options
if (typeof targetDir === 'string') {
if (typeof dir !== 'string') {
// addFiles({"apples":"oranges"},"pears")
throw new Error(
'specifying a target directory name when the dir is an object of name:target doesn\'t make sense. try addFiles({dir:target})');
}
dir = {[targetDir]: dir};
} else if (targetDir) {
// options!
options = targetDir;
}
// have to wrap in promise because the tar stream can emit error out of band
let p = new Promise(async (resolve, reject) => {
const tarStream = packer.pack(dir, options);
tarStream.on('error', (e: Error) => reject(e));
const gzip = zlib.createGzip();
const uncompressedHash = crypto.createHash('sha256');
tarStream.on('data', (buf: Buffer) => {
uncompressedHash.update(buf);
});
tarStream.pipe(gzip);
const client = await this.client(this.targetImage, true);
const result = await client.upload(gzip);
const uncompressedDigest = 'sha256:' + uncompressedHash.digest('hex');
resolve(await this.addLayer(
result.digest, uncompressedDigest, result.contentLength));
});
p = this.pending.track(p);
return p as Promise<{
mediaType: string; digest: string; size: number;
urls: string[] | undefined;
uncompressedDigest: string;
}>;
}
async getImageData() {
if (!this.imageData) {
this.imageData = this.loadImageData();
this.pending.track(this.imageData);
this.imageData.then((data) => {
this.originalManifest = JSON.parse(JSON.stringify(data.manifest));
});
}
return this.imageData;
}
async loadImageData(image?: ImageLocation) {
image = (image ? image : this.image);
const client = await this.client(image);
const manifest = await client.manifest(image.tag || 'latest');
const configBlob = await client.blob(manifest.config.digest) + '';
const config = JSON.parse(configBlob) as ImageConfig;
return {manifest, config};
}
client(_image?: ImageLocation|string, write?: boolean) {
let image: ImageLocation;
if (typeof _image === 'string') {
image = parseSpecifier(_image);
} else {
// typescript!!!
image = _image as ImageLocation;
}
image = (image ? image : this.image);
const scope = write ? 'push,pull' : 'pull';
let key = [image.registry, image.namespace, image.image].join(',');
const writeKey = key + ',push,pull';
const readKey = key + ',pull';
// default to most permissive cached client even if it doesn't match scope.
if (this.clients[writeKey]) {
return this.clients[writeKey];
} else if (!write && this.clients[readKey]) {
return this.clients[readKey];
}
key += ',' + scope;
const promiseOfClient =
auth(image, scope, this.options.auth || {}).then((registryAuth) => {
const registryClient = new RegistryClient(
image!.registry, this.nameSpacedImageName(image), registryAuth);
return registryClient;
});
this.clients[key] = promiseOfClient;
return promiseOfClient;
}
async save(tags?: string[], options?: SyncOptions&{
Env?: string[],
Cmd?: string[],
WorkingDir?: string
}) {
const targetImage = this.targetImage;
const client = await this.client(targetImage, true);
const imageData = await this.getImageData();
tags = tags || [targetImage.tag || 'latest'];
options = options || {};
await this.syncBaseImage(options);
await Promise.all(this.pending.active());
if (options.Cmd || this.Cmd) {
imageData.config.config.Cmd = options.Cmd || this.Cmd!;
}
if (options.Env || this.Env) {
[].push.apply(imageData.config.config.Env, options.Env || this.Env || []);
}
if (options.WorkingDir || this.WorkingDir) {
imageData.config.config.WorkingDir =
options.WorkingDir || this.WorkingDir!;
}
// are all layers done uploading?
const uploadResult =
await client.upload(Buffer.from(JSON.stringify(imageData.config)));
imageData.manifest.config.digest = uploadResult.digest;
imageData.manifest.config.size = uploadResult.contentLength;
// console.log('config upload result.', uploadResult);
// put the manifest once per tag
return Promise
.all(tags.filter((v) => !!v).map((tag) => {
return client.manifestUpload(
encodeURIComponent(tag), imageData.manifest);
}))
.then((results) => {
return results[0];
});
}
private authKey(image: ImageLocation) {
if (image.registry.indexOf('gcr.io')) {
// should use same auth if in same google cloud project.
return [image.registry, image.namespace].join(',');
}
return [image.registry, image.namespace, image.image].join(',');
}
// verify that every layer is in the target and copy missing layers from base
// to target
async sync(options?: SyncOptions) {
options =
Object.assign({copyRemoteLayers: true, ignoreExists: false}, options);
// ensure image data has been loaded.
await this.getImageData();
// use base manifest for sync
const manifest = this.originalManifest;
if (!manifest) {
throw new Error(
'get image data failed to populate originalManifest somehow.');
}
const client = await this.client(this.image);
const targetClient = await this.client(this.targetImage, true);
// check that every layer in source image is present in target registry
const copies: Array<Promise<{}>> = [];
manifest.layers.forEach((layer) => {
// note: support *not* copying nondistributable layers by default once
// it's supported by gcr.
if (!options!.copyRemoteLayers && layer.urls) {
return;
}
const p = targetClient.blobExists(layer.digest).then((exists) => {
if (!exists || options!.ignoreExists) {
// TODO if they are the same registry but different namespaces try
// mount first.
const action = () => {
return new Promise(async (resolve, reject) => {
const stream = await client.blob(layer.digest, true);
// if the stream ends without the correct byte length
let bytes = 0;
stream.on('data', (b) => {
bytes += b.length;
});
stream.on('end', () => {
if (bytes !== layer.size) {
reject(Error(
'failed to get all of the bytes from the blob stream.'));
}
});
stream.on('error', (err: Error) => {
reject(err);
});
try {
resolve(await targetClient.upload(
stream, layer.size, layer.digest));
} catch (e) {
console.error(
'error syncing layer ' + layer.digest +
' to target registry:\n' + e);
reject(e);
}
});
};
return retry(action, {retries: 3});
}
return true;
});
copies.push(p);
});
const all = Promise.all(copies);
this.pending.track(all);
return all;
}
private async syncBaseImage(options?: SyncOptions) {
const sameRegistry = this.image.registry === this.targetImage.registry;
const sameProject = this.image.namespace === this.targetImage.namespace;
if (sameRegistry && sameProject) {
return;
}
if (this.syncedBaseImage) {
return;
}
this.syncedBaseImage = true;
return this.sync(options);
}
private nameSpacedImageName(image?: ImageLocation) {
image = (image ? image : this.image);
return (image.namespace ? image.namespace + '/' : '') + image.image;
}
}
export const auth = async (
image: ImageLocation|string, scope: string, options?: AuthConfig) => {
// todo: distinguish better between when we should try creds helpers vs only
// built in.
if (typeof image === 'string') {
image = parseSpecifier(image);
}
try {
if (image.registry.indexOf('gcr.io') > -1) {
return await gcrAuth(
image, scope, options ? options['gcr.io'] || {} : {});
} else if (image.registry.indexOf('docker.io') > -1) {
return await dockerAuth(
image, scope, options ? options['docker.io'] : undefined);
}
} catch (e) {
// console.error(
// 'gcr or docker.io auth threw.\n' + e +
// '\n falling back to cred helpers.');
}
const credHelpers = new DockerCredentialHelpers();
const res = await credHelpers.auth(image.registry);
return res;
};
export const pack = packer.pack;
// expose CustomFile to pass in image.addFiles
export const CustomFile = packer.CustomFile;
export interface AuthConfig {
'gcr.io'?: GoogleAuthOptions;
// tslint:disable-next-line:no-any
'docker.io'?: any;
// tslint:disable-next-line:no-any
[k: string]: any;
}
export interface SyncOptions {
copyRemoteLayers?: boolean;
ignoreExists?: boolean;
}