-
Notifications
You must be signed in to change notification settings - Fork 28
/
util.js
158 lines (131 loc) · 5.25 KB
/
util.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
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
const fs = require('fs');
const path = require('path');
const net = require('net');
const _ = require('lodash');
const logger = require('./util/log/log4js-configured').getLogger('util')
const cfg = require('./config')
class Util {
async checkRemotePort(server, port, options = {throws: true}) {
logger.debug(`Check whether remote port is accessible for: ${server}:${port}`, options);
return new Promise(async (resolve, reject) => {
if (!cfg.SKIP_CHECK_PORTS_TIMEOUT_SECONDS) {
resolveIfTakesLongerThanTimeout(resolve, reject, options);
let client = net.createConnection({host: server, port: port}, () => {
logger.debug(`Remote port is accessible: ${server}:${port}`);
client.end();
resolve(true);
});
client.on("error", e => {
logger.debug(`\nError accessing remote port, ${server}:${port}. Throwing: ${options.throws}\n`, e)
return options.throws
? reject(`Endpoint is unreachable: ${server}:${port}. ${e && e.message}`)
: resolve(false)
});
} else {
logger.warn(`Skip waiting for peer availability. Waited for ${cfg.SKIP_CHECK_PORTS_TIMEOUT_SECONDS} before continue`)
return resolve(true);
}
});
function resolveIfTakesLongerThanTimeout(resolve, reject, options={}) {
setTimeout(() => {
return options.throws ? reject(`Timeout checking remote port: ${server}:${port}`) : resolve(false)
}, options.timeout || 1000)
}
}
async retryOperation(nTimes, period, fn) {
return new Promise(async (resolve, reject) => {
if (nTimes <= 0) return reject('Retried invocation unsuccessful');
try {
let response = await fn();
resolve(response);
} catch (e) {
return reject(e)
}
}).catch(async (err) => {
logger.trace(`Retry attempt: ${nTimes}. Error: `, err);
if (nTimes === 1) {
throw new Error(err);
} else {
await this.sleep(period);
return await this.retryOperation(nTimes - 1, period, fn);
}
});
}
filterOrderersOut(organizations) {
return _.filter(organizations,
o => !_.includes(_.get(o, 'id'), 'orderer')
&& !_.includes(_.get(o, 'id'), 'osn')
&& !_.includes(_.get(o, 'id'), 'raft'));
}
loadPemFromFile(pemFilePath) {
let certData = fs.readFileSync(pemFilePath);
return Buffer.from(certData).toString()
}
async sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
convertStringValToMapVal(keyValueMap) {
return _.mapValues(keyValueMap, value => _.keyBy(_.split(value, ' '), v => v));
}
linesToKeyValueList(currHostsLines) {
let currHosts = _.map(currHostsLines, line => {
const ipsNames = _.split(_.trim(line), /[ \t]/);
let key = ipsNames[0];
let names = ipsNames.slice(1);
return {[key]: _.join(names, ' ')}
});
return _.reduce(currHosts, (result, h) => {
let key = _.keys(h)[0];
result[key] = h[key];
return result;
}, {});
}
mergeKeyValueLists(map1, map2) {
let hostsMap = this.convertStringValToMapVal(map1);
let listMap = this.convertStringValToMapVal(map2);
_.merge(hostsMap, listMap);
const result = _.mapValues(hostsMap, valKV => _.join(_.keys(valKV), ' '));
return result;
}
writeHostFile(keyValueHostRecords, dir) {
const file = path.join(dir, 'hosts')
if (this.existsAndIsFile(file)) {
try {
const currHostsLines = fs.readFileSync(file, 'utf-8').split('\n');
const currHosts = this.linesToKeyValueList(currHostsLines);
let newHostsMap = this.mergeKeyValueLists(currHosts, keyValueHostRecords);
let hostsFileContent = `# replaced by writeFile \n`;
_.forOwn(newHostsMap, (value, key) => {
hostsFileContent = hostsFileContent + key + ' ' + value + '\n';
});
fs.writeFileSync(file, hostsFileContent);
logger.info(`written: ${file}\n`, hostsFileContent);
} catch (err) {
logger.error(`cannot writeFile ${file}`, err);
}
} else {
logger.debug(`Skipping ${file}`);
}
}
existsAndIsFile(file) {
try {
fs.accessSync(file, fs.constants.W_OK);
return fs.statSync(file).isFile()
} catch (e) {
logger.debug(`Cannot open file ${file}`, e);
}
}
splitOutputToMultiline(str) {
return _.split(str, '\n')
}
sortAndFilterObjectProps(obj, filterFunc = () => true) {
return _.reduce(_.entries(obj).filter(filterFunc).sort(),
(res, entry) => {
res[entry[0]] = entry[1];
return res
},
{}
);
}
}
module.exports = new Util();