-
Notifications
You must be signed in to change notification settings - Fork 1
/
consul-register.js
97 lines (83 loc) · 2.6 KB
/
consul-register.js
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
'use strict';
var consul = require('./consul-client.js')();
var exitHook = require('exit-hook');
var serviceId;
module.exports.createServiceObject = createServiceObject;
module.exports.register = register;
module.exports.deregister = deregister;
module.exports.maintenance = maintenance;
function createServiceObject (config) {
var service = {
id: config.name + '-' + config.container_id,
name: config.name,
address: config.ip_address,
port: config.port,
tags: config.tags
};
service.checks = createChecks(config);
console.log('[magistrate] Created service object:', service);
return service;
}
function register (service, cb) {
if (!cb) cb = noop;
if (!consul) return cb('Consul client doesn\'t exist');
if (!service) return cb('Missing service');
consul.agent.service.register(service, function (err) {
if (err) console.error({ service: service, error: err }, 'Error while registering service');
serviceId = service.id;
// Make sure that we deregister this service when the process is terminating
exitHook(function (next) {
console.log('[magistrate] exit-hook, Deregister service');
deregister(function (err, id) {
console.log('[magistrate] Finished deregistering service %s', id, (err || ''));
next();
});
});
cb(err, service);
});
}
function deregister (cb) {
if (!cb) cb = noop;
if (!consul) return cb('Consul client doesn\'t exist');
consul.agent.service.deregister({ id: serviceId }, function (err) {
if (err) console.error({ service_id: serviceId, error: err }, 'Error while deregistering service');
cb(err, serviceId);
});
}
function maintenance (enable, reason, cb) {
if (!cb) cb = noop;
if (!consul) return cb('Consul client doesn\'t exist');
consul.agent.service.maintenance({
id: serviceId,
enable: enable,
reason: reason
}, function (err) {
if (err) console.error({ service_id: serviceId, error: err }, 'Error toggling maintenance mode');
cb(err, serviceId);
});
}
function createChecks (config) {
if (config.health_check_type === 'http') {
return [ createHttpCheck(config) ];
} else if (config.health_check_type === 'tcp') {
return [ createTcpCheck(config) ];
}
return null;
}
function createTcpCheck (config) {
return {
name: config.name + ' tcp call',
tcp: config.ip_address + ':' + config.port,
interval: '10s',
timeout: '1s'
};
}
function createHttpCheck (config) {
return {
name: config.name + ' http call',
http: 'http://' + config.ip_address + ':' + config.port + '/',
interval: '10s',
timeout: '1s'
};
}
function noop () {}