-
Notifications
You must be signed in to change notification settings - Fork 7
/
nodes.ts
485 lines (444 loc) · 14.8 KB
/
nodes.ts
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
import { Client as RMBClient } from "@threefold/rmb_direct_client";
import { default as PrivateIp } from "private-ip";
import urlJoin from "url-join";
import { GridClient } from "../client";
import { RMB } from "../clients";
import { Graphql } from "../clients/graphql/client";
import { TFClient } from "../clients/tf-grid/client";
import { send } from "../helpers/requests";
import { FilterOptions } from "../modules/models";
interface FarmInfo {
name: string;
farmId: number;
twinId: number;
version: number;
pricingPolicyId: number;
stellarAddress: string;
publicIps: PublicIps[];
}
interface PublicIps {
id: string;
ip: string;
contractId: number;
gateway: string;
}
interface NodeInfo {
version: number;
id: string;
nodeId: number;
farmId: number;
twinId: number;
gridVersion: number;
uptime: number;
created: number;
farmingPolicyId: number;
updatedAt: string;
total_resources: NodeResources;
used_resources: NodeResources;
location: {
country: string;
city: string;
};
publicConfig: PublicConfig;
status: string;
certificationType: string;
hasGPU: boolean;
extraFee: number;
rentedByTwinId: number;
}
interface PublicConfig {
domain: string;
gw4: string;
gw6: string;
ipv4: string;
ipv6: string;
}
interface NodeResources {
cru: number;
sru: number;
hru: number;
mru: number;
ipv4u: number;
}
interface NodeCapacity {
capacity: {
total_resources: NodeResources;
used_resources: NodeResources;
};
}
interface RMBNodeCapacity {
total: NodeResources;
used: NodeResources;
}
enum DiskTypes {
SSD = "ssd",
HDD = "hdd",
}
export interface StoragePool {
type: DiskTypes;
size: number;
used: number;
}
class Nodes {
gqlClient: Graphql;
rmb: RMB;
constructor(public graphqlURL: string, public proxyURL: string, rmbClient: RMBClient) {
this.gqlClient = new Graphql(graphqlURL);
this.rmb = new RMB(rmbClient);
}
async getNodeTwinId(node_id: number): Promise<number> {
const body = `query getNodeTwinId($nodeId: Int!){
nodes(where: { nodeID_eq: $nodeId }) {
twinID
}
}`;
return this.gqlClient
.query(body, { nodeId: node_id })
.then(response => {
if (response["data"]["nodes"]["length"] === 0) {
throw Error(`Couldn't find a node with id: ${node_id}`);
}
return response["data"]["nodes"][0]["twinID"];
})
.catch(err => {
throw Error(`Error getting node twin ID for ID ${node_id}: ${err}`);
});
}
async getAccessNodes(): Promise<Record<string, unknown>> {
const accessNodes = {};
const nodes = await this.filterNodes({ accessNodeV4: true, accessNodeV6: true });
for (const node of nodes) {
const ipv4 = node.publicConfig.ipv4;
const ipv6 = node.publicConfig.ipv6;
const domain = node.publicConfig.domain;
if (PrivateIp(ipv4.split("/")[0]) === false) {
accessNodes[+node.nodeId] = { ipv4: ipv4, ipv6: ipv6, domain: domain };
}
}
if (Object.keys(accessNodes).length === 0) {
throw Error("Couldn't find any node with public config");
}
console.log(accessNodes);
return accessNodes;
}
async getNodeIdFromContractId(contractId: number, mnemonic: string): Promise<number> {
const tfclient = new TFClient(
GridClient.config.substrateURL,
mnemonic,
GridClient.config.storeSecret,
GridClient.config.keypairType,
);
return tfclient.contracts
.get({ id: contractId })
.then(contract => {
if (!contract.contractType.nodeContract)
throw Error(`Couldn't get node id for this contract ${contractId}. It's not a node contract`);
return contract.contractType.nodeContract.nodeId;
})
.catch(err => {
throw Error(`Error getting node ID from contract ID ${contractId}: ${err}`);
});
}
_g2b(GB: number): number {
return GB * 1024 ** 3;
}
async getFarms(page = 1, pageSize = 50, url = ""): Promise<FarmInfo[]> {
let r: string;
if (url) r = url;
else r = this.proxyURL;
return send("get", urlJoin(r, `/farms?page=${page}&size=${pageSize}`), "", {})
.then(res => {
return res;
})
.catch(err => {
throw Error(`Error listing farms with page ${page} and size ${pageSize}: ${err}`);
});
}
async getAllFarms(url = ""): Promise<FarmInfo[]> {
try {
const farmsCount = await this.gqlClient.getItemTotalCount("farms", "(orderBy: farmID_ASC)");
return await this.getFarms(1, farmsCount, url);
} catch (err) {
throw Error(`Error listing all farms: ${err}`);
}
}
async checkFarmHasFreePublicIps(farmId: number, farms: FarmInfo[] = null, url = ""): Promise<boolean> {
if (!farms) {
farms = await this.getAllFarms(url);
}
return farms
.filter(farm => farm.publicIps.filter(ip => ip.contractId === 0).length > 0)
.map(farm => farm.farmId)
.includes(farmId);
}
async getNodes(page = 1, pageSize = 50, url = ""): Promise<NodeInfo[]> {
let r: string;
if (url) r = url;
else r = this.proxyURL;
return send("get", urlJoin(r, `/nodes?page=${page}&size=${pageSize}`), "", {})
.then(ret => {
return ret;
})
.catch(err => {
throw Error(`Error listing nodes with page ${page} and size ${pageSize}: ${err}`);
});
}
async getAllNodes(url = ""): Promise<NodeInfo[]> {
try {
const nodesCount = await this.gqlClient.getItemTotalCount("nodes", "(orderBy: nodeID_ASC)");
return await this.getNodes(1, nodesCount, url);
} catch (err) {
throw Error(`Error listing all nodes: ${err}`);
}
}
async getNodesByFarmId(farmId: number, url = ""): Promise<NodeInfo[]> {
let nodesCount = 0;
try {
nodesCount = await this.gqlClient.getItemTotalCount(
"nodes",
`(where: {farmID_eq: ${farmId}}, orderBy: nodeID_ASC)`,
);
} catch (err) {
throw Error(`Error getting total nodes count: ${err}`);
}
let r: string;
if (url) r = url;
else r = this.proxyURL;
return send("get", urlJoin(r, `/nodes?farm_id=${farmId}&size=${nodesCount}`), "", {})
.then(res => {
if (res) return res;
else throw new Error(`The farm with id ${farmId}: doesn't have any nodes`);
})
.catch(err => {
throw Error(`Error getting nodes by farm ID ${farmId}: ${err}`);
});
}
async getNode(nodeId, url = ""): Promise<NodeInfo> {
let r: string;
if (url) r = url;
else r = this.proxyURL;
return send("get", urlJoin(r, `/nodes?node_id=${nodeId}`), "", {})
.then(ret => {
if (ret.length !== 0) return ret[0];
})
.catch(err => {
throw Error(`Error getting node with ID ${nodeId}: ${err}`);
});
}
async getNodeFreeResources(nodeId: number, source: "proxy" | "zos" = "proxy", url = ""): Promise<NodeResources> {
if (source == "zos") {
const node_twin_id = await this.getNodeTwinId(nodeId);
return this.rmb
.request([node_twin_id], "zos.statistics.get", "")
.then(res => {
const node: RMBNodeCapacity = res;
const ret: NodeResources = { cru: 0, mru: 0, hru: 0, sru: 0, ipv4u: 0 };
ret.mru = +node.total.mru - +node.used.mru;
ret.sru = +node.total.sru - +node.used.sru;
ret.hru = +node.total.hru - +node.used.hru;
return ret;
})
.catch(err => {
throw Error(`Error getting node ${nodeId}: ${err}`);
});
}
let r: string;
if (url) r = url;
else r = this.proxyURL;
return send("get", urlJoin(r, `/nodes/${nodeId}`), "", {})
.then(res => {
const node: NodeCapacity = res;
const ret: NodeResources = { cru: 0, mru: 0, hru: 0, sru: 0, ipv4u: 0 };
ret.mru = +node.capacity.total_resources.mru - +node.capacity.used_resources.mru;
ret.sru = +node.capacity.total_resources.sru - +node.capacity.used_resources.sru;
ret.hru = +node.capacity.total_resources.hru - +node.capacity.used_resources.hru;
return ret;
})
.catch(err => {
console.log(err);
if (err.response.status === 404) {
throw Error(`Node: ${nodeId} is not found`);
} else if (err.response.status === 502) {
throw Error(`Node: ${nodeId} is not reachable`);
} else {
throw err;
}
});
}
async filterNodes(options: FilterOptions = {}, url = ""): Promise<NodeInfo[]> {
let nodes: NodeInfo[] = [];
url = url || this.proxyURL;
const query = this.getUrlQuery(options);
try {
nodes = await send("get", urlJoin(url, `/nodes?${query}`), "", {});
} catch {
throw Error(`Invalid query: ${query}`);
}
if (nodes.length) {
nodes = nodes.filter(n => !(options.nodeExclude && options.nodeExclude?.includes(n.nodeId)));
}
return nodes;
}
/**
* Get farm id from farm name.
* It returns 0 in case the farm name is not found.
* @param {string} name
* @returns {Promise<number>}
*/
async getFarmIdFromFarmName(name: string, farms: FarmInfo[] = null, url = ""): Promise<number> {
if (!farms) {
farms = await this.getAllFarms(url);
}
const filteredFarms = farms.filter(f => String(f.name).toLowerCase() === name.toLowerCase());
if (filteredFarms.length === 0) {
return 0; // not found
}
return filteredFarms[0].farmId;
}
getUrlQuery(options: FilterOptions = {}) {
const params = {
free_mru: Math.ceil(this._g2b(options.mru)) || "",
free_sru: Math.ceil(this._g2b(options.sru)) || "",
free_hru: Math.ceil(this._g2b(options.hru)) || "",
free_ips: options.publicIPs ? 1 : "",
ipv4: options.accessNodeV4,
ipv6: options.accessNodeV6,
gateway: options.gateway,
certification_type: options.certified ? "Certified" : "",
farm_ids: [options.farmId],
farm_name: options.farmName,
country: options.country,
city: options.city,
dedicated: options.dedicated,
available_for: options.availableFor,
status: "up",
page: options.page,
size: options.size,
has_gpu: options.hasGPU,
rented_by: options.rentedBy,
};
if (options.gateway) {
params["ipv4"] = true;
params["ipv6"] = true;
params["domain"] = true;
}
return Object.entries(params)
.map(param => param.join("="))
.join("&");
}
async nodeHasResources(nodeId: number, options: FilterOptions): Promise<boolean> {
const resources = await this.getNodeFreeResources(nodeId, "zos");
if (
resources.mru < this._g2b(options.mru) ||
resources.sru < this._g2b(options.sru) ||
resources.hru < this._g2b(options.hru)
) {
return false;
}
return true;
}
async nodeAvailableForTwinId(nodeId: number, twinId: number): Promise<boolean> {
return send("get", urlJoin(this.proxyURL, `/nodes/${nodeId}`), "", {})
.then(node => {
if (node.rentedByTwinId != twinId && (node.dedicated || node.rentContractId != 0)) {
return false;
}
return true;
})
.catch(err => {
throw Error(`Error checking if node ${nodeId} is available for twin ${twinId}: ${err}`);
});
}
/**
* Allocates a disk of a given size to a list of disk pools.
*
* @param diskPools - An array of numbers representing the available disk space in each pool.
* @param disk - The size of the disk to be allocated.
* @returns A boolean value indicating whether the disk was successfully allocated or not.
* Returns true if the disk was allocated to a pool, false otherwise.
*/
allocateDiskToPools(diskPools: number[], disk: number): boolean {
for (const index in diskPools) {
if (diskPools[index] >= disk) {
diskPools[index] -= disk;
return true;
}
}
return false;
}
/**
* Sorts an array of numbers in descending order.
*
* @param array - The array of numbers to be sorted in descending order.
*/
sortArrayDesc(array: number[]): void {
array.sort((a, b) => b - a);
}
/**
* Fits disks into disk pools based on their sizes.
*
* @param disks - An array of disk sizes required to be fitted into the pool.
* @param pool - An array representing the available disk space in the pool.
* @param type - A DiskTypes enum value representing the type of disk being allocated.
* @throws {Error} - If the required disk cannot be fitted into the pool.
*/
fitDisksInDisksPool(disks: number[], pools: number[], type: DiskTypes): void {
disks.forEach(disk => {
if (!this.allocateDiskToPools(pools, disk)) {
throw new Error(
`Cannot fit the required ${type.toUpperCase()} disk with size ${(disk / 1024 ** 3).toFixed(2)} GB`,
);
}
this.sortArrayDesc(pools);
});
}
/**
* Verifies the storage pool capacity of a node for different disk types.
*
* @param ssdDisks - An array of SSD disk sizes required for the deployment.
* @param hddDisks - An array of HDD disk sizes required for the deployment.
* @param rootFileSystemDisks - An array of disk sizes required for the deployment's root file system.
* @param nodeId - The ID of the node to be verified.
* @returns {Promise<boolean>} - True if the node has enough capacity, otherwise false.
* @throws {Error} - If there is an error in getting the node's information or if the required deployment can't be fitted.
*/
async verifyNodeStoragePoolCapacity(
ssdDisks: number[],
hddDisks: number[],
rootFileSystemDisks: number[],
nodeId: number,
): Promise<boolean> {
const ssdPools: number[] = [];
const hddPools: number[] = [];
try {
const nodeTwinId = await this.getNodeTwinId(nodeId);
((await this.rmb.request([nodeTwinId], "zos.storage.pools", "")) as StoragePool[]).forEach(
(disk: StoragePool) => {
disk.type === DiskTypes.SSD ? ssdPools.push(disk.size - disk.used) : hddPools.push(disk.size - disk.used);
},
);
} catch (err) {
throw new Error(`Error getting node ${nodeId}: ${err}`);
}
this.sortArrayDesc(hddPools);
this.sortArrayDesc(ssdPools);
this.sortArrayDesc(rootFileSystemDisks);
this.sortArrayDesc(ssdDisks);
this.sortArrayDesc(hddDisks);
try {
this.fitDisksInDisksPool(ssdDisks, ssdPools, DiskTypes.SSD);
this.fitDisksInDisksPool(hddDisks, hddPools, DiskTypes.HDD);
this.fitDisksInDisksPool(rootFileSystemDisks, ssdPools, DiskTypes.SSD);
return true;
} catch (error) {
throw new Error(
`${(error as Error).message}, on Node ${nodeId} with disk pools:
SSD: ${ssdPools.map(disk => (disk / 1024 ** 3).toFixed(2).toString() + "GB ")}
HDD: ${hddPools.map(disk => (disk / 1024 ** 3).toFixed(2).toString() + "GB ")}
Please select another Node\n`,
);
}
}
// TODO : add get node by its node ID like the one in modules
}
export { Nodes, FarmInfo, NodeResources, NodeInfo, PublicIps, PublicConfig };