Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add architect push cmd #18

Merged
merged 6 commits into from
Jun 4, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ node_modules
.idea
architect_services
oclif.manifest.json
*.env
49 changes: 49 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,18 @@
"@oclif/errors": "^1.2.2",
"@oclif/plugin-help": "^2.1.2",
"@types/auth0": "^2.9.11",
"@types/dotenv": "^6.1.1",
"@types/fs-extra": "^7.0.0",
"@types/joi": "^14.3.3",
"@types/keytar": "^4.4.0",
"@types/listr": "^0.14.0",
"@types/request": "^2.48.1",
"auth0": "^2.17.0",
"chalk": "^2.4.1",
"dotenv": "^8.0.0",
"fs-extra": "^8.0.1",
"inquirer": "^6.2.0",
"joi": "^14.3.1",
"keytar": "^4.6.0",
"listr": "^0.14.3",
"oclif": "^1.12.5",
Expand Down
52 changes: 52 additions & 0 deletions src/app-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import * as dotenv from 'dotenv';
import * as Joi from 'joi';

const CONFIG_SCHEMA: Joi.ObjectSchema = Joi.object({
OAUTH_DOMAIN: Joi
.string()
.hostname()
.default('architect.auth0.com'),
OAUTH_CLIENT_ID: Joi
.string()
.default('X9U08B2hg6QEmRUIFKZoCSqgNBmAM6aU'),
DEFAULT_REGISTRY_HOST: Joi
.string()
.uri()
.default('registry.architect.io'),
API_HOST: Joi
.string()
.uri()
.default('https://api.architect.io')
});

const validate_config = (
input_config: { [key: string]: any },
): { [key: string]: string } => {
const { error, value: validatedEnvConfig } = Joi.validate(
input_config,
CONFIG_SCHEMA,
{ stripUnknown: true },
);
if (error) {
throw new Error(`Config validation error: ${error.message}`);
}
return validatedEnvConfig;
};

export class AppConfig {
readonly oauth_domain: string;
readonly oauth_client_id: string;
readonly default_registry_host: string;
readonly api_host: string;

constructor() {
// Load environment params from a .env file if found
dotenv.config();

const app_env = validate_config(process.env);
this.oauth_domain = app_env.OAUTH_DOMAIN;
this.oauth_client_id = app_env.OAUTH_CLIENT_ID;
this.default_registry_host = app_env.DEFAULT_REGISTRY_HOST;
this.api_host = app_env.API_HOST;
}
}
33 changes: 30 additions & 3 deletions src/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,15 @@ import * as keytar from 'keytar';
import * as request from 'request';
import * as url from 'url';

import { AppConfig } from './app-config';

export default abstract class extends Command {
app_config!: AppConfig;
architect!: ArchitectClient;

async init() {
this.architect = new ArchitectClient();
this.app_config = new AppConfig();
this.architect = new ArchitectClient(this.app_config.api_host);
}

styled_json(obj: object) {
Expand All @@ -16,8 +20,30 @@ export default abstract class extends Command {
}
}

class UserEntity {
readonly access_token: string;
readonly username: string;

constructor(partial: { [key: string]: string }) {
this.access_token = partial.access_token;
this.username = partial['https://architect.io/username'];
}
}

class ArchitectClient {
private readonly domain = 'https://api.architect.io';
private readonly domain: string;

constructor(domain: string) {
this.domain = domain;
}

async getUser() {
const credentials = await keytar.findCredentials('architect.io');
if (credentials.length === 0) {
throw Error('denied: `architect login` required');
}
return new UserEntity(JSON.parse(credentials[0].password));
}

async get(path: string) {
return this.request('GET', path);
Expand All @@ -40,7 +66,8 @@ class ArchitectClient {
if (credentials.length === 0) {
throw Error('denied: `architect login` required');
}
const access_token = JSON.parse(credentials[0].password).access_token;
const user = await this.getUser();
const access_token = user.access_token;

const options = {
url: url.resolve(this.domain, path),
Expand Down
91 changes: 50 additions & 41 deletions src/commands/build.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { flags } from '@oclif/command';
import chalk from 'chalk';
import { execSync } from 'child_process';
import { exec } from 'child_process';
import * as Listr from 'listr';
import * as path from 'path';

import Command from '../base';
Expand All @@ -11,7 +12,6 @@ import Install from './install';

const _info = chalk.blue;
const _error = chalk.red;
const _success = chalk.green;

export default class Build extends Command {
static description = `Create an ${MANAGED_PATHS.ARCHITECT_JSON} file for a service`;
Expand All @@ -37,53 +37,62 @@ export default class Build extends Command {
}
];

async run() {
const { args } = this.parse(Build);
let root_service_path = process.cwd();
if (args.context) {
root_service_path = path.resolve(args.context);
}
static async getTasks(service_path: string, tag?: string, recursive?: boolean): Promise<Listr.ListrTask[]> {
const dependencies = await ServiceConfig.getDependencies(service_path, recursive);
const tasks: Listr.ListrTask[] = [];

try {
await this.buildImage(root_service_path);
} catch (err) {
this.error(_error(err.message));
}
dependencies.forEach(dependency => {
tasks.push({
title: `Building docker image for ${_info(dependency.service_config.name)}`,
task: async () => {
const install_tasks = await Install.getTasks(dependency.service_path);
const build_task = {
title: 'Building',
task: async () => {
await Build.buildImage(dependency.service_path, dependency.service_config, tag);
}
};
return new Listr(install_tasks.concat([build_task]));
}
});
});
return tasks;
}

async buildImage(service_path: string) {
const { flags } = this.parse(Build);
const service_config = ServiceConfig.loadFromPath(service_path);
static async buildImage(service_path: string, service_config: ServiceConfig, tag?: string) {
const dockerfile_path = path.join(__dirname, '../../Dockerfile');
const tag_name = tag || `architect-${service_config.name}`;

// execSync caused the output logs to hang
await new Promise(resolve => {
const thread = exec([
'docker', 'build',
'--compress',
'--build-arg', `SERVICE_LANGUAGE=${service_config.language}`,
'-t', tag_name,
'-f', dockerfile_path,
'--label', `architect.json='${JSON.stringify(service_config)}'`,
service_path
].join(' '));

thread.on('close', () => {
resolve();
});
});
}

async run() {
const { args, flags } = this.parse(Build);
if (flags.recursive && flags.tag) {
this.error(_error('Cannot override tag for recursive builds'));
this.error(_error('Cannot specify tag for recursive builds'));
}

if (flags.recursive) {
const dependency_names = Object.keys(service_config.dependencies);
for (let dependency_name of dependency_names) {
const dependency_path = ServiceConfig.parsePathFromDependencyIdentifier(
service_config.dependencies[dependency_name],
service_path
);
await this.buildImage(dependency_path);
}
let root_service_path = process.cwd();
if (args.context) {
root_service_path = path.resolve(args.context);
}

this.log(_info(`Building docker image for ${service_config.name}`));
const dockerfile_path = path.join(__dirname, '../../Dockerfile');
await Install.run(['--prefix', service_path]);
const tag_name = flags.tag || `architect-${service_config.name}`;

execSync([
'docker', 'build',
'--compress',
'--build-arg', `SERVICE_LANGUAGE=${service_config.language}`,
'-t', tag_name,
'-f', dockerfile_path,
'--label', `architect.json='${JSON.stringify(service_config)}'`,
service_path
].join(' '));
this.log(_success(`Successfully built image for ${service_config.name}`));
const tasks = new Listr(await Build.getTasks(root_service_path, flags.tag, flags.recursive), { concurrent: 2 });
await tasks.run();
}
}
Loading