1 import { Component, Input, OnChanges, OnInit, TemplateRef, ViewChild } from '@angular/core';
2 import { Validators } from '@angular/forms';
4 import { I18n } from '@ngx-translate/i18n-polyfill';
11 } from 'angular-tree-component';
12 import * as _ from 'lodash';
13 import * as moment from 'moment';
14 import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
16 import { CephfsService } from '../../../shared/api/cephfs.service';
17 import { ConfirmationModalComponent } from '../../../shared/components/confirmation-modal/confirmation-modal.component';
18 import { CriticalConfirmationModalComponent } from '../../../shared/components/critical-confirmation-modal/critical-confirmation-modal.component';
19 import { FormModalComponent } from '../../../shared/components/form-modal/form-modal.component';
20 import { ActionLabelsI18n } from '../../../shared/constants/app.constants';
21 import { Icons } from '../../../shared/enum/icons.enum';
22 import { NotificationType } from '../../../shared/enum/notification-type.enum';
23 import { CdValidators } from '../../../shared/forms/cd-validators';
24 import { CdFormModalFieldConfig } from '../../../shared/models/cd-form-modal-field-config';
25 import { CdTableAction } from '../../../shared/models/cd-table-action';
26 import { CdTableColumn } from '../../../shared/models/cd-table-column';
27 import { CdTableSelection } from '../../../shared/models/cd-table-selection';
32 } from '../../../shared/models/cephfs-directory-models';
33 import { Permission } from '../../../shared/models/permissions';
34 import { CdDatePipe } from '../../../shared/pipes/cd-date.pipe';
35 import { DimlessBinaryPipe } from '../../../shared/pipes/dimless-binary.pipe';
36 import { AuthStorageService } from '../../../shared/services/auth-storage.service';
37 import { NotificationService } from '../../../shared/services/notification.service';
41 // Used in quota table
43 value: number | string;
55 selector: 'cd-cephfs-directories',
56 templateUrl: './cephfs-directories.component.html',
57 styleUrls: ['./cephfs-directories.component.scss']
59 export class CephfsDirectoriesComponent implements OnInit, OnChanges {
60 @ViewChild(TreeComponent, { static: false })
61 treeComponent: TreeComponent;
62 @ViewChild('origin', { static: true })
63 originTmpl: TemplateRef<any>;
68 private modalRef: BsModalRef;
69 private dirs: CephfsDir[];
70 private nodeIds: { [path: string]: CephfsDir };
71 private requestedPaths: string[];
72 private loadingTimeout: any;
75 loadingIndicator = false;
77 treeOptions: ITreeOptions = {
78 useVirtualScroll: true,
79 getChildren: (node: TreeNode): Promise<any[]> => {
80 return this.updateDirectory(node.id);
84 click: this.selectAndShowNode.bind(this),
85 expanderClick: this.selectAndShowNode.bind(this)
90 permission: Permission;
91 selectedDir: CephfsDir;
92 settings: QuotaSetting[];
94 columns: CdTableColumn[];
95 selection: CdTableSelection;
96 tableActions: CdTableAction[];
97 updateSelection: Function;
100 columns: CdTableColumn[];
101 selection: CdTableSelection;
102 tableActions: CdTableAction[];
103 updateSelection: Function;
108 private authStorageService: AuthStorageService,
109 private modalService: BsModalService,
110 private cephfsService: CephfsService,
111 private cdDatePipe: CdDatePipe,
113 private actionLabels: ActionLabelsI18n,
114 private notificationService: NotificationService,
115 private dimlessBinaryPipe: DimlessBinaryPipe
118 private selectAndShowNode(tree: TreeModel, node: TreeNode, $event: any) {
119 TREE_ACTIONS.TOGGLE_EXPANDED(tree, node, $event);
120 this.selectNode(node);
123 private selectNode(node: TreeNode) {
124 TREE_ACTIONS.TOGGLE_ACTIVE(undefined, node, undefined);
125 this.selectedDir = this.getDirectory(node);
126 if (node.id === '/') {
129 this.setSettings(node);
133 this.permission = this.authStorageService.getPermissions().cephfs;
134 this.setUpQuotaTable();
135 this.setUpSnapshotTable();
138 private setUpQuotaTable() {
143 name: this.i18n('Name'),
148 name: this.i18n('Value'),
153 prop: 'row.originPath',
154 name: this.i18n('Origin'),
156 cellTemplate: this.originTmpl,
160 selection: new CdTableSelection(),
161 updateSelection: (selection: CdTableSelection) => {
162 this.quota.selection = selection;
166 name: this.actionLabels.SET,
168 permission: 'update',
169 visible: (selection) =>
170 !selection.hasSelection || (selection.first() && selection.first().dirValue === 0),
171 click: () => this.updateQuotaModal()
174 name: this.actionLabels.UPDATE,
176 permission: 'update',
177 visible: (selection) => selection.first() && selection.first().dirValue > 0,
178 click: () => this.updateQuotaModal()
181 name: this.actionLabels.UNSET,
183 permission: 'update',
184 disable: (selection) =>
185 !selection.hasSelection || (selection.first() && selection.first().dirValue === 0),
186 click: () => this.unsetQuotaModal()
192 private setUpSnapshotTable() {
197 name: this.i18n('Name'),
202 name: this.i18n('Path'),
208 name: this.i18n('Created'),
210 pipe: this.cdDatePipe
213 selection: new CdTableSelection(),
214 updateSelection: (selection: CdTableSelection) => {
215 this.snapshot.selection = selection;
219 name: this.actionLabels.CREATE,
221 permission: 'create',
222 canBePrimary: (selection) => !selection.hasSelection,
223 click: () => this.createSnapshot()
226 name: this.actionLabels.DELETE,
228 permission: 'delete',
229 click: () => this.deleteSnapshotModal(),
230 canBePrimary: (selection) => selection.hasSelection,
231 disable: (selection) => !selection.hasSelection
238 this.selectedDir = undefined;
240 this.requestedPaths = [];
248 private setRootNode() {
258 private firstCall() {
261 this.getNode(path).loadNodeChildren();
265 updateDirectory(path: string): Promise<any[]> {
266 this.unsetLoadingIndicator();
267 if (!this.requestedPaths.includes(path)) {
268 this.requestedPaths.push(path);
269 } else if (this.loading[path] === true) {
270 return undefined; // Path is currently fetched.
272 return new Promise((resolve) => {
273 this.setLoadingIndicator(path, true);
274 this.cephfsService.lsDir(this.id, path).subscribe((dirs) => {
275 this.updateTreeStructure(dirs);
276 this.updateQuotaTable();
278 resolve(this.getChildren(path));
279 this.setLoadingIndicator(path, false);
284 private setLoadingIndicator(path: string, loading: boolean) {
285 this.loading[path] = loading;
286 this.unsetLoadingIndicator();
289 private getSubDirectories(path: string, tree: CephfsDir[] = this.dirs): CephfsDir[] {
290 return tree.filter((d) => d.parent === path);
293 private getChildren(path: string): any[] {
294 const subTree = this.getSubTree(path);
295 return _.sortBy(this.getSubDirectories(path), 'path').map((dir) =>
296 this.createNode(dir, subTree)
300 private createNode(dir: CephfsDir, subTree?: CephfsDir[]): any {
301 this.nodeIds[dir.path] = dir;
303 this.getSubTree(dir.parent);
308 hasChildren: this.getSubDirectories(dir.path, subTree).length > 0
312 private getSubTree(path: string): CephfsDir[] {
313 return this.dirs.filter((d) => d.parent && d.parent.startsWith(path));
316 private setSettings(node: TreeNode) {
317 const readable = (value: number, fn?: (arg0: number) => number | string): number | string =>
318 value ? (fn ? fn(value) : value) : '';
321 this.getQuota(node, 'max_files', readable),
322 this.getQuota(node, 'max_bytes', (value) =>
323 readable(value, (v) => this.dimlessBinaryPipe.transform(v))
331 valueConvertFn: (number: number) => number | string
333 // Get current maximum
334 const currentPath = tree.id;
335 tree = this.getOrigin(tree, quotaKey);
336 const dir = this.getDirectory(tree);
337 const value = dir.quotas[quotaKey];
338 // Get next tree maximum
339 // => The value that isn't changeable through a change of the current directories quota value
340 let nextMaxValue = value;
341 let nextMaxPath = dir.path;
342 if (tree.id === currentPath) {
343 if (tree.parent.id === '/') {
344 // The value will never inherit any other value, so it has no maximum.
347 const nextMaxDir = this.getDirectory(this.getOrigin(tree.parent, quotaKey));
348 nextMaxValue = nextMaxDir.quotas[quotaKey];
349 nextMaxPath = nextMaxDir.path;
354 name: quotaKey === 'max_bytes' ? this.i18n('Max size') : this.i18n('Max files'),
355 value: valueConvertFn(value),
356 originPath: value ? dir.path : ''
359 dirValue: this.nodeIds[currentPath].quotas[quotaKey],
362 path: nextMaxValue ? nextMaxPath : ''
368 * Get the node where the quota limit originates from in the current node
370 * Example as it's a recursive method:
372 * | Path + Value | Call depth | useOrigin? | Output |
373 * |:-------------:|:----------:|:---------------------:|:------:|
374 * | /a/b/c/d (15) | 1st | 2nd (5) < 15 => false | /a/b |
375 * | /a/b/c (20) | 2nd | 3rd (5) < 20 => false | /a/b |
376 * | /a/b (5) | 3rd | 4th (10) < 5 => true | /a/b |
377 * | /a (10) | 4th | 10 => true | /a |
380 private getOrigin(tree: TreeNode, quotaSetting: string): TreeNode {
381 if (tree.parent && tree.parent.id !== '/') {
382 const current = this.getQuotaFromTree(tree, quotaSetting);
384 // Get the next used quota and node above the current one (until it hits the root directory)
385 const originTree = this.getOrigin(tree.parent, quotaSetting);
386 const inherited = this.getQuotaFromTree(originTree, quotaSetting);
388 // Select if the current quota is in use or the above
389 const useOrigin = current === 0 || (inherited !== 0 && inherited < current);
390 return useOrigin ? originTree : tree;
395 private getQuotaFromTree(tree: TreeNode, quotaSetting: string): number {
396 return this.getDirectory(tree).quotas[quotaSetting];
399 private getDirectory(node: TreeNode): CephfsDir {
400 const path = node.id as string;
401 return this.nodeIds[path];
404 selectOrigin(path: string) {
405 this.selectNode(this.getNode(path));
408 private getNode(path: string): TreeNode {
409 return this.treeComponent.treeModel.getNodeById(path);
413 const path = this.selectedDir.path;
414 const selection: QuotaSetting = this.quota.selection.first();
415 const nextMax = selection.nextTreeMaximum;
416 const key = selection.quotaKey;
417 const value = selection.dirValue;
418 this.modalService.show(FormModalComponent, {
420 titleText: this.getModalQuotaTitle(
421 value === 0 ? this.actionLabels.SET : this.actionLabels.UPDATE,
424 message: nextMax.value
425 ? this.i18n('The inherited {{quotaValue}} is the maximum value to be used.', {
426 quotaValue: this.getQuotaValueFromPathMsg(nextMax.value, nextMax.path)
429 fields: [this.getQuotaFormField(selection.row.name, key, value, nextMax.value)],
430 submitButtonText: this.i18n('Save'),
431 onSubmit: (values: CephfsQuotas) => this.updateQuota(values)
436 private getModalQuotaTitle(action: string, path: string): string {
437 return this.i18n("{{action}} CephFS {{quotaName}} quota for '{{path}}'", {
439 quotaName: this.getQuotaName(),
444 private getQuotaName(): string {
445 return this.isBytesQuotaSelected() ? this.i18n('size') : this.i18n('files');
448 private isBytesQuotaSelected(): boolean {
449 return this.quota.selection.first().quotaKey === 'max_bytes';
452 private getQuotaValueFromPathMsg(value: number, path: string): string {
453 return this.i18n("{{quotaName}} quota {{value}} from '{{path}}'", {
454 value: this.isBytesQuotaSelected() ? this.dimlessBinaryPipe.transform(value) : value,
455 quotaName: this.getQuotaName(),
460 private getQuotaFormField(
465 ): CdFormModalFieldConfig {
466 const isBinary = name === 'max_bytes';
467 const formValidators = [isBinary ? CdValidators.binaryMin(0) : Validators.min(0)];
469 formValidators.push(isBinary ? CdValidators.binaryMax(maxValue) : Validators.max(maxValue));
471 const field: CdFormModalFieldConfig = {
472 type: isBinary ? 'binary' : 'number',
476 validators: formValidators,
481 min: this.i18n(`Value has to be at least {{value}} or more`, { value: 0 }),
482 max: this.i18n(`Value has to be at most {{value}} or less`, { value: maxValue })
488 private updateQuota(values: CephfsQuotas, onSuccess?: Function) {
489 const path = this.selectedDir.path;
490 const key = this.quota.selection.first().quotaKey;
492 this.selectedDir.quotas[key] === 0
493 ? this.actionLabels.SET
495 ? this.actionLabels.UNSET
496 : this.i18n('Updated');
497 this.cephfsService.updateQuota(this.id, path, values).subscribe(() => {
501 this.notificationService.show(
502 NotificationType.success,
503 this.getModalQuotaTitle(action, path)
505 this.forceDirRefresh();
510 const path = this.selectedDir.path;
511 const selection: QuotaSetting = this.quota.selection.first();
512 const key = selection.quotaKey;
513 const nextMax = selection.nextTreeMaximum;
514 const dirValue = selection.dirValue;
516 this.modalRef = this.modalService.show(ConfirmationModalComponent, {
518 titleText: this.getModalQuotaTitle(this.actionLabels.UNSET, path),
519 buttonText: this.actionLabels.UNSET,
520 description: this.i18n(`{{action}} {{quotaValue}} {{conclusion}}.`, {
521 action: this.actionLabels.UNSET,
522 quotaValue: this.getQuotaValueFromPathMsg(dirValue, path),
525 ? nextMax.value > dirValue
526 ? this.i18n('in order to inherit {{quotaValue}}', {
527 quotaValue: this.getQuotaValueFromPathMsg(nextMax.value, nextMax.path)
529 : this.i18n("which isn't used because of the inheritance of {{quotaValue}}", {
530 quotaValue: this.getQuotaValueFromPathMsg(nextMax.value, nextMax.path)
532 : this.i18n('in order to have no quota on the directory')
534 onSubmit: () => this.updateQuota({ [key]: 0 }, () => this.modalRef.hide())
540 // Create a snapshot. Auto-generate a snapshot name by default.
541 const path = this.selectedDir.path;
542 this.modalService.show(FormModalComponent, {
544 titleText: this.i18n('Create Snapshot'),
545 message: this.i18n('Please enter the name of the snapshot.'),
550 value: `${moment().toISOString(true)}`,
554 submitButtonText: this.i18n('Create Snapshot'),
555 onSubmit: (values: CephfsSnapshot) => {
556 this.cephfsService.mkSnapshot(this.id, path, values.name).subscribe((name) => {
557 this.notificationService.show(
558 NotificationType.success,
559 this.i18n('Created snapshot "{{name}}" for "{{path}}"', {
564 this.forceDirRefresh();
572 * Forces an update of the current selected directory
574 * As all nodes point by their path on an directory object, the easiest way is to update
575 * the objects by merge with their latest change.
577 private forceDirRefresh(path?: string) {
579 const dir = this.selectedDir;
581 throw new Error('This function can only be called without path if an selection was made');
583 // Parent has to be called in order to update the object referring
584 // to the current selected directory
585 path = dir.parent ? dir.parent : dir.path;
587 const node = this.getNode(path);
588 node.loadNodeChildren();
591 private updateTreeStructure(dirs: CephfsDir[]) {
592 const getChildrenAndPaths = (
593 directories: CephfsDir[],
595 ): { children: CephfsDir[]; paths: string[] } => {
596 const children = directories.filter((d) => d.parent === parent);
597 const paths = children.map((d) => d.path);
598 return { children, paths };
601 const parents = _.uniq(dirs.map((d) => d.parent).sort());
602 parents.forEach((p) => {
603 const received = getChildrenAndPaths(dirs, p);
604 const cached = getChildrenAndPaths(this.dirs, p);
606 cached.children.forEach((d) => {
607 if (!received.paths.includes(d.path)) {
608 this.removeOldDirectory(d);
611 received.children.forEach((d) => {
612 if (cached.paths.includes(d.path)) {
613 this.updateExistingDirectory(cached.children, d);
615 this.addNewDirectory(d);
621 private removeOldDirectory(rmDir: CephfsDir) {
622 const path = rmDir.path;
623 // Remove directory from local variables
624 _.remove(this.dirs, (d) => d.path === path);
625 delete this.nodeIds[path];
626 this.updateDirectoriesParentNode(rmDir);
629 private updateDirectoriesParentNode(dir: CephfsDir) {
630 const parent = dir.parent;
634 const node = this.getNode(parent);
636 // Node will not be found for new sub sub directories - this is the intended behaviour
639 const children = this.getChildren(parent);
640 node.data.children = children;
641 node.data.hasChildren = children.length > 0;
642 this.treeComponent.treeModel.update();
645 private addNewDirectory(newDir: CephfsDir) {
646 this.dirs.push(newDir);
647 this.nodeIds[newDir.path] = newDir;
648 this.updateDirectoriesParentNode(newDir);
651 private updateExistingDirectory(source: CephfsDir[], updatedDir: CephfsDir) {
652 const currentDirObject = source.find((sub) => sub.path === updatedDir.path);
653 Object.assign(currentDirObject, updatedDir);
656 private updateQuotaTable() {
657 const node = this.selectedDir ? this.getNode(this.selectedDir.path) : undefined;
658 if (node && node.id !== '/') {
659 this.setSettings(node);
663 private updateTree(force: boolean = false) {
664 if (this.loadingIndicator && !force) {
665 // In order to make the page scrollable during load, the render cycle for each node
666 // is omitted and only be called if all updates were loaded.
669 this.treeComponent.treeModel.update();
670 this.nodes = [...this.nodes];
671 this.treeComponent.sizeChanged();
674 deleteSnapshotModal() {
675 this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, {
677 itemDescription: this.i18n('CephFs Snapshot'),
678 itemNames: this.snapshot.selection.selected.map(
679 (snapshot: CephfsSnapshot) => snapshot.name
681 submitAction: () => this.deleteSnapshot()
687 const path = this.selectedDir.path;
688 this.snapshot.selection.selected.forEach((snapshot: CephfsSnapshot) => {
689 const name = snapshot.name;
690 this.cephfsService.rmSnapshot(this.id, path, name).subscribe(() => {
691 this.notificationService.show(
692 NotificationType.success,
693 this.i18n('Deleted snapshot "{{name}}" for "{{path}}"', {
700 this.modalRef.hide();
701 this.forceDirRefresh();
704 refreshAllDirectories() {
705 // In order to make the page scrollable during load, the render cycle for each node
706 // is omitted and only be called if all updates were loaded.
707 this.loadingIndicator = true;
708 this.requestedPaths.map((path) => this.forceDirRefresh(path));
709 const interval = setInterval(() => {
710 this.updateTree(true);
711 if (!this.loadingIndicator) {
712 clearInterval(interval);
717 unsetLoadingIndicator() {
718 if (!this.loadingIndicator) {
721 clearTimeout(this.loadingTimeout);
722 this.loadingTimeout = setTimeout(() => {
723 const loading = Object.values(this.loading).some((l) => l);
725 return this.unsetLoadingIndicator();
727 this.loadingIndicator = false;
729 // The problem is that we can't subscribe to an useful updated tree event and the time
730 // between fetching all calls and rebuilding the tree can take some time