joyent-portal/packages/portal-api/lib/watch/container-pilot.js

538 lines
12 KiB
JavaScript
Raw Normal View History

'use strict';
const Events = require('events');
const Flatten = require('lodash.flatten');
const Triton = require('triton');
const VAsync = require('vasync');
const Wreck = require('wreck');
const CIDRMatcher = require('cidr-matcher');
const ForceArray = require('force-array');
const Get = require('lodash.get');
const Uniq = require('lodash.uniq');
const Hasha = require('hasha');
2017-07-13 18:22:05 +03:00
const ParamCase = require('param-case');
const Queue = require('./queue');
module.exports = class ContainerPilotWatcher extends Events {
constructor (options) {
super();
options = options || {};
// todo assert options
this._data = options.data;
this._frequency = options.frequency || 1000;
2017-07-13 20:22:00 +03:00
const TritonClient = options.Triton || Triton;
TritonClient.createClient({
profile: {
url: options.url || process.env.SDC_URL,
account: options.account || process.env.SDC_ACCOUNT,
keyId: options.keyId || process.env.SDC_KEY_ID
}
}, (err, client) => {
if (err) {
this.emit('error', err);
return;
}
this._triton = client.cloudapi;
});
}
poll () {
if (this._timeoutId) {
return;
}
this._timeoutId = setTimeout(() => {
this.check((err) => {
if (err) {
this.emit('error', err);
}
delete this._timeoutId;
this.poll();
});
}, this._frequency);
}
_getDeploymentGroups (cb) {
const getInstances = (service, next) => {
service.instances({}, (err, instances) => {
if (err) {
return next(err);
}
next(null, Object.assign({}, service, {
instances
}));
});
};
const getServices = (deploymentGroup, next) => {
deploymentGroup.services({}, (err, services) => {
if (err) {
return next(err);
}
if (!services || !services.length) {
return next();
}
VAsync.forEachParallel({
inputs: services,
func: getInstances
}, (err, result) => {
if (err) {
return next(err);
}
next(null, Object.assign({}, deploymentGroup, {
services: result.successes
}));
});
});
};
const handleDeploymentGroups = (err, deploymentGroups) => {
if (err) {
return cb(err);
}
VAsync.forEachParallel({
inputs: deploymentGroups,
func: getServices
}, (err, result) => {
cb(err, result.successes);
});
};
const getDeploymentGroups = (err, portal) => {
if (err || !portal) {
return cb(err);
}
portal.deploymentGroups({}, handleDeploymentGroups);
};
this._data.getPortal({}, getDeploymentGroups);
}
_getNetworks (networkIds = [], cb) {
VAsync.forEachParallel({
inputs: networkIds,
func: (id, next) => {
this._triton.getNetwork(id, next);
}
}, (err, results) => {
cb(err, ForceArray((results || {}).successes));
});
}
_getPublicIps (machine, cb) {
this._getNetworks(machine.networks, (err, networks) => {
if (err) {
return cb(err);
}
const privateNetworkSubnets = networks
.filter((network) => {
return !network['public'];
})
.map((network) => {
return network.subnet;
})
.filter(Boolean);
const cidr = new CIDRMatcher(privateNetworkSubnets);
const nonPrivateIps = machine.ips.filter((ip) => {
return !cidr.contains(ip);
});
cb(null, nonPrivateIps);
});
}
_fetchInstanceStatus (instance, cb) {
const { machineId } = instance;
const handleStatuses = (err, results) => {
if (err) {
this.emit('error', err);
return cb();
}
const statuses = ForceArray((results || {}).successes);
const status = statuses.filter(Boolean).shift();
if (!status) {
return cb(null, instance);
}
const services = ForceArray(status.Services).filter(({ Name }) => {
return Name !== 'containerpilot';
});
cb(null, Object.assign({}, instance, {
cp: Object.assign({}, status, {
Services: services
})
}));
};
const fetchStatus = (ip, next) => {
Wreck.get(`http://${ip}:9090/status`, {
timeout: 1000 // 1s
}, (err, res, payload) => {
if (err) {
this.emit('error', err);
return next();
}
if (Buffer.isBuffer(payload)) {
payload = payload.toString();
}
try {
const status = JSON.parse(payload);
next(null, status);
} catch (err) {
this.emit('error', err);
next();
}
});
};
const handlePublicIps = (err, ips) => {
if (err) {
this.emit('error', err);
return cb();
}
VAsync.forEachParallel({
inputs: ips,
func: fetchStatus
}, handleStatuses);
};
this._triton.getMachine(machineId, (err, machine) => {
if (err) {
this.emit('error', err);
return cb();
}
this._getPublicIps(machine, handlePublicIps);
});
}
_fetchServiceStatus (service, cb) {
VAsync.forEachParallel({
inputs: service.instances,
func: (instance, next) => {
this._fetchInstanceStatus(instance, next);
}
}, (err, results) => {
if (err) {
this.emit('error', err);
}
cb(null, Object.assign({}, service, {
instances: ForceArray((results || {}).successes)
}));
});
}
_fetchDeploymentGroupStatus (dg, cb) {
if (!dg || !dg.services || !dg.services.length) {
return cb();
}
VAsync.forEachParallel({
inputs: dg.services,
func: (service, next) => {
this._fetchServiceStatus(service, next);
}
}, (err, results) => {
if (err) {
this.emit('error', err);
}
cb(null, Object.assign({}, dg, {
services: ForceArray((results || {}).successes)
}));
});
}
_saveInstance ({ id, healthy, watches, jobs }, cb) {
if (!id) {
return cb();
}
this._data.updateInstance({
id,
healthy,
watches,
jobs
}, cb);
}
2017-07-13 18:22:05 +03:00
_saveService ({ id, instances, connections, branches }, cb) {
if (!id) {
return cb();
}
VAsync.forEachParallel({
inputs: instances,
func: (instance, next) => {
this._saveInstance(instance, next);
}
}, (err) => {
if (err) {
return cb(err);
}
this._data.updateService({
id,
2017-07-13 18:22:05 +03:00
connections,
branches
}, cb);
});
}
_saveDeploymentGroup (dg, cb) {
VAsync.forEachParallel({
inputs: dg.services,
func: (service, next) => {
this._saveService(service, next);
}
}, cb);
}
2017-08-28 23:31:38 +03:00
static _resolveServiceConnections ({ services, service }) {
2017-07-13 18:22:05 +03:00
const watches = Uniq(
Flatten(
ForceArray(service.instances).map(({ watches }) => {
return watches;
})
)
);
return watches
.map((jobName) => {
return services.reduce((serviceId, service) => {
if (serviceId) {
return serviceId;
}
const thisServiceJobs = Uniq(
Flatten(
ForceArray(service.instances).map(({ jobs }) => {
return jobs;
})
)
);
if (thisServiceJobs.indexOf(jobName) >= 0) {
return service.id;
}
return serviceId;
}, null);
})
.filter(Boolean)
2017-07-19 19:10:51 +03:00
.filter((serviceId) => {
return service.id !== serviceId;
});
2017-07-13 18:22:05 +03:00
}
2017-08-28 23:31:38 +03:00
static _resolveInstanceHealth ({ name }, instance) {
2017-07-13 18:22:05 +03:00
if (!instance) {
return 'UNAVAILABLE';
}
2017-07-13 18:22:05 +03:00
if (!instance.cp) {
return 'UNAVAILABLE';
}
2017-07-13 18:22:05 +03:00
const jobNames = Get(instance, 'cp.Services');
2017-07-13 18:22:05 +03:00
const serviceJobs = jobNames.filter(({ Name }) => {
return Name === name;
});
2017-07-13 18:22:05 +03:00
if (serviceJobs.length) {
return serviceJobs.shift().Status.toUpperCase();
}
2017-07-13 18:22:05 +03:00
const almostJobNameRegexp = new RegExp(`${name}-.*`);
const almostServiceJobs = jobNames.filter(({ Name }) => {
return almostJobNameRegexp.test(Name);
2017-07-13 18:22:05 +03:00
});
2017-07-13 18:22:05 +03:00
if (almostServiceJobs.length) {
return almostServiceJobs.shift().Status.toUpperCase();
}
2017-07-13 18:22:05 +03:00
return 'UNKNOWN';
}
2017-08-28 23:31:38 +03:00
static _resolveServiceBranches ({ name, slug, instances }) {
if (instances.length <= 1) {
return [];
}
2017-07-13 18:22:05 +03:00
const deviantJobNames = Uniq(Flatten(instances.map(({ jobs }) => {
return Flatten(jobs.filter((jobName) => {
return new RegExp(`${name}-.*`).test(jobName);
}));
})));
if (!deviantJobNames || !deviantJobNames.length) {
2017-07-13 18:22:05 +03:00
return [];
}
2017-07-13 18:22:05 +03:00
const defaultBranch = instances.reduce((service, { id, jobs }) => {
if (jobs.indexOf(name) >= 0) {
return Object.assign(service, {
instances: service.instances.concat(id)
});
}
2017-07-13 18:22:05 +03:00
return service;
}, {
name: name,
slug: slug,
instances: []
});
defaultBranch.id = Hasha(JSON.stringify(defaultBranch));
2017-07-13 18:22:05 +03:00
const branches = instances.reduce((branches, { id, jobs }) => {
if (defaultBranch.instances.indexOf(id) >= 0) {
return branches;
}
2017-07-13 18:22:05 +03:00
const branchName = jobs
.filter((jobName) => {
return deviantJobNames.indexOf(jobName) >= 0;
})
.shift();
if (!branches[branchName]) {
branches[branchName] = {
name: branchName,
slug: ParamCase(branchName),
instances: []
};
branches[branchName].id = Hasha(JSON.stringify(branches[branchName]));
2017-07-13 18:22:05 +03:00
}
branches[branchName].instances.push(id);
return branches;
}, {});
return Object.values(branches).concat(defaultBranch);
}
2017-08-28 23:31:38 +03:00
static _resolveDeploymentGroups (dgs) {
2017-07-13 18:22:05 +03:00
return dgs
.filter(Boolean)
.map((dg) => {
return Object.assign({}, dg, {
services: ForceArray(dg.services).map((service) => {
return Object.assign({}, service, {
instances: ForceArray(service.instances).map((instance) => {
const watches = Get(instance, 'cp.Watches', []);
const jobs = Get(instance, 'cp.Services', []).map(({ Name }) => {
return Name;
});
2017-07-13 18:22:05 +03:00
return Object.assign({}, instance, {
2017-08-28 23:31:38 +03:00
healthy: ContainerPilotWatcher._resolveInstanceHealth(service, instance),
jobs,
watches
2017-07-13 18:22:05 +03:00
});
})
});
})
});
})
.map((dg) => {
return Object.assign({}, dg, {
services: ForceArray(dg.services).map((service) => {
return Object.assign({}, service, {
2017-08-28 23:31:38 +03:00
branches: ContainerPilotWatcher._resolveServiceBranches(service),
connections: ContainerPilotWatcher._resolveServiceConnections({
2017-07-13 18:22:05 +03:00
services: dg.services,
service
})
});
})
});
});
}
check (cb) {
if (!this._triton) {
return cb();
}
const handleStatuses = (err, results) => {
if (err) {
this.emit('error', err);
}
2017-08-28 23:31:38 +03:00
const dgs = ContainerPilotWatcher._resolveDeploymentGroups(
2017-07-13 18:22:05 +03:00
ForceArray((results || {}).successes)
);
VAsync.forEachParallel({
inputs: dgs,
func: (dg, next) => {
Queue(dg.id, () => {
return new Promise((resolve) => {
this._saveDeploymentGroup(dg, (err) => {
resolve();
next(err);
});
});
});
}
2017-07-13 20:22:00 +03:00
}, (err) => {
if (err) {
this.emit('error', err);
}
cb(null, dgs);
});
};
const fetchStatuses = (err, dgs) => {
if (err) {
this.emit('error', err);
return cb();
}
if (!dgs || !dgs.length) {
return cb();
}
VAsync.forEachParallel({
inputs: dgs,
func: (dg, next) => {
this._fetchDeploymentGroupStatus(dg, next);
}
}, handleStatuses);
};
this._getDeploymentGroups(fetchStatuses);
}
};