forked from noobaa/noobaa-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpool_server.js
More file actions
1505 lines (1352 loc) · 57.2 KB
/
pool_server.js
File metadata and controls
1505 lines (1352 loc) · 57.2 KB
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (C) 2016 NooBaa */
/**
*
* POOL_SERVER
*
*/
'use strict';
const _ = require('lodash');
const P = require('../../util/promise');
const dbg = require('../../util/debug_module')(__filename);
const config = require('../../../config');
const { RpcError } = require('../../rpc');
const size_utils = require('../../util/size_utils');
const addr_utils = require('../../util/addr_utils');
const server_rpc = require('../server_rpc');
const Dispatcher = require('../notifications/dispatcher');
const nodes_client = require('../node_services/nodes_client');
const system_store = require('../system_services/system_store').get_instance();
const cloud_utils = require('../../util/cloud_utils');
const auth_server = require('../common_services/auth_server');
const HistoryDataStore = require('../analytic_services/history_data_store').HistoryDataStore;
const IoStatsStore = require('../analytic_services/io_stats_store').IoStatsStore;
const pool_ctrls = require('./pool_controllers');
const func_store = require('../func_services/func_store');
const { KubeStore } = require('../kube-store.js');
const POOL_STORAGE_DEFAULTS = Object.freeze({
total: 0,
free: 0,
used_other: 0,
unavailable_free: 0,
unavailable_used: 0,
used: 0,
reserved: 0,
});
const POOL_NODES_INFO_DEFAULTS = Object.freeze({
count: 0,
// storage_count: 0,
online: 0,
by_mode: {},
});
const POOL_HOSTS_INFO_DEFAULTS = Object.freeze({
count: 0,
by_mode: {},
by_service: {},
});
// key: namespace_resource_id, value: { last_monitoring: date, issues: array of issues }
// (see namespace_resource_schema)
const map_issues_and_monitoring_report = new Map();
const NO_CAPAITY_LIMIT = 1024 ** 2; // 1MB
const LOW_CAPACITY_HARD_LIMIT = 30 * (1024 ** 3); // 30GB
// hold the factory function that create the pool controllers for the system pools.
let create_pool_controller = default_create_pool_controller;
// This code should fix and pending changes to hosts pools in the case
// that the server process was stopped unexpectedly.
async function _init() {
await P.wait_until(() => system_store.is_finished_initial_load);
// Ensure that all account are not using mongo pool as default resource after
// at least one pool is in optimal state.
update_account_default_resource();
}
function default_create_pool_controller(system, pool) {
return pool.hosts_pool_info.is_managed ?
new pool_ctrls.ManagedStatefulSetPoolController(system.name, pool.name) :
new pool_ctrls.UnmanagedStatefulSetPoolController(system.name, pool.name);
}
function set_pool_controller_factory(pool_controller_factory) {
if (pool_controller_factory === null) {
create_pool_controller = default_create_pool_controller;
} else if (_.isFunction(pool_controller_factory)) {
create_pool_controller = pool_controller_factory;
} else {
throw new TypeError('Invalid pool_controller_factory, must be a function or null');
}
}
// The function checks whether the pool/resource has an owner
// and only allows deletion in case that the owner is also the requester of the deletion
function check_deletion_ownership(req, resource_owner_id) {
if (config.RESTRICT_RESOURCE_DELETION) {
if (!resource_owner_id) {
dbg.error('check_deletion_ownership: pool has no owner');
throw new RpcError('INTERNAL_ERROR', 'The pool has no owner, and thus cannot be deleted');
}
const requester_is_sys_owner = String(req.account._id) === String(req.system.owner._id);
if (!requester_is_sys_owner && String(resource_owner_id) !== String(req.account._id)) {
dbg.error('check_deletion_ownership: requester (', req.account._id, ') is not the owner (', resource_owner_id, ') of the resource');
throw new RpcError('UNAUTHORIZED', 'The pool or resource can be deleted only by its owner or the system administrator');
}
}
}
function new_pool_defaults(name, system_id, resource_type, pool_node_type, owner_id) {
const now = Date.now();
return {
_id: system_store.new_system_store_id(),
system: system_id,
name: name,
owner_id,
resource_type: resource_type,
pool_node_type: pool_node_type,
storage_stats: {
blocks_size: 0,
last_update: now - (2 * config.MD_GRACE_IN_MILLISECONDS)
},
};
}
function new_namespace_resource_defaults(name, system_id, account_id, connection, nsfs_config, access_mode) {
return {
_id: system_store.new_system_store_id(),
system: system_id,
account: account_id,
name,
connection,
nsfs_config,
access_mode
};
}
async function create_hosts_pool(req) {
try {
// Trigger partial aggregation for the Prometheus metrics
server_rpc.client.stats.get_partial_stats({
requester: 'create_hosts_pool',
}, {
auth_token: req.auth_token
});
} catch (error) {
dbg.error('create_hosts_pool: get_partial_stats failed with', error);
}
const { system, rpc_params, account } = req;
const pool = new_pool_defaults(rpc_params.name, system._id, 'HOSTS', 'BLOCK_STORE_FS', req.account._id);
const MIN_PV_SIZE_GB = 16;
const PV_SIZE_GB = 20;
const GB = 1024 ** 3;
const conf_volume_size = rpc_params.host_config && rpc_params.host_config.volume_size;
if (conf_volume_size && conf_volume_size < MIN_PV_SIZE_GB * GB) {
dbg.error(`create_hosts_pool: insufficient PV size, minimal PV size is ${MIN_PV_SIZE_GB}GB`);
throw new RpcError('BAD_REQUEST', `insufficient PV size, minimal PV size is ${MIN_PV_SIZE_GB}GB`);
}
pool.hosts_pool_info = _.cloneDeep(
_.defaultsDeep(_.pick(rpc_params, [
'is_managed',
'host_count',
'host_config',
'backingstore'
]), {
host_config: {
volume_size: PV_SIZE_GB * GB
}
})
);
dbg.log0('create_hosts_pool: Creating new pool', pool);
await system_store.make_changes({
insert: {
pools: [pool],
},
});
const { hosts_pool_info } = pool;
Dispatcher.instance().activity({
event: 'resource.create',
level: 'info',
system: system._id,
actor: account._id,
pool: pool._id,
desc: `A ${
hosts_pool_info.is_managed ? 'managed' : 'unmanaged'
} pool ${
rpc_params.name
} with ${
hosts_pool_info.host_count
} nodes was created by ${
account.email.unwrap()
}`,
});
try {
const routing_hint = hosts_pool_info.is_managed ? 'INTERNAL' : 'EXTERNAL';
const agent_install_string = await get_agent_install_conf(system, pool, account, routing_hint);
const agent_profile = Object.assign(
JSON.parse(process.env.AGENT_PROFILE || '{}'),
hosts_pool_info.host_config
);
const account_roles = req.account.roles_by_system[req.system._id];
let res = agent_install_string;
if (!account_roles.includes('operator')) {
// Ask the pool controller to create backing agents for the pool
const pool_ctrl = create_pool_controller(system, pool);
res = await pool_ctrl.create(
hosts_pool_info.host_count,
agent_install_string,
agent_profile
);
}
return res;
} catch (err) {
console.error(`create_hosts_pool: Could not deploy underlaying agents, got: ${err.message}`);
throw err;
}
}
async function get_hosts_pool_agent_config(req) {
const pool = find_pool_by_name(req);
if (!pool.hosts_pool_info) {
throw new RpcError('INVALID_POOL_TYPE', `pool ${pool.name} not a hosts pool`);
}
const agent_install_string = await get_agent_install_conf(req.system, pool, req.account, 'INTERNAL');
return agent_install_string;
}
async function get_agent_install_conf(system, pool, account, routing_hint) {
let cfg = system_store.data.agent_configs
.find(conf => conf.pool === pool._id);
if (!cfg) {
// create new configuration with the required settings
dbg.log0(`creating new installation string for pool: ${pool.name} (${pool._id})`);
const conf_id = system_store.new_system_store_id();
cfg = {
_id: conf_id,
name: String(conf_id),
system: system._id,
pool: pool._id,
exclude_drives: [],
use_storage: true,
routing_hint
};
await system_store.make_changes({
insert: {
agent_configs: [cfg]
}
});
}
// Creating a new create_auth_token for conf_id
const create_node_token = auth_server.make_auth_token({
system_id: system._id,
account_id: account._id,
role: 'create_node',
extra: { agent_config_id: cfg._id }
});
const addr = addr_utils.get_base_address(system.system_address, { hint: routing_hint });
const install_string = JSON.stringify({
address: addr.toString(),
routing_hint,
system: system.name,
create_node_token,
root_path: './noobaa_storage/'
});
return Buffer.from(install_string).toString('base64');
}
async function create_namespace_resource(req) {
req.rpc_params.access_mode = req.rpc_params.access_mode || 'READ_WRITE';
const name = req.rpc_params.name;
let namespace_resource;
if (req.rpc_params.nsfs_config) {
namespace_resource = new_namespace_resource_defaults(name, req.system._id, req.account._id, undefined, req.rpc_params.nsfs_config,
req.rpc_params.access_mode);
const already_used_by = system_store.data.namespace_resources.find(cur_nsr => cur_nsr.nsfs_config &&
(cur_nsr.nsfs_config.fs_root_path === namespace_resource.nsfs_config.fs_root_path));
if (already_used_by) {
dbg.error(`fs root path ${already_used_by.nsfs_config.fs_root_path} already exported by ${already_used_by.name}`);
throw new RpcError('IN_USE', 'Target already in use');
}
} else {
const connection = cloud_utils.find_cloud_connection(req.account, req.rpc_params.connection);
const secret_key = system_store.master_key_manager.encrypt_sensitive_string_with_master_key_id(
connection.secret_key, req.account.master_key_id._id);
let azure_log_access_keys;
if (connection.azure_log_access_keys) {
azure_log_access_keys = {
azure_client_id: connection.azure_log_access_keys.azure_client_id,
azure_client_secret: system_store.master_key_manager.encrypt_sensitive_string_with_master_key_id(
connection.azure_log_access_keys.azure_client_secret, req.account.master_key_id._id
),
azure_tenant_id: connection.azure_log_access_keys.azure_tenant_id,
azure_logs_analytics_workspace_id: connection.azure_log_access_keys.azure_logs_analytics_workspace_id
};
}
namespace_resource = new_namespace_resource_defaults(name, req.system._id, req.account._id, _.omitBy({
aws_sts_arn: connection.aws_sts_arn,
endpoint: connection.endpoint,
target_bucket: req.rpc_params.target_bucket,
access_key: connection.access_key,
auth_method: connection.auth_method,
cp_code: connection.cp_code || undefined,
secret_key,
endpoint_type: connection.endpoint_type || 'AWS',
region: connection.region,
azure_log_access_keys,
}, _.isUndefined), undefined, req.rpc_params.access_mode);
const cloud_buckets = await server_rpc.client.bucket.get_cloud_buckets({
connection: connection.name,
}, {
auth_token: req.auth_token
});
if (!cloud_buckets.find(bucket_name => bucket_name.name.unwrap() === req.rpc_params.target_bucket)) {
dbg.error('This endpoint target bucket does not exist');
throw new RpcError('INVALID_TARGET', 'Target bucket doesn\'t exist');
}
const already_used_by = cloud_utils.get_used_cloud_targets([namespace_resource.connection.endpoint_type],
system_store.data.buckets, system_store.data.pools, system_store.data.namespace_resources)
.find(candidate_target => (candidate_target.endpoint === namespace_resource.connection.endpoint &&
candidate_target.target_name === namespace_resource.connection.target_bucket));
if (already_used_by) {
dbg.error(`This endpoint is already being used by a ${already_used_by.usage_type}: ${already_used_by.source_name}`);
throw new RpcError('IN_USE', 'Target already in use');
}
}
if (req.rpc_params.namespace_store) {
namespace_resource.namespace_store = req.rpc_params.namespace_store;
}
dbg.log0('creating namespace_resource:', namespace_resource);
return system_store.make_changes({
insert: {
namespace_resources: [namespace_resource]
}
});
// .then(() => {
// Dispatcher.instance().activity({
// event: 'resource.cloud_create',
// level: 'info',
// system: req.system._id,
// actor: req.account && req.account._id,
// pool: pool._id,
// desc: `${pool.name} was created by ${req.account && req.account.email.unwrap()}`,
// });
// })
}
async function create_cloud_pool(req) {
const name = req.rpc_params.name;
const connection = cloud_utils.find_cloud_connection(req.account, req.rpc_params.connection);
const secret_key = system_store.master_key_manager.encrypt_sensitive_string_with_master_key_id(
connection.secret_key, req.account.master_key_id._id);
const cloud_info = _.omitBy({
endpoint: connection.endpoint,
target_bucket: req.rpc_params.target_bucket,
auth_method: connection.auth_method,
access_keys: {
access_key: connection.access_key,
secret_key,
account_id: req.account._id
},
aws_sts_arn: connection.aws_sts_arn,
region: connection.region,
endpoint_type: connection.endpoint_type || 'AWS',
backingstore: req.rpc_params.backingstore,
available_capacity: req.rpc_params.available_capacity,
storage_limit: req.rpc_params.storage_limit,
}, _.isUndefined);
const cloud_buckets = await server_rpc.client.bucket.get_cloud_buckets({
connection: connection.name,
}, {
auth_token: req.auth_token
});
if (!cloud_buckets.find(bucket_name => bucket_name.name.unwrap() === cloud_info.target_bucket)) {
dbg.error('This endpoint target bucket does not exist');
throw new RpcError('INVALID_TARGET', 'Target bucket doesn\'t exist');
}
const already_used_by = cloud_utils.get_used_cloud_targets([cloud_info.endpoint_type],
system_store.data.buckets, system_store.data.pools, system_store.data.namespace_resources)
.find(candidate_target => (candidate_target.endpoint === cloud_info.endpoint &&
candidate_target.target_name === cloud_info.target_bucket));
if (already_used_by) {
dbg.error(`This endpoint is already being used by a ${already_used_by.usage_type}: ${already_used_by.source_name}`);
throw new RpcError('IN_USE', 'Target already in use');
}
if (req.rpc_params.storage_limit < config.ENOUGH_ROOM_IN_TIER_THRESHOLD) {
throw new RpcError('INVALID_STORAGE_LIMIT', 'new storage limit is smaller than the minimum allowed');
}
try {
// Trigger partial aggregation for the Prometheus metrics
server_rpc.client.stats.get_partial_stats({
requester: 'create_cloud_pool',
}, {
auth_token: req.auth_token
});
} catch (error) {
dbg.error('create_cloud_pool: get_partial_stats failed with', error);
}
const map_pool_type = {
AWSSTS: 'BLOCK_STORE_S3',
AWS: 'BLOCK_STORE_S3',
S3_COMPATIBLE: 'BLOCK_STORE_S3',
FLASHBLADE: 'BLOCK_STORE_S3',
IBM_COS: 'BLOCK_STORE_S3',
AZURE: 'BLOCK_STORE_AZURE',
GOOGLE: 'BLOCK_STORE_GOOGLE'
};
const pool_node_type = map_pool_type[connection.endpoint_type];
const pool = new_pool_defaults(name, req.system._id, 'CLOUD', pool_node_type, req.account._id);
dbg.log0('Creating new cloud_pool', pool);
pool.cloud_pool_info = cloud_info;
dbg.log0('got connection for cloud pool:', connection);
await system_store.make_changes({
insert: {
pools: [pool]
}
});
await server_rpc.client.hosted_agents.create_pool_agent({
pool_name: req.rpc_params.name,
}, {
auth_token: req.auth_token
});
Dispatcher.instance().activity({
event: 'resource.cloud_create',
level: 'info',
system: req.system._id,
actor: req.account && req.account._id,
pool: pool._id,
desc: `${pool.name} was created by ${req.account && req.account.email.unwrap()}`,
});
}
async function update_cloud_pool(req) {
const pool = find_pool_by_name(req);
if (!pool.cloud_pool_info) {
throw new RpcError('INVALID_POOL_TYPE', `pool ${pool.name} is not a cloud pool`);
}
const updates = {
_id: pool._id,
$set: {},
$unset: {},
};
// Handle total capacity changes
const new_available_capacity = req.rpc_params.available_capacity;
if (new_available_capacity !== 'undefined') {
if (new_available_capacity < 0) {
throw new RpcError('INVALID_AVAIL_CAPACITY', 'Available capacity must be a positive quantity');
}
updates.$set['cloud_pool_info.available_capacity'] = new_available_capacity;
}
// Handle storage limit changes
const new_storage_limit = req.rpc_params.storage_limit;
if (new_storage_limit) {
const pool_info = await read_pool(req);
const storage_minimum = Math.max(pool_info.storage.used, config.ENOUGH_ROOM_IN_TIER_THRESHOLD);
if (new_storage_limit < storage_minimum) {
throw new RpcError('INVALID_STORAGE_LIMIT', 'new storage limit is smaller than size already used by pool or the minimum allowed');
}
dbg.log0(`update_cloud_pool: updating ${pool.name} storage limit to ${new_storage_limit}, current usage is ${storage_minimum}`);
updates.$set['cloud_pool_info.storage_limit'] = new_storage_limit;
} else if (new_storage_limit === null && pool.cloud_pool_info.storage_limit) {
dbg.log0(`update_cloud_pool: removing ${pool.name} storage limit`);
updates.$unset['cloud_pool_info.storage_limit'] = 1;
}
await system_store.make_changes({
update: {
pools: [updates],
}
});
// Update hosted agents in any case of storage limit changes
if (!_.isUndefined(new_storage_limit)) {
await server_rpc.client.hosted_agents.update_storage_limit({
pool_ids: [String(pool._id)],
storage_limit: new_storage_limit
}, {
auth_token: req.auth_token
});
}
}
function create_mongo_pool(req) {
const name = req.rpc_params.name;
const mongo_info = {};
if (config.DB_TYPE !== 'mongodb') {
dbg.error(`Cannot create mongo pool with DB_TYPE=${config.DB_TYPE}`);
throw new Error(`Cannot create mongo pool with DB_TYPE=${config.DB_TYPE}`);
}
if (get_internal_mongo_pool(req.system)) {
dbg.error('System already has mongo pool');
throw new Error('System already has mongo pool');
}
const pool = new_pool_defaults(name, req.system._id, 'INTERNAL', 'BLOCK_STORE_MONGO');
dbg.log0('Creating new mongo_pool', pool);
pool.mongo_pool_info = mongo_info;
return system_store.make_changes({
insert: {
pools: [pool]
}
})
.then(res => server_rpc.client.hosted_agents.create_pool_agent({
pool_name: req.rpc_params.name,
}, {
auth_token: req.auth_token
}));
// .then(() => {
// Dispatcher.instance().activity({
// event: 'resource.cloud_create',
// level: 'info',
// system: req.system._id,
// actor: req.account && req.account._id,
// pool: pool._id,
// desc: `${pool.name} was created by ${req.account && req.account.email.unwrap()}`,
// });
// })
}
async function read_pool(req) {
const pool = find_pool_by_name(req);
const nodes_aggregate_pool = await nodes_client.instance().aggregate_nodes_by_pool([pool.name], req.system._id);
const hosts_aggregate_pool = await nodes_client.instance().aggregate_hosts_by_pool([pool.name], req.system._id);
return get_pool_info(pool, nodes_aggregate_pool, hosts_aggregate_pool);
}
function read_namespace_resource(req) {
const namespace_resource = find_namespace_resource_by_name(req);
return P.resolve()
.then(() => get_namespace_resource_info(namespace_resource));
}
async function scale_hosts_pool(req) {
const pool = find_pool_by_name(req);
if (!pool.hosts_pool_info) {
throw new RpcError('INVALID_POOL_TYPE', `pool ${pool.name} is not a hosts pool`);
}
const pool_info = await read_pool(req);
const { host_count } = req.rpc_params;
const current_host_count = pool_info.hosts.count;
const current_configured_count = pool.hosts_pool_info.host_count;
if (pool.mode === 'DELETING') {
throw new RpcError('INVALID_POOL_STATE', `pool ${pool.name} is being deleted`);
}
if (host_count < current_host_count) {
throw new RpcError('INVALID_POOL_STATE', `can't scale down ${pool.name} hosts count to less than current connected hosts`);
}
const pool_ctrl = create_pool_controller(req.system, pool);
await pool_ctrl.scale(host_count);
if (host_count === current_configured_count) {
// Nothing to do as the DB not changing
return;
}
Dispatcher.instance().activity({
event: 'resource.scale',
level: 'info',
system: req.system._id,
actor: req.account._id,
pool: pool._id,
desc: `Pool ${
pool.name
} was scaled ${
host_count > current_configured_count ? 'up' : 'down'
} from ${
current_configured_count
} to ${
host_count
} by ${
req.account.email.unwrap()
}`
});
// Update the host pool info.
dbg.log0(`scale_hosts_pool: updating ${pool.name} host count from ${current_configured_count} to ${host_count}`);
return system_store.make_changes({
update: {
pools: [{
_id: pool._id,
'hosts_pool_info.host_count': host_count
}]
}
});
}
async function update_hosts_pool(req) {
const pool = find_pool_by_name(req);
if (!pool.hosts_pool_info) {
throw new RpcError('INVALID_POOL_TYPE', `pool ${pool.name} is not a hosts pool`);
}
const backingstore = await KubeStore.instance.read_backingstore(pool.name);
const host_count = backingstore.spec.pvPool.numVolumes;
const configured_host_count = pool.hosts_pool_info.host_count;
Dispatcher.instance().activity({
event: 'resource.scale',
level: 'info',
system: req.system._id,
actor: req.account._id,
pool: pool._id,
desc: `Pool ${
pool.name
} was scaled ${
host_count > configured_host_count ? 'up' : 'down'
} from ${
configured_host_count
} to ${
host_count
} by ${
req.account.email.unwrap()
}`
});
// Update the host pool info.
dbg.log0(`update_hosts_pool: updating ${pool.name} host count from ${configured_host_count} to ${host_count}`);
return system_store.make_changes({
update: {
pools: [{
_id: pool._id,
'hosts_pool_info.host_count': host_count
}]
}
});
}
function delete_pool(req) {
const pool = find_pool_by_name(req);
// rebuild_object_links() resolves the pool's owner_id to the account object
// which is why we have to access ._id to get the actual ID
check_deletion_ownership(req, pool.owner_id?._id);
if (pool.hosts_pool_info) {
return delete_hosts_pool(req, pool);
} else {
return delete_resource_pool(req, pool);
}
}
function delete_namespace_resource(req) {
const ns = find_namespace_resource_by_name(req);
check_deletion_ownership(req, ns.account._id);
dbg.log0('Deleting namespace resource', ns.name);
return P.resolve()
.then(() => {
const reason = check_namespace_resource_deletion(ns);
if (reason) {
throw new RpcError(reason, 'Cannot delete namespace resource');
}
return system_store.make_changes({
remove: {
namespace_resources: [ns._id]
}
});
})
.then(() => {
// do nothing.
});
}
async function delete_hosts_pool(req, pool) {
dbg.log0('delete_hosts_pool: deleting hosts pool', pool.name);
const account_roles = req.account.roles_by_system[req.system._id];
const reason = check_pool_deletion(pool);
if (reason === 'IS_BACKINGSTORE') {
if (!account_roles.includes('operator')) {
throw new RpcError(reason, 'Cannot delete pool');
}
} else if (reason && reason !== 'BEING_DELETED') {
throw new RpcError(reason, 'Cannot delete pool');
}
if (!account_roles.includes('operator')) {
const pool_ctrl = create_pool_controller(req.system, pool);
await pool_ctrl.delete();
}
const { host_count } = pool.hosts_pool_info;
if (host_count > 0) {
await system_store.make_changes({
update: {
pools: [{
_id: pool._id,
'hosts_pool_info.host_count': 0
}]
}
});
await nodes_client.instance()
.delete_hosts_by_pool(pool.name, req.system._id);
}
const current_host_count = await get_current_hosts_count(pool.name, req.system._id);
if (current_host_count > 0) {
if (account_roles.includes('operator') || reason === 'BEING_DELETED') {
throw new RpcError('BEING_DELETED', 'Cannot delete pool');
}
} else {
dbg.log0(`delete_hosts_pool: removing pool ${pool.name} from the database`);
await system_store.make_changes({
remove: {
pools: [pool._id]
}
});
Dispatcher.instance().activity({
event: 'resource.delete',
level: 'info',
system: req.system._id,
pool: pool._id,
desc: `${pool.name} was emptyed and deleted`,
});
const related_funcs = await func_store.instance().list_funcs_by_pool(req.system._id, pool._id);
for (const func of related_funcs) {
const new_pools_arr = func.pools.filter(function(obj) {
return obj.toString() !== (pool._id).toString();
});
await func_store.instance().update_func(func._id, { 'pools': new_pools_arr });
}
}
}
async function get_current_hosts_count(pool_name, system_id) {
const hosts_aggregate = await nodes_client.instance()
.aggregate_hosts_by_pool([pool_name], system_id);
const { count, by_mode } = hosts_aggregate.nodes;
return count - (by_mode.INITIALIZING || 0);
}
function delete_resource_pool(req, pool) {
dbg.log0('Deleting resource pool', pool.name);
const pool_name = pool.name;
return P.resolve()
.then(() => {
const reason = check_resource_pool_deletion(pool);
if (reason === 'IS_BACKINGSTORE') {
const account_roles = req.account.roles_by_system[req.system._id];
if (!account_roles.includes('operator')) {
throw new RpcError(reason, 'Cannot delete pool');
}
} else if (reason) {
throw new RpcError(reason, 'Cannot delete pool');
}
return nodes_client.instance().list_nodes_by_pool(pool.name, req.system._id);
})
.then(function(pool_nodes) {
if (!pool_nodes || pool_nodes.total_count === 0) {
// handle edge case where the cloud pool is deleted before it's node is registered in nodes monitor.
// in that case, send remove_cloud_agent to hosted_agents, which should also remove the pool.
dbg.log0(`resource_pool ${pool_name} does not have any nodes in nodes_monitor. delete agent and pool from hosted_agents`);
return server_rpc.client.hosted_agents.remove_pool_agent({
pool_name: pool.name
}, {
auth_token: req.auth_token
});
}
return P.map_one_by_one(pool_nodes.nodes, node =>
nodes_client.instance().delete_node_by_name(req.system._id, node.name)
)
.then(function() {
// rename the deleted pool to avoid an edge case where there are collisions
// with a new resource pool name
const db_update = {
_id: pool._id,
name: pool.name + '#' + pool._id
};
const pending_del_property = pool.resource_type === 'INTERNAL' ?
'mongo_pool_info.pending_delete' : 'cloud_pool_info.pending_delete';
// mark the resource pool as pending delete
db_update[pending_del_property] = true;
return system_store.make_changes({
update: {
pools: [db_update]
}
});
});
})
.then(() => {
const { account } = req;
if (pool.resource_type === 'CLOUD') {
Dispatcher.instance().activity({
event: 'resource.cloud_delete',
level: 'info',
system: req.system._id,
actor: account && account._id,
pool: pool._id,
desc: `${pool_name} was deleted by ${account && account.email.unwrap()}`,
});
}
})
.then(() => {
// do nothing.
});
}
function get_associated_buckets(req) {
const pool = find_pool_by_name(req);
return get_associated_buckets_int(pool);
}
async function get_namespace_stats_by_cloud_service(system, start_date, end_date) {
const ns_stats = _.keyBy(await IoStatsStore.instance().get_all_namespace_resources_stats({ system, start_date, end_date }),
stat => String(stat._id));
const grouped_stats = _.omit(_.groupBy(ns_stats, stat => {
const ns_resource = system_store.data.get_by_id(stat._id);
const endpoint_type = _.get(ns_resource, 'connection.endpoint_type');
return endpoint_type || 'OTHER';
}), 'OTHER');
return _.map(grouped_stats, (stats, service) => {
const reduced_stats = stats.reduce((prev, current) => ({
read_count: prev.read_count + (current.read_count || 0),
write_count: prev.write_count + (current.write_count || 0),
read_bytes: prev.read_bytes + (current.read_bytes || 0),
write_bytes: prev.write_bytes + (current.write_bytes || 0),
}), {
read_count: 0,
write_count: 0,
read_bytes: 0,
write_bytes: 0,
});
reduced_stats.service = service;
return reduced_stats;
});
}
async function get_cloud_services_stats(req) {
const { start_date, end_date } = req.rpc_params;
const [cloud_stats, namespace_stats] = await P.all([
nodes_client.instance().get_nodes_stats_by_cloud_service(req.system._id, start_date, end_date),
get_namespace_stats_by_cloud_service(req.system._id, start_date, end_date)
]);
const all_services = {};
for (const service of config.SERVICES_TYPES) {
all_services[service] = {
service,
read_bytes: 0,
read_count: 0,
write_bytes: 0,
write_count: 0
};
}
for (const acc of system_store.data.accounts) {
if (acc.sync_credentials_cache) {
acc.sync_credentials_cache.forEach(conn => {
all_services[conn.endpoint_type] = all_services[conn.endpoint_type] || {
service: conn.endpoint_type,
read_bytes: 0,
read_count: 0,
write_bytes: 0,
write_count: 0
};
});
}
}
const cloud_stats_by_service = _.keyBy(cloud_stats, 'service');
const ns_stats_by_service = _.keyBy(namespace_stats, 'service');
_.mergeWith(all_services, cloud_stats_by_service, ns_stats_by_service, (a = {}, b = {}) => ({
service: a.service || b.service,
read_count: (a.read_count || 0) + (b.read_count || 0),
write_count: (a.write_count || 0) + (b.write_count || 0),
read_bytes: (a.read_bytes || 0) + (b.read_bytes || 0),
write_bytes: (a.write_bytes || 0) + (b.write_bytes || 0),
}));
return _.values(all_services);
}
function get_pool_history(req) {
const pool_list = req.rpc_params.pool_list;
return HistoryDataStore.instance().get_pool_history()
.then(history_records => history_records.map(history_record => ({
timestamp: history_record.time_stamp.getTime(),
pool_list: history_record.system_snapshot.pools
.filter(pool => (!pool.mongo_info) && (!pool_list || pool_list.includes(pool.name)))
.map(pool => {
const { name, storage, cloud_info, mongo_info } = pool;
let resource_type = 'HOSTS';
if (cloud_info) {
resource_type = 'CLOUD';
} else if (mongo_info) {
resource_type = 'INTERNAL';
}
return {
name,
storage,
resource_type
};
})
})));
}
// UTILS //////////////////////////////////////////////////////////
// TODO: Notice that does not include pools in disabled tiers
// What should we do in that case? Shall we delete the pool or not?
function get_associated_buckets_int(pool) {
const associated_buckets = _.filter(pool.system.buckets_by_name, function(bucket) {
if (bucket.deleting) return false;
return _.find(bucket.tiering.tiers, function(tier_and_order) {
return _.find(tier_and_order.tier.mirrors, function(mirror) {
return _.find(mirror.spread_pools, function(spread_pool) {
return String(pool._id) === String(spread_pool._id);
});
});
});
});
return _.map(associated_buckets, function(bucket) {
return bucket.name;
});
}
function has_associated_buckets_int(pool, { exclude_deleting_buckets } = {}) {
const associated_bucket = _.find(pool.system.buckets_by_name, function(bucket) {
if (bucket.deleting && exclude_deleting_buckets) return false;
return _.find(bucket.tiering && bucket.tiering.tiers, function(tier_and_order) {
return _.find(tier_and_order.tier.mirrors, function(mirror) {
return _.find(mirror.spread_pools, function(spread_pool) {
return String(pool._id) === String(spread_pool._id);
});
});
});
});
return Boolean(associated_bucket);
}
function get_associated_accounts(pool) {
return system_store.data.accounts
.filter(account => (!account.is_support &&
account.default_resource &&
account.default_resource._id === pool._id
))
.map(associated_account => associated_account.email);
}
function find_pool_by_name(req) {
const name = req.rpc_params.name;
const pool = req.system.pools_by_name[name];
if (!pool) {
throw new RpcError('NO_SUCH_POOL', 'No such pool: ' + name);
}
return pool;
}
async function assign_pool_to_region(req) {
const name = req.rpc_params.name;
const pool = req.system.pools_by_name[name];
if (!pool) {
throw new RpcError('NO_SUCH_POOL', 'No such pool: ' + name);
}
if (pool.resource_type === 'INTERNAL') {
throw new RpcError('NO_REGION_ON_INTERNAL', 'Can\'t set region for internal resource');
}
if (pool.region === req.rpc_params.region) return;
if (req.rpc_params.region === '' && _.isUndefined(pool.region)) return;
let desc;
if (req.rpc_params.region === '') {
await system_store.make_changes({
update: {
pools: [{
_id: pool._id,
$unset: { region: 1 },
}]