-
Notifications
You must be signed in to change notification settings - Fork 1
/
consulLib.js
93 lines (85 loc) · 3.1 KB
/
consulLib.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
var Q = require('q');
var request = require('request');
var os = require('os');
// test commit2
var util = require('util');
var fromCallback = function (fn) {
var deferred = Q.defer();
fn(function (err, data) {
if (err) {
deferred.reject(err);
}
else {
deferred.resolve(data);
}
});
return deferred.promise;
};
var consulAddr = 'consul';
var consulPort = 38500;
var consul = require('consul')({ host: consulAddr,
port: consulPort,
promisify: fromCallback });
function registerService() {
var nodeName = os.hostname();
var serviceName = 'cf-show-nodejs';
var servicePort = 3000;
var ip = require('ip');
var ip = ip.address();
var consulAclToken = "";
var nodeServiceDef = {
"Node": nodeName,
"Address": ip,
"Service": {
"Service": serviceName,
"Address": ip,
"TaggedAddresses": {
"wan": ip
},
"Port": servicePort
},
"Check": {
"Node": nodeName,
"CheckID": "service:" + serviceName,
"Name": "Dummy Check",
"Notes": "",
"Status": "passing",
"ServiceID": serviceName
},
"WriteRequest": {
"Token": consulAclToken
}
};
Q.nfcall(request.put, {headers: {'content-type': 'application/json'},
url: util.format('http://%s:%s/v1/catalog/register', consulAddr, consulPort),
body: JSON.stringify(nodeServiceDef)})
.then(function(consulResponse){
// consul response body should be true
if (consulResponse[1] === 'true' ) {
console.log("Node has been registered in Consul: ip = " + ip + " , nodeName = " + nodeName + " !!!");
return Q.resolve("Node has been registered in Consul");
}
else
return Q.reject(consulResponse[1] || 'empty consul response');
})
.catch(function(error) {
console.log("NODE REGISTER ERROR: " + error.toString() + " ip = " + ip + " , nodeName = " + nodeName + " Retry after 2s ...");
return Q.delay(2000)
.then(function() { return registerService()});
});
}
function putKv(k, v) {
Q.all([consul.kv.set({ key: k, value: v})])
.then(function(consulResponse){
return consulResponse.every(i => i === true)? Q.resolve("KV Q.all test") : Q.reject("KV - something failed");
})
.then(function(){ console.log(util.format("Consul kv.set SUCCESS: %s = %s ", k , v));
return Q.resolve("Consul kv.set SUCCESS");
})
.catch(function(error) {
console.log(util.format("Consul kv.set ERROR: %s : %s = %s ", error.toString(), k , v));
return Q.reject(error);
});
}
module.exports.putKv = putKv;
module.exports.registerService = registerService;