Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-configuration-form/rbd-configuration-form.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import _ from 'lodash'; import { ReplaySubject } from 'rxjs'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { RbdConfigurationEntry, RbdConfigurationSourceField, RbdConfigurationType } from '~/app/shared/models/configuration'; import { FormatterService } from '~/app/shared/services/formatter.service'; import { RbdConfigurationService } from '~/app/shared/services/rbd-configuration.service'; @Component({ selector: 'cd-rbd-configuration-form', templateUrl: './rbd-configuration-form.component.html', styleUrls: ['./rbd-configuration-form.component.scss'] }) export class RbdConfigurationFormComponent implements OnInit { @Input() form: CdFormGroup; @Input() initializeData = new ReplaySubject<{ initialData: RbdConfigurationEntry[]; sourceType: RbdConfigurationSourceField; }>(1); @Output() changes = new EventEmitter<any>(); icons = Icons; ngDataReady = new EventEmitter<any>(); initialData: RbdConfigurationEntry[]; configurationType = RbdConfigurationType; sectionVisibility: { [key: string]: boolean } = {}; constructor( public formatterService: FormatterService, public rbdConfigurationService: RbdConfigurationService ) {} ngOnInit() { const configFormGroup = this.createConfigurationFormGroup(); this.form.addControl('configuration', configFormGroup); // Listen to changes and emit the values to the parent component configFormGroup.valueChanges.subscribe(() => { this.changes.emit(this.getDirtyValues.bind(this)); }); if (this.initializeData) { this.initializeData.subscribe((data: Record<string, any>) => { this.initialData = data.initialData; const dataType = data.sourceType; this.rbdConfigurationService.getWritableOptionFields().forEach((option) => { const optionData = data.initialData .filter((entry: Record<string, any>) => entry.name === option.name) .pop(); if (optionData && optionData['source'] === dataType) { this.form.get(`configuration.${option.name}`).setValue(optionData['value']); } }); this.ngDataReady.emit(); }); } this.rbdConfigurationService .getWritableSections() .forEach((section) => (this.sectionVisibility[section.class] = false)); } getDirtyValues(includeLocalValues = false, localFieldType?: RbdConfigurationSourceField) { if (includeLocalValues && !localFieldType) { const msg = 'ProgrammingError: If local values shall be included, a proper localFieldType argument has to be provided, too'; throw new Error(msg); } const result = {}; this.rbdConfigurationService.getWritableOptionFields().forEach((config) => { const control: any = this.form.get('configuration').get(config.name); const dirty = control.dirty; if (this.initialData && this.initialData[config.name] === control.value) { return; // Skip controls with initial data loaded } if (dirty || (includeLocalValues && control['source'] === localFieldType)) { if (control.value === null) { result[config.name] = control.value; } else if (config.type === RbdConfigurationType.bps) { result[config.name] = this.formatterService.toBytes(control.value); } else if (config.type === RbdConfigurationType.milliseconds) { result[config.name] = this.formatterService.toMilliseconds(control.value); } else if (config.type === RbdConfigurationType.iops) { result[config.name] = this.formatterService.toIops(control.value); } else { result[config.name] = control.value; } } }); return result; } /** * Dynamically create form controls. */ private createConfigurationFormGroup() { const configFormGroup = new CdFormGroup({}); this.rbdConfigurationService.getWritableOptionFields().forEach((c) => { let control: FormControl; if ( c.type === RbdConfigurationType.milliseconds || c.type === RbdConfigurationType.iops || c.type === RbdConfigurationType.bps ) { let initialValue = 0; _.forEach(this.initialData, (configList) => { if (configList['name'] === c.name) { initialValue = configList['value']; } }); control = new FormControl(initialValue, Validators.min(0)); } else { throw new Error( `Type ${c.type} is unknown, you may need to add it to RbdConfiguration class` ); } configFormGroup.addControl(c.name, control); }); return configFormGroup; } /** * Reset the value. The inherited value will be used instead. */ reset(optionName: string) { const formControl: any = this.form.get('configuration').get(optionName); if (formControl.disabled) { formControl.setValue(formControl['previousValue'] || 0); formControl.enable(); if (!formControl['previousValue']) { formControl.markAsPristine(); } } else { formControl['previousValue'] = formControl.value; formControl.setValue(null); formControl.markAsDirty(); formControl.disable(); } } isDisabled(optionName: string) { return this.form.get('configuration').get(optionName).disabled; } toggleSectionVisibility(className: string) { this.sectionVisibility[className] = !this.sectionVisibility[className]; } }
5,671
32.964072
120
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-configuration-list/rbd-configuration-list.component.html
<cd-table #poolConfTable [data]="data" [columns]="poolConfigurationColumns" identifier="name"> </cd-table> <ng-template #configurationSourceTpl let-value="value"> <div [ngSwitch]="value"> <span *ngSwitchCase="'global'" i18n>Global</span> <strong *ngSwitchCase="'image'" i18n>Image</strong> <strong *ngSwitchCase="'pool'" i18n>Pool</strong> </div> </ng-template> <ng-template #configurationValueTpl let-row="row" let-value="value"> <div [ngSwitch]="row.type"> <span *ngSwitchCase="typeField.bps">{{ value | dimlessBinaryPerSecond }}</span> <span *ngSwitchCase="typeField.milliseconds">{{ value | milliseconds }}</span> <span *ngSwitchCase="typeField.iops">{{ value | iops }}</span> <span *ngSwitchDefault>{{ value }}</span> </div> </ng-template>
887
28.6
83
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-configuration-list/rbd-configuration-list.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbDropdownModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'; import { NgxDatatableModule } from '@swimlane/ngx-datatable'; import { ChartsModule } from 'ng2-charts'; import { ComponentsModule } from '~/app/shared/components/components.module'; import { RbdConfigurationEntry } from '~/app/shared/models/configuration'; import { FormatterService } from '~/app/shared/services/formatter.service'; import { RbdConfigurationService } from '~/app/shared/services/rbd-configuration.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdConfigurationListComponent } from './rbd-configuration-list.component'; describe('RbdConfigurationListComponent', () => { let component: RbdConfigurationListComponent; let fixture: ComponentFixture<RbdConfigurationListComponent>; configureTestBed({ imports: [ BrowserAnimationsModule, FormsModule, NgxDatatableModule, RouterTestingModule, ComponentsModule, NgbDropdownModule, ChartsModule, SharedModule, NgbTooltipModule ], declarations: [RbdConfigurationListComponent], providers: [FormatterService, RbdConfigurationService] }); beforeEach(() => { fixture = TestBed.createComponent(RbdConfigurationListComponent); component = fixture.componentInstance; component.data = []; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('filters options out which are not defined in RbdConfigurationService', () => { const fakeOption = { name: 'foo', source: 0, value: '50' } as RbdConfigurationEntry; const realOption = { name: 'rbd_qos_read_iops_burst', source: 0, value: '50' } as RbdConfigurationEntry; component.data = [fakeOption, realOption]; component.ngOnChanges(); expect(component.data.length).toBe(1); expect(component.data.pop()).toBe(realOption); }); it('should filter the source column by its piped value', () => { const poolConfTable = component.poolConfTable; poolConfTable.data = [ { name: 'rbd_qos_read_iops_burst', source: 0, value: '50' }, { name: 'rbd_qos_read_iops_limit', source: 1, value: '50' }, { name: 'rbd_qos_write_iops_limit', source: 0, value: '100' }, { name: 'rbd_qos_write_iops_burst', source: 2, value: '100' } ]; const filter = (keyword: string) => { poolConfTable.search = keyword; poolConfTable.updateFilter(); return poolConfTable.rows; }; expect(filter('').length).toBe(4); expect(filter('source:global').length).toBe(2); expect(filter('source:pool').length).toBe(1); expect(filter('source:image').length).toBe(1); expect(filter('source:zero').length).toBe(0); }); });
3,213
31.14
90
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-configuration-list/rbd-configuration-list.component.ts
import { Component, Input, OnChanges, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { TableComponent } from '~/app/shared/datatable/table/table.component'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { RbdConfigurationEntry, RbdConfigurationSourceField, RbdConfigurationType } from '~/app/shared/models/configuration'; import { RbdConfigurationSourcePipe } from '~/app/shared/pipes/rbd-configuration-source.pipe'; import { FormatterService } from '~/app/shared/services/formatter.service'; import { RbdConfigurationService } from '~/app/shared/services/rbd-configuration.service'; @Component({ selector: 'cd-rbd-configuration-table', templateUrl: './rbd-configuration-list.component.html', styleUrls: ['./rbd-configuration-list.component.scss'] }) export class RbdConfigurationListComponent implements OnInit, OnChanges { @Input() data: RbdConfigurationEntry[]; poolConfigurationColumns: CdTableColumn[]; @ViewChild('configurationSourceTpl', { static: true }) configurationSourceTpl: TemplateRef<any>; @ViewChild('configurationValueTpl', { static: true }) configurationValueTpl: TemplateRef<any>; @ViewChild('poolConfTable', { static: true }) poolConfTable: TableComponent; readonly sourceField = RbdConfigurationSourceField; readonly typeField = RbdConfigurationType; constructor( public formatterService: FormatterService, private rbdConfigurationService: RbdConfigurationService ) {} ngOnInit() { this.poolConfigurationColumns = [ { prop: 'displayName', name: $localize`Name` }, { prop: 'description', name: $localize`Description` }, { prop: 'name', name: $localize`Key` }, { prop: 'source', name: $localize`Source`, cellTemplate: this.configurationSourceTpl, pipe: new RbdConfigurationSourcePipe() }, { prop: 'value', name: $localize`Value`, cellTemplate: this.configurationValueTpl } ]; } ngOnChanges(): void { if (!this.data) { return; } // Filter settings out which are not listed in RbdConfigurationService this.data = this.data.filter((row) => this.rbdConfigurationService .getOptionFields() .map((o) => o.name) .includes(row.name) ); } }
2,288
33.681818
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-details/rbd-details.component.html
<ng-template #usageNotAvailableTooltipTpl> <ng-container i18n>Only available for RBD images with <strong>fast-diff</strong> enabled</ng-container> </ng-template> <ng-container *ngIf="selection && selection.source !== 'REMOVING'"> <nav ngbNav #nav="ngbNav" class="nav-tabs" cdStatefulTab="rbd-details"> <ng-container ngbNavItem="details"> <a ngbNavLink i18n>Details</a> <ng-template ngbNavContent> <table class="table table-striped table-bordered"> <tbody> <tr> <td i18n class="bold w-25">Name</td> <td class="w-75">{{ selection.name }}</td> </tr> <tr> <td i18n class="bold">Pool</td> <td>{{ selection.pool_name }}</td> </tr> <tr> <td i18n class="bold">Data Pool</td> <td>{{ selection.data_pool | empty }}</td> </tr> <tr> <td i18n class="bold">Created</td> <td>{{ selection.timestamp | cdDate }}</td> </tr> <tr> <td i18n class="bold">Size</td> <td>{{ selection.size | dimlessBinary }}</td> </tr> <tr> <td i18n class="bold">Objects</td> <td>{{ selection.num_objs | dimless }}</td> </tr> <tr> <td i18n class="bold">Object size</td> <td>{{ selection.obj_size | dimlessBinary }}</td> </tr> <tr> <td i18n class="bold">Features</td> <td> <span *ngFor="let feature of selection.features_name"> <span class="badge badge-dark me-2">{{ feature }}</span> </span> </td> </tr> <tr> <td i18n class="bold">Provisioned</td> <td> <span *ngIf="selection.features_name?.indexOf('fast-diff') === -1"> <span class="form-text text-muted" [ngbTooltip]="usageNotAvailableTooltipTpl" placement="top" i18n>N/A</span> </span> <span *ngIf="selection.features_name?.indexOf('fast-diff') !== -1"> {{ selection.disk_usage | dimlessBinary }} </span> </td> </tr> <tr> <td i18n class="bold">Total provisioned</td> <td> <span *ngIf="selection.features_name?.indexOf('fast-diff') === -1"> <span class="form-text text-muted" [ngbTooltip]="usageNotAvailableTooltipTpl" placement="top" i18n>N/A</span> </span> <span *ngIf="selection.features_name?.indexOf('fast-diff') !== -1"> {{ selection.total_disk_usage | dimlessBinary }} </span> </td> </tr> <tr> <td i18n class="bold">Striping unit</td> <td>{{ selection.stripe_unit | dimlessBinary }}</td> </tr> <tr> <td i18n class="bold">Striping count</td> <td>{{ selection.stripe_count }}</td> </tr> <tr> <td i18n class="bold">Parent</td> <td> <span *ngIf="selection.parent">{{ selection.parent.pool_name }}<span *ngIf="selection.parent.pool_namespace">/{{ selection.parent.pool_namespace }}</span>/{{ selection.parent.image_name }}@{{ selection.parent.snap_name }}</span> <span *ngIf="!selection.parent">-</span> </td> </tr> <tr> <td i18n class="bold">Block name prefix</td> <td>{{ selection.block_name_prefix }}</td> </tr> <tr> <td i18n class="bold">Order</td> <td>{{ selection.order }}</td> </tr> <tr> <td i18n class="bold">Format Version</td> <td>{{ selection.image_format }}</td> </tr> </tbody> </table> </ng-template> </ng-container> <ng-container ngbNavItem="snapshots"> <a ngbNavLink i18n>Snapshots</a> <ng-template ngbNavContent> <cd-rbd-snapshot-list [snapshots]="selection.snapshots" [featuresName]="selection.features_name" [poolName]="selection.pool_name" [primary]="selection.primary" [namespace]="selection.namespace" [mirroring]="selection.mirror_mode" [rbdName]="selection.name"></cd-rbd-snapshot-list> </ng-template> </ng-container> <ng-container ngbNavItem="configuration"> <a ngbNavLink i18n>Configuration</a> <ng-template ngbNavContent> <cd-rbd-configuration-table [data]="selection['configuration']"></cd-rbd-configuration-table> </ng-template> </ng-container> <ng-container ngbNavItem="performance"> <a ngbNavLink i18n>Performance</a> <ng-template ngbNavContent> <cd-grafana i18n-title title="RBD details" [grafanaPath]="rbdDashboardUrl" [type]="'metrics'" uid="YhCYGcuZz" grafanaStyle="one"> </cd-grafana> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="nav"></div> </ng-container> <ng-container *ngIf="selection && selection.source === 'REMOVING'"> <cd-alert-panel type="warning" i18n>Information can not be displayed for RBD in status 'Removing'.</cd-alert-panel> </ng-container> <ng-template #poolConfigurationSourceTpl let-row="row" let-value="value"> <ng-container *ngIf="+value; else global"> <strong i18n i18n-ngbTooltip ngbTooltip="This setting overrides the global value">Image</strong> </ng-container> <ng-template #global> <span i18n i18n-ngbTooltip ngbTooltip="This is the global value. No value for this option has been set for this image.">Global</span> </ng-template> </ng-template>
6,689
35.162162
183
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-details/rbd-details.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdConfigurationListComponent } from '../rbd-configuration-list/rbd-configuration-list.component'; import { RbdSnapshotListComponent } from '../rbd-snapshot-list/rbd-snapshot-list.component'; import { RbdDetailsComponent } from './rbd-details.component'; describe('RbdDetailsComponent', () => { let component: RbdDetailsComponent; let fixture: ComponentFixture<RbdDetailsComponent>; configureTestBed({ declarations: [RbdDetailsComponent, RbdSnapshotListComponent, RbdConfigurationListComponent], imports: [SharedModule, NgbTooltipModule, RouterTestingModule, NgbNavModule] }); beforeEach(() => { fixture = TestBed.createComponent(RbdDetailsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,172
36.83871
107
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-details/rbd-details.component.ts
import { Component, Input, OnChanges, TemplateRef, ViewChild } from '@angular/core'; import { NgbNav } from '@ng-bootstrap/ng-bootstrap'; import { RbdFormModel } from '../rbd-form/rbd-form.model'; @Component({ selector: 'cd-rbd-details', templateUrl: './rbd-details.component.html', styleUrls: ['./rbd-details.component.scss'] }) export class RbdDetailsComponent implements OnChanges { @Input() selection: RbdFormModel; @Input() images: any; @ViewChild('poolConfigurationSourceTpl', { static: true }) poolConfigurationSourceTpl: TemplateRef<any>; @ViewChild(NgbNav, { static: true }) nav: NgbNav; rbdDashboardUrl: string; ngOnChanges() { if (this.selection) { this.rbdDashboardUrl = `rbd-details?var-Pool=${this.selection['pool_name']}&var-Image=${this.selection['name']}`; } } }
829
24.9375
119
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-form/rbd-feature.interface.ts
export interface RbdImageFeature { desc: string; allowEnable: boolean; allowDisable: boolean; requires?: string; interlockedWith?: string; key?: string; initDisabled?: boolean; }
193
18.4
34
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-form/rbd-form-clone-request.model.ts
import { RbdConfigurationEntry } from '~/app/shared/models/configuration'; export class RbdFormCloneRequestModel { child_pool_name: string; child_namespace: string; child_image_name: string; obj_size: number; features: Array<string> = []; stripe_unit: number; stripe_count: number; data_pool: string; configuration?: RbdConfigurationEntry[]; }
363
25
74
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-form/rbd-form-copy-request.model.ts
import { RbdConfigurationEntry } from '~/app/shared/models/configuration'; export class RbdFormCopyRequestModel { dest_pool_name: string; dest_namespace: string; dest_image_name: string; snapshot_name: string; obj_size: number; features: Array<string> = []; stripe_unit: number; stripe_count: number; data_pool: string; configuration: RbdConfigurationEntry[]; }
383
24.6
74
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-form/rbd-form-create-request.model.ts
import { RbdFormModel } from './rbd-form.model'; export class RbdFormCreateRequestModel extends RbdFormModel { features: Array<string> = []; }
146
23.5
61
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-form/rbd-form-edit-request.model.ts
import { RbdConfigurationEntry } from '~/app/shared/models/configuration'; export class RbdFormEditRequestModel { name: string; size: number; features: Array<string> = []; configuration: RbdConfigurationEntry[]; enable_mirror?: boolean; mirror_mode?: string; primary?: boolean; force?: boolean; schedule_interval: string; remove_scheduling? = false; }
374
22.4375
74
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-form/rbd-form-mode.enum.ts
export enum RbdFormMode { editing = 'editing', cloning = 'cloning', copying = 'copying' }
96
15.166667
25
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-form/rbd-form-response.model.ts
import { RbdFormModel } from './rbd-form.model'; import { RbdParentModel } from './rbd-parent.model'; export class RbdFormResponseModel extends RbdFormModel { features_name: string[]; parent: RbdParentModel; }
215
26
56
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-form/rbd-form.component.html
<div class="cd-col-form" *cdFormLoading="loading"> <form name="rbdForm" #formDir="ngForm" [formGroup]="rbdForm" novalidate> <div class="card"> <div i18n="form title" class="card-header">{{ action | titlecase }} {{ resource | upperFirst }}</div> <div class="card-body"> <!-- Parent --> <div class="form-group row" *ngIf="rbdForm.getValue('parent')"> <label i18n class="cd-col-form-label" for="name">{{ action | titlecase }} from</label> <div class="cd-col-form-input"> <input class="form-control" type="text" id="parent" name="parent" formControlName="parent"> <hr> </div> </div> <!-- Name --> <div class="form-group row"> <label class="cd-col-form-label required" for="name" i18n>Name</label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="Name..." id="name" name="name" formControlName="name" autofocus> <span class="invalid-feedback" *ngIf="rbdForm.showError('name', formDir, 'required')"> <ng-container i18n>This field is required.</ng-container> </span> <span class="invalid-feedback" *ngIf="rbdForm.showError('name', formDir, 'pattern')"> <ng-container i18n>'/' and '@' are not allowed.</ng-container> </span> </div> </div> <!-- Pool --> <div class="form-group row" (change)="onPoolChange($event.target.value)"> <label class="cd-col-form-label" [ngClass]="{'required': mode !== 'editing'}" for="pool" i18n>Pool</label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="Pool name..." id="pool" name="pool" formControlName="pool" *ngIf="mode === 'editing' || !poolPermission.read"> <select id="pool" name="pool" class="form-select" formControlName="pool" *ngIf="mode !== 'editing' && poolPermission.read" (change)="setPoolMirrorMode()"> <option *ngIf="pools === null" [ngValue]="null" i18n>Loading...</option> <option *ngIf="pools !== null && pools.length === 0" [ngValue]="null" i18n>-- No rbd pools available --</option> <option *ngIf="pools !== null && pools.length > 0" [ngValue]="null" i18n>-- Select a pool --</option> <option *ngFor="let pool of pools" [value]="pool.pool_name">{{ pool.pool_name }}</option> </select> <span *ngIf="rbdForm.showError('pool', formDir, 'required')" class="invalid-feedback" i18n>This field is required.</span> </div> </div> <!-- Namespace --> <div class="form-group row" *ngIf="mode !== 'editing' && rbdForm.getValue('pool') && namespaces === null"> <div class="cd-col-form-offset"> <i [ngClass]="[icons.spinner, icons.spin]"></i> </div> </div> <div class="form-group row" *ngIf="(mode === 'editing' && rbdForm.getValue('namespace')) || mode !== 'editing' && (namespaces && namespaces.length > 0 || !poolPermission.read)"> <label class="cd-col-form-label" for="pool"> Namespace </label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="Namespace..." id="namespace" name="namespace" formControlName="namespace" *ngIf="mode === 'editing' || !poolPermission.read"> <select id="namespace" name="namespace" class="form-select" formControlName="namespace" *ngIf="mode !== 'editing' && poolPermission.read"> <option *ngIf="pools === null" [ngValue]="null" i18n>Loading...</option> <option *ngIf="pools !== null && pools.length === 0" [ngValue]="null" i18n>-- No namespaces available --</option> <option *ngIf="pools !== null && pools.length > 0" [ngValue]="null" i18n>-- Select a namespace --</option> <option *ngFor="let namespace of namespaces" [value]="namespace">{{ namespace }}</option> </select> </div> </div> <!-- Use a dedicated pool --> <div class="form-group row"> <div class="cd-col-form-offset"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="useDataPool" name="useDataPool" formControlName="useDataPool" (change)="onUseDataPoolChange()"> <label class="custom-control-label" for="useDataPool" i18n>Use a dedicated data pool</label> <cd-helper *ngIf="allDataPools.length <= 1"> <span i18n>You need more than one pool with the rbd application label use to use a dedicated data pool.</span> </cd-helper> </div> </div> </div> <!-- Data Pool --> <div class="form-group row" *ngIf="rbdForm.getValue('useDataPool')"> <label class="cd-col-form-label" for="dataPool"> <span [ngClass]="{'required': mode !== 'editing'}" i18n>Data pool</span> <cd-helper i18n-html html="Dedicated pool that stores the object-data of the RBD."> </cd-helper> </label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="Data pool name..." id="dataPool" name="dataPool" formControlName="dataPool" *ngIf="mode === 'editing' || !poolPermission.read"> <select id="dataPool" name="dataPool" class="form-select" formControlName="dataPool" (change)="onDataPoolChange($event.target.value)" *ngIf="mode !== 'editing' && poolPermission.read"> <option *ngIf="dataPools === null" [ngValue]="null" i18n>Loading...</option> <option *ngIf="dataPools !== null && dataPools.length === 0" [ngValue]="null" i18n>-- No data pools available --</option> <option *ngIf="dataPools !== null && dataPools.length > 0" [ngValue]="null">-- Select a data pool -- </option> <option *ngFor="let dataPool of dataPools" [value]="dataPool.pool_name">{{ dataPool.pool_name }}</option> </select> <span class="invalid-feedback" *ngIf="rbdForm.showError('dataPool', formDir, 'required')" i18n>This field is required.</span> </div> </div> <!-- Size --> <div class="form-group row"> <label class="cd-col-form-label required" for="size" i18n>Size</label> <div class="cd-col-form-input"> <input id="size" name="size" class="form-control" type="text" formControlName="size" i18n-placeholder placeholder="e.g., 10GiB" defaultUnit="GiB" cdDimlessBinary> <span class="invalid-feedback" *ngIf="rbdForm.showError('size', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="rbdForm.showError('size', formDir, 'invalidSizeObject')" i18n>You have to increase the size.</span> </div> </div> <!-- Features --> <div class="form-group row" formGroupName="features"> <label i18n class="cd-col-form-label" for="features">Features</label> <div class="cd-col-form-input"> <div class="custom-control custom-checkbox" *ngFor="let feature of featuresList"> <input type="checkbox" class="custom-control-input" id="{{ feature.key }}" name="{{ feature.key }}" formControlName="{{ feature.key }}"> <label class="custom-control-label" for="{{ feature.key }}">{{ feature.desc }}</label> <cd-helper *ngIf="feature.helperHtml" html="{{ feature.helperHtml }}"> </cd-helper> </div> </div> </div> <!-- Mirroring --> <div class="form-group row"> <div class="cd-col-form-offset"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="mirroring" name="mirroring" (change)="setMirrorMode()" formControlName="mirroring"> <label class="custom-control-label" for="mirroring">Mirroring</label> <cd-helper *ngIf="mirroring === false && this.currentPoolName"> <span i18n>You need to enable a <b>mirror mode</b> in the selected pool. Please <a [routerLink]="['/block/mirroring', {outlets: {modal: ['edit', currentPoolName]}}]">click here to select a mode and enable it in this pool.</a></span> </cd-helper> </div> <div *ngIf="mirroring"> <div class="custom-control custom-radio ms-2" *ngFor="let option of mirroringOptions"> <input type="radio" class="form-check-input" [id]="option" [value]="option" name="mirroringMode" (change)="setExclusiveLock()" formControlName="mirroringMode" [attr.disabled]="(poolMirrorMode === 'pool' && option === 'snapshot') ? true : null"> <label class="form-check-label" [for]="option">{{ option | titlecase }}</label> <cd-helper *ngIf="poolMirrorMode === 'pool' && option === 'snapshot'"> <span i18n>You need to enable <b>image mirror mode</b> in the selected pool. Please <a [routerLink]="['/block/mirroring', {outlets: {modal: ['edit', currentPoolName]}}]">click here to select a mode and enable it in this pool.</a></span> </cd-helper> </div> </div> </div> </div> <div class="form-group row" *ngIf="rbdForm.getValue('mirroringMode') === 'snapshot' && mirroring"> <label class="cd-col-form-label" i18n>Schedule Interval <cd-helper i18n-html html="Create Mirror-Snapshots automatically on a periodic basis. The interval can be specified in days, hours, or minutes using d, h, m suffix respectively. To create mirror snapshots, you must import or create and have available peers to mirror"> </cd-helper></label> <div class="cd-col-form-input"> <input id="schedule" name="schedule" class="form-control" type="text" formControlName="schedule" i18n-placeholder placeholder="e.g., 12h or 1d or 10m" [attr.disabled]="(peerConfigured === false) ? true : null"> </div> </div> <!-- Advanced --> <div class="row"> <div class="col-sm-12"> <a class="float-end margin-right-md" (click)="advancedEnabled = true; false" *ngIf="!advancedEnabled" href="" i18n>Advanced...</a> </div> </div> <div [hidden]="!advancedEnabled"> <legend class="cd-header" i18n>Advanced</legend> <div class="col-md-12"> <h4 class="cd-header" i18n>Striping</h4> <!-- Object Size --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="size">Object size<cd-helper>Objects in the Ceph Storage Cluster have a maximum configurable size (e.g., 2MB, 4MB, etc.). The object size should be large enough to accommodate many stripe units, and should be a multiple of the stripe unit.</cd-helper></label> <div class="cd-col-form-input"> <select id="obj_size" name="obj_size" class="form-select" formControlName="obj_size"> <option *ngFor="let objectSize of objectSizes" [value]="objectSize">{{ objectSize }}</option> </select> </div> </div> <!-- stripingUnit --> <div class="form-group row"> <label class="cd-col-form-label" [ngClass]="{'required': rbdForm.getValue('stripingCount')}" for="stripingUnit" i18n>Stripe unit<cd-helper>Stripes have a configurable unit size (e.g., 64kb). The Ceph Client divides the data it will write to objects into equally sized stripe units, except for the last stripe unit. A stripe width, should be a fraction of the Object Size so that an object may contain many stripe units.</cd-helper></label> <div class="cd-col-form-input"> <select id="stripingUnit" name="stripingUnit" class="form-select" formControlName="stripingUnit"> <option i18n [ngValue]="null">-- Select stripe unit --</option> <option *ngFor="let objectSize of objectSizes" [value]="objectSize">{{ objectSize }}</option> </select> <span class="invalid-feedback" *ngIf="rbdForm.showError('stripingUnit', formDir, 'required')" i18n>This field is required because stripe count is defined!</span> <span class="invalid-feedback" *ngIf="rbdForm.showError('stripingUnit', formDir, 'invalidStripingUnit')" i18n>Stripe unit is greater than object size.</span> </div> </div> <!-- Stripe Count --> <div class="form-group row"> <label class="cd-col-form-label" [ngClass]="{'required': rbdForm.getValue('stripingUnit')}" for="stripingCount" i18n>Stripe count<cd-helper>The Ceph Client writes a sequence of stripe units over a series of objects determined by the stripe count. The series of objects is called an object set. After the Ceph Client writes to the last object in the object set, it returns to the first object in the object set.</cd-helper></label> <div class="cd-col-form-input"> <input id="stripingCount" name="stripingCount" formControlName="stripingCount" class="form-control" type="number"> <span class="invalid-feedback" *ngIf="rbdForm.showError('stripingCount', formDir, 'required')" i18n>This field is required because stripe unit is defined!</span> <span class="invalid-feedback" *ngIf="rbdForm.showError('stripingCount', formDir, 'min')" i18n>Stripe count must be greater than 0.</span> </div> </div> </div> <cd-rbd-configuration-form [form]="rbdForm" [initializeData]="initializeConfigData" (changes)="getDirtyConfigurationValues = $event"></cd-rbd-configuration-form> </div> </div> <div class="card-footer"> <cd-form-button-panel (submitActionEvent)="submit()" [form]="formDir" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)" wrappingClass="text-right"></cd-form-button-panel> </div> </div> </form> </div>
17,893
44.186869
348
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-form/rbd-form.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { ActivatedRoute, Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { NEVER, of } from 'rxjs'; import { delay } from 'rxjs/operators'; import { Pool } from '~/app/ceph/pool/pool'; import { PoolService } from '~/app/shared/api/pool.service'; import { RbdService } from '~/app/shared/api/rbd.service'; import { ImageSpec } from '~/app/shared/models/image-spec'; import { SharedModule } from '~/app/shared/shared.module'; import { ActivatedRouteStub } from '~/testing/activated-route-stub'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdConfigurationFormComponent } from '../rbd-configuration-form/rbd-configuration-form.component'; import { RbdImageFeature } from './rbd-feature.interface'; import { RbdFormMode } from './rbd-form-mode.enum'; import { RbdFormResponseModel } from './rbd-form-response.model'; import { RbdFormComponent } from './rbd-form.component'; describe('RbdFormComponent', () => { const urlPrefix = { create: '/block/rbd/create', edit: '/block/rbd/edit', clone: '/block/rbd/clone', copy: '/block/rbd/copy' }; let component: RbdFormComponent; let fixture: ComponentFixture<RbdFormComponent>; let activatedRoute: ActivatedRouteStub; const mock: { rbd: RbdFormResponseModel; pools: Pool[]; defaultFeatures: string[] } = { rbd: {} as RbdFormResponseModel, pools: [], defaultFeatures: [] }; const setRouterUrl = ( action: 'create' | 'edit' | 'clone' | 'copy', poolName?: string, imageName?: string ) => { component['routerUrl'] = [urlPrefix[action], poolName, imageName].filter((x) => x).join('/'); }; const queryNativeElement = (cssSelector: string) => fixture.debugElement.query(By.css(cssSelector)).nativeElement; configureTestBed({ imports: [ HttpClientTestingModule, ReactiveFormsModule, RouterTestingModule, ToastrModule.forRoot(), SharedModule ], declarations: [RbdFormComponent, RbdConfigurationFormComponent], providers: [ { provide: ActivatedRoute, useValue: new ActivatedRouteStub({ pool: 'foo', name: 'bar', snap: undefined }) }, RbdService ] }); beforeEach(() => { fixture = TestBed.createComponent(RbdFormComponent); component = fixture.componentInstance; activatedRoute = <ActivatedRouteStub>TestBed.inject(ActivatedRoute); component.loadingReady(); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('create/edit/clone/copy image', () => { let createAction: jasmine.Spy; let editAction: jasmine.Spy; let cloneAction: jasmine.Spy; let copyAction: jasmine.Spy; let rbdServiceGetSpy: jasmine.Spy; let routerNavigate: jasmine.Spy; const DELAY = 100; const getPool = ( pool_name: string, type: 'replicated' | 'erasure', flags_names: string, application_metadata: string[] ): Pool => ({ pool_name, flags_names, application_metadata, type } as Pool); beforeEach(() => { createAction = spyOn(component, 'createAction').and.returnValue(of(null)); editAction = spyOn(component, 'editAction'); editAction.and.returnValue(of(null)); cloneAction = spyOn(component, 'cloneAction').and.returnValue(of(null)); copyAction = spyOn(component, 'copyAction').and.returnValue(of(null)); spyOn(component, 'setResponse').and.stub(); routerNavigate = spyOn(TestBed.inject(Router), 'navigate').and.stub(); mock.pools = [ getPool('one', 'replicated', '', []), getPool('two', 'replicated', '', ['rbd']), getPool('three', 'replicated', '', ['rbd']), getPool('four', 'erasure', '', ['rbd']), getPool('four', 'erasure', 'ec_overwrites', ['rbd']) ]; spyOn(TestBed.inject(PoolService), 'list').and.callFake(() => of(mock.pools)); rbdServiceGetSpy = spyOn(TestBed.inject(RbdService), 'get'); mock.rbd = ({ pool_name: 'foo', pool_image: 'bar' } as any) as RbdFormResponseModel; rbdServiceGetSpy.and.returnValue(of(mock.rbd)); component.mode = undefined; }); it('should create image', () => { component.ngOnInit(); component.submit(); expect(createAction).toHaveBeenCalledTimes(1); expect(editAction).toHaveBeenCalledTimes(0); expect(cloneAction).toHaveBeenCalledTimes(0); expect(copyAction).toHaveBeenCalledTimes(0); expect(routerNavigate).toHaveBeenCalledTimes(1); }); it('should unsubscribe right after image data is received', () => { setRouterUrl('edit', 'foo', 'bar'); rbdServiceGetSpy.and.returnValue(of(mock.rbd)); editAction.and.returnValue(NEVER); expect(component['rbdImage'].observers.length).toEqual(0); component.ngOnInit(); // Subscribes to image once during init component.submit(); expect(component['rbdImage'].observers.length).toEqual(1); expect(createAction).toHaveBeenCalledTimes(0); expect(editAction).toHaveBeenCalledTimes(1); expect(cloneAction).toHaveBeenCalledTimes(0); expect(copyAction).toHaveBeenCalledTimes(0); expect(routerNavigate).toHaveBeenCalledTimes(0); }); it('should not edit image if no image data is received', fakeAsync(() => { setRouterUrl('edit', 'foo', 'bar'); rbdServiceGetSpy.and.returnValue(of(mock.rbd).pipe(delay(DELAY))); component.ngOnInit(); component.submit(); expect(createAction).toHaveBeenCalledTimes(0); expect(editAction).toHaveBeenCalledTimes(0); expect(cloneAction).toHaveBeenCalledTimes(0); expect(copyAction).toHaveBeenCalledTimes(0); expect(routerNavigate).toHaveBeenCalledTimes(0); tick(DELAY); })); describe('disable data pools', () => { beforeEach(() => { component.ngOnInit(); }); it('should be enabled with more than 1 pool', () => { component['handleExternalData'](mock); expect(component.allDataPools.length).toBe(3); expect(component.rbdForm.get('useDataPool').disabled).toBe(false); mock.pools.pop(); component['handleExternalData'](mock); expect(component.allDataPools.length).toBe(2); expect(component.rbdForm.get('useDataPool').disabled).toBe(false); }); it('should be disabled with 1 pool', () => { mock.pools = [mock.pools[0]]; component['handleExternalData'](mock); expect(component.rbdForm.get('useDataPool').disabled).toBe(true); }); // Reason for 2 tests - useDataPool is not re-enabled anywhere else it('should be disabled without any pool', () => { mock.pools = []; component['handleExternalData'](mock); expect(component.rbdForm.get('useDataPool').disabled).toBe(true); }); }); it('should edit image after image data is received', () => { setRouterUrl('edit', 'foo', 'bar'); component.ngOnInit(); component.submit(); expect(createAction).toHaveBeenCalledTimes(0); expect(editAction).toHaveBeenCalledTimes(1); expect(cloneAction).toHaveBeenCalledTimes(0); expect(copyAction).toHaveBeenCalledTimes(0); expect(routerNavigate).toHaveBeenCalledTimes(1); }); it('should not clone image if no image data is received', fakeAsync(() => { setRouterUrl('clone', 'foo', 'bar'); rbdServiceGetSpy.and.returnValue(of(mock.rbd).pipe(delay(DELAY))); component.ngOnInit(); component.submit(); expect(createAction).toHaveBeenCalledTimes(0); expect(editAction).toHaveBeenCalledTimes(0); expect(cloneAction).toHaveBeenCalledTimes(0); expect(copyAction).toHaveBeenCalledTimes(0); expect(routerNavigate).toHaveBeenCalledTimes(0); tick(DELAY); })); it('should clone image after image data is received', () => { setRouterUrl('clone', 'foo', 'bar'); component.ngOnInit(); component.submit(); expect(createAction).toHaveBeenCalledTimes(0); expect(editAction).toHaveBeenCalledTimes(0); expect(cloneAction).toHaveBeenCalledTimes(1); expect(copyAction).toHaveBeenCalledTimes(0); expect(routerNavigate).toHaveBeenCalledTimes(1); }); it('should not copy image if no image data is received', fakeAsync(() => { setRouterUrl('copy', 'foo', 'bar'); rbdServiceGetSpy.and.returnValue(of(mock.rbd).pipe(delay(DELAY))); component.ngOnInit(); component.submit(); expect(createAction).toHaveBeenCalledTimes(0); expect(editAction).toHaveBeenCalledTimes(0); expect(cloneAction).toHaveBeenCalledTimes(0); expect(copyAction).toHaveBeenCalledTimes(0); expect(routerNavigate).toHaveBeenCalledTimes(0); tick(DELAY); })); it('should copy image after image data is received', () => { setRouterUrl('copy', 'foo', 'bar'); component.ngOnInit(); component.submit(); expect(createAction).toHaveBeenCalledTimes(0); expect(editAction).toHaveBeenCalledTimes(0); expect(cloneAction).toHaveBeenCalledTimes(0); expect(copyAction).toHaveBeenCalledTimes(1); expect(routerNavigate).toHaveBeenCalledTimes(1); }); }); describe('should test decodeURIComponent of params', () => { let rbdService: RbdService; beforeEach(() => { rbdService = TestBed.inject(RbdService); component.mode = RbdFormMode.editing; fixture.detectChanges(); spyOn(rbdService, 'get').and.callThrough(); }); it('with namespace', () => { activatedRoute.setParams({ image_spec: 'foo%2Fbar%2Fbaz' }); expect(rbdService.get).toHaveBeenCalledWith(new ImageSpec('foo', 'bar', 'baz')); }); it('without snapName', () => { activatedRoute.setParams({ image_spec: 'foo%2Fbar', snap: undefined }); expect(rbdService.get).toHaveBeenCalledWith(new ImageSpec('foo', null, 'bar')); expect(component.snapName).toBeUndefined(); }); it('with snapName', () => { activatedRoute.setParams({ image_spec: 'foo%2Fbar', snap: 'baz%2Fbaz' }); expect(rbdService.get).toHaveBeenCalledWith(new ImageSpec('foo', null, 'bar')); expect(component.snapName).toBe('baz/baz'); }); }); describe('test image configuration component', () => { it('is visible', () => { fixture.detectChanges(); expect( fixture.debugElement.query(By.css('cd-rbd-configuration-form')).nativeElement.parentElement .hidden ).toBe(true); }); }); describe('tests for feature flags', () => { let deepFlatten: any, layering: any, exclusiveLock: any, objectMap: any, fastDiff: any; const defaultFeatures = [ // Supposed to be enabled by default 'deep-flatten', 'exclusive-lock', 'fast-diff', 'layering', 'object-map' ]; const allFeatureNames = [ 'deep-flatten', 'layering', 'exclusive-lock', 'object-map', 'fast-diff' ]; const setFeatures = (features: Record<string, RbdImageFeature>) => { component.features = features; component.featuresList = component.objToArray(features); component.createForm(); }; const getFeatureNativeElements = () => allFeatureNames.map((f) => queryNativeElement(`#${f}`)); it('should convert feature flags correctly in the constructor', () => { setFeatures({ one: { desc: 'one', allowEnable: true, allowDisable: true }, two: { desc: 'two', allowEnable: true, allowDisable: true }, three: { desc: 'three', allowEnable: true, allowDisable: true } }); expect(component.featuresList).toEqual([ { desc: 'one', key: 'one', allowDisable: true, allowEnable: true }, { desc: 'two', key: 'two', allowDisable: true, allowEnable: true }, { desc: 'three', key: 'three', allowDisable: true, allowEnable: true } ]); }); describe('test edit form flags', () => { const prepare = (pool: string, image: string, enabledFeatures: string[]): void => { const rbdService = TestBed.inject(RbdService); spyOn(rbdService, 'get').and.returnValue( of({ name: image, pool_name: pool, features_name: enabledFeatures }) ); spyOn(rbdService, 'defaultFeatures').and.returnValue(of(defaultFeatures)); setRouterUrl('edit', pool, image); fixture.detectChanges(); [deepFlatten, layering, exclusiveLock, objectMap, fastDiff] = getFeatureNativeElements(); }; it('should have the interlock feature for flags disabled, if one feature is not set', () => { prepare('rbd', 'foobar', ['deep-flatten', 'exclusive-lock', 'layering', 'object-map']); expect(objectMap.disabled).toBe(false); expect(fastDiff.disabled).toBe(false); expect(objectMap.checked).toBe(true); expect(fastDiff.checked).toBe(false); fastDiff.click(); fastDiff.click(); expect(objectMap.checked).toBe(true); // Shall not be disabled by `fast-diff`! }); it('should not disable object-map when fast-diff is unchecked', () => { prepare('rbd', 'foobar', ['deep-flatten', 'exclusive-lock', 'layering', 'object-map']); fastDiff.click(); fastDiff.click(); expect(objectMap.checked).toBe(true); // Shall not be disabled by `fast-diff`! }); it('should not enable fast-diff when object-map is checked', () => { prepare('rbd', 'foobar', ['deep-flatten', 'exclusive-lock', 'layering', 'object-map']); objectMap.click(); objectMap.click(); expect(fastDiff.checked).toBe(false); // Shall not be disabled by `fast-diff`! }); }); describe('test create form flags', () => { beforeEach(() => { const rbdService = TestBed.inject(RbdService); spyOn(rbdService, 'defaultFeatures').and.returnValue(of(defaultFeatures)); setRouterUrl('create'); fixture.detectChanges(); [deepFlatten, layering, exclusiveLock, objectMap, fastDiff] = getFeatureNativeElements(); }); it('should initialize the checkboxes correctly', () => { expect(deepFlatten.disabled).toBe(false); expect(layering.disabled).toBe(false); expect(exclusiveLock.disabled).toBe(false); expect(objectMap.disabled).toBe(false); expect(fastDiff.disabled).toBe(false); expect(deepFlatten.checked).toBe(true); expect(layering.checked).toBe(true); expect(exclusiveLock.checked).toBe(true); expect(objectMap.checked).toBe(true); expect(fastDiff.checked).toBe(true); }); it('should disable features if their requirements are not met (exclusive-lock)', () => { exclusiveLock.click(); // unchecks exclusive-lock expect(objectMap.disabled).toBe(true); expect(fastDiff.disabled).toBe(true); }); it('should disable features if their requirements are not met (object-map)', () => { objectMap.click(); // unchecks object-map expect(fastDiff.disabled).toBe(true); }); }); describe('test mirroring options', () => { beforeEach(() => { component.ngOnInit(); fixture.detectChanges(); const mirroring = fixture.debugElement.query(By.css('#mirroring')).nativeElement; mirroring.click(); fixture.detectChanges(); }); it('should verify two mirroring options are shown', () => { const journal = fixture.debugElement.query(By.css('#journal')).nativeElement; const snapshot = fixture.debugElement.query(By.css('#snapshot')).nativeElement; expect(journal).not.toBeNull(); expect(snapshot).not.toBeNull(); }); it('should verify only snapshot is disabled for pools that are in pool mirror mode', () => { component.poolMirrorMode = 'pool'; fixture.detectChanges(); const journal = fixture.debugElement.query(By.css('#journal')).nativeElement; const snapshot = fixture.debugElement.query(By.css('#snapshot')).nativeElement; expect(journal.disabled).toBe(false); expect(snapshot.disabled).toBe(true); }); it('should set and disable exclusive-lock only for the journal mode', () => { component.poolMirrorMode = 'pool'; component.mirroring = true; const journal = fixture.debugElement.query(By.css('#journal')).nativeElement; journal.click(); fixture.detectChanges(); const exclusiveLocks = fixture.debugElement.query(By.css('#exclusive-lock')).nativeElement; expect(exclusiveLocks.checked).toBe(true); expect(exclusiveLocks.disabled).toBe(true); }); it('should have journaling feature for journaling mirror mode on createRequest', () => { component.mirroring = true; fixture.detectChanges(); const journal = fixture.debugElement.query(By.css('#journal')).nativeElement; journal.click(); expect(journal.checked).toBe(true); const request = component.createRequest(); expect(request.features).toContain('journaling'); }); it('should have journaling feature for journaling mirror mode on editRequest', () => { component.mirroring = true; fixture.detectChanges(); const journal = fixture.debugElement.query(By.css('#journal')).nativeElement; journal.click(); expect(journal.checked).toBe(true); const request = component.editRequest(); expect(request.features).toContain('journaling'); }); }); }); });
18,003
36.045267
107
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-form/rbd-form.component.ts
import { Component, OnInit } from '@angular/core'; import { FormControl, ValidatorFn, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import _ from 'lodash'; import { forkJoin, Observable, ReplaySubject } from 'rxjs'; import { first, switchMap } from 'rxjs/operators'; import { Pool } from '~/app/ceph/pool/pool'; import { PoolService } from '~/app/shared/api/pool.service'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { RbdService } from '~/app/shared/api/rbd.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdForm } from '~/app/shared/forms/cd-form'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { RbdConfigurationEntry, RbdConfigurationSourceField } from '~/app/shared/models/configuration'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { ImageSpec } from '~/app/shared/models/image-spec'; import { Permission } from '~/app/shared/models/permissions'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { FormatterService } from '~/app/shared/services/formatter.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { RBDImageFormat, RbdModel } from '../rbd-list/rbd-model'; import { RbdImageFeature } from './rbd-feature.interface'; import { RbdFormCloneRequestModel } from './rbd-form-clone-request.model'; import { RbdFormCopyRequestModel } from './rbd-form-copy-request.model'; import { RbdFormCreateRequestModel } from './rbd-form-create-request.model'; import { RbdFormEditRequestModel } from './rbd-form-edit-request.model'; import { RbdFormMode } from './rbd-form-mode.enum'; import { RbdFormResponseModel } from './rbd-form-response.model'; class ExternalData { rbd: RbdFormResponseModel; defaultFeatures: string[]; pools: Pool[]; } @Component({ selector: 'cd-rbd-form', templateUrl: './rbd-form.component.html', styleUrls: ['./rbd-form.component.scss'] }) export class RbdFormComponent extends CdForm implements OnInit { poolPermission: Permission; rbdForm: CdFormGroup; getDirtyConfigurationValues: ( includeLocalField?: boolean, localField?: RbdConfigurationSourceField ) => RbdConfigurationEntry[]; namespaces: Array<string> = []; namespacesByPoolCache = {}; pools: Array<Pool> = null; allPools: Array<Pool> = null; dataPools: Array<Pool> = null; allDataPools: Array<Pool> = []; features: { [key: string]: RbdImageFeature }; featuresList: RbdImageFeature[] = []; initializeConfigData = new ReplaySubject<{ initialData: RbdConfigurationEntry[]; sourceType: RbdConfigurationSourceField; }>(1); pool: string; peerConfigured = false; advancedEnabled = false; public rbdFormMode = RbdFormMode; mode: RbdFormMode; response: RbdFormResponseModel; snapName: string; defaultObjectSize = '4 MiB'; mirroringOptions = ['journal', 'snapshot']; poolMirrorMode: string; mirroring = false; currentPoolName = ''; objectSizes: Array<string> = [ '4 KiB', '8 KiB', '16 KiB', '32 KiB', '64 KiB', '128 KiB', '256 KiB', '512 KiB', '1 MiB', '2 MiB', '4 MiB', '8 MiB', '16 MiB', '32 MiB' ]; defaultStripingUnit = '4 MiB'; defaultStripingCount = 1; action: string; resource: string; private rbdImage = new ReplaySubject(1); private routerUrl: string; icons = Icons; constructor( private authStorageService: AuthStorageService, private route: ActivatedRoute, private poolService: PoolService, private rbdService: RbdService, private formatter: FormatterService, private taskWrapper: TaskWrapperService, private dimlessBinaryPipe: DimlessBinaryPipe, public actionLabels: ActionLabelsI18n, private router: Router, private rbdMirroringService: RbdMirroringService ) { super(); this.routerUrl = this.router.url; this.poolPermission = this.authStorageService.getPermissions().pool; this.resource = $localize`RBD`; this.features = { 'deep-flatten': { desc: $localize`Deep flatten`, requires: null, allowEnable: false, allowDisable: true }, layering: { desc: $localize`Layering`, requires: null, allowEnable: false, allowDisable: false }, 'exclusive-lock': { desc: $localize`Exclusive lock`, requires: null, allowEnable: true, allowDisable: true }, 'object-map': { desc: $localize`Object map (requires exclusive-lock)`, requires: 'exclusive-lock', allowEnable: true, allowDisable: true, initDisabled: true }, 'fast-diff': { desc: $localize`Fast diff (interlocked with object-map)`, requires: 'object-map', allowEnable: true, allowDisable: true, interlockedWith: 'object-map', initDisabled: true } }; this.featuresList = this.objToArray(this.features); this.createForm(); } objToArray(obj: { [key: string]: any }) { return _.map(obj, (o, key) => Object.assign(o, { key: key })); } createForm() { this.rbdForm = new CdFormGroup( { parent: new FormControl(''), name: new FormControl('', { validators: [Validators.required, Validators.pattern(/^[^@/]+?$/)] }), pool: new FormControl(null, { validators: [Validators.required] }), namespace: new FormControl(null), useDataPool: new FormControl(false), dataPool: new FormControl(null), size: new FormControl(null, { updateOn: 'blur' }), obj_size: new FormControl(this.defaultObjectSize), features: new CdFormGroup( this.featuresList.reduce((acc: object, e) => { acc[e.key] = new FormControl({ value: false, disabled: !!e.initDisabled }); return acc; }, {}) ), mirroring: new FormControl(''), schedule: new FormControl('', { validators: [Validators.pattern(/^([0-9]+)d|([0-9]+)h|([0-9]+)m$/)] // check schedule interval to be in format - 1d or 1h or 1m }), mirroringMode: new FormControl(''), stripingUnit: new FormControl(this.defaultStripingUnit), stripingCount: new FormControl(this.defaultStripingCount, { updateOn: 'blur' }) }, this.validateRbdForm(this.formatter) ); } disableForEdit() { this.rbdForm.get('parent').disable(); this.rbdForm.get('pool').disable(); this.rbdForm.get('namespace').disable(); this.rbdForm.get('useDataPool').disable(); this.rbdForm.get('dataPool').disable(); this.rbdForm.get('obj_size').disable(); this.rbdForm.get('stripingUnit').disable(); this.rbdForm.get('stripingCount').disable(); /* RBD Image Format v1 */ this.rbdImage.subscribe((image: RbdModel) => { if (image.image_format === RBDImageFormat.V1) { this.rbdForm.get('deep-flatten').disable(); this.rbdForm.get('layering').disable(); this.rbdForm.get('exclusive-lock').disable(); } }); } disableForClone() { this.rbdForm.get('parent').disable(); this.rbdForm.get('size').disable(); } disableForCopy() { this.rbdForm.get('parent').disable(); this.rbdForm.get('size').disable(); } ngOnInit() { this.prepareFormForAction(); this.gatherNeededData().subscribe(this.handleExternalData.bind(this)); } setExclusiveLock() { if (this.mirroring && this.rbdForm.get('mirroringMode').value === 'journal') { this.rbdForm.get('exclusive-lock').setValue(true); this.rbdForm.get('exclusive-lock').disable(); } else { this.rbdForm.get('exclusive-lock').enable(); if (this.poolMirrorMode === 'pool') { this.rbdForm.get('mirroringMode').setValue(this.mirroringOptions[0]); } } } setMirrorMode() { this.mirroring = !this.mirroring; this.setExclusiveLock(); this.checkPeersConfigured(); } checkPeersConfigured(poolname?: string) { var Poolname = poolname ? poolname : this.rbdForm.get('pool').value; this.rbdMirroringService.getPeerForPool(Poolname).subscribe((resp: any) => { if (resp.length > 0) { this.peerConfigured = true; } }); } setPoolMirrorMode() { this.currentPoolName = this.mode === this.rbdFormMode.editing ? this.response?.pool_name : this.rbdForm.getValue('pool'); if (this.currentPoolName) { this.rbdMirroringService.refresh(); this.rbdMirroringService.subscribeSummary((data) => { const pool = data.content_data.pools.find((o: any) => o.name === this.currentPoolName); this.poolMirrorMode = pool.mirror_mode; if (pool.mirror_mode === 'disabled') { this.mirroring = false; this.rbdForm.get('mirroring').setValue(this.mirroring); this.rbdForm.get('mirroring').disable(); } }); } this.setExclusiveLock(); } private prepareFormForAction() { const url = this.routerUrl; if (url.startsWith('/block/rbd/edit')) { this.mode = this.rbdFormMode.editing; this.action = this.actionLabels.EDIT; this.disableForEdit(); } else if (url.startsWith('/block/rbd/clone')) { this.mode = this.rbdFormMode.cloning; this.disableForClone(); this.action = this.actionLabels.CLONE; } else if (url.startsWith('/block/rbd/copy')) { this.mode = this.rbdFormMode.copying; this.action = this.actionLabels.COPY; this.disableForCopy(); } else { this.action = this.actionLabels.CREATE; } _.each(this.features, (feature) => { this.rbdForm .get('features') .get(feature.key) .valueChanges.subscribe((value) => this.featureFormUpdate(feature.key, value)); }); } private gatherNeededData(): Observable<object> { const promises = {}; if (this.mode) { // Mode is not set for creation this.route.params.subscribe((params: { image_spec: string; snap: string }) => { const imageSpec = ImageSpec.fromString(decodeURIComponent(params.image_spec)); if (params.snap) { this.snapName = decodeURIComponent(params.snap); } promises['rbd'] = this.rbdService.get(imageSpec); this.checkPeersConfigured(imageSpec.poolName); }); } else { // New image promises['defaultFeatures'] = this.rbdService.defaultFeatures(); } if (this.mode !== this.rbdFormMode.editing && this.poolPermission.read) { promises['pools'] = this.poolService.list([ 'pool_name', 'type', 'flags_names', 'application_metadata' ]); } return forkJoin(promises); } private handleExternalData(data: ExternalData) { this.handlePoolData(data.pools); this.setPoolMirrorMode(); if (data.defaultFeatures) { // Fetched only during creation this.setFeatures(data.defaultFeatures); } if (data.rbd) { // Not fetched for creation const resp = data.rbd; this.setResponse(resp, this.snapName); this.rbdImage.next(resp); } this.loadingReady(); } private handlePoolData(data: Pool[]) { if (!data) { // Not fetched while editing return; } const pools: Pool[] = []; const dataPools = []; for (const pool of data) { if (this.rbdService.isRBDPool(pool)) { if (pool.type === 'replicated') { pools.push(pool); dataPools.push(pool); } else if (pool.type === 'erasure' && pool.flags_names.indexOf('ec_overwrites') !== -1) { dataPools.push(pool); } } } this.pools = pools; this.allPools = pools; this.dataPools = dataPools; this.allDataPools = dataPools; if (this.pools.length === 1) { const poolName = this.pools[0].pool_name; this.rbdForm.get('pool').setValue(poolName); this.onPoolChange(poolName); } if (this.allDataPools.length <= 1) { this.rbdForm.get('useDataPool').disable(); } } onPoolChange(selectedPoolName: string) { const dataPoolControl = this.rbdForm.get('dataPool'); if (dataPoolControl.value === selectedPoolName) { dataPoolControl.setValue(null); } this.dataPools = this.allDataPools ? this.allDataPools.filter((dataPool: any) => { return dataPool.pool_name !== selectedPoolName; }) : []; this.namespaces = null; if (selectedPoolName in this.namespacesByPoolCache) { this.namespaces = this.namespacesByPoolCache[selectedPoolName]; } else { this.rbdService.listNamespaces(selectedPoolName).subscribe((namespaces: any[]) => { namespaces = namespaces.map((namespace) => namespace.namespace); this.namespacesByPoolCache[selectedPoolName] = namespaces; this.namespaces = namespaces; }); } this.rbdForm.get('namespace').setValue(null); } onUseDataPoolChange() { if (!this.rbdForm.getValue('useDataPool')) { this.rbdForm.get('dataPool').setValue(null); this.onDataPoolChange(null); } } onDataPoolChange(selectedDataPoolName: string) { const newPools = this.allPools.filter((pool: Pool) => { return pool.pool_name !== selectedDataPoolName; }); if (this.rbdForm.getValue('pool') === selectedDataPoolName) { this.rbdForm.get('pool').setValue(null); } this.pools = newPools; } validateRbdForm(formatter: FormatterService): ValidatorFn { return (formGroup: CdFormGroup) => { // Data Pool const useDataPoolControl = formGroup.get('useDataPool'); const dataPoolControl = formGroup.get('dataPool'); let dataPoolControlErrors = null; if (useDataPoolControl.value && dataPoolControl.value == null) { dataPoolControlErrors = { required: true }; } dataPoolControl.setErrors(dataPoolControlErrors); // Size const sizeControl = formGroup.get('size'); const objectSizeControl = formGroup.get('obj_size'); const objectSizeInBytes = formatter.toBytes( objectSizeControl.value != null ? objectSizeControl.value : this.defaultObjectSize ); const stripingCountControl = formGroup.get('stripingCount'); const stripingCount = stripingCountControl.value != null ? stripingCountControl.value : this.defaultStripingCount; let sizeControlErrors = null; if (sizeControl.value === null) { sizeControlErrors = { required: true }; } else { const sizeInBytes = formatter.toBytes(sizeControl.value); if (stripingCount * objectSizeInBytes > sizeInBytes) { sizeControlErrors = { invalidSizeObject: true }; } } sizeControl.setErrors(sizeControlErrors); // Striping Unit const stripingUnitControl = formGroup.get('stripingUnit'); let stripingUnitControlErrors = null; if (stripingUnitControl.value === null && stripingCountControl.value !== null) { stripingUnitControlErrors = { required: true }; } else if (stripingUnitControl.value !== null) { const stripingUnitInBytes = formatter.toBytes(stripingUnitControl.value); if (stripingUnitInBytes > objectSizeInBytes) { stripingUnitControlErrors = { invalidStripingUnit: true }; } } stripingUnitControl.setErrors(stripingUnitControlErrors); // Striping Count let stripingCountControlErrors = null; if (stripingCountControl.value === null && stripingUnitControl.value !== null) { stripingCountControlErrors = { required: true }; } else if (stripingCount < 1) { stripingCountControlErrors = { min: true }; } stripingCountControl.setErrors(stripingCountControlErrors); return null; }; } deepBoxCheck(key: string, checked: boolean) { const childFeatures = this.getDependentChildFeatures(key); childFeatures.forEach((feature) => { const featureControl = this.rbdForm.get(feature.key); if (checked) { featureControl.enable({ emitEvent: false }); } else { featureControl.disable({ emitEvent: false }); featureControl.setValue(false, { emitEvent: false }); this.deepBoxCheck(feature.key, checked); } const featureFormGroup = this.rbdForm.get('features'); if (this.mode === this.rbdFormMode.editing && featureFormGroup.get(feature.key).enabled) { if (this.response.features_name.indexOf(feature.key) !== -1 && !feature.allowDisable) { featureFormGroup.get(feature.key).disable(); } else if ( this.response.features_name.indexOf(feature.key) === -1 && !feature.allowEnable ) { featureFormGroup.get(feature.key).disable(); } } }); } protected getDependentChildFeatures(featureKey: string) { return _.filter(this.features, (f) => f.requires === featureKey) || []; } interlockCheck(key: string, checked: boolean) { // Adds a compatibility layer for Ceph cluster where the feature interlock of features hasn't // been implemented yet. It disables the feature interlock for images which only have one of // both interlocked features (at the time of this writing: object-map and fast-diff) enabled. const feature = this.featuresList.find((f) => f.key === key); if (this.response) { // Ignore `create` page const hasInterlockedFeature = feature.interlockedWith != null; const dependentInterlockedFeature = this.featuresList.find( (f) => f.interlockedWith === feature.key ); const isOriginFeatureEnabled = !!this.response.features_name.find((e) => e === feature.key); // in this case: fast-diff if (hasInterlockedFeature) { const isLinkedEnabled = !!this.response.features_name.find( (e) => e === feature.interlockedWith ); // depends: object-map if (isOriginFeatureEnabled !== isLinkedEnabled) { return; // Ignore incompatible setting because it's from a previous cluster version } } else if (dependentInterlockedFeature) { const isOtherInterlockedFeatureEnabled = !!this.response.features_name.find( (e) => e === dependentInterlockedFeature.key ); if (isOtherInterlockedFeatureEnabled !== isOriginFeatureEnabled) { return; // Ignore incompatible setting because it's from a previous cluster version } } } if (checked) { _.filter(this.features, (f) => f.interlockedWith === key).forEach((f) => this.rbdForm.get(f.key).setValue(true, { emitEvent: false }) ); } else { if (feature.interlockedWith) { // Don't skip emitting the event here, as it prevents `fast-diff` from // becoming disabled when manually unchecked. This is because it // triggers an update on `object-map` and if `object-map` doesn't emit, // `fast-diff` will not be automatically disabled. this.rbdForm.get('features').get(feature.interlockedWith).setValue(false); } } } featureFormUpdate(key: string, checked: boolean) { if (checked) { const required = this.features[key].requires; if (required && !this.rbdForm.getValue(required)) { this.rbdForm.get(`features.${key}`).setValue(false); return; } } this.deepBoxCheck(key, checked); this.interlockCheck(key, checked); } setFeatures(features: Array<string>) { const featuresControl = this.rbdForm.get('features'); _.forIn(this.features, (feature) => { if (features.indexOf(feature.key) !== -1) { featuresControl.get(feature.key).setValue(true); } this.featureFormUpdate(feature.key, featuresControl.get(feature.key).value); }); } setResponse(response: RbdFormResponseModel, snapName: string) { this.response = response; const imageSpec = new ImageSpec( response.pool_name, response.namespace, response.name ).toString(); if (this.mode === this.rbdFormMode.cloning) { this.rbdForm.get('parent').setValue(`${imageSpec}@${snapName}`); } else if (this.mode === this.rbdFormMode.copying) { if (snapName) { this.rbdForm.get('parent').setValue(`${imageSpec}@${snapName}`); } else { this.rbdForm.get('parent').setValue(`${imageSpec}`); } } else if (response.parent) { const parent = response.parent; this.rbdForm .get('parent') .setValue(`${parent.pool_name}/${parent.image_name}@${parent.snap_name}`); } if (this.mode === this.rbdFormMode.editing) { this.rbdForm.get('name').setValue(response.name); if (response?.mirror_mode === 'snapshot' || response.features_name.includes('journaling')) { this.mirroring = true; this.rbdForm.get('mirroring').setValue(this.mirroring); this.rbdForm.get('mirroringMode').setValue(response?.mirror_mode); this.rbdForm.get('schedule').setValue(response?.schedule_interval); } else { this.mirroring = false; this.rbdForm.get('mirroring').setValue(this.mirroring); } this.setPoolMirrorMode(); } this.rbdForm.get('pool').setValue(response.pool_name); this.onPoolChange(response.pool_name); this.rbdForm.get('namespace').setValue(response.namespace); if (response.data_pool) { this.rbdForm.get('useDataPool').setValue(true); this.rbdForm.get('dataPool').setValue(response.data_pool); } this.rbdForm.get('size').setValue(this.dimlessBinaryPipe.transform(response.size)); this.rbdForm.get('obj_size').setValue(this.dimlessBinaryPipe.transform(response.obj_size)); this.setFeatures(response.features_name); this.rbdForm .get('stripingUnit') .setValue(this.dimlessBinaryPipe.transform(response.stripe_unit)); this.rbdForm.get('stripingCount').setValue(response.stripe_count); /* Configuration */ this.initializeConfigData.next({ initialData: this.response.configuration, sourceType: RbdConfigurationSourceField.image }); } createRequest() { const request = new RbdFormCreateRequestModel(); request.pool_name = this.rbdForm.getValue('pool'); request.namespace = this.rbdForm.getValue('namespace'); request.name = this.rbdForm.getValue('name'); request.schedule_interval = this.rbdForm.getValue('schedule'); request.size = this.formatter.toBytes(this.rbdForm.getValue('size')); if (this.poolMirrorMode === 'image') { request.mirror_mode = this.rbdForm.getValue('mirroringMode'); } this.addObjectSizeAndStripingToRequest(request); request.configuration = this.getDirtyConfigurationValues(); return request; } private addObjectSizeAndStripingToRequest( request: RbdFormCreateRequestModel | RbdFormCloneRequestModel | RbdFormCopyRequestModel ) { request.obj_size = this.formatter.toBytes(this.rbdForm.getValue('obj_size')); _.forIn(this.features, (feature) => { if (this.rbdForm.getValue(feature.key)) { request.features.push(feature.key); } }); if (this.mirroring && this.rbdForm.getValue('mirroringMode') === 'journal') { request.features.push('journaling'); } /* Striping */ request.stripe_unit = this.formatter.toBytes(this.rbdForm.getValue('stripingUnit')); request.stripe_count = this.rbdForm.getValue('stripingCount'); request.data_pool = this.rbdForm.getValue('dataPool'); } createAction(): Observable<any> { const request = this.createRequest(); return this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/create', { pool_name: request.pool_name, namespace: request.namespace, image_name: request.name, schedule_interval: request.schedule_interval, start_time: request.start_time }), call: this.rbdService.create(request) }); } editRequest() { const request = new RbdFormEditRequestModel(); request.name = this.rbdForm.getValue('name'); request.schedule_interval = this.rbdForm.getValue('schedule'); request.name = this.rbdForm.getValue('name'); request.size = this.formatter.toBytes(this.rbdForm.getValue('size')); _.forIn(this.features, (feature) => { if (this.rbdForm.getValue(feature.key)) { request.features.push(feature.key); } }); request.enable_mirror = this.rbdForm.getValue('mirroring'); if (request.enable_mirror) { if (this.rbdForm.getValue('mirroringMode') === 'journal') { request.features.push('journaling'); } if (this.poolMirrorMode === 'image') { request.mirror_mode = this.rbdForm.getValue('mirroringMode'); } } else { const index = request.features.indexOf('journaling', 0); if (index > -1) { request.features.splice(index, 1); } } request.configuration = this.getDirtyConfigurationValues(); return request; } cloneRequest(): RbdFormCloneRequestModel { const request = new RbdFormCloneRequestModel(); request.child_pool_name = this.rbdForm.getValue('pool'); request.child_namespace = this.rbdForm.getValue('namespace'); request.child_image_name = this.rbdForm.getValue('name'); this.addObjectSizeAndStripingToRequest(request); request.configuration = this.getDirtyConfigurationValues( true, RbdConfigurationSourceField.image ); return request; } editAction(): Observable<any> { const imageSpec = new ImageSpec( this.response.pool_name, this.response.namespace, this.response.name ); return this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/edit', { image_spec: imageSpec.toString() }), call: this.rbdService.update(imageSpec, this.editRequest()) }); } cloneAction(): Observable<any> { const request = this.cloneRequest(); const imageSpec = new ImageSpec( this.response.pool_name, this.response.namespace, this.response.name ); return this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/clone', { parent_image_spec: imageSpec.toString(), parent_snap_name: this.snapName, child_pool_name: request.child_pool_name, child_namespace: request.child_namespace, child_image_name: request.child_image_name }), call: this.rbdService.cloneSnapshot(imageSpec, this.snapName, request) }); } copyRequest(): RbdFormCopyRequestModel { const request = new RbdFormCopyRequestModel(); if (this.snapName) { request.snapshot_name = this.snapName; } request.dest_pool_name = this.rbdForm.getValue('pool'); request.dest_namespace = this.rbdForm.getValue('namespace'); request.dest_image_name = this.rbdForm.getValue('name'); this.addObjectSizeAndStripingToRequest(request); request.configuration = this.getDirtyConfigurationValues( true, RbdConfigurationSourceField.image ); return request; } copyAction(): Observable<any> { const request = this.copyRequest(); const imageSpec = new ImageSpec( this.response.pool_name, this.response.namespace, this.response.name ); return this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/copy', { src_image_spec: imageSpec.toString(), dest_pool_name: request.dest_pool_name, dest_namespace: request.dest_namespace, dest_image_name: request.dest_image_name }), call: this.rbdService.copy(imageSpec, request) }); } submit() { if (!this.mode) { this.rbdImage.next('create'); } this.rbdImage .pipe( first(), switchMap(() => { if (this.mode === this.rbdFormMode.editing) { return this.editAction(); } else if (this.mode === this.rbdFormMode.cloning) { return this.cloneAction(); } else if (this.mode === this.rbdFormMode.copying) { return this.copyAction(); } else { return this.createAction(); } }) ) .subscribe( () => undefined, () => this.rbdForm.setErrors({ cdSubmitButton: true }), () => this.router.navigate(['/block/rbd']) ); } }
28,594
33.660606
137
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-form/rbd-form.model.ts
import { RbdConfigurationEntry } from '~/app/shared/models/configuration'; export class RbdFormModel { name: string; pool_name: string; namespace: string; data_pool: string; size: number; /* Striping */ obj_size: number; stripe_unit: number; stripe_count: number; /* Configuration */ configuration: RbdConfigurationEntry[]; /* Deletion process */ source?: string; enable_mirror?: boolean; mirror_mode?: string; schedule_interval: string; start_time: string; }
500
17.555556
74
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-form/rbd-parent.model.ts
export class RbdParentModel { image_name: string; pool_name: string; pool_namespace: string; snap_name: string; }
122
16.571429
29
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-list/rbd-list.component.html
<cd-rbd-tabs></cd-rbd-tabs> <cd-table #table [data]="images" columnMode="flex" [columns]="columns" identifier="unique_id" [searchableObjects]="true" [serverSide]="true" [count]="count" forceIdentifier="true" selectionType="single" [hasDetails]="true" [status]="tableStatus" [maxLimit]="25" [autoReload]="-1" (fetchData)="taskListService.fetch($event)" (setExpandedRow)="setExpandedRow($event)" (updateSelection)="updateSelection($event)"> <cd-table-actions class="table-actions" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> <cd-rbd-details cdTableDetail [selection]="expandedRow"> </cd-rbd-details> </cd-table> <ng-template #scheduleStatus> <div i18n [innerHtml]="'Only available for RBD images with <strong>fast-diff</strong> enabled'"></div> </ng-template> <ng-template #provisionedNotAvailableTooltipTpl let-row="row"> <span *ngIf="row.disk_usage === null && !row.features_name.includes('fast-diff'); else provisioned" [ngbTooltip]="usageNotAvailableTooltipTpl" placement="top" i18n>N/A</span> <ng-template #provisioned i18n>{{row.disk_usage | dimlessBinary}}</ng-template> </ng-template> <ng-template #totalProvisionedNotAvailableTooltipTpl let-row="row"> <span *ngIf="row.total_disk_usage === null && !row.features_name.includes('fast-diff'); else totalProvisioned" [ngbTooltip]="usageNotAvailableTooltipTpl" placement="top" i18n>N/A</span> <ng-template #totalProvisioned i18n>{{row.total_disk_usage | dimlessBinary}}</ng-template> </ng-template> <ng-template #parentTpl let-value="value"> <span *ngIf="value">{{ value.pool_name }}<span *ngIf="value.pool_namespace">/{{ value.pool_namespace }}</span>/{{ value.image_name }}@{{ value.snap_name }}</span> <span *ngIf="!value">-</span> </ng-template> <ng-template #mirroringTpl let-value="value" let-row="row"> <span *ngIf="value.length === 3; else probb" class="badge badge-info">{{ value[0] }}</span>&nbsp; <span *ngIf="value.length === 3" class="badge badge-info">{{ value[1] }}</span>&nbsp; <span *ngIf="row.primary === true" class="badge badge-info" i18n>primary</span> <span *ngIf="row.primary === false" class="badge badge-info" i18n>secondary</span> <ng-template #probb> <span class="badge badge-info">{{ value }}</span> </ng-template> </ng-template> <ng-template #ScheduleTpl let-value="value" let-row="row"> <span *ngIf="value.length === 3" class="badge badge-info">{{ value[2] | cdDate }}</span> </ng-template> <ng-template #flattenTpl let-value> You are about to flatten <strong>{{ value.child }}</strong>. <br> <br> All blocks will be copied from parent <strong>{{ value.parent }}</strong> to child <strong>{{ value.child }}</strong>. </ng-template> <ng-template #deleteTpl let-hasSnapshots="hasSnapshots" let-snapshots="snapshots"> <div class="alert alert-warning" *ngIf="hasSnapshots" role="alert"> <span i18n>Deleting this image will also delete all its snapshots.</span> <br> <ng-container *ngIf="snapshots.length > 0"> <span i18n>The following snapshots are currently protected and will be removed:</span> <ul> <li *ngFor="let snapshot of snapshots">{{ snapshot }}</li> </ul> </ng-container> </div> </ng-template> <ng-template #removingStatTpl let-column="column" let-value="value" let-row="row"> <i [ngClass]="[icons.spinner, icons.spin]" *ngIf="row.cdExecuting"></i> <span [ngClass]="column?.customTemplateConfig?.valueClass"> {{ value }} </span> <span *ngIf="row.cdExecuting" [ngClass]="column?.customTemplateConfig?.executingClass ? column.customTemplateConfig.executingClass : 'text-muted italic'"> ({{ row.cdExecuting }}) </span> <i *ngIf="row.source && row.source === 'REMOVING'" i18n-title title="RBD in status 'Removing'" class="{{ icons.warning }} warn"></i> </ng-template> <ng-template #forcePromoteConfirmation> <cd-alert-panel type="warning">{{ errorMessage }}</cd-alert-panel> <div class="m-4" i18n> <strong> Do you want to force the operation? </strong> </div> </ng-template>
4,692
31.365517
125
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-list/rbd-list.component.spec.ts
import { HttpHeaders } from '@angular/common/http'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { BehaviorSubject, of } from 'rxjs'; import { RbdService } from '~/app/shared/api/rbd.service'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; import { ExecutingTask } from '~/app/shared/models/executing-task'; import { SummaryService } from '~/app/shared/services/summary.service'; import { TaskListService } from '~/app/shared/services/task-list.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, expectItemTasks, PermissionHelper } from '~/testing/unit-test-helper'; import { RbdConfigurationListComponent } from '../rbd-configuration-list/rbd-configuration-list.component'; import { RbdDetailsComponent } from '../rbd-details/rbd-details.component'; import { RbdSnapshotListComponent } from '../rbd-snapshot-list/rbd-snapshot-list.component'; import { RbdTabsComponent } from '../rbd-tabs/rbd-tabs.component'; import { RbdListComponent } from './rbd-list.component'; import { RbdModel } from './rbd-model'; describe('RbdListComponent', () => { let fixture: ComponentFixture<RbdListComponent>; let component: RbdListComponent; let summaryService: SummaryService; let rbdService: RbdService; let headers: HttpHeaders; const refresh = (data: any) => { summaryService['summaryDataSource'].next(data); }; configureTestBed({ imports: [ BrowserAnimationsModule, SharedModule, NgbNavModule, NgbTooltipModule, ToastrModule.forRoot(), RouterTestingModule, HttpClientTestingModule ], declarations: [ RbdListComponent, RbdDetailsComponent, RbdSnapshotListComponent, RbdConfigurationListComponent, RbdTabsComponent ], providers: [TaskListService] }); beforeEach(() => { fixture = TestBed.createComponent(RbdListComponent); component = fixture.componentInstance; summaryService = TestBed.inject(SummaryService); rbdService = TestBed.inject(RbdService); headers = new HttpHeaders().set('X-Total-Count', '10'); // this is needed because summaryService isn't being reset after each test. summaryService['summaryDataSource'] = new BehaviorSubject(null); summaryService['summaryData$'] = summaryService['summaryDataSource'].asObservable(); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('after ngOnInit', () => { beforeEach(() => { fixture.detectChanges(); spyOn(rbdService, 'list').and.callThrough(); }); it('should load images on init', () => { refresh({}); expect(rbdService.list).toHaveBeenCalled(); }); it('should not load images on init because no data', () => { refresh(undefined); expect(rbdService.list).not.toHaveBeenCalled(); }); it('should call error function on init when summary service fails', () => { spyOn(component.table, 'reset'); summaryService['summaryDataSource'].error(undefined); expect(component.table.reset).toHaveBeenCalled(); }); }); describe('handling of provisioned columns', () => { let rbdServiceListSpy: jasmine.Spy; const images = [ { name: 'img1', pool_name: 'rbd', features_name: ['layering', 'exclusive-lock'], disk_usage: null, total_disk_usage: null }, { name: 'img2', pool_name: 'rbd', features_name: ['layering', 'exclusive-lock', 'object-map', 'fast-diff'], disk_usage: 1024, total_disk_usage: 1024 } ]; beforeEach(() => { component.images = images; refresh({ executing_tasks: [], finished_tasks: [] }); rbdServiceListSpy = spyOn(rbdService, 'list'); }); it('should display N/A for Provisioned & Total Provisioned columns if disk usage is null', () => { rbdServiceListSpy.and.callFake(() => of([{ pool_name: 'rbd', value: images, headers: headers }]) ); fixture.detectChanges(); const spanWithoutFastDiff = fixture.debugElement.nativeElement.querySelectorAll( '.datatable-body-cell-label span' ); // check image with disk usage = null & fast-diff disabled expect(spanWithoutFastDiff[6].textContent).toBe('N/A'); images[0]['features_name'] = ['layering', 'exclusive-lock', 'object-map', 'fast-diff']; component.images = images; refresh({ executing_tasks: [], finished_tasks: [] }); rbdServiceListSpy.and.callFake(() => of([{ pool_name: 'rbd', value: images, headers: headers }]) ); fixture.detectChanges(); const spanWithFastDiff = fixture.debugElement.nativeElement.querySelectorAll( '.datatable-body-cell-label span' ); // check image with disk usage = null & fast-diff changed to enabled expect(spanWithFastDiff[6].textContent).toBe('-'); }); }); describe('handling of deletion', () => { beforeEach(() => { fixture.detectChanges(); }); it('should check if there are no snapshots', () => { component.selection.add({ id: '-1', name: 'rbd1', pool_name: 'rbd' }); expect(component.hasSnapshots()).toBeFalsy(); }); it('should check if there are snapshots', () => { component.selection.add({ id: '-1', name: 'rbd1', pool_name: 'rbd', snapshots: [{}, {}] }); expect(component.hasSnapshots()).toBeTruthy(); }); it('should get delete disable description', () => { component.selection.add({ id: '-1', name: 'rbd1', pool_name: 'rbd', snapshots: [ { children: [{}] } ] }); expect(component.getDeleteDisableDesc(component.selection)).toBe( 'This RBD has cloned snapshots. Please delete related RBDs before deleting this RBD.' ); }); it('should list all protected snapshots', () => { component.selection.add({ id: '-1', name: 'rbd1', pool_name: 'rbd', snapshots: [ { name: 'snap1', is_protected: false }, { name: 'snap2', is_protected: true } ] }); expect(component.listProtectedSnapshots()).toEqual(['snap2']); }); }); describe('handling of executing tasks', () => { let images: RbdModel[]; const addImage = (name: string) => { const model = new RbdModel(); model.id = '-1'; model.name = name; model.pool_name = 'rbd'; images.push(model); }; const addTask = (name: string, image_name: string) => { const task = new ExecutingTask(); task.name = name; switch (task.name) { case 'rbd/copy': task.metadata = { dest_pool_name: 'rbd', dest_namespace: null, dest_image_name: 'd' }; break; case 'rbd/clone': task.metadata = { child_pool_name: 'rbd', child_namespace: null, child_image_name: 'd' }; break; case 'rbd/create': task.metadata = { pool_name: 'rbd', namespace: null, image_name: image_name }; break; default: task.metadata = { image_spec: `rbd/${image_name}` }; break; } summaryService.addRunningTask(task); }; beforeEach(() => { images = []; addImage('a'); addImage('b'); addImage('c'); component.images = images; refresh({ executing_tasks: [], finished_tasks: [] }); spyOn(rbdService, 'list').and.callFake(() => of([{ pool_name: 'rbd', value: images, headers: headers }]) ); fixture.detectChanges(); }); it('should gets all images without tasks', () => { expect(component.images.length).toBe(3); expect(component.images.every((image: any) => !image.cdExecuting)).toBeTruthy(); }); it('should add a new image from a task', () => { addTask('rbd/create', 'd'); expect(component.images.length).toBe(4); expectItemTasks(component.images[0], undefined); expectItemTasks(component.images[1], undefined); expectItemTasks(component.images[2], undefined); expectItemTasks(component.images[3], 'Creating'); }); it('should show when a image is being cloned', () => { addTask('rbd/clone', 'd'); expect(component.images.length).toBe(4); expectItemTasks(component.images[0], undefined); expectItemTasks(component.images[1], undefined); expectItemTasks(component.images[2], undefined); expectItemTasks(component.images[3], 'Cloning'); }); it('should show when a image is being copied', () => { addTask('rbd/copy', 'd'); expect(component.images.length).toBe(4); expectItemTasks(component.images[0], undefined); expectItemTasks(component.images[1], undefined); expectItemTasks(component.images[2], undefined); expectItemTasks(component.images[3], 'Copying'); }); it('should show when an existing image is being modified', () => { addTask('rbd/edit', 'a'); expectItemTasks(component.images[0], 'Updating'); addTask('rbd/delete', 'b'); expectItemTasks(component.images[1], 'Deleting'); addTask('rbd/flatten', 'c'); expectItemTasks(component.images[2], 'Flattening'); expect(component.images.length).toBe(3); }); }); it('should test all TableActions combinations', () => { const permissionHelper: PermissionHelper = new PermissionHelper(component.permission); const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions( component.tableActions ); expect(tableActions).toEqual({ 'create,update,delete': { actions: [ 'Create', 'Edit', 'Copy', 'Flatten', 'Resync', 'Delete', 'Move to Trash', 'Remove Scheduling', 'Promote', 'Demote' ], primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,update': { actions: [ 'Create', 'Edit', 'Copy', 'Flatten', 'Resync', 'Remove Scheduling', 'Promote', 'Demote' ], primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,delete': { actions: ['Create', 'Copy', 'Delete', 'Move to Trash'], primary: { multiple: 'Create', executing: 'Copy', single: 'Copy', no: 'Create' } }, create: { actions: ['Create', 'Copy'], primary: { multiple: 'Create', executing: 'Copy', single: 'Copy', no: 'Create' } }, 'update,delete': { actions: [ 'Edit', 'Flatten', 'Resync', 'Delete', 'Move to Trash', 'Remove Scheduling', 'Promote', 'Demote' ], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, update: { actions: ['Edit', 'Flatten', 'Resync', 'Remove Scheduling', 'Promote', 'Demote'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, delete: { actions: ['Delete', 'Move to Trash'], primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); const getActionDisable = (name: string) => component.tableActions.find((o) => o.name === name).disable; const testActions = (selection: any, expected: { [action: string]: string | boolean }) => { expect(getActionDisable('Edit')(selection)).toBe(expected.edit || false); expect(getActionDisable('Delete')(selection)).toBe(expected.delete || false); expect(getActionDisable('Copy')(selection)).toBe(expected.copy || false); expect(getActionDisable('Flatten')(selection)).toBeTruthy(); expect(getActionDisable('Move to Trash')(selection)).toBe(expected.moveTrash || false); }; it('should test TableActions with valid/invalid image name', () => { component.selection.selected = [ { name: 'foobar', pool_name: 'rbd', snapshots: [] } ]; testActions(component.selection, {}); component.selection.selected = [ { name: 'foo/bar', pool_name: 'rbd', snapshots: [] } ]; const message = `This RBD image has an invalid name and can't be managed by ceph.`; const expected = { edit: message, delete: message, copy: message, moveTrash: message }; testActions(component.selection, expected); }); it('should disable edit, copy, flatten and move action if RBD is in status `Removing`', () => { component.selection.selected = [ { name: 'foobar', pool_name: 'rbd', snapshots: [], source: 'REMOVING' } ]; const message = `Action not possible for an RBD in status 'Removing'`; const expected = { edit: message, copy: message, moveTrash: message }; testActions(component.selection, expected); }); });
13,913
30.694761
107
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-list/rbd-list.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { Observable, Subscriber } from 'rxjs'; import { RbdService } from '~/app/shared/api/rbd.service'; import { ListWithDetails } from '~/app/shared/classes/list-with-details.class'; import { TableStatus } from '~/app/shared/classes/table-status'; import { ConfirmationModalComponent } from '~/app/shared/components/confirmation-modal/confirmation-modal.component'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { TableComponent } from '~/app/shared/datatable/table/table.component'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { ImageSpec } from '~/app/shared/models/image-spec'; import { Permission } from '~/app/shared/models/permissions'; import { Task } from '~/app/shared/models/task'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { DimlessPipe } from '~/app/shared/pipes/dimless.pipe'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { CdTableServerSideService } from '~/app/shared/services/cd-table-server-side.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { TaskListService } from '~/app/shared/services/task-list.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { URLBuilderService } from '~/app/shared/services/url-builder.service'; import { RbdFormEditRequestModel } from '../rbd-form/rbd-form-edit-request.model'; import { RbdParentModel } from '../rbd-form/rbd-parent.model'; import { RbdTrashMoveModalComponent } from '../rbd-trash-move-modal/rbd-trash-move-modal.component'; import { RBDImageFormat, RbdModel } from './rbd-model'; const BASE_URL = 'block/rbd'; @Component({ selector: 'cd-rbd-list', templateUrl: './rbd-list.component.html', styleUrls: ['./rbd-list.component.scss'], providers: [ TaskListService, { provide: URLBuilderService, useValue: new URLBuilderService(BASE_URL) } ] }) export class RbdListComponent extends ListWithDetails implements OnInit { @ViewChild(TableComponent, { static: true }) table: TableComponent; @ViewChild('usageTpl') usageTpl: TemplateRef<any>; @ViewChild('parentTpl', { static: true }) parentTpl: TemplateRef<any>; @ViewChild('nameTpl') nameTpl: TemplateRef<any>; @ViewChild('ScheduleTpl', { static: true }) ScheduleTpl: TemplateRef<any>; @ViewChild('mirroringTpl', { static: true }) mirroringTpl: TemplateRef<any>; @ViewChild('flattenTpl', { static: true }) flattenTpl: TemplateRef<any>; @ViewChild('deleteTpl', { static: true }) deleteTpl: TemplateRef<any>; @ViewChild('removingStatTpl', { static: true }) removingStatTpl: TemplateRef<any>; @ViewChild('provisionedNotAvailableTooltipTpl', { static: true }) provisionedNotAvailableTooltipTpl: TemplateRef<any>; @ViewChild('totalProvisionedNotAvailableTooltipTpl', { static: true }) totalProvisionedNotAvailableTooltipTpl: TemplateRef<any>; @ViewChild('forcePromoteConfirmation', { static: true }) forcePromoteConfirmation: TemplateRef<any>; permission: Permission; tableActions: CdTableAction[]; images: any; columns: CdTableColumn[]; retries: number; tableStatus = new TableStatus('light'); selection = new CdTableSelection(); icons = Icons; count = 0; private tableContext: CdTableFetchDataContext = null; modalRef: NgbModalRef; errorMessage: string; builders = { 'rbd/create': (metadata: object) => this.createRbdFromTask(metadata['pool_name'], metadata['namespace'], metadata['image_name']), 'rbd/delete': (metadata: object) => this.createRbdFromTaskImageSpec(metadata['image_spec']), 'rbd/clone': (metadata: object) => this.createRbdFromTask( metadata['child_pool_name'], metadata['child_namespace'], metadata['child_image_name'] ), 'rbd/copy': (metadata: object) => this.createRbdFromTask( metadata['dest_pool_name'], metadata['dest_namespace'], metadata['dest_image_name'] ) }; remove_scheduling: boolean; private createRbdFromTaskImageSpec(imageSpecStr: string): RbdModel { const imageSpec = ImageSpec.fromString(imageSpecStr); return this.createRbdFromTask(imageSpec.poolName, imageSpec.namespace, imageSpec.imageName); } private createRbdFromTask(pool: string, namespace: string, name: string): RbdModel { const model = new RbdModel(); model.id = '-1'; model.unique_id = '-1'; model.name = name; model.namespace = namespace; model.pool_name = pool; model.image_format = RBDImageFormat.V2; return model; } constructor( private authStorageService: AuthStorageService, private rbdService: RbdService, private dimlessBinaryPipe: DimlessBinaryPipe, private dimlessPipe: DimlessPipe, private modalService: ModalService, private taskWrapper: TaskWrapperService, public taskListService: TaskListService, private urlBuilder: URLBuilderService, public actionLabels: ActionLabelsI18n ) { super(); this.permission = this.authStorageService.getPermissions().rbdImage; const getImageUri = () => this.selection.first() && new ImageSpec( this.selection.first().pool_name, this.selection.first().namespace, this.selection.first().name ).toStringEncoded(); const addAction: CdTableAction = { permission: 'create', icon: Icons.add, routerLink: () => this.urlBuilder.getCreate(), canBePrimary: (selection: CdTableSelection) => !selection.hasSingleSelection, name: this.actionLabels.CREATE }; const editAction: CdTableAction = { permission: 'update', icon: Icons.edit, routerLink: () => this.urlBuilder.getEdit(getImageUri()), name: this.actionLabels.EDIT, disable: (selection: CdTableSelection) => this.getRemovingStatusDesc(selection) || this.getInvalidNameDisable(selection) }; const deleteAction: CdTableAction = { permission: 'delete', icon: Icons.destroy, click: () => this.deleteRbdModal(), name: this.actionLabels.DELETE, disable: (selection: CdTableSelection) => this.getDeleteDisableDesc(selection) }; const resyncAction: CdTableAction = { permission: 'update', icon: Icons.refresh, click: () => this.resyncRbdModal(), name: this.actionLabels.RESYNC, disable: (selection: CdTableSelection) => this.getResyncDisableDesc(selection) }; const copyAction: CdTableAction = { permission: 'create', canBePrimary: (selection: CdTableSelection) => selection.hasSingleSelection, disable: (selection: CdTableSelection) => this.getRemovingStatusDesc(selection) || this.getInvalidNameDisable(selection) || !!selection.first().cdExecuting, icon: Icons.copy, routerLink: () => `/block/rbd/copy/${getImageUri()}`, name: this.actionLabels.COPY }; const flattenAction: CdTableAction = { permission: 'update', disable: (selection: CdTableSelection) => this.getRemovingStatusDesc(selection) || this.getInvalidNameDisable(selection) || selection.first().cdExecuting || !selection.first().parent, icon: Icons.flatten, click: () => this.flattenRbdModal(), name: this.actionLabels.FLATTEN }; const moveAction: CdTableAction = { permission: 'delete', icon: Icons.trash, click: () => this.trashRbdModal(), name: this.actionLabels.TRASH, disable: (selection: CdTableSelection) => this.getRemovingStatusDesc(selection) || this.getInvalidNameDisable(selection) || selection.first().image_format === RBDImageFormat.V1 }; const removeSchedulingAction: CdTableAction = { permission: 'update', icon: Icons.edit, click: () => this.removeSchedulingModal(), name: this.actionLabels.REMOVE_SCHEDULING, disable: (selection: CdTableSelection) => this.getRemovingStatusDesc(selection) || this.getInvalidNameDisable(selection) || selection.first().schedule_info === undefined }; const promoteAction: CdTableAction = { permission: 'update', icon: Icons.edit, click: () => this.actionPrimary(true), name: this.actionLabels.PROMOTE, visible: () => this.selection.first() != null && !this.selection.first().primary, disable: () => this.selection.first().mirror_mode === 'Disabled' ? 'Mirroring needs to be enabled on the image to perform this action' : '' }; const demoteAction: CdTableAction = { permission: 'update', icon: Icons.edit, click: () => this.actionPrimary(false), name: this.actionLabels.DEMOTE, visible: () => this.selection.first() != null && this.selection.first().primary, disable: () => this.selection.first().mirror_mode === 'Disabled' ? 'Mirroring needs to be enabled on the image to perform this action' : '' }; this.tableActions = [ addAction, editAction, copyAction, flattenAction, resyncAction, deleteAction, moveAction, removeSchedulingAction, promoteAction, demoteAction ]; } ngOnInit() { this.columns = [ { name: $localize`Name`, prop: 'name', flexGrow: 2, cellTemplate: this.removingStatTpl }, { name: $localize`Pool`, prop: 'pool_name', flexGrow: 2 }, { name: $localize`Namespace`, prop: 'namespace', flexGrow: 2 }, { name: $localize`Size`, prop: 'size', flexGrow: 1, cellClass: 'text-right', sortable: false, pipe: this.dimlessBinaryPipe }, { name: $localize`Objects`, prop: 'num_objs', flexGrow: 1, cellClass: 'text-right', sortable: false, pipe: this.dimlessPipe }, { name: $localize`Object size`, prop: 'obj_size', flexGrow: 1, cellClass: 'text-right', sortable: false, pipe: this.dimlessBinaryPipe }, { name: $localize`Provisioned`, prop: 'disk_usage', cellClass: 'text-center', flexGrow: 1, pipe: this.dimlessBinaryPipe, sortable: false, cellTemplate: this.provisionedNotAvailableTooltipTpl }, { name: $localize`Total provisioned`, prop: 'total_disk_usage', cellClass: 'text-center', flexGrow: 1, pipe: this.dimlessBinaryPipe, sortable: false, cellTemplate: this.totalProvisionedNotAvailableTooltipTpl }, { name: $localize`Parent`, prop: 'parent', flexGrow: 2, sortable: false, cellTemplate: this.parentTpl }, { name: $localize`Mirroring`, prop: 'mirror_mode', flexGrow: 3, sortable: false, cellTemplate: this.mirroringTpl }, { name: $localize`Next Scheduled Snapshot`, prop: 'mirror_mode', flexGrow: 3, sortable: false, cellTemplate: this.ScheduleTpl } ]; const itemFilter = (entry: Record<string, any>, task: Task) => { let taskImageSpec: string; switch (task.name) { case 'rbd/copy': taskImageSpec = new ImageSpec( task.metadata['dest_pool_name'], task.metadata['dest_namespace'], task.metadata['dest_image_name'] ).toString(); break; case 'rbd/clone': taskImageSpec = new ImageSpec( task.metadata['child_pool_name'], task.metadata['child_namespace'], task.metadata['child_image_name'] ).toString(); break; case 'rbd/create': taskImageSpec = new ImageSpec( task.metadata['pool_name'], task.metadata['namespace'], task.metadata['image_name'] ).toString(); break; default: taskImageSpec = task.metadata['image_spec']; break; } return ( taskImageSpec === new ImageSpec(entry.pool_name, entry.namespace, entry.name).toString() ); }; const taskFilter = (task: Task) => { return [ 'rbd/clone', 'rbd/copy', 'rbd/create', 'rbd/delete', 'rbd/edit', 'rbd/flatten', 'rbd/trash/move' ].includes(task.name); }; this.taskListService.init( (context) => this.getRbdImages(context), (resp) => this.prepareResponse(resp), (images) => (this.images = images), () => this.onFetchError(), taskFilter, itemFilter, this.builders ); } onFetchError() { this.table.reset(); // Disable loading indicator. this.tableStatus = new TableStatus('danger'); } getRbdImages(context: CdTableFetchDataContext) { if (context !== null) { this.tableContext = context; } if (this.tableContext == null) { this.tableContext = new CdTableFetchDataContext(() => undefined); } return this.rbdService.list(this.tableContext?.toParams()); } prepareResponse(resp: any[]): any[] { let images: any[] = []; resp.forEach((pool) => { images = images.concat(pool.value); }); images.forEach((image) => { if (image.schedule_info !== undefined) { let scheduling: any[] = []; const scheduleStatus = 'scheduled'; let nextSnapshotDate = +new Date(image.schedule_info.schedule_time); const offset = new Date().getTimezoneOffset(); nextSnapshotDate = nextSnapshotDate + Math.abs(offset) * 60000; scheduling.push(image.mirror_mode, scheduleStatus, nextSnapshotDate); image.mirror_mode = scheduling; scheduling = []; } }); if (images.length > 0) { this.count = CdTableServerSideService.getCount(resp[0]); } else { this.count = 0; } return images; } updateSelection(selection: CdTableSelection) { this.selection = selection; } deleteRbdModal() { const poolName = this.selection.first().pool_name; const namespace = this.selection.first().namespace; const imageName = this.selection.first().name; const imageSpec = new ImageSpec(poolName, namespace, imageName); this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: 'RBD', itemNames: [imageSpec], bodyTemplate: this.deleteTpl, bodyContext: { hasSnapshots: this.hasSnapshots(), snapshots: this.listProtectedSnapshots() }, submitActionObservable: () => this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/delete', { image_spec: imageSpec.toString() }), call: this.rbdService.delete(imageSpec) }) }); } resyncRbdModal() { const poolName = this.selection.first().pool_name; const namespace = this.selection.first().namespace; const imageName = this.selection.first().name; const imageSpec = new ImageSpec(poolName, namespace, imageName); this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: 'RBD', itemNames: [imageSpec], actionDescription: 'resync', submitActionObservable: () => this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/edit', { image_spec: imageSpec.toString() }), call: this.rbdService.update(imageSpec, { resync: true }) }) }); } trashRbdModal() { const initialState = { poolName: this.selection.first().pool_name, namespace: this.selection.first().namespace, imageName: this.selection.first().name, hasSnapshots: this.hasSnapshots() }; this.modalRef = this.modalService.show(RbdTrashMoveModalComponent, initialState); } flattenRbd(imageSpec: ImageSpec) { this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('rbd/flatten', { image_spec: imageSpec.toString() }), call: this.rbdService.flatten(imageSpec) }) .subscribe({ complete: () => { this.modalRef.close(); } }); } flattenRbdModal() { const poolName = this.selection.first().pool_name; const namespace = this.selection.first().namespace; const imageName = this.selection.first().name; const parent: RbdParentModel = this.selection.first().parent; const parentImageSpec = new ImageSpec( parent.pool_name, parent.pool_namespace, parent.image_name ); const childImageSpec = new ImageSpec(poolName, namespace, imageName); const initialState = { titleText: 'RBD flatten', buttonText: 'Flatten', bodyTpl: this.flattenTpl, bodyData: { parent: `${parentImageSpec}@${parent.snap_name}`, child: childImageSpec.toString() }, onSubmit: () => { this.flattenRbd(childImageSpec); } }; this.modalRef = this.modalService.show(ConfirmationModalComponent, initialState); } editRequest() { const request = new RbdFormEditRequestModel(); request.remove_scheduling = !request.remove_scheduling; return request; } removeSchedulingModal() { const imageName = this.selection.first().name; const imageSpec = new ImageSpec( this.selection.first().pool_name, this.selection.first().namespace, this.selection.first().name ); this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { actionDescription: 'remove scheduling on', itemDescription: $localize`image`, itemNames: [`${imageName}`], submitActionObservable: () => new Observable((observer: Subscriber<any>) => { this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('rbd/edit', { image_spec: imageSpec.toString() }), call: this.rbdService.update(imageSpec, this.editRequest()) }) .subscribe({ error: (resp) => observer.error(resp), complete: () => { this.modalRef.close(); } }); }) }); } actionPrimary(primary: boolean) { const request = new RbdFormEditRequestModel(); request.primary = primary; request.features = null; const imageSpec = new ImageSpec( this.selection.first().pool_name, this.selection.first().namespace, this.selection.first().name ); this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('rbd/edit', { image_spec: imageSpec.toString() }), call: this.rbdService.update(imageSpec, request) }) .subscribe( () => {}, (error) => { error.preventDefault(); if (primary) { this.errorMessage = error.error['detail'].replace(/\[.*?\]\s*/, ''); request.force = true; this.modalRef = this.modalService.show(ConfirmationModalComponent, { titleText: $localize`Warning`, buttonText: $localize`Enforce`, warning: true, bodyTpl: this.forcePromoteConfirmation, onSubmit: () => { this.rbdService.update(imageSpec, request).subscribe( () => { this.modalRef.close(); }, () => { this.modalRef.close(); } ); } }); } } ); } hasSnapshots() { const snapshots = this.selection.first()['snapshots'] || []; return snapshots.length > 0; } hasClonedSnapshots(image: object) { const snapshots = image['snapshots'] || []; return snapshots.some((snap: object) => snap['children'] && snap['children'].length > 0); } listProtectedSnapshots() { const first = this.selection.first(); const snapshots = first['snapshots']; return snapshots.reduce((accumulator: string[], snap: object) => { if (snap['is_protected']) { accumulator.push(snap['name']); } return accumulator; }, []); } getDeleteDisableDesc(selection: CdTableSelection): string | boolean { const first = selection.first(); if (first && this.hasClonedSnapshots(first)) { return $localize`This RBD has cloned snapshots. Please delete related RBDs before deleting this RBD.`; } return this.getInvalidNameDisable(selection) || this.hasClonedSnapshots(selection.first()); } getResyncDisableDesc(selection: CdTableSelection): string | boolean { const first = selection.first(); if (first && this.imageIsPrimary(first)) { return $localize`Primary RBD images cannot be resynced`; } return this.getInvalidNameDisable(selection); } imageIsPrimary(image: object) { return image['primary']; } getInvalidNameDisable(selection: CdTableSelection): string | boolean { const first = selection.first(); if (first?.name?.match(/[@/]/)) { return $localize`This RBD image has an invalid name and can't be managed by ceph.`; } return !selection.first() || !selection.hasSingleSelection; } getRemovingStatusDesc(selection: CdTableSelection): string | boolean { const first = selection.first(); if (first?.source === 'REMOVING') { return $localize`Action not possible for an RBD in status 'Removing'`; } return false; } }
22,381
32.158519
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-list/rbd-model.ts
export class RbdModel { id: string; unique_id: string; name: string; pool_name: string; namespace: string; image_format: RBDImageFormat; cdExecuting: string; } export enum RBDImageFormat { V1 = 1, V2 = 2 }
226
13.1875
31
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-namespace-form/rbd-namespace-form-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container class="modal-title" i18n>Create Namespace</ng-container> <ng-container class="modal-content"> <form name="namespaceForm" #formDir="ngForm" [formGroup]="namespaceForm" novalidate> <div class="modal-body"> <!-- Pool --> <div class="form-group row"> <label class="cd-col-form-label required" for="pool" i18n>Pool</label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="Pool name..." id="pool" name="pool" formControlName="pool" *ngIf="!poolPermission.read"> <select id="pool" name="pool" class="form-select" formControlName="pool" *ngIf="poolPermission.read"> <option *ngIf="pools === null" [ngValue]="null" i18n>Loading...</option> <option *ngIf="pools !== null && pools.length === 0" [ngValue]="null" i18n>-- No rbd pools available --</option> <option *ngIf="pools !== null && pools.length > 0" [ngValue]="null" i18n>-- Select a pool --</option> <option *ngFor="let pool of pools" [value]="pool.pool_name">{{ pool.pool_name }}</option> </select> <span *ngIf="namespaceForm.showError('pool', formDir, 'required')" class="invalid-feedback" i18n>This field is required.</span> </div> </div> <!-- Name --> <div class="form-group row"> <label class="cd-col-form-label required" for="namespace" i18n>Name</label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="Namespace name..." id="namespace" name="namespace" formControlName="namespace" autofocus> <span class="invalid-feedback" *ngIf="namespaceForm.showError('namespace', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="namespaceForm.showError('namespace', formDir, 'namespaceExists')" i18n>Namespace already exists.</span> </div> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="submit()" [form]="namespaceForm" [submitText]="actionLabels.CREATE"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
3,012
36.6625
90
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-namespace-form/rbd-namespace-form-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { ComponentsModule } from '~/app/shared/components/components.module'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdNamespaceFormModalComponent } from './rbd-namespace-form-modal.component'; describe('RbdNamespaceFormModalComponent', () => { let component: RbdNamespaceFormModalComponent; let fixture: ComponentFixture<RbdNamespaceFormModalComponent>; configureTestBed({ imports: [ ReactiveFormsModule, ComponentsModule, HttpClientTestingModule, ToastrModule.forRoot(), RouterTestingModule ], declarations: [RbdNamespaceFormModalComponent], providers: [NgbActiveModal, AuthStorageService] }); beforeEach(() => { fixture = TestBed.createComponent(RbdNamespaceFormModalComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,377
33.45
86
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-namespace-form/rbd-namespace-form-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { AbstractControl, AsyncValidatorFn, FormControl, ValidationErrors, ValidatorFn } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { Subject } from 'rxjs'; import { Pool } from '~/app/ceph/pool/pool'; import { PoolService } from '~/app/shared/api/pool.service'; import { RbdService } from '~/app/shared/api/rbd.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { NotificationService } from '~/app/shared/services/notification.service'; @Component({ selector: 'cd-rbd-namespace-form-modal', templateUrl: './rbd-namespace-form-modal.component.html', styleUrls: ['./rbd-namespace-form-modal.component.scss'] }) export class RbdNamespaceFormModalComponent implements OnInit { poolPermission: Permission; pools: Array<Pool> = null; pool: string; namespace: string; namespaceForm: CdFormGroup; editing = false; public onSubmit: Subject<void>; constructor( public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private authStorageService: AuthStorageService, private notificationService: NotificationService, private poolService: PoolService, private rbdService: RbdService ) { this.poolPermission = this.authStorageService.getPermissions().pool; this.createForm(); } createForm() { this.namespaceForm = new CdFormGroup( { pool: new FormControl(''), namespace: new FormControl('') }, this.validator(), this.asyncValidator() ); } validator(): ValidatorFn { return (control: AbstractControl) => { const poolCtrl = control.get('pool'); const namespaceCtrl = control.get('namespace'); let poolErrors = null; if (!poolCtrl.value) { poolErrors = { required: true }; } poolCtrl.setErrors(poolErrors); let namespaceErrors = null; if (!namespaceCtrl.value) { namespaceErrors = { required: true }; } namespaceCtrl.setErrors(namespaceErrors); return null; }; } asyncValidator(): AsyncValidatorFn { return (control: AbstractControl): Promise<ValidationErrors | null> => { return new Promise((resolve) => { const poolCtrl = control.get('pool'); const namespaceCtrl = control.get('namespace'); this.rbdService.listNamespaces(poolCtrl.value).subscribe((namespaces: any[]) => { if (namespaces.some((ns) => ns.namespace === namespaceCtrl.value)) { const error = { namespaceExists: true }; namespaceCtrl.setErrors(error); resolve(error); } else { resolve(null); } }); }); }; } ngOnInit() { this.onSubmit = new Subject(); if (this.poolPermission.read) { this.poolService.list(['pool_name', 'type', 'application_metadata']).then((resp) => { const pools: Pool[] = []; for (const pool of resp) { if (this.rbdService.isRBDPool(pool) && pool.type === 'replicated') { pools.push(pool); } } this.pools = pools; if (this.pools.length === 1) { const poolName = this.pools[0]['pool_name']; this.namespaceForm.get('pool').setValue(poolName); } }); } } submit() { const pool = this.namespaceForm.getValue('pool'); const namespace = this.namespaceForm.getValue('namespace'); const finishedTask = new FinishedTask(); finishedTask.name = 'rbd/namespace/create'; finishedTask.metadata = { pool: pool, namespace: namespace }; this.rbdService .createNamespace(pool, namespace) .toPromise() .then(() => { this.notificationService.show( NotificationType.success, $localize`Created namespace '${pool}/${namespace}'` ); this.activeModal.close(); this.onSubmit.next(); }) .catch(() => { this.namespaceForm.setErrors({ cdSubmitButton: true }); }); } }
4,442
29.641379
91
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-namespace-list/rbd-namespace-list.component.html
<cd-rbd-tabs></cd-rbd-tabs> <cd-table [data]="namespaces" (fetchData)="refresh()" columnMode="flex" [columns]="columns" identifier="id" forceIdentifier="true" selectionType="single" (updateSelection)="updateSelection($event)"> <div class="table-actions btn-toolbar"> <cd-table-actions class="btn-group" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> </div> </cd-table>
572
29.157895
54
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-namespace-list/rbd-namespace-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { TaskListService } from '~/app/shared/services/task-list.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdTabsComponent } from '../rbd-tabs/rbd-tabs.component'; import { RbdNamespaceListComponent } from './rbd-namespace-list.component'; describe('RbdNamespaceListComponent', () => { let component: RbdNamespaceListComponent; let fixture: ComponentFixture<RbdNamespaceListComponent>; configureTestBed({ declarations: [RbdNamespaceListComponent, RbdTabsComponent], imports: [ BrowserAnimationsModule, SharedModule, HttpClientTestingModule, RouterTestingModule, ToastrModule.forRoot(), NgbNavModule ], providers: [TaskListService] }); beforeEach(() => { fixture = TestBed.createComponent(RbdNamespaceListComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,426
32.97619
79
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-namespace-list/rbd-namespace-list.component.ts
import { Component, OnInit } from '@angular/core'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { forkJoin, Observable } from 'rxjs'; import { PoolService } from '~/app/shared/api/pool.service'; import { RbdService } from '~/app/shared/api/rbd.service'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { TaskListService } from '~/app/shared/services/task-list.service'; import { RbdNamespaceFormModalComponent } from '../rbd-namespace-form/rbd-namespace-form-modal.component'; @Component({ selector: 'cd-rbd-namespace-list', templateUrl: './rbd-namespace-list.component.html', styleUrls: ['./rbd-namespace-list.component.scss'], providers: [TaskListService] }) export class RbdNamespaceListComponent implements OnInit { columns: CdTableColumn[]; namespaces: any; modalRef: NgbModalRef; permission: Permission; selection = new CdTableSelection(); tableActions: CdTableAction[]; constructor( private authStorageService: AuthStorageService, private rbdService: RbdService, private poolService: PoolService, private modalService: ModalService, private notificationService: NotificationService, public actionLabels: ActionLabelsI18n ) { this.permission = this.authStorageService.getPermissions().rbdImage; const createAction: CdTableAction = { permission: 'create', icon: Icons.add, click: () => this.createModal(), name: this.actionLabels.CREATE }; const deleteAction: CdTableAction = { permission: 'delete', icon: Icons.destroy, click: () => this.deleteModal(), name: this.actionLabels.DELETE, disable: () => this.getDeleteDisableDesc() }; this.tableActions = [createAction, deleteAction]; } ngOnInit() { this.columns = [ { name: $localize`Namespace`, prop: 'namespace', flexGrow: 1 }, { name: $localize`Pool`, prop: 'pool', flexGrow: 1 }, { name: $localize`Total images`, prop: 'num_images', flexGrow: 1 } ]; this.refresh(); } refresh() { this.poolService.list(['pool_name', 'type', 'application_metadata']).then((pools: any) => { pools = pools.filter( (pool: any) => this.rbdService.isRBDPool(pool) && pool.type === 'replicated' ); const promisses: Observable<any>[] = []; pools.forEach((pool: any) => { promisses.push(this.rbdService.listNamespaces(pool['pool_name'])); }); if (promisses.length > 0) { forkJoin(promisses).subscribe((data: Array<Array<string>>) => { const result: any[] = []; for (let i = 0; i < data.length; i++) { const namespaces = data[i]; const pool_name = pools[i]['pool_name']; namespaces.forEach((namespace: any) => { result.push({ id: `${pool_name}/${namespace.namespace}`, pool: pool_name, namespace: namespace.namespace, num_images: namespace.num_images }); }); } this.namespaces = result; }); } else { this.namespaces = []; } }); } updateSelection(selection: CdTableSelection) { this.selection = selection; } createModal() { this.modalRef = this.modalService.show(RbdNamespaceFormModalComponent); this.modalRef.componentInstance.onSubmit.subscribe(() => { this.refresh(); }); } deleteModal() { const pool = this.selection.first().pool; const namespace = this.selection.first().namespace; this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: 'Namespace', itemNames: [`${pool}/${namespace}`], submitAction: () => this.rbdService.deleteNamespace(pool, namespace).subscribe( () => { this.notificationService.show( NotificationType.success, $localize`Deleted namespace '${pool}/${namespace}'` ); this.modalRef.close(); this.refresh(); }, () => { this.modalRef.componentInstance.stopLoadingSpinner(); } ) }); } getDeleteDisableDesc(): string | boolean { const first = this.selection.first(); if (first?.num_images > 0) { return $localize`Namespace contains images`; } return !this.selection?.first(); } }
5,283
32.443038
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-performance/rbd-performance.component.html
<cd-rbd-tabs></cd-rbd-tabs> <cd-grafana i18n-title title="RBD overview" [grafanaPath]="'rbd-overview?'" [type]="'metrics'" uid="41FrpeUiz" grafanaStyle="two"> </cd-grafana>
234
22.5
43
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-performance/rbd-performance.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdTabsComponent } from '../rbd-tabs/rbd-tabs.component'; import { RbdPerformanceComponent } from './rbd-performance.component'; describe('RbdPerformanceComponent', () => { let component: RbdPerformanceComponent; let fixture: ComponentFixture<RbdPerformanceComponent>; configureTestBed({ imports: [HttpClientTestingModule, RouterTestingModule, SharedModule, NgbNavModule], declarations: [RbdPerformanceComponent, RbdTabsComponent] }); beforeEach(() => { fixture = TestBed.createComponent(RbdPerformanceComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,088
34.129032
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-performance/rbd-performance.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'cd-rbd-performance', templateUrl: './rbd-performance.component.html', styleUrls: ['./rbd-performance.component.scss'] }) export class RbdPerformanceComponent {}
235
25.222222
50
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-snapshot-form/rbd-snapshot-form-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container i18n="form title" class="modal-title">{{ action | titlecase }} {{ resource | upperFirst }}</ng-container> <ng-container class="modal-content"> <form name="snapshotForm" #formDir="ngForm" [formGroup]="snapshotForm" novalidate> <div class="modal-body"> <!-- Name --> <div class="form-group row"> <label class="cd-col-form-label required" for="snapshotName" i18n>Name</label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="Snapshot name..." id="snapshotName" name="snapshotName" [attr.disabled]="((mirroring === 'snapshot') ? true : null) && (snapshotForm.getValue('mirrorImageSnapshot') === true) ? true: null" formControlName="snapshotName" autofocus> <span class="invalid-feedback" *ngIf="snapshotForm.showError('snapshotName', formDir, 'required')" i18n>This field is required.</span> <span *ngIf="((mirroring === 'snapshot') ? true : null) && (snapshotForm.getValue('mirrorImageSnapshot') === true) ? true: null" i18n>Snapshot mode is enabled on image <b>{{ imageName }}</b>: snapshot names are auto generated</span> </div> </div> <ng-container *ngIf="(mirroring === 'snapshot') ? true : null"> <div class="form-group row" *ngIf="peerConfigured$ | async as peerConfigured"> <div class="cd-col-form-offset"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" formControlName="mirrorImageSnapshot" name="mirrorImageSnapshot" id="mirrorImageSnapshot" [attr.disabled]="!(peerConfigured.length > 0) ? true : null" (change)="onMirrorCheckBoxChange()"> <label for="mirrorImageSnapshot" class="custom-control-label" i18n>Mirror Image Snapshot</label> <cd-helper i18n *ngIf="!peerConfigured.length > 0">The peer must be registered to do this action.</cd-helper> </div> </div> </div> </ng-container> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="submit()" [form]="snapshotForm" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
2,896
45.725806
151
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-snapshot-form/rbd-snapshot-form-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { ComponentsModule } from '~/app/shared/components/components.module'; import { PipesModule } from '~/app/shared/pipes/pipes.module'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdSnapshotFormModalComponent } from './rbd-snapshot-form-modal.component'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { of } from 'rxjs'; describe('RbdSnapshotFormModalComponent', () => { let component: RbdSnapshotFormModalComponent; let fixture: ComponentFixture<RbdSnapshotFormModalComponent>; let rbdMirrorService: RbdMirroringService; configureTestBed({ imports: [ ReactiveFormsModule, ComponentsModule, PipesModule, HttpClientTestingModule, ToastrModule.forRoot(), RouterTestingModule ], declarations: [RbdSnapshotFormModalComponent], providers: [NgbActiveModal, AuthStorageService] }); beforeEach(() => { fixture = TestBed.createComponent(RbdSnapshotFormModalComponent); component = fixture.componentInstance; rbdMirrorService = TestBed.inject(RbdMirroringService); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should show "Create" text', () => { fixture.detectChanges(); const header = fixture.debugElement.nativeElement.querySelector('h4'); expect(header.textContent).toBe('Create RBD Snapshot'); const button = fixture.debugElement.nativeElement.querySelector('cd-submit-button'); expect(button.textContent).toBe('Create RBD Snapshot'); }); it('should show "Rename" text', () => { component.setEditing(); fixture.detectChanges(); const header = fixture.debugElement.nativeElement.querySelector('h4'); expect(header.textContent).toBe('Rename RBD Snapshot'); const button = fixture.debugElement.nativeElement.querySelector('cd-submit-button'); expect(button.textContent).toBe('Rename RBD Snapshot'); }); it('should enable the mirror image snapshot creation when peer is configured', () => { spyOn(rbdMirrorService, 'getPeerForPool').and.returnValue(of(['test_peer'])); component.mirroring = 'snapshot'; component.ngOnInit(); fixture.detectChanges(); const radio = fixture.debugElement.nativeElement.querySelector('#mirrorImageSnapshot'); expect(radio.disabled).toBe(false); }); it('should disable the mirror image snapshot creation when peer is not configured', () => { spyOn(rbdMirrorService, 'getPeerForPool').and.returnValue(of([])); component.mirroring = 'snapshot'; component.ngOnInit(); fixture.detectChanges(); const radio = fixture.debugElement.nativeElement.querySelector('#mirrorImageSnapshot'); expect(radio.disabled).toBe(true); }); });
3,189
36.529412
93
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-snapshot-form/rbd-snapshot-form-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { Observable, Subject } from 'rxjs'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { RbdService } from '~/app/shared/api/rbd.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { ImageSpec } from '~/app/shared/models/image-spec'; import { NotificationService } from '~/app/shared/services/notification.service'; import { TaskManagerService } from '~/app/shared/services/task-manager.service'; @Component({ selector: 'cd-rbd-snapshot-form-modal', templateUrl: './rbd-snapshot-form-modal.component.html', styleUrls: ['./rbd-snapshot-form-modal.component.scss'] }) export class RbdSnapshotFormModalComponent implements OnInit { poolName: string; namespace: string; imageName: string; snapName: string; mirroring: string; snapshotForm: CdFormGroup; editing = false; action: string; resource: string; public onSubmit: Subject<string> = new Subject(); peerConfigured$: Observable<any>; constructor( public activeModal: NgbActiveModal, private rbdService: RbdService, private taskManagerService: TaskManagerService, private notificationService: NotificationService, private actionLabels: ActionLabelsI18n, private rbdMirrorService: RbdMirroringService ) { this.action = this.actionLabels.CREATE; this.resource = $localize`RBD Snapshot`; this.createForm(); } createForm() { this.snapshotForm = new CdFormGroup({ snapshotName: new FormControl('', { validators: [Validators.required] }), mirrorImageSnapshot: new FormControl(false, {}) }); } ngOnInit(): void { this.peerConfigured$ = this.rbdMirrorService.getPeerForPool(this.poolName); } setSnapName(snapName: string) { this.snapName = snapName; this.snapshotForm.get('snapshotName').setValue(snapName); } onMirrorCheckBoxChange() { if (this.snapshotForm.getValue('mirrorImageSnapshot') === true) { this.snapshotForm.get('snapshotName').setValue(''); this.snapshotForm.get('snapshotName').clearValidators(); } else { this.snapshotForm.get('snapshotName').setValue(this.snapName); this.snapshotForm.get('snapshotName').setValidators([Validators.required]); } } /** * Set the 'editing' flag. If set to TRUE, the modal dialog is in * 'Edit' mode, otherwise in 'Create' mode. * @param {boolean} editing */ setEditing(editing: boolean = true) { this.editing = editing; this.action = this.editing ? this.actionLabels.RENAME : this.actionLabels.CREATE; } editAction() { const snapshotName = this.snapshotForm.getValue('snapshotName'); const imageSpec = new ImageSpec(this.poolName, this.namespace, this.imageName); const finishedTask = new FinishedTask(); finishedTask.name = 'rbd/snap/edit'; finishedTask.metadata = { image_spec: imageSpec.toString(), snapshot_name: snapshotName }; this.rbdService .renameSnapshot(imageSpec, this.snapName, snapshotName) .toPromise() .then(() => { this.taskManagerService.subscribe( finishedTask.name, finishedTask.metadata, (asyncFinishedTask: FinishedTask) => { this.notificationService.notifyTask(asyncFinishedTask); } ); this.activeModal.close(); this.onSubmit.next(this.snapName); }) .catch(() => { this.snapshotForm.setErrors({ cdSubmitButton: true }); }); } createAction() { const snapshotName = this.snapshotForm.getValue('snapshotName'); const mirrorImageSnapshot = this.snapshotForm.getValue('mirrorImageSnapshot'); const imageSpec = new ImageSpec(this.poolName, this.namespace, this.imageName); const finishedTask = new FinishedTask(); finishedTask.name = 'rbd/snap/create'; finishedTask.metadata = { image_spec: imageSpec.toString(), snapshot_name: snapshotName }; this.rbdService .createSnapshot(imageSpec, snapshotName, mirrorImageSnapshot) .toPromise() .then(() => { this.taskManagerService.subscribe( finishedTask.name, finishedTask.metadata, (asyncFinishedTask: FinishedTask) => { this.notificationService.notifyTask(asyncFinishedTask); } ); this.activeModal.close(); this.onSubmit.next(snapshotName); }) .catch(() => { this.snapshotForm.setErrors({ cdSubmitButton: true }); }); } submit() { if (this.editing) { this.editAction(); } else { this.createAction(); } } }
4,923
30.974026
85
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-snapshot-list/rbd-snapshot-actions.model.ts
import { RbdService } from '~/app/shared/api/rbd.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; export class RbdSnapshotActionsModel { create: CdTableAction; rename: CdTableAction; protect: CdTableAction; unprotect: CdTableAction; clone: CdTableAction; copy: CdTableAction; rollback: CdTableAction; deleteSnap: CdTableAction; ordering: CdTableAction[]; cloneFormatVersion = 1; constructor( actionLabels: ActionLabelsI18n, public featuresName: string[], rbdService: RbdService ) { rbdService.cloneFormatVersion().subscribe((version: number) => { this.cloneFormatVersion = version; }); this.create = { permission: 'create', icon: Icons.add, name: actionLabels.CREATE }; this.rename = { permission: 'update', icon: Icons.edit, name: actionLabels.RENAME, disable: (selection: CdTableSelection) => this.disableForMirrorSnapshot(selection) || !selection.hasSingleSelection }; this.protect = { permission: 'update', icon: Icons.lock, visible: (selection: CdTableSelection) => selection.hasSingleSelection && !selection.first().is_protected, name: actionLabels.PROTECT, disable: (selection: CdTableSelection) => this.disableForMirrorSnapshot(selection) }; this.unprotect = { permission: 'update', icon: Icons.unlock, visible: (selection: CdTableSelection) => selection.hasSingleSelection && selection.first().is_protected, name: actionLabels.UNPROTECT, disable: (selection: CdTableSelection) => this.disableForMirrorSnapshot(selection) }; this.clone = { permission: 'create', canBePrimary: (selection: CdTableSelection) => selection.hasSingleSelection, disable: (selection: CdTableSelection) => this.getCloneDisableDesc(selection, this.featuresName) || this.disableForMirrorSnapshot(selection), icon: Icons.clone, name: actionLabels.CLONE }; this.copy = { permission: 'create', canBePrimary: (selection: CdTableSelection) => selection.hasSingleSelection, disable: (selection: CdTableSelection) => !selection.hasSingleSelection || selection.first().cdExecuting || this.disableForMirrorSnapshot(selection), icon: Icons.copy, name: actionLabels.COPY }; this.rollback = { permission: 'update', icon: Icons.undo, name: actionLabels.ROLLBACK, disable: (selection: CdTableSelection) => this.disableForMirrorSnapshot(selection) || !selection.hasSingleSelection }; this.deleteSnap = { permission: 'delete', icon: Icons.destroy, disable: (selection: CdTableSelection) => { const first = selection.first(); return ( !selection.hasSingleSelection || first.cdExecuting || first.is_protected || this.disableForMirrorSnapshot(selection) ); }, name: actionLabels.DELETE }; this.ordering = [ this.create, this.rename, this.protect, this.unprotect, this.clone, this.copy, this.rollback, this.deleteSnap ]; } getCloneDisableDesc(selection: CdTableSelection, featuresName: string[]): boolean | string { if (selection.hasSingleSelection && !selection.first().cdExecuting) { if (!featuresName?.includes('layering')) { return $localize`Parent image must support Layering`; } if (this.cloneFormatVersion === 1 && !selection.first().is_protected) { return $localize`Snapshot must be protected in order to clone.`; } return false; } return true; } disableForMirrorSnapshot(selection: CdTableSelection) { return ( selection.hasSingleSelection && selection.first().mirror_mode === 'snapshot' && selection.first().name.includes('.mirror.') ); } }
4,170
30.126866
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-snapshot-list/rbd-snapshot-list.component.html
<cd-table [data]="data" columnMode="flex" selectionType="single" (updateSelection)="updateSelection($event)" [columns]="columns"> <cd-table-actions class="table-actions" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> </cd-table> <ng-template #rollbackTpl let-value> <ng-container i18n>You are about to rollback</ng-container> <strong> {{ value.snapName }}</strong>. </ng-template>
557
30
61
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-snapshot-list/rbd-snapshot-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbModalModule, NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { MockComponent } from 'ng-mocks'; import { ToastrModule } from 'ngx-toastr'; import { Subject, throwError as observableThrowError } from 'rxjs'; import { RbdService } from '~/app/shared/api/rbd.service'; import { ComponentsModule } from '~/app/shared/components/components.module'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { DataTableModule } from '~/app/shared/datatable/datatable.module'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { ExecutingTask } from '~/app/shared/models/executing-task'; import { Permissions } from '~/app/shared/models/permissions'; import { PipesModule } from '~/app/shared/pipes/pipes.module'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SummaryService } from '~/app/shared/services/summary.service'; import { TaskListService } from '~/app/shared/services/task-list.service'; import { configureTestBed, expectItemTasks, PermissionHelper } from '~/testing/unit-test-helper'; import { RbdSnapshotFormModalComponent } from '../rbd-snapshot-form/rbd-snapshot-form-modal.component'; import { RbdTabsComponent } from '../rbd-tabs/rbd-tabs.component'; import { RbdSnapshotActionsModel } from './rbd-snapshot-actions.model'; import { RbdSnapshotListComponent } from './rbd-snapshot-list.component'; import { RbdSnapshotModel } from './rbd-snapshot.model'; describe('RbdSnapshotListComponent', () => { let component: RbdSnapshotListComponent; let fixture: ComponentFixture<RbdSnapshotListComponent>; let summaryService: SummaryService; const fakeAuthStorageService = { isLoggedIn: () => { return true; }, getPermissions: () => { return new Permissions({ 'rbd-image': ['read', 'update', 'create', 'delete'] }); } }; configureTestBed( { declarations: [ RbdSnapshotListComponent, RbdTabsComponent, MockComponent(RbdSnapshotFormModalComponent) ], imports: [ BrowserAnimationsModule, ComponentsModule, DataTableModule, HttpClientTestingModule, PipesModule, RouterTestingModule, NgbNavModule, ToastrModule.forRoot(), NgbModalModule ], providers: [ { provide: AuthStorageService, useValue: fakeAuthStorageService }, TaskListService ] }, [CriticalConfirmationModalComponent] ); beforeEach(() => { fixture = TestBed.createComponent(RbdSnapshotListComponent); component = fixture.componentInstance; component.ngOnChanges(); summaryService = TestBed.inject(SummaryService); }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); describe('api delete request', () => { let called: boolean; let rbdService: RbdService; let notificationService: NotificationService; let authStorageService: AuthStorageService; beforeEach(() => { fixture.detectChanges(); const modalService = TestBed.inject(ModalService); const actionLabelsI18n = TestBed.inject(ActionLabelsI18n); called = false; rbdService = new RbdService(null, null); notificationService = new NotificationService(null, null, null); authStorageService = new AuthStorageService(); authStorageService.set('user', { 'rbd-image': ['create', 'read', 'update', 'delete'] }); component = new RbdSnapshotListComponent( authStorageService, modalService, null, null, rbdService, null, notificationService, null, null, actionLabelsI18n, null ); spyOn(rbdService, 'deleteSnapshot').and.returnValue(observableThrowError({ status: 500 })); spyOn(notificationService, 'notifyTask').and.stub(); }); it('should call stopLoadingSpinner if the request fails', fakeAsync(() => { component.updateSelection(new CdTableSelection([{ name: 'someName' }])); expect(called).toBe(false); component.deleteSnapshotModal(); spyOn(component.modalRef.componentInstance, 'stopLoadingSpinner').and.callFake(() => { called = true; }); component.modalRef.componentInstance.submitAction(); tick(500); expect(called).toBe(true); })); }); describe('handling of executing tasks', () => { let snapshots: RbdSnapshotModel[]; const addSnapshot = (name: string) => { const model = new RbdSnapshotModel(); model.id = 1; model.name = name; snapshots.push(model); }; const addTask = (task_name: string, snapshot_name: string) => { const task = new ExecutingTask(); task.name = task_name; task.metadata = { image_spec: 'rbd/foo', snapshot_name: snapshot_name }; summaryService.addRunningTask(task); }; const refresh = (data: any) => { summaryService['summaryDataSource'].next(data); }; beforeEach(() => { fixture.detectChanges(); snapshots = []; addSnapshot('a'); addSnapshot('b'); addSnapshot('c'); component.snapshots = snapshots; component.poolName = 'rbd'; component.rbdName = 'foo'; refresh({ executing_tasks: [], finished_tasks: [] }); component.ngOnChanges(); fixture.detectChanges(); }); it('should gets all snapshots without tasks', () => { expect(component.snapshots.length).toBe(3); expect(component.snapshots.every((image) => !image.cdExecuting)).toBeTruthy(); }); it('should add a new image from a task', () => { addTask('rbd/snap/create', 'd'); expect(component.snapshots.length).toBe(4); expectItemTasks(component.snapshots[0], undefined); expectItemTasks(component.snapshots[1], undefined); expectItemTasks(component.snapshots[2], undefined); expectItemTasks(component.snapshots[3], 'Creating'); }); it('should show when an existing image is being modified', () => { addTask('rbd/snap/edit', 'a'); addTask('rbd/snap/delete', 'b'); addTask('rbd/snap/rollback', 'c'); expect(component.snapshots.length).toBe(3); expectItemTasks(component.snapshots[0], 'Updating'); expectItemTasks(component.snapshots[1], 'Deleting'); expectItemTasks(component.snapshots[2], 'Rolling back'); }); }); describe('snapshot modal dialog', () => { beforeEach(() => { component.poolName = 'pool01'; component.rbdName = 'image01'; spyOn(TestBed.inject(ModalService), 'show').and.callFake(() => { const ref: any = {}; ref.componentInstance = new RbdSnapshotFormModalComponent( null, null, null, null, TestBed.inject(ActionLabelsI18n), null ); ref.componentInstance.onSubmit = new Subject(); return ref; }); }); it('should display old snapshot name', () => { component.selection.selected = [{ name: 'oldname' }]; component.openEditSnapshotModal(); expect(component.modalRef.componentInstance.snapName).toBe('oldname'); expect(component.modalRef.componentInstance.editing).toBeTruthy(); }); it('should display suggested snapshot name', () => { component.openCreateSnapshotModal(); expect(component.modalRef.componentInstance.snapName).toMatch( RegExp(`^${component.rbdName}_[\\d-]+T[\\d.:]+[\\+-][\\d:]+$`) ); }); }); it('should test all TableActions combinations', () => { component.ngOnInit(); const permissionHelper: PermissionHelper = new PermissionHelper(component.permission); const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions( component.tableActions ); expect(tableActions).toEqual({ 'create,update,delete': { actions: [ 'Create', 'Rename', 'Protect', 'Unprotect', 'Clone', 'Copy', 'Rollback', 'Delete' ], primary: { multiple: 'Create', executing: 'Rename', single: 'Rename', no: 'Create' } }, 'create,update': { actions: ['Create', 'Rename', 'Protect', 'Unprotect', 'Clone', 'Copy', 'Rollback'], primary: { multiple: 'Create', executing: 'Rename', single: 'Rename', no: 'Create' } }, 'create,delete': { actions: ['Create', 'Clone', 'Copy', 'Delete'], primary: { multiple: 'Create', executing: 'Clone', single: 'Clone', no: 'Create' } }, create: { actions: ['Create', 'Clone', 'Copy'], primary: { multiple: 'Create', executing: 'Clone', single: 'Clone', no: 'Create' } }, 'update,delete': { actions: ['Rename', 'Protect', 'Unprotect', 'Rollback', 'Delete'], primary: { multiple: 'Rename', executing: 'Rename', single: 'Rename', no: 'Rename' } }, update: { actions: ['Rename', 'Protect', 'Unprotect', 'Rollback'], primary: { multiple: 'Rename', executing: 'Rename', single: 'Rename', no: 'Rename' } }, delete: { actions: ['Delete'], primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); describe('clone button disable state', () => { let actions: RbdSnapshotActionsModel; beforeEach(() => { fixture.detectChanges(); const rbdService = TestBed.inject(RbdService); const actionLabelsI18n = TestBed.inject(ActionLabelsI18n); actions = new RbdSnapshotActionsModel(actionLabelsI18n, [], rbdService); }); it('should be disabled with version 1 and protected false', () => { const selection = new CdTableSelection([{ name: 'someName', is_protected: false }]); const disableDesc = actions.getCloneDisableDesc(selection, ['layering']); expect(disableDesc).toBe('Snapshot must be protected in order to clone.'); }); it.each([ [1, true], [2, true], [2, false] ])('should be enabled with version %d and protected %s', (version, is_protected) => { actions.cloneFormatVersion = version; const selection = new CdTableSelection([{ name: 'someName', is_protected: is_protected }]); const disableDesc = actions.getCloneDisableDesc(selection, ['layering']); expect(disableDesc).toBe(false); }); }); });
11,277
35.736156
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-snapshot-list/rbd-snapshot-list.component.ts
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnChanges, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import moment from 'moment'; import { of } from 'rxjs'; import { RbdService } from '~/app/shared/api/rbd.service'; import { CdHelperClass } from '~/app/shared/classes/cd-helper.class'; import { ConfirmationModalComponent } from '~/app/shared/components/confirmation-modal/confirmation-modal.component'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { ExecutingTask } from '~/app/shared/models/executing-task'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { ImageSpec } from '~/app/shared/models/image-spec'; import { Permission } from '~/app/shared/models/permissions'; import { Task } from '~/app/shared/models/task'; import { CdDatePipe } from '~/app/shared/pipes/cd-date.pipe'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SummaryService } from '~/app/shared/services/summary.service'; import { TaskListService } from '~/app/shared/services/task-list.service'; import { TaskManagerService } from '~/app/shared/services/task-manager.service'; import { RbdSnapshotFormModalComponent } from '../rbd-snapshot-form/rbd-snapshot-form-modal.component'; import { RbdSnapshotActionsModel } from './rbd-snapshot-actions.model'; import { RbdSnapshotModel } from './rbd-snapshot.model'; @Component({ selector: 'cd-rbd-snapshot-list', templateUrl: './rbd-snapshot-list.component.html', styleUrls: ['./rbd-snapshot-list.component.scss'], providers: [TaskListService], changeDetection: ChangeDetectionStrategy.OnPush }) export class RbdSnapshotListComponent implements OnInit, OnChanges { @Input() snapshots: RbdSnapshotModel[] = []; @Input() featuresName: string[]; @Input() poolName: string; @Input() namespace: string; @Input() mirroring: string; @Input() primary: boolean; @Input() rbdName: string; @ViewChild('nameTpl') nameTpl: TemplateRef<any>; @ViewChild('rollbackTpl', { static: true }) rollbackTpl: TemplateRef<any>; permission: Permission; selection = new CdTableSelection(); tableActions: CdTableAction[]; rbdTableActions: RbdSnapshotActionsModel; imageSpec: ImageSpec; data: RbdSnapshotModel[]; columns: CdTableColumn[]; modalRef: NgbModalRef; builders = { 'rbd/snap/create': (metadata: any) => { const model = new RbdSnapshotModel(); model.name = metadata['snapshot_name']; return model; } }; constructor( private authStorageService: AuthStorageService, private modalService: ModalService, private dimlessBinaryPipe: DimlessBinaryPipe, private cdDatePipe: CdDatePipe, private rbdService: RbdService, private taskManagerService: TaskManagerService, private notificationService: NotificationService, private summaryService: SummaryService, private taskListService: TaskListService, private actionLabels: ActionLabelsI18n, private cdr: ChangeDetectorRef ) { this.permission = this.authStorageService.getPermissions().rbdImage; } ngOnInit() { this.columns = [ { name: $localize`Name`, prop: 'name', cellTransformation: CellTemplate.executing, flexGrow: 2 }, { name: $localize`Size`, prop: 'size', flexGrow: 1, cellClass: 'text-right', pipe: this.dimlessBinaryPipe }, { name: $localize`Provisioned`, prop: 'disk_usage', flexGrow: 1, cellClass: 'text-right', pipe: this.dimlessBinaryPipe }, { name: $localize`State`, prop: 'is_protected', flexGrow: 1, cellTransformation: CellTemplate.badge, customTemplateConfig: { map: { true: { value: $localize`PROTECTED`, class: 'badge-success' }, false: { value: $localize`UNPROTECTED`, class: 'badge-info' } } } }, { name: $localize`Created`, prop: 'timestamp', flexGrow: 1, pipe: this.cdDatePipe } ]; this.imageSpec = new ImageSpec(this.poolName, this.namespace, this.rbdName); this.rbdTableActions = new RbdSnapshotActionsModel( this.actionLabels, this.featuresName, this.rbdService ); this.rbdTableActions.create.click = () => this.openCreateSnapshotModal(); this.rbdTableActions.rename.click = () => this.openEditSnapshotModal(); this.rbdTableActions.protect.click = () => this.toggleProtection(); this.rbdTableActions.unprotect.click = () => this.toggleProtection(); const getImageUri = () => this.selection.first() && `${this.imageSpec.toStringEncoded()}/${encodeURIComponent(this.selection.first().name)}`; this.rbdTableActions.clone.routerLink = () => `/block/rbd/clone/${getImageUri()}`; this.rbdTableActions.copy.routerLink = () => `/block/rbd/copy/${getImageUri()}`; this.rbdTableActions.rollback.click = () => this.rollbackModal(); this.rbdTableActions.deleteSnap.click = () => this.deleteSnapshotModal(); this.tableActions = this.rbdTableActions.ordering; const itemFilter = (entry: any, task: Task) => { return entry.name === task.metadata['snapshot_name']; }; const taskFilter = (task: Task) => { return ( ['rbd/snap/create', 'rbd/snap/delete', 'rbd/snap/edit', 'rbd/snap/rollback'].includes( task.name ) && this.imageSpec.toString() === task.metadata['image_spec'] ); }; this.taskListService.init( () => of(this.snapshots), null, (items) => { const hasChanges = CdHelperClass.updateChanged(this, { data: items }); if (hasChanges) { this.cdr.detectChanges(); this.data = [...this.data]; } }, () => { const hasChanges = CdHelperClass.updateChanged(this, { data: this.snapshots }); if (hasChanges) { this.cdr.detectChanges(); this.data = [...this.data]; } }, taskFilter, itemFilter, this.builders ); } ngOnChanges() { if (this.columns) { this.imageSpec = new ImageSpec(this.poolName, this.namespace, this.rbdName); if (this.rbdTableActions) { this.rbdTableActions.featuresName = this.featuresName; } this.taskListService.fetch(); } } private openSnapshotModal(taskName: string, snapName: string = null) { const modalVariables = { mirroring: this.mirroring }; this.modalRef = this.modalService.show(RbdSnapshotFormModalComponent, modalVariables); this.modalRef.componentInstance.poolName = this.poolName; this.modalRef.componentInstance.imageName = this.rbdName; this.modalRef.componentInstance.namespace = this.namespace; if (snapName) { this.modalRef.componentInstance.setEditing(); } else { // Auto-create a name for the snapshot: <image_name>_<timestamp_ISO_8601> // https://en.wikipedia.org/wiki/ISO_8601 snapName = `${this.rbdName}_${moment().toISOString(true)}`; } this.modalRef.componentInstance.setSnapName(snapName); this.modalRef.componentInstance.onSubmit.subscribe((snapshotName: string) => { const executingTask = new ExecutingTask(); executingTask.name = taskName; executingTask.metadata = { image_spec: this.imageSpec.toString(), snapshot_name: snapshotName }; this.summaryService.addRunningTask(executingTask); }); } openCreateSnapshotModal() { this.openSnapshotModal('rbd/snap/create'); } openEditSnapshotModal() { this.openSnapshotModal('rbd/snap/edit', this.selection.first().name); } toggleProtection() { const snapshotName = this.selection.first().name; const isProtected = this.selection.first().is_protected; const finishedTask = new FinishedTask(); finishedTask.name = 'rbd/snap/edit'; const imageSpec = new ImageSpec(this.poolName, this.namespace, this.rbdName); finishedTask.metadata = { image_spec: imageSpec.toString(), snapshot_name: snapshotName }; this.rbdService .protectSnapshot(imageSpec, snapshotName, !isProtected) .toPromise() .then(() => { const executingTask = new ExecutingTask(); executingTask.name = finishedTask.name; executingTask.metadata = finishedTask.metadata; this.summaryService.addRunningTask(executingTask); this.taskManagerService.subscribe( finishedTask.name, finishedTask.metadata, (asyncFinishedTask: FinishedTask) => { this.notificationService.notifyTask(asyncFinishedTask); } ); }); } _asyncTask(task: string, taskName: string, snapshotName: string) { const finishedTask = new FinishedTask(); finishedTask.name = taskName; finishedTask.metadata = { image_spec: new ImageSpec(this.poolName, this.namespace, this.rbdName).toString(), snapshot_name: snapshotName }; const imageSpec = new ImageSpec(this.poolName, this.namespace, this.rbdName); this.rbdService[task](imageSpec, snapshotName) .toPromise() .then(() => { const executingTask = new ExecutingTask(); executingTask.name = finishedTask.name; executingTask.metadata = finishedTask.metadata; this.summaryService.addRunningTask(executingTask); this.modalRef.close(); this.taskManagerService.subscribe( executingTask.name, executingTask.metadata, (asyncFinishedTask: FinishedTask) => { this.notificationService.notifyTask(asyncFinishedTask); } ); }) .catch(() => { this.modalRef.componentInstance.stopLoadingSpinner(); }); } rollbackModal() { const snapshotName = this.selection.selected[0].name; const imageSpec = new ImageSpec(this.poolName, this.namespace, this.rbdName).toString(); const initialState = { titleText: $localize`RBD snapshot rollback`, buttonText: $localize`Rollback`, bodyTpl: this.rollbackTpl, bodyData: { snapName: `${imageSpec}@${snapshotName}` }, onSubmit: () => { this._asyncTask('rollbackSnapshot', 'rbd/snap/rollback', snapshotName); } }; this.modalRef = this.modalService.show(ConfirmationModalComponent, initialState); } deleteSnapshotModal() { const snapshotName = this.selection.selected[0].name; this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: $localize`RBD snapshot`, itemNames: [snapshotName], submitAction: () => this._asyncTask('deleteSnapshot', 'rbd/snap/delete', snapshotName) }); } updateSelection(selection: CdTableSelection) { this.selection = selection; } }
11,651
33.371681
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-snapshot-list/rbd-snapshot.model.ts
export class RbdSnapshotModel { id: number; name: string; size: number; timestamp: string; is_protected: boolean; cdExecuting: string; }
150
14.1
31
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-tabs/rbd-tabs.component.html
<ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link" routerLink="/block/rbd" routerLinkActive="active" ariaCurrentWhenActive="page" [routerLinkActiveOptions]="{exact: true}" i18n>Images</a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/block/rbd/namespaces" routerLinkActive="active" ariaCurrentWhenActive="page" [routerLinkActiveOptions]="{exact: true}" i18n>Namespaces</a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/block/rbd/trash" routerLinkActive="active" ariaCurrentWhenActive="page" [routerLinkActiveOptions]="{exact: true}" i18n>Trash</a> </li> <li class="nav-item" *ngIf="grafanaPermission.read"> <a class="nav-link" routerLink="/block/rbd/performance" routerLinkActive="active" ariaCurrentWhenActive="page" [routerLinkActiveOptions]="{exact: true}" i18n>Overall Performance</a> </li> </ul>
1,026
27.527778
48
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-tabs/rbd-tabs.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdTabsComponent } from './rbd-tabs.component'; describe('RbdTabsComponent', () => { let component: RbdTabsComponent; let fixture: ComponentFixture<RbdTabsComponent>; configureTestBed({ imports: [RouterTestingModule, NgbNavModule], declarations: [RbdTabsComponent] }); beforeEach(() => { fixture = TestBed.createComponent(RbdTabsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
784
27.035714
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-tabs/rbd-tabs.component.ts
import { Component } from '@angular/core'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; @Component({ selector: 'cd-rbd-tabs', templateUrl: './rbd-tabs.component.html', styleUrls: ['./rbd-tabs.component.scss'] }) export class RbdTabsComponent { grafanaPermission: Permission; url: string; constructor(private authStorageService: AuthStorageService) { this.grafanaPermission = this.authStorageService.getPermissions().grafana; } }
548
27.894737
80
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-trash-list/rbd-trash-list.component.html
<cd-rbd-tabs></cd-rbd-tabs> <cd-table [data]="images" columnMode="flex" [columns]="columns" identifier="id" forceIdentifier="true" selectionType="single" [status]="tableStatus" [autoReload]="-1" (fetchData)="taskListService.fetch()" (updateSelection)="updateSelection($event)"> <div class="table-actions btn-toolbar"> <cd-table-actions class="btn-group" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> <button class="btn btn-light" type="button" (click)="purgeModal()" [disabled]="disablePurgeBtn" *ngIf="permission.delete"> <i [ngClass]="[icons.destroy]" aria-hidden="true"></i> <ng-container i18n>Purge Trash</ng-container> </button> </div> </cd-table> <ng-template #expiresTpl let-row="row" let-value="value"> <ng-container *ngIf="row.cdIsExpired" i18n>Expired at</ng-container> <ng-container *ngIf="!row.cdIsExpired" i18n>Protected until</ng-container> {{ value | cdDate }} </ng-template> <ng-template #deleteTpl let-expiresAt="expiresAt" let-isExpired="isExpired"> <p class="text-danger" *ngIf="!isExpired"> <strong> <ng-container i18n>This image is protected until {{ expiresAt | cdDate }}.</ng-container> </strong> </p> </ng-template>
1,558
28.415094
95
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-trash-list/rbd-trash-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import moment from 'moment'; import { NgxPipeFunctionModule } from 'ngx-pipe-function'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { RbdService } from '~/app/shared/api/rbd.service'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { ExecutingTask } from '~/app/shared/models/executing-task'; import { Summary } from '~/app/shared/models/summary.model'; import { SummaryService } from '~/app/shared/services/summary.service'; import { TaskListService } from '~/app/shared/services/task-list.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, expectItemTasks } from '~/testing/unit-test-helper'; import { RbdTabsComponent } from '../rbd-tabs/rbd-tabs.component'; import { RbdTrashListComponent } from './rbd-trash-list.component'; describe('RbdTrashListComponent', () => { let component: RbdTrashListComponent; let fixture: ComponentFixture<RbdTrashListComponent>; let summaryService: SummaryService; let rbdService: RbdService; configureTestBed({ declarations: [RbdTrashListComponent, RbdTabsComponent], imports: [ BrowserAnimationsModule, HttpClientTestingModule, RouterTestingModule, SharedModule, NgbNavModule, NgxPipeFunctionModule, ToastrModule.forRoot() ], providers: [TaskListService] }); beforeEach(() => { fixture = TestBed.createComponent(RbdTrashListComponent); component = fixture.componentInstance; summaryService = TestBed.inject(SummaryService); rbdService = TestBed.inject(RbdService); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should load trash images when summary is trigged', () => { spyOn(rbdService, 'listTrash').and.callThrough(); summaryService['summaryDataSource'].next(new Summary()); expect(rbdService.listTrash).toHaveBeenCalled(); }); it('should call updateSelection', () => { expect(component.selection.hasSelection).toBeFalsy(); component.updateSelection(new CdTableSelection(['foo'])); expect(component.selection.hasSelection).toBeTruthy(); }); describe('handling of executing tasks', () => { let images: any[]; const addImage = (id: string) => { images.push({ id: id, pool_name: 'pl' }); }; const addTask = (name: string, image_id: string) => { const task = new ExecutingTask(); task.name = name; task.metadata = { image_id_spec: `pl/${image_id}` }; summaryService.addRunningTask(task); }; beforeEach(() => { images = []; addImage('1'); addImage('2'); component.images = images; summaryService['summaryDataSource'].next(new Summary()); spyOn(rbdService, 'listTrash').and.callFake(() => of([{ pool_name: 'rbd', status: 1, value: images }]) ); fixture.detectChanges(); }); it('should gets all images without tasks', () => { expect(component.images.length).toBe(2); expect( component.images.every((image: Record<string, any>) => !image.cdExecuting) ).toBeTruthy(); }); it('should show when an existing image is being modified', () => { addTask('rbd/trash/remove', '1'); addTask('rbd/trash/restore', '2'); expect(component.images.length).toBe(2); expectItemTasks(component.images[0], 'Deleting'); expectItemTasks(component.images[1], 'Restoring'); }); }); describe('display purge button', () => { let images: any[]; const addImage = (id: string) => { images.push({ id: id, pool_name: 'pl', deferment_end_time: moment() }); }; beforeEach(() => { summaryService['summaryDataSource'].next(new Summary()); spyOn(rbdService, 'listTrash').and.callFake(() => { of([{ pool_name: 'rbd', status: 1, value: images }]); }); fixture.detectChanges(); }); it('should show button disabled when no image is in trash', () => { expect(component.disablePurgeBtn).toBeTruthy(); }); it('should show button enabled when an existing image is in trash', () => { images = []; addImage('1'); const payload = [{ pool_name: 'rbd', status: 1, value: images }]; component.prepareResponse(payload); expect(component.disablePurgeBtn).toBeFalsy(); }); it('should show button with delete permission', () => { component.permission = { read: true, create: true, delete: true, update: true }; fixture.detectChanges(); const purge = fixture.debugElement.query(By.css('.table-actions button .fa-times')); expect(purge).not.toBeNull(); }); it('should remove button without delete permission', () => { component.permission = { read: true, create: true, delete: false, update: true }; fixture.detectChanges(); const purge = fixture.debugElement.query(By.css('.table-actions button .fa-times')); expect(purge).toBeNull(); }); }); });
5,541
31.034682
90
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-trash-list/rbd-trash-list.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import moment from 'moment'; import { RbdService } from '~/app/shared/api/rbd.service'; import { TableStatusViewCache } from '~/app/shared/classes/table-status-view-cache'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { TableComponent } from '~/app/shared/datatable/table/table.component'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { Icons } from '~/app/shared/enum/icons.enum'; import { ViewCacheStatus } from '~/app/shared/enum/view-cache-status.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { ExecutingTask } from '~/app/shared/models/executing-task'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { ImageSpec } from '~/app/shared/models/image-spec'; import { Permission } from '~/app/shared/models/permissions'; import { Task } from '~/app/shared/models/task'; import { CdDatePipe } from '~/app/shared/pipes/cd-date.pipe'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { TaskListService } from '~/app/shared/services/task-list.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { RbdTrashPurgeModalComponent } from '../rbd-trash-purge-modal/rbd-trash-purge-modal.component'; import { RbdTrashRestoreModalComponent } from '../rbd-trash-restore-modal/rbd-trash-restore-modal.component'; @Component({ selector: 'cd-rbd-trash-list', templateUrl: './rbd-trash-list.component.html', styleUrls: ['./rbd-trash-list.component.scss'], providers: [TaskListService] }) export class RbdTrashListComponent implements OnInit { @ViewChild(TableComponent, { static: true }) table: TableComponent; @ViewChild('expiresTpl', { static: true }) expiresTpl: TemplateRef<any>; @ViewChild('deleteTpl', { static: true }) deleteTpl: TemplateRef<any>; icons = Icons; columns: CdTableColumn[]; executingTasks: ExecutingTask[] = []; images: any; modalRef: NgbModalRef; permission: Permission; retries: number; selection = new CdTableSelection(); tableActions: CdTableAction[]; tableStatus = new TableStatusViewCache(); disablePurgeBtn = true; constructor( private authStorageService: AuthStorageService, private rbdService: RbdService, private modalService: ModalService, private cdDatePipe: CdDatePipe, public taskListService: TaskListService, private taskWrapper: TaskWrapperService, public actionLabels: ActionLabelsI18n ) { this.permission = this.authStorageService.getPermissions().rbdImage; const restoreAction: CdTableAction = { permission: 'update', icon: Icons.undo, click: () => this.restoreModal(), name: this.actionLabels.RESTORE }; const deleteAction: CdTableAction = { permission: 'delete', icon: Icons.destroy, click: () => this.deleteModal(), name: this.actionLabels.DELETE }; this.tableActions = [restoreAction, deleteAction]; } ngOnInit() { this.columns = [ { name: $localize`ID`, prop: 'id', flexGrow: 1, cellTransformation: CellTemplate.executing }, { name: $localize`Name`, prop: 'name', flexGrow: 1 }, { name: $localize`Pool`, prop: 'pool_name', flexGrow: 1 }, { name: $localize`Namespace`, prop: 'namespace', flexGrow: 1 }, { name: $localize`Status`, prop: 'deferment_end_time', flexGrow: 1, cellTemplate: this.expiresTpl }, { name: $localize`Deleted At`, prop: 'deletion_time', flexGrow: 1, pipe: this.cdDatePipe } ]; const itemFilter = (entry: any, task: Task) => { const imageSpec = new ImageSpec(entry.pool_name, entry.namespace, entry.id); return imageSpec.toString() === task.metadata['image_id_spec']; }; const taskFilter = (task: Task) => { return ['rbd/trash/remove', 'rbd/trash/restore'].includes(task.name); }; this.taskListService.init( () => this.rbdService.listTrash(), (resp) => this.prepareResponse(resp), (images) => (this.images = images), () => this.onFetchError(), taskFilter, itemFilter, undefined ); } prepareResponse(resp: any[]): any[] { let images: any[] = []; const viewCacheStatusMap = {}; resp.forEach((pool: Record<string, any>) => { if (_.isUndefined(viewCacheStatusMap[pool.status])) { viewCacheStatusMap[pool.status] = []; } viewCacheStatusMap[pool.status].push(pool.pool_name); images = images.concat(pool.value); this.disablePurgeBtn = !images.length; }); let status: number; if (viewCacheStatusMap[3]) { status = 3; } else if (viewCacheStatusMap[1]) { status = 1; } else if (viewCacheStatusMap[2]) { status = 2; } if (status) { const statusFor = (viewCacheStatusMap[status].length > 1 ? 'pools ' : 'pool ') + viewCacheStatusMap[status].join(); this.tableStatus = new TableStatusViewCache(status, statusFor); } else { this.tableStatus = new TableStatusViewCache(); } images.forEach((image) => { image.cdIsExpired = moment().isAfter(image.deferment_end_time); }); return images; } onFetchError() { this.table.reset(); // Disable loading indicator. this.tableStatus = new TableStatusViewCache(ViewCacheStatus.ValueException); } updateSelection(selection: CdTableSelection) { this.selection = selection; } restoreModal() { const initialState = { poolName: this.selection.first().pool_name, namespace: this.selection.first().namespace, imageName: this.selection.first().name, imageId: this.selection.first().id }; this.modalRef = this.modalService.show(RbdTrashRestoreModalComponent, initialState); } deleteModal() { const poolName = this.selection.first().pool_name; const namespace = this.selection.first().namespace; const imageId = this.selection.first().id; const expiresAt = this.selection.first().deferment_end_time; const isExpired = moment().isAfter(expiresAt); const imageIdSpec = new ImageSpec(poolName, namespace, imageId); this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: 'RBD', itemNames: [imageIdSpec], bodyTemplate: this.deleteTpl, bodyContext: { expiresAt, isExpired }, submitActionObservable: () => this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/trash/remove', { image_id_spec: imageIdSpec.toString() }), call: this.rbdService.removeTrash(imageIdSpec, true) }) }); } purgeModal() { this.modalService.show(RbdTrashPurgeModalComponent); } }
7,443
31.938053
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-trash-move-modal/rbd-trash-move-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container i18n class="modal-title">Move an image to trash</ng-container> <ng-container class="modal-content"> <form name="moveForm" class="form" #formDir="ngForm" [formGroup]="moveForm" novalidate> <div class="modal-body"> <div class="alert alert-warning" *ngIf="hasSnapshots" role="alert"> <span i18n>This image contains snapshot(s), which will prevent it from being removed after moved to trash.</span> </div> <p i18n>To move <kbd>{{ imageSpecStr }}</kbd> to trash, click <kbd>Move</kbd>. Optionally, you can pick an expiration date.</p> <div class="form-group"> <label class="col-form-label" for="expiresAt" i18n>Protection expires at</label> <input type="text" placeholder="NOT PROTECTED" i18n-placeholder class="form-control" formControlName="expiresAt" [ngbPopover]="popContent" triggers="manual" #p="ngbPopover" (click)="p.open()" (keypress)="p.close()"> <span class="invalid-feedback" *ngIf="moveForm.showError('expiresAt', formDir, 'format')" i18n>Wrong date format. Please use "YYYY-MM-DD HH:mm:ss".</span> <span class="invalid-feedback" *ngIf="moveForm.showError('expiresAt', formDir, 'expired')" i18n>Protection has already expired. Please pick a future date or leave it empty.</span> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="moveImage()" [form]="moveForm" [submitText]="actionLabels.MOVE"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal> <ng-template #popContent> <cd-date-time-picker [control]="moveForm.get('expiresAt')"></cd-date-time-picker> </ng-template>
2,134
35.810345
104
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-trash-move-modal/rbd-trash-move-modal.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal, NgbPopoverModule } from '@ng-bootstrap/ng-bootstrap'; import moment from 'moment'; import { ToastrModule } from 'ngx-toastr'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdTrashMoveModalComponent } from './rbd-trash-move-modal.component'; describe('RbdTrashMoveModalComponent', () => { let component: RbdTrashMoveModalComponent; let fixture: ComponentFixture<RbdTrashMoveModalComponent>; let httpTesting: HttpTestingController; configureTestBed({ imports: [ ReactiveFormsModule, HttpClientTestingModule, RouterTestingModule, SharedModule, ToastrModule.forRoot(), NgbPopoverModule ], declarations: [RbdTrashMoveModalComponent], providers: [NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(RbdTrashMoveModalComponent); component = fixture.componentInstance; httpTesting = TestBed.inject(HttpTestingController); component.poolName = 'foo'; component.imageName = 'bar'; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); expect(component.moveForm).toBeDefined(); }); it('should finish running ngOnInit', () => { expect(component.pattern).toEqual('foo/bar'); }); describe('should call moveImage', () => { let notificationService: NotificationService; beforeEach(() => { notificationService = TestBed.inject(NotificationService); spyOn(notificationService, 'show').and.stub(); spyOn(component.activeModal, 'close').and.callThrough(); }); afterEach(() => { expect(notificationService.show).toHaveBeenCalledTimes(1); expect(component.activeModal.close).toHaveBeenCalledTimes(1); }); it('with normal delay', () => { component.moveImage(); const req = httpTesting.expectOne('api/block/image/foo%2Fbar/move_trash'); req.flush(null); expect(req.request.body).toEqual({ delay: 0 }); }); it('with delay < 0', () => { const oldDate = moment().subtract(24, 'hour').toDate(); component.moveForm.patchValue({ expiresAt: oldDate }); component.moveImage(); const req = httpTesting.expectOne('api/block/image/foo%2Fbar/move_trash'); req.flush(null); expect(req.request.body).toEqual({ delay: 0 }); }); it('with delay < 0', () => { const oldDate = moment().add(24, 'hour').toISOString(); component.moveForm.patchValue({ expiresAt: oldDate }); component.moveImage(); const req = httpTesting.expectOne('api/block/image/foo%2Fbar/move_trash'); req.flush(null); expect(req.request.body.delay).toBeGreaterThan(76390); }); }); });
3,140
32.063158
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-trash-move-modal/rbd-trash-move-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import moment from 'moment'; import { RbdService } from '~/app/shared/api/rbd.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { CdValidators } from '~/app/shared/forms/cd-validators'; import { ExecutingTask } from '~/app/shared/models/executing-task'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { ImageSpec } from '~/app/shared/models/image-spec'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; @Component({ selector: 'cd-rbd-trash-move-modal', templateUrl: './rbd-trash-move-modal.component.html', styleUrls: ['./rbd-trash-move-modal.component.scss'] }) export class RbdTrashMoveModalComponent implements OnInit { // initial state poolName: string; namespace: string; imageName: string; hasSnapshots: boolean; imageSpec: ImageSpec; imageSpecStr: string; executingTasks: ExecutingTask[]; moveForm: CdFormGroup; pattern: string; constructor( private rbdService: RbdService, public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private fb: CdFormBuilder, private taskWrapper: TaskWrapperService ) { this.createForm(); } createForm() { this.moveForm = this.fb.group({ expiresAt: [ '', [ CdValidators.custom('format', (expiresAt: string) => { const result = expiresAt === '' || moment(expiresAt, 'YYYY-MM-DD HH:mm:ss').isValid(); return !result; }), CdValidators.custom('expired', (expiresAt: string) => { const result = moment().isAfter(expiresAt); return result; }) ] ] }); } ngOnInit() { this.imageSpec = new ImageSpec(this.poolName, this.namespace, this.imageName); this.imageSpecStr = this.imageSpec.toString(); this.pattern = `${this.poolName}/${this.imageName}`; } moveImage() { let delay = 0; const expiresAt = this.moveForm.getValue('expiresAt'); if (expiresAt) { delay = moment(expiresAt, 'YYYY-MM-DD HH:mm:ss').diff(moment(), 'seconds', true); } if (delay < 0) { delay = 0; } this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('rbd/trash/move', { image_spec: this.imageSpecStr }), call: this.rbdService.moveTrash(this.imageSpec, delay) }) .subscribe({ complete: () => { this.activeModal.close(); } }); } }
2,744
27.894737
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-trash-purge-modal/rbd-trash-purge-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container i18n class="modal-title">Purge Trash</ng-container> <ng-container class="modal-content"> <form name="purgeForm" class="form" #formDir="ngForm" [formGroup]="purgeForm" novalidate> <div class="modal-body"> <p i18n>To purge, select&nbsp; <kbd>All</kbd>&nbsp; or one pool and click&nbsp; <kbd>Purge</kbd>.&nbsp;</p> <div class="form-group"> <label class="col-form-label mx-auto" i18n>Pool:</label> <input class="form-control" type="text" placeholder="Pool name..." i18n-placeholder formControlName="poolName" *ngIf="!poolPermission.read"> <select id="poolName" name="poolName" class="form-control" formControlName="poolName" *ngIf="poolPermission.read"> <option value="" i18n>All</option> <option *ngFor="let pool of pools" [value]="pool">{{ pool }}</option> </select> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="purge()" [form]="purgeForm" [submitText]="actionLabels.PURGE"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
1,525
31.468085
87
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-trash-purge-modal/rbd-trash-purge-modal.component.spec.ts
import { HttpClientTestingModule, HttpTestingController, TestRequest } from '@angular/common/http/testing'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { Permission } from '~/app/shared/models/permissions'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdTrashPurgeModalComponent } from './rbd-trash-purge-modal.component'; describe('RbdTrashPurgeModalComponent', () => { let component: RbdTrashPurgeModalComponent; let fixture: ComponentFixture<RbdTrashPurgeModalComponent>; let httpTesting: HttpTestingController; configureTestBed({ imports: [ HttpClientTestingModule, ReactiveFormsModule, SharedModule, ToastrModule.forRoot(), RouterTestingModule ], declarations: [RbdTrashPurgeModalComponent], providers: [NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(RbdTrashPurgeModalComponent); httpTesting = TestBed.inject(HttpTestingController); component = fixture.componentInstance; }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should finish ngOnInit', fakeAsync(() => { component.poolPermission = new Permission(['read', 'create', 'update', 'delete']); fixture.detectChanges(); const req = httpTesting.expectOne('api/pool?attrs=pool_name,application_metadata'); req.flush([ { application_metadata: ['foo'], pool_name: 'bar' }, { application_metadata: ['rbd'], pool_name: 'baz' } ]); tick(); expect(component.pools).toEqual(['baz']); expect(component.purgeForm).toBeTruthy(); })); it('should call ngOnInit without pool permissions', () => { component.poolPermission = new Permission([]); component.ngOnInit(); httpTesting.verify(); }); describe('should call purge', () => { let notificationService: NotificationService; let activeModal: NgbActiveModal; let req: TestRequest; beforeEach(() => { fixture.detectChanges(); notificationService = TestBed.inject(NotificationService); activeModal = TestBed.inject(NgbActiveModal); component.purgeForm.patchValue({ poolName: 'foo' }); spyOn(activeModal, 'close').and.stub(); spyOn(component.purgeForm, 'setErrors').and.stub(); spyOn(notificationService, 'show').and.stub(); component.purge(); req = httpTesting.expectOne('api/block/image/trash/purge/?pool_name=foo'); }); it('with success', () => { req.flush(null); expect(component.purgeForm.setErrors).toHaveBeenCalledTimes(0); expect(component.activeModal.close).toHaveBeenCalledTimes(1); }); it('with failure', () => { req.flush(null, { status: 500, statusText: 'failure' }); expect(component.purgeForm.setErrors).toHaveBeenCalledTimes(1); expect(component.activeModal.close).toHaveBeenCalledTimes(0); }); }); });
3,364
30.745283
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-trash-purge-modal/rbd-trash-purge-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { Pool } from '~/app/ceph/pool/pool'; import { PoolService } from '~/app/shared/api/pool.service'; import { RbdService } from '~/app/shared/api/rbd.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; @Component({ selector: 'cd-rbd-trash-purge-modal', templateUrl: './rbd-trash-purge-modal.component.html', styleUrls: ['./rbd-trash-purge-modal.component.scss'] }) export class RbdTrashPurgeModalComponent implements OnInit { poolPermission: Permission; purgeForm: CdFormGroup; pools: any[]; constructor( private authStorageService: AuthStorageService, private rbdService: RbdService, public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private fb: CdFormBuilder, private poolService: PoolService, private taskWrapper: TaskWrapperService ) { this.poolPermission = this.authStorageService.getPermissions().pool; } createForm() { this.purgeForm = this.fb.group({ poolName: '' }); } ngOnInit() { if (this.poolPermission.read) { this.poolService.list(['pool_name', 'application_metadata']).then((resp) => { this.pools = resp .filter((pool: Pool) => pool.application_metadata.includes('rbd')) .map((pool: Pool) => pool.pool_name); }); } this.createForm(); } purge() { const poolName = this.purgeForm.getValue('poolName') || ''; this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('rbd/trash/purge', { pool_name: poolName }), call: this.rbdService.purgeTrash(poolName) }) .subscribe({ error: () => { this.purgeForm.setErrors({ cdSubmitButton: true }); }, complete: () => { this.activeModal.close(); } }); } }
2,360
30.48
83
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-trash-restore-modal/rbd-trash-restore-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container i18n class="modal-title">Restore Image</ng-container> <ng-container class="modal-content"> <form name="restoreForm" class="form" #formDir="ngForm" [formGroup]="restoreForm" novalidate> <div class="modal-body"> <p i18n>To restore&nbsp; <kbd>{{ imageSpec }}@{{ imageId }}</kbd>,&nbsp; type the image's new name and click&nbsp; <kbd>Restore</kbd>.</p> <div class="form-group"> <label class="col-form-label" for="name" i18n>New Name</label> <input type="text" class="form-control" name="name" id="name" autocomplete="off" formControlName="name" autofocus> <span class="invalid-feedback" *ngIf="restoreForm.showError('name', formDir, 'required')" i18n>This field is required.</span> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="restore()" [form]="restoreForm" [submitText]="actionLabels.RESTORE"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
1,364
31.5
89
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-trash-restore-modal/rbd-trash-restore-modal.component.spec.ts
import { HttpClientTestingModule, HttpTestingController, TestRequest } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdTrashRestoreModalComponent } from './rbd-trash-restore-modal.component'; describe('RbdTrashRestoreModalComponent', () => { let component: RbdTrashRestoreModalComponent; let fixture: ComponentFixture<RbdTrashRestoreModalComponent>; configureTestBed({ declarations: [RbdTrashRestoreModalComponent], imports: [ ReactiveFormsModule, HttpClientTestingModule, ToastrModule.forRoot(), SharedModule, RouterTestingModule ], providers: [NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(RbdTrashRestoreModalComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('should call restore', () => { let httpTesting: HttpTestingController; let notificationService: NotificationService; let activeModal: NgbActiveModal; let req: TestRequest; beforeEach(() => { httpTesting = TestBed.inject(HttpTestingController); notificationService = TestBed.inject(NotificationService); activeModal = TestBed.inject(NgbActiveModal); component.poolName = 'foo'; component.imageName = 'bar'; component.imageId = '113cb6963793'; component.ngOnInit(); spyOn(activeModal, 'close').and.stub(); spyOn(component.restoreForm, 'setErrors').and.stub(); spyOn(notificationService, 'show').and.stub(); component.restore(); req = httpTesting.expectOne('api/block/image/trash/foo%2F113cb6963793/restore'); }); it('with success', () => { req.flush(null); expect(component.restoreForm.setErrors).toHaveBeenCalledTimes(0); expect(component.activeModal.close).toHaveBeenCalledTimes(1); }); it('with failure', () => { req.flush(null, { status: 500, statusText: 'failure' }); expect(component.restoreForm.setErrors).toHaveBeenCalledTimes(1); expect(component.activeModal.close).toHaveBeenCalledTimes(0); }); }); });
2,646
31.280488
86
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-trash-restore-modal/rbd-trash-restore-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { RbdService } from '~/app/shared/api/rbd.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { ExecutingTask } from '~/app/shared/models/executing-task'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { ImageSpec } from '~/app/shared/models/image-spec'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; @Component({ selector: 'cd-rbd-trash-restore-modal', templateUrl: './rbd-trash-restore-modal.component.html', styleUrls: ['./rbd-trash-restore-modal.component.scss'] }) export class RbdTrashRestoreModalComponent implements OnInit { poolName: string; namespace: string; imageName: string; imageSpec: string; imageId: string; executingTasks: ExecutingTask[]; restoreForm: CdFormGroup; constructor( private rbdService: RbdService, public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private fb: CdFormBuilder, private taskWrapper: TaskWrapperService ) {} ngOnInit() { this.imageSpec = new ImageSpec(this.poolName, this.namespace, this.imageName).toString(); this.restoreForm = this.fb.group({ name: this.imageName }); } restore() { const name = this.restoreForm.getValue('name'); const imageSpec = new ImageSpec(this.poolName, this.namespace, this.imageId); this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('rbd/trash/restore', { image_id_spec: imageSpec.toString(), new_image_name: name }), call: this.rbdService.restoreTrash(imageSpec, name) }) .subscribe({ error: () => { this.restoreForm.setErrors({ cdSubmitButton: true }); }, complete: () => { this.activeModal.close(); } }); } }
2,080
30.530303
93
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { TreeModule } from '@circlon/angular-tree-component'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { ChartsModule } from 'ng2-charts'; import { AppRoutingModule } from '~/app/app-routing.module'; import { SharedModule } from '~/app/shared/shared.module'; import { CephfsChartComponent } from './cephfs-chart/cephfs-chart.component'; import { CephfsClientsComponent } from './cephfs-clients/cephfs-clients.component'; import { CephfsDetailComponent } from './cephfs-detail/cephfs-detail.component'; import { CephfsDirectoriesComponent } from './cephfs-directories/cephfs-directories.component'; import { CephfsListComponent } from './cephfs-list/cephfs-list.component'; import { CephfsTabsComponent } from './cephfs-tabs/cephfs-tabs.component'; @NgModule({ imports: [CommonModule, SharedModule, AppRoutingModule, ChartsModule, TreeModule, NgbNavModule], declarations: [ CephfsDetailComponent, CephfsClientsComponent, CephfsChartComponent, CephfsListComponent, CephfsTabsComponent, CephfsDirectoriesComponent ] }) export class CephfsModule {}
1,193
40.172414
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-chart/cephfs-chart.component.html
<div class="chart-container"> <canvas baseChart #chartCanvas [datasets]="chart.datasets" [options]="chart.options" [chartType]="chart.chartType"> </canvas> <div class="chartjs-tooltip" #chartTooltip> <table></table> </div> </div>
289
21.307692
40
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-chart/cephfs-chart.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ChartsModule } from 'ng2-charts'; import { configureTestBed } from '~/testing/unit-test-helper'; import { CephfsChartComponent } from './cephfs-chart.component'; describe('CephfsChartComponent', () => { let component: CephfsChartComponent; let fixture: ComponentFixture<CephfsChartComponent>; const counter = [ [0, 15], [5, 15], [10, 25], [15, 50] ]; configureTestBed({ imports: [ChartsModule], declarations: [CephfsChartComponent] }); beforeEach(() => { fixture = TestBed.createComponent(CephfsChartComponent); component = fixture.componentInstance; component.mdsCounter = { 'mds_server.handle_client_request': counter, 'mds_mem.ino': counter, name: 'a' }; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('completed the chart', () => { const lhs = component.chart.datasets[0].data; expect(lhs.length).toBe(3); expect(lhs).toEqual([ { x: 5000, y: 15 }, { x: 10000, y: 25 }, { x: 15000, y: 50 } ]); const rhs = component.chart.datasets[1].data; expect(rhs.length).toBe(3); expect(rhs).toEqual([ { x: 5000, y: 0 }, { x: 10000, y: 10 }, { x: 15000, y: 25 } ]); }); it('should force angular to update the chart datasets array in order to update the graph', () => { const oldDatasets = component.chart.datasets; component.ngOnChanges(); expect(oldDatasets).toEqual(component.chart.datasets); expect(oldDatasets).not.toBe(component.chart.datasets); }); });
1,795
20.902439
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-chart/cephfs-chart.component.ts
import { Component, ElementRef, Input, OnChanges, OnInit, ViewChild } from '@angular/core'; import { ChartDataSets, ChartOptions, ChartPoint, ChartType } from 'chart.js'; import _ from 'lodash'; import moment from 'moment'; import { ChartTooltip } from '~/app/shared/models/chart-tooltip'; @Component({ selector: 'cd-cephfs-chart', templateUrl: './cephfs-chart.component.html', styleUrls: ['./cephfs-chart.component.scss'] }) export class CephfsChartComponent implements OnChanges, OnInit { @ViewChild('chartCanvas', { static: true }) chartCanvas: ElementRef; @ViewChild('chartTooltip', { static: true }) chartTooltip: ElementRef; @Input() mdsCounter: any; lhsCounter = 'mds_mem.ino'; rhsCounter = 'mds_server.handle_client_request'; chart: { datasets: ChartDataSets[]; options: ChartOptions; chartType: ChartType; } = { datasets: [ { label: this.lhsCounter, yAxisID: 'LHS', data: [], lineTension: 0.1 }, { label: this.rhsCounter, yAxisID: 'RHS', data: [], lineTension: 0.1 } ], options: { title: { text: '', display: true }, responsive: true, maintainAspectRatio: false, legend: { position: 'top' }, scales: { xAxes: [ { position: 'top', type: 'time', time: { displayFormats: { quarter: 'MMM YYYY' } }, ticks: { maxRotation: 0 } } ], yAxes: [ { id: 'LHS', type: 'linear', position: 'left' }, { id: 'RHS', type: 'linear', position: 'right' } ] }, tooltips: { enabled: false, mode: 'index', intersect: false, position: 'nearest', callbacks: { // Pick the Unix timestamp of the first tooltip item. title: (tooltipItems, data): string => { let ts = 0; if (tooltipItems.length > 0) { const item = tooltipItems[0]; const point = data.datasets[item.datasetIndex].data[item.index] as ChartPoint; ts = point.x as number; } return ts.toString(); } } } }, chartType: 'line' }; ngOnInit() { if (_.isUndefined(this.mdsCounter)) { return; } this.setChartTooltip(); this.updateChart(); } ngOnChanges() { if (_.isUndefined(this.mdsCounter)) { return; } this.updateChart(); } private setChartTooltip() { const chartTooltip = new ChartTooltip( this.chartCanvas, this.chartTooltip, (tooltip: any) => tooltip.caretX + 'px', (tooltip: any) => tooltip.caretY - tooltip.height - 23 + 'px' ); chartTooltip.getTitle = (ts) => moment(ts, 'x').format('LTS'); chartTooltip.checkOffset = true; const chartOptions: ChartOptions = { title: { text: this.mdsCounter.name }, tooltips: { custom: (tooltip) => chartTooltip.customTooltips(tooltip) } }; _.merge(this.chart, { options: chartOptions }); } private updateChart() { const chartDataSets: ChartDataSets[] = [ { data: this.convertTimeSeries(this.mdsCounter[this.lhsCounter]) }, { data: this.deltaTimeSeries(this.mdsCounter[this.rhsCounter]) } ]; _.merge(this.chart, { datasets: chartDataSets }); this.chart.datasets = [...this.chart.datasets]; // Force angular to update } /** * Convert ceph-mgr's time series format (list of 2-tuples * with seconds-since-epoch timestamps) into what chart.js * can handle (list of objects with millisecs-since-epoch * timestamps) */ private convertTimeSeries(sourceSeries: any) { const data: any[] = []; _.each(sourceSeries, (dp) => { data.push({ x: dp[0] * 1000, y: dp[1] }); }); /** * MDS performance counters chart is expecting the same number of items * from each data series. Since in deltaTimeSeries we are ignoring the first * element, we will do the same here. */ data.shift(); return data; } private deltaTimeSeries(sourceSeries: any) { let i; let prev = sourceSeries[0]; const result = []; for (i = 1; i < sourceSeries.length; i++) { const cur = sourceSeries[i]; result.push({ x: cur[0] * 1000, y: cur[1] - prev[1] }); prev = cur; } return result; } }
4,703
22.878173
92
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-clients/cephfs-clients.component.html
<cd-table [data]="clients.data" [columns]="columns" [status]="clients.status" [autoReload]="-1" (fetchData)="triggerApiUpdate.emit()" selectionType="single" (updateSelection)="updateSelection($event)"> <cd-table-actions class="table-actions" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> </cd-table>
479
33.285714
54
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-clients/cephfs-clients.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ToastrModule } from 'ngx-toastr'; import { TableStatusViewCache } from '~/app/shared/classes/table-status-view-cache'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; import { ViewCacheStatus } from '~/app/shared/enum/view-cache-status.enum'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, PermissionHelper } from '~/testing/unit-test-helper'; import { CephfsClientsComponent } from './cephfs-clients.component'; describe('CephfsClientsComponent', () => { let component: CephfsClientsComponent; let fixture: ComponentFixture<CephfsClientsComponent>; configureTestBed({ imports: [ BrowserAnimationsModule, ToastrModule.forRoot(), SharedModule, HttpClientTestingModule ], declarations: [CephfsClientsComponent] }); beforeEach(() => { fixture = TestBed.createComponent(CephfsClientsComponent); component = fixture.componentInstance; component.clients = { status: new TableStatusViewCache(ViewCacheStatus.ValueOk), data: [{}, {}, {}, {}] }; }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should test all TableActions combinations', () => { const permissionHelper: PermissionHelper = new PermissionHelper(component.permission); const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions( component.tableActions ); expect(tableActions).toEqual({ 'create,update,delete': { actions: ['Evict'], primary: { multiple: 'Evict', executing: 'Evict', single: 'Evict', no: 'Evict' } }, 'create,update': { actions: ['Evict'], primary: { multiple: 'Evict', executing: 'Evict', single: 'Evict', no: 'Evict' } }, 'create,delete': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, create: { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, 'update,delete': { actions: ['Evict'], primary: { multiple: 'Evict', executing: 'Evict', single: 'Evict', no: 'Evict' } }, update: { actions: ['Evict'], primary: { multiple: 'Evict', executing: 'Evict', single: 'Evict', no: 'Evict' } }, delete: { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); });
2,859
33.047619
101
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-clients/cephfs-clients.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { CephfsService } from '~/app/shared/api/cephfs.service'; import { TableStatusViewCache } from '~/app/shared/classes/table-status-view-cache'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; @Component({ selector: 'cd-cephfs-clients', templateUrl: './cephfs-clients.component.html', styleUrls: ['./cephfs-clients.component.scss'] }) export class CephfsClientsComponent implements OnInit { @Input() id: number; @Input() clients: { data: any[]; status: TableStatusViewCache; }; @Output() triggerApiUpdate = new EventEmitter(); columns: CdTableColumn[]; permission: Permission; tableActions: CdTableAction[]; modalRef: NgbModalRef; selection = new CdTableSelection(); constructor( private cephfsService: CephfsService, private modalService: ModalService, private notificationService: NotificationService, private authStorageService: AuthStorageService, private actionLabels: ActionLabelsI18n ) { this.permission = this.authStorageService.getPermissions().cephfs; const evictAction: CdTableAction = { permission: 'update', icon: Icons.signOut, click: () => this.evictClientModal(), name: this.actionLabels.EVICT }; this.tableActions = [evictAction]; } ngOnInit() { this.columns = [ { prop: 'id', name: $localize`id` }, { prop: 'type', name: $localize`type` }, { prop: 'state', name: $localize`state` }, { prop: 'version', name: $localize`version` }, { prop: 'hostname', name: $localize`Host` }, { prop: 'root', name: $localize`root` } ]; } updateSelection(selection: CdTableSelection) { this.selection = selection; } evictClient(clientId: number) { this.cephfsService.evictClient(this.id, clientId).subscribe( () => { this.triggerApiUpdate.emit(); this.modalRef.close(); this.notificationService.show( NotificationType.success, $localize`Evicted client '${clientId}'` ); }, () => { this.modalRef.componentInstance.stopLoadingSpinner(); } ); } evictClientModal() { const clientId = this.selection.first().id; this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: 'client', itemNames: [clientId], actionDescription: 'evict', submitAction: () => this.evictClient(clientId) }); } }
3,374
31.76699
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-detail/cephfs-detail.component.html
<div class="row"> <div class="col-sm-6"> <legend i18n>Ranks</legend> <cd-table [data]="data.ranks" [columns]="columns.ranks" [toolHeader]="false"> </cd-table> <legend i18n>Standbys</legend> <cd-table-key-value [data]="standbys"> </cd-table-key-value> </div> <div class="col-sm-6"> <legend i18n>Pools</legend> <cd-table [data]="data.pools" [columns]="columns.pools" [toolHeader]="false"> </cd-table> </div> </div> <legend i18n>MDS performance counters</legend> <div class="row" *ngFor="let mdsCounter of objectValues(data.mdsCounters); trackBy: trackByFn"> <div class="col-md-12"> <cd-cephfs-chart [mdsCounter]="mdsCounter"></cd-cephfs-chart> </div> </div> <!-- templates --> <ng-template #poolUsageTpl let-row="row"> <cd-usage-bar [total]="row.size" [used]="row.used" [title]="row.pool_name"></cd-usage-bar> </ng-template> <ng-template #activityTmpl let-row="row" let-value="value"> {{ row.state === 'standby-replay' ? 'Evts' : 'Reqs' }}: {{ value | dimless }} /s </ng-template>
1,172
25.659091
83
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-detail/cephfs-detail.component.spec.ts
import { Component, Input } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { CephfsDetailComponent } from './cephfs-detail.component'; @Component({ selector: 'cd-cephfs-chart', template: '' }) class CephfsChartStubComponent { @Input() mdsCounter: any; } describe('CephfsDetailComponent', () => { let component: CephfsDetailComponent; let fixture: ComponentFixture<CephfsDetailComponent>; const updateDetails = ( standbys: string, pools: any[], ranks: any[], mdsCounters: object, name: string ) => { component.data = { standbys, pools, ranks, mdsCounters, name }; fixture.detectChanges(); }; configureTestBed({ imports: [SharedModule], declarations: [CephfsDetailComponent, CephfsChartStubComponent] }); beforeEach(() => { fixture = TestBed.createComponent(CephfsDetailComponent); component = fixture.componentInstance; updateDetails('b', [], [], { a: { name: 'a', x: [0], y: [0, 1] } }, 'someFs'); fixture.detectChanges(); component.ngOnChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('prepares standby on change', () => { expect(component.standbys).toEqual([{ key: 'Standby daemons', value: 'b' }]); }); });
1,450
24.910714
82
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-detail/cephfs-detail.component.ts
import { Component, Input, OnChanges, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { DimlessPipe } from '~/app/shared/pipes/dimless.pipe'; @Component({ selector: 'cd-cephfs-detail', templateUrl: './cephfs-detail.component.html', styleUrls: ['./cephfs-detail.component.scss'] }) export class CephfsDetailComponent implements OnChanges, OnInit { @ViewChild('poolUsageTpl', { static: true }) poolUsageTpl: TemplateRef<any>; @ViewChild('activityTmpl', { static: true }) activityTmpl: TemplateRef<any>; @Input() data: { standbys: string; pools: any[]; ranks: any[]; mdsCounters: object; name: string; }; columns: { ranks: CdTableColumn[]; pools: CdTableColumn[]; }; standbys: any[] = []; objectValues = Object.values; constructor(private dimlessBinary: DimlessBinaryPipe, private dimless: DimlessPipe) {} ngOnChanges() { this.setStandbys(); } private setStandbys() { this.standbys = [ { key: $localize`Standby daemons`, value: this.data.standbys } ]; } ngOnInit() { this.columns = { ranks: [ { prop: 'rank', name: $localize`Rank` }, { prop: 'state', name: $localize`State` }, { prop: 'mds', name: $localize`Daemon` }, { prop: 'activity', name: $localize`Activity`, cellTemplate: this.activityTmpl }, { prop: 'dns', name: $localize`Dentries`, pipe: this.dimless }, { prop: 'inos', name: $localize`Inodes`, pipe: this.dimless }, { prop: 'dirs', name: $localize`Dirs`, pipe: this.dimless }, { prop: 'caps', name: $localize`Caps`, pipe: this.dimless } ], pools: [ { prop: 'pool', name: $localize`Pool` }, { prop: 'type', name: $localize`Type` }, { prop: 'size', name: $localize`Size`, pipe: this.dimlessBinary }, { name: $localize`Usage`, cellTemplate: this.poolUsageTpl, comparator: (_valueA: any, _valueB: any, rowA: any, rowB: any) => { const valA = rowA.used / rowA.avail; const valB = rowB.used / rowB.avail; if (valA === valB) { return 0; } if (valA > valB) { return 1; } else { return -1; } } } as CdTableColumn ] }; } trackByFn(_index: any, item: any) { return item.name; } }
2,569
26.934783
92
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-directories/cephfs-directories.component.html
<div class="row"> <div class="col-sm-4 pe-0"> <div class="card"> <div class="card-header"> <button type="button" [class.disabled]="loadingIndicator" class="btn btn-light pull-right" (click)="refreshAllDirectories()"> <i [ngClass]="[icons.large, icons.refresh]" [class.fa-spin]="loadingIndicator"></i> </button> </div> <div class="card-body"> <tree-root *ngIf="nodes" [nodes]="nodes" [options]="treeOptions"> <ng-template #loadingTemplate> <i [ngClass]="[icons.spinner, icons.spin]"></i> </ng-template> </tree-root> </div> </div> </div> <!-- Selection details --> <div class="col-sm-8 metadata" *ngIf="selectedDir"> <div class="card"> <div class="card-header"> {{ selectedDir.path }} </div> <div class="card-body"> <ng-container *ngIf="selectedDir.path !== '/'"> <legend i18n>Quotas</legend> <cd-table [data]="settings" [columns]="quota.columns" [limit]="0" [footer]="false" selectionType="single" (updateSelection)="quota.updateSelection($event)" [onlyActionHeader]="true" identifier="quotaKey" [forceIdentifier]="true" [toolHeader]="false"> <cd-table-actions class="only-table-actions" [permission]="permission" [selection]="quota.selection" [tableActions]="quota.tableActions"> </cd-table-actions> </cd-table> </ng-container> <legend i18n>Snapshots</legend> <cd-table [data]="selectedDir.snapshots" [columns]="snapshot.columns" identifier="name" forceIdentifier="true" selectionType="multiClick" (updateSelection)="snapshot.updateSelection($event)"> <cd-table-actions class="table-actions" [permission]="permission" [selection]="snapshot.selection" [tableActions]="snapshot.tableActions"> </cd-table-actions> </cd-table> </div> </div> </div> </div> <ng-template #origin let-row="row" let-value="value"> <span class="quota-origin" (click)="selectOrigin(value)">{{value}}</span> </ng-template>
2,652
33.907895
71
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-directories/cephfs-directories.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { Type } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { Validators } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { TreeComponent, TreeModule, TREE_ACTIONS } from '@circlon/angular-tree-component'; import { NgbActiveModal, NgbModalModule, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { Observable, of } from 'rxjs'; import { CephfsService } from '~/app/shared/api/cephfs.service'; import { ConfirmationModalComponent } from '~/app/shared/components/confirmation-modal/confirmation-modal.component'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { FormModalComponent } from '~/app/shared/components/form-modal/form-modal.component'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdValidators } from '~/app/shared/forms/cd-validators'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { CephfsDir, CephfsQuotas, CephfsSnapshot } from '~/app/shared/models/cephfs-directory-models'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, modalServiceShow, PermissionHelper } from '~/testing/unit-test-helper'; import { CephfsDirectoriesComponent } from './cephfs-directories.component'; describe('CephfsDirectoriesComponent', () => { let component: CephfsDirectoriesComponent; let fixture: ComponentFixture<CephfsDirectoriesComponent>; let cephfsService: CephfsService; let noAsyncUpdate: boolean; let lsDirSpy: jasmine.Spy; let modalShowSpy: jasmine.Spy; let notificationShowSpy: jasmine.Spy; let minValidator: jasmine.Spy; let maxValidator: jasmine.Spy; let minBinaryValidator: jasmine.Spy; let maxBinaryValidator: jasmine.Spy; let modal: NgbModalRef; // Get's private attributes or functions const get = { nodeIds: (): { [path: string]: CephfsDir } => component['nodeIds'], dirs: (): CephfsDir[] => component['dirs'], requestedPaths: (): string[] => component['requestedPaths'] }; // Object contains mock data that will be reset before each test. let mockData: { nodes: any; parent: any; createdSnaps: CephfsSnapshot[] | any[]; deletedSnaps: CephfsSnapshot[] | any[]; updatedQuotas: { [path: string]: CephfsQuotas }; createdDirs: CephfsDir[]; }; // Object contains mock functions const mockLib = { quotas: (max_bytes: number, max_files: number): CephfsQuotas => ({ max_bytes, max_files }), snapshots: (dirPath: string, howMany: number): CephfsSnapshot[] => { const name = 'someSnapshot'; const snapshots = []; const oneDay = 3600 * 24 * 1000; for (let i = 0; i < howMany; i++) { const snapName = `${name}${i + 1}`; const path = `${dirPath}/.snap/${snapName}`; const created = new Date(+new Date() - oneDay * i).toString(); snapshots.push({ name: snapName, path, created }); } return snapshots; }, dir: (parentPath: string, name: string, modifier: number): CephfsDir => { const dirPath = `${parentPath === '/' ? '' : parentPath}/${name}`; let snapshots = mockLib.snapshots(parentPath, modifier); const extraSnapshots = mockData.createdSnaps.filter((s) => s.path === dirPath); if (extraSnapshots.length > 0) { snapshots = snapshots.concat(extraSnapshots); } const deletedSnapshots = mockData.deletedSnaps .filter((s) => s.path === dirPath) .map((s) => s.name); if (deletedSnapshots.length > 0) { snapshots = snapshots.filter((s) => !deletedSnapshots.includes(s.name)); } return { name, path: dirPath, parent: parentPath, quotas: Object.assign( mockLib.quotas(1024 * modifier, 10 * modifier), mockData.updatedQuotas[dirPath] || {} ), snapshots: snapshots }; }, // Only used inside other mocks lsSingleDir: (path = ''): CephfsDir[] => { const customDirs = mockData.createdDirs.filter((d) => d.parent === path); const isCustomDir = mockData.createdDirs.some((d) => d.path === path); if (isCustomDir || path.includes('b')) { // 'b' has no sub directories return customDirs; } return customDirs.concat([ // Directories are not sorted! mockLib.dir(path, 'c', 3), mockLib.dir(path, 'a', 1), mockLib.dir(path, 'b', 2) ]); }, lsDir: (_id: number, path = ''): Observable<CephfsDir[]> => { // will return 2 levels deep let data = mockLib.lsSingleDir(path); const paths = data.map((dir) => dir.path); paths.forEach((pathL2) => { data = data.concat(mockLib.lsSingleDir(pathL2)); }); if (path === '' || path === '/') { // Adds root directory on ls of '/' to the directories list. const root = mockLib.dir(path, '/', 1); root.path = '/'; root.parent = undefined; root.quotas = undefined; data = [root].concat(data); } return of(data); }, mkSnapshot: (_id: any, path: string, name: string): Observable<string> => { mockData.createdSnaps.push({ name, path, created: new Date().toString() }); return of(name); }, rmSnapshot: (_id: any, path: string, name: string): Observable<string> => { mockData.deletedSnaps.push({ name, path, created: new Date().toString() }); return of(name); }, updateQuota: (_id: any, path: string, updated: CephfsQuotas): Observable<string> => { mockData.updatedQuotas[path] = Object.assign(mockData.updatedQuotas[path] || {}, updated); return of('Response'); }, modalShow: (comp: Type<any>, init: any): any => { modal = modalServiceShow(comp, init); return modal; }, getNodeById: (path: string) => { return mockLib.useNode(path); }, updateNodes: (path: string) => { const p: Promise<any[]> = component.treeOptions.getChildren({ id: path }); return noAsyncUpdate ? () => p : mockLib.asyncNodeUpdate(p); }, asyncNodeUpdate: fakeAsync((p: Promise<any[]>) => { p.then((nodes) => { mockData.nodes = mockData.nodes.concat(nodes); }); tick(); }), changeId: (id: number) => { // For some reason this spy has to be renewed after usage spyOn(global, 'setTimeout').and.callFake((fn) => fn()); component.id = id; component.ngOnChanges(); mockData.nodes = component.nodes.concat(mockData.nodes); }, selectNode: (path: string) => { component.treeOptions.actionMapping.mouse.click(undefined, mockLib.useNode(path), undefined); }, // Creates TreeNode with parents until root useNode: (path: string): { id: string; parent: any; data: any; loadNodeChildren: Function } => { const parentPath = path.split('/'); parentPath.pop(); const parentIsRoot = parentPath.length === 1; const parent = parentIsRoot ? { id: '/' } : mockLib.useNode(parentPath.join('/')); return { id: path, parent, data: {}, loadNodeChildren: () => mockLib.updateNodes(path) }; }, treeActions: { toggleActive: (_a: any, node: any, _b: any) => { return mockLib.updateNodes(node.id); } }, mkDir: (path: string, name: string, maxFiles: number, maxBytes: number) => { const dir = mockLib.dir(path, name, 3); dir.quotas.max_bytes = maxBytes * 1024; dir.quotas.max_files = maxFiles; mockData.createdDirs.push(dir); // Below is needed for quota tests only where 4 dirs are mocked get.nodeIds()[dir.path] = dir; mockData.nodes.push({ id: dir.path }); }, createSnapshotThroughModal: (name: string) => { component.createSnapshot(); modal.componentInstance.onSubmitForm({ name }); }, deleteSnapshotsThroughModal: (snapshots: CephfsSnapshot[]) => { component.snapshot.selection.selected = snapshots; component.deleteSnapshotModal(); modal.componentInstance.callSubmitAction(); }, updateQuotaThroughModal: (attribute: string, value: number) => { component.quota.selection.selected = component.settings.filter( (q) => q.quotaKey === attribute ); component.updateQuotaModal(); modal.componentInstance.onSubmitForm({ [attribute]: value }); }, unsetQuotaThroughModal: (attribute: string) => { component.quota.selection.selected = component.settings.filter( (q) => q.quotaKey === attribute ); component.unsetQuotaModal(); modal.componentInstance.onSubmit(); }, setFourQuotaDirs: (quotas: number[][]) => { expect(quotas.length).toBe(4); // Make sure this function is used correctly let path = ''; quotas.forEach((quota, index) => { index += 1; mockLib.mkDir(path === '' ? '/' : path, index.toString(), quota[0], quota[1]); path += '/' + index; }); mockData.parent = { value: '3', id: '/1/2/3', parent: { value: '2', id: '/1/2', parent: { value: '1', id: '/1', parent: { value: '/', id: '/' } } } }; mockLib.selectNode('/1/2/3/4'); } }; // Expects that are used frequently const assert = { dirLength: (n: number) => expect(get.dirs().length).toBe(n), nodeLength: (n: number) => expect(mockData.nodes.length).toBe(n), lsDirCalledTimes: (n: number) => expect(lsDirSpy).toHaveBeenCalledTimes(n), lsDirHasBeenCalledWith: (id: number, paths: string[]) => { paths.forEach((path) => expect(lsDirSpy).toHaveBeenCalledWith(id, path)); assert.lsDirCalledTimes(paths.length); }, requestedPaths: (expected: string[]) => expect(get.requestedPaths()).toEqual(expected), snapshotsByName: (snaps: string[]) => expect(component.selectedDir.snapshots.map((s) => s.name)).toEqual(snaps), dirQuotas: (bytes: number, files: number) => { expect(component.selectedDir.quotas).toEqual({ max_bytes: bytes, max_files: files }); }, noQuota: (key: 'bytes' | 'files') => { assert.quotaRow(key, '', 0, ''); }, quotaIsNotInherited: (key: 'bytes' | 'files', shownValue: any, nextMaximum: number) => { const dir = component.selectedDir; const path = dir.path; assert.quotaRow(key, shownValue, nextMaximum, path); }, quotaIsInherited: (key: 'bytes' | 'files', shownValue: any, path: string) => { const isBytes = key === 'bytes'; const nextMaximum = get.nodeIds()[path].quotas[isBytes ? 'max_bytes' : 'max_files']; assert.quotaRow(key, shownValue, nextMaximum, path); }, quotaRow: ( key: 'bytes' | 'files', shownValue: number | string, nextTreeMaximum: number, originPath: string ) => { const isBytes = key === 'bytes'; expect(component.settings[isBytes ? 1 : 0]).toEqual({ row: { name: `Max ${isBytes ? 'size' : key}`, value: shownValue, originPath }, quotaKey: `max_${key}`, dirValue: expect.any(Number), nextTreeMaximum: { value: nextTreeMaximum, path: expect.any(String) } }); }, quotaUnsetModalTexts: (titleText: string, message: string, notificationMsg: string) => { expect(modalShowSpy).toHaveBeenCalledWith( ConfirmationModalComponent, expect.objectContaining({ titleText, description: message, buttonText: 'Unset' }) ); expect(notificationShowSpy).toHaveBeenCalledWith(NotificationType.success, notificationMsg); }, quotaUpdateModalTexts: (titleText: string, message: string, notificationMsg: string) => { expect(modalShowSpy).toHaveBeenCalledWith( FormModalComponent, expect.objectContaining({ titleText, message, submitButtonText: 'Save' }) ); expect(notificationShowSpy).toHaveBeenCalledWith(NotificationType.success, notificationMsg); }, quotaUpdateModalField: ( type: string, label: string, key: string, value: number, max: number, errors?: { [key: string]: string } ) => { expect(modalShowSpy).toHaveBeenCalledWith( FormModalComponent, expect.objectContaining({ fields: [ { type, label, errors, name: key, value, validators: expect.anything(), required: true } ] }) ); if (type === 'binary') { expect(minBinaryValidator).toHaveBeenCalledWith(0); expect(maxBinaryValidator).toHaveBeenCalledWith(max); } else { expect(minValidator).toHaveBeenCalledWith(0); expect(maxValidator).toHaveBeenCalledWith(max); } } }; configureTestBed( { imports: [ HttpClientTestingModule, SharedModule, RouterTestingModule, TreeModule, ToastrModule.forRoot(), NgbModalModule ], declarations: [CephfsDirectoriesComponent], providers: [NgbActiveModal] }, [CriticalConfirmationModalComponent, FormModalComponent, ConfirmationModalComponent] ); beforeEach(() => { noAsyncUpdate = false; mockData = { nodes: [], parent: undefined, createdSnaps: [], deletedSnaps: [], createdDirs: [], updatedQuotas: {} }; cephfsService = TestBed.inject(CephfsService); lsDirSpy = spyOn(cephfsService, 'lsDir').and.callFake(mockLib.lsDir); spyOn(cephfsService, 'mkSnapshot').and.callFake(mockLib.mkSnapshot); spyOn(cephfsService, 'rmSnapshot').and.callFake(mockLib.rmSnapshot); spyOn(cephfsService, 'quota').and.callFake(mockLib.updateQuota); modalShowSpy = spyOn(TestBed.inject(ModalService), 'show').and.callFake(mockLib.modalShow); notificationShowSpy = spyOn(TestBed.inject(NotificationService), 'show').and.stub(); fixture = TestBed.createComponent(CephfsDirectoriesComponent); component = fixture.componentInstance; fixture.detectChanges(); spyOn(TREE_ACTIONS, 'TOGGLE_ACTIVE').and.callFake(mockLib.treeActions.toggleActive); component.treeComponent = { sizeChanged: () => null, treeModel: { getNodeById: mockLib.getNodeById, update: () => null } } as TreeComponent; }); it('should create', () => { expect(component).toBeTruthy(); }); describe('mock self test', () => { it('tests snapshots mock', () => { expect(mockLib.snapshots('/a', 1).map((s) => ({ name: s.name, path: s.path }))).toEqual([ { name: 'someSnapshot1', path: '/a/.snap/someSnapshot1' } ]); expect(mockLib.snapshots('/a/b', 3).map((s) => ({ name: s.name, path: s.path }))).toEqual([ { name: 'someSnapshot1', path: '/a/b/.snap/someSnapshot1' }, { name: 'someSnapshot2', path: '/a/b/.snap/someSnapshot2' }, { name: 'someSnapshot3', path: '/a/b/.snap/someSnapshot3' } ]); }); it('tests dir mock', () => { const path = '/a/b/c'; mockData.createdSnaps = [ { path, name: 's1' }, { path, name: 's2' } ]; mockData.deletedSnaps = [ { path, name: 'someSnapshot2' }, { path, name: 's2' } ]; const dir = mockLib.dir('/a/b', 'c', 2); expect(dir.path).toBe('/a/b/c'); expect(dir.parent).toBe('/a/b'); expect(dir.quotas).toEqual({ max_bytes: 2048, max_files: 20 }); expect(dir.snapshots.map((s) => s.name)).toEqual(['someSnapshot1', 's1']); }); it('tests lsdir mock', () => { let dirs: CephfsDir[] = []; mockLib.lsDir(2, '/a').subscribe((x) => (dirs = x)); expect(dirs.map((d) => d.path)).toEqual([ '/a/c', '/a/a', '/a/b', '/a/c/c', '/a/c/a', '/a/c/b', '/a/a/c', '/a/a/a', '/a/a/b' ]); }); describe('test quota update mock', () => { const PATH = '/a'; const ID = 2; const updateQuota = (quotas: CephfsQuotas) => mockLib.updateQuota(ID, PATH, quotas); const expectMockUpdate = (max_bytes?: number, max_files?: number) => expect(mockData.updatedQuotas[PATH]).toEqual({ max_bytes, max_files }); const expectLsUpdate = (max_bytes?: number, max_files?: number) => { let dir: CephfsDir; mockLib.lsDir(ID, '/').subscribe((dirs) => (dir = dirs.find((d) => d.path === PATH))); expect(dir.quotas).toEqual({ max_bytes, max_files }); }; it('tests to set quotas', () => { expectLsUpdate(1024, 10); updateQuota({ max_bytes: 512 }); expectMockUpdate(512); expectLsUpdate(512, 10); updateQuota({ max_files: 100 }); expectMockUpdate(512, 100); expectLsUpdate(512, 100); }); it('tests to unset quotas', () => { updateQuota({ max_files: 0 }); expectMockUpdate(undefined, 0); expectLsUpdate(1024, 0); updateQuota({ max_bytes: 0 }); expectMockUpdate(0, 0); expectLsUpdate(0, 0); }); }); }); it('calls lsDir only if an id exits', () => { assert.lsDirCalledTimes(0); mockLib.changeId(1); assert.lsDirCalledTimes(1); expect(lsDirSpy).toHaveBeenCalledWith(1, '/'); mockLib.changeId(2); assert.lsDirCalledTimes(2); expect(lsDirSpy).toHaveBeenCalledWith(2, '/'); }); describe('listing sub directories', () => { beforeEach(() => { mockLib.changeId(1); /** * Tree looks like this: * v / * > a * * b * > c * */ }); it('expands first level', () => { // Tree will only show '*' if nor 'loadChildren' or 'children' are defined expect( mockData.nodes.map((node: any) => ({ [node.id]: node.hasChildren || node.isExpanded || Boolean(node.children) })) ).toEqual([{ '/': true }, { '/a': true }, { '/b': false }, { '/c': true }]); }); it('resets all dynamic content on id change', () => { mockLib.selectNode('/a'); /** * Tree looks like this: * v / * v a <- Selected * > a * * b * > c * * b * > c * */ assert.requestedPaths(['/', '/a']); assert.nodeLength(7); assert.dirLength(16); expect(component.selectedDir).toBeDefined(); mockLib.changeId(undefined); assert.dirLength(0); assert.requestedPaths([]); expect(component.selectedDir).not.toBeDefined(); }); it('should select a node and show the directory contents', () => { mockLib.selectNode('/a'); const dir = get.dirs().find((d) => d.path === '/a'); expect(component.selectedDir).toEqual(dir); assert.quotaIsNotInherited('files', 10, 0); assert.quotaIsNotInherited('bytes', '1 KiB', 0); }); it('should extend the list by subdirectories when expanding', () => { mockLib.selectNode('/a'); mockLib.selectNode('/a/c'); /** * Tree looks like this: * v / * v a * > a * * b * v c <- Selected * > a * * b * > c * * b * > c * */ assert.lsDirCalledTimes(3); assert.requestedPaths(['/', '/a', '/a/c']); assert.dirLength(22); assert.nodeLength(10); }); it('should update the tree after each selection', () => { const spy = spyOn(component.treeComponent, 'sizeChanged').and.callThrough(); expect(spy).toHaveBeenCalledTimes(0); mockLib.selectNode('/a'); expect(spy).toHaveBeenCalledTimes(1); mockLib.selectNode('/a/c'); expect(spy).toHaveBeenCalledTimes(2); }); it('should select parent by path', () => { mockLib.selectNode('/a'); mockLib.selectNode('/a/c'); mockLib.selectNode('/a/c/a'); component.selectOrigin('/a'); expect(component.selectedDir.path).toBe('/a'); }); it('should refresh directories with no sub directories as they could have some now', () => { mockLib.selectNode('/b'); /** * Tree looks like this: * v / * > a * * b <- Selected * > c * */ assert.lsDirCalledTimes(2); assert.requestedPaths(['/', '/b']); assert.nodeLength(4); }); describe('used quotas', () => { it('should use no quota if none is set', () => { mockLib.setFourQuotaDirs([ [0, 0], [0, 0], [0, 0], [0, 0] ]); assert.noQuota('files'); assert.noQuota('bytes'); assert.dirQuotas(0, 0); }); it('should use quota from upper parents', () => { mockLib.setFourQuotaDirs([ [100, 0], [0, 8], [0, 0], [0, 0] ]); assert.quotaIsInherited('files', 100, '/1'); assert.quotaIsInherited('bytes', '8 KiB', '/1/2'); assert.dirQuotas(0, 0); }); it('should use quota from the parent with the lowest value (deep inheritance)', () => { mockLib.setFourQuotaDirs([ [200, 1], [100, 4], [400, 3], [300, 2] ]); assert.quotaIsInherited('files', 100, '/1/2'); assert.quotaIsInherited('bytes', '1 KiB', '/1'); assert.dirQuotas(2048, 300); }); it('should use current value', () => { mockLib.setFourQuotaDirs([ [200, 2], [300, 4], [400, 3], [100, 1] ]); assert.quotaIsNotInherited('files', 100, 200); assert.quotaIsNotInherited('bytes', '1 KiB', 2048); assert.dirQuotas(1024, 100); }); }); }); describe('snapshots', () => { beforeEach(() => { mockLib.changeId(1); mockLib.selectNode('/a'); }); it('should create a snapshot', () => { mockLib.createSnapshotThroughModal('newSnap'); expect(cephfsService.mkSnapshot).toHaveBeenCalledWith(1, '/a', 'newSnap'); assert.snapshotsByName(['someSnapshot1', 'newSnap']); }); it('should delete a snapshot', () => { mockLib.createSnapshotThroughModal('deleteMe'); mockLib.deleteSnapshotsThroughModal([component.selectedDir.snapshots[1]]); assert.snapshotsByName(['someSnapshot1']); }); it('should delete all snapshots', () => { mockLib.createSnapshotThroughModal('deleteAll'); mockLib.deleteSnapshotsThroughModal(component.selectedDir.snapshots); assert.snapshotsByName([]); }); }); it('should test all snapshot table actions combinations', () => { const permissionHelper: PermissionHelper = new PermissionHelper(component.permission); const tableActions = permissionHelper.setPermissionsAndGetActions( component.snapshot.tableActions ); expect(tableActions).toEqual({ 'create,update,delete': { actions: ['Create', 'Delete'], primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Create' } }, 'create,update': { actions: ['Create'], primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' } }, 'create,delete': { actions: ['Create', 'Delete'], primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Create' } }, create: { actions: ['Create'], primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' } }, 'update,delete': { actions: ['Delete'], primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' } }, update: { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, delete: { actions: ['Delete'], primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); describe('quotas', () => { beforeEach(() => { // Spies minValidator = spyOn(Validators, 'min').and.callThrough(); maxValidator = spyOn(Validators, 'max').and.callThrough(); minBinaryValidator = spyOn(CdValidators, 'binaryMin').and.callThrough(); maxBinaryValidator = spyOn(CdValidators, 'binaryMax').and.callThrough(); // Select /a/c/b mockLib.changeId(1); mockLib.selectNode('/a'); mockLib.selectNode('/a/c'); mockLib.selectNode('/a/c/b'); // Quotas after selection assert.quotaIsInherited('files', 10, '/a'); assert.quotaIsInherited('bytes', '1 KiB', '/a'); assert.dirQuotas(2048, 20); }); describe('update modal', () => { describe('max_files', () => { beforeEach(() => { mockLib.updateQuotaThroughModal('max_files', 5); }); it('should update max_files correctly', () => { expect(cephfsService.quota).toHaveBeenCalledWith(1, '/a/c/b', { max_files: 5 }); assert.quotaIsNotInherited('files', 5, 10); }); it('uses the correct form field', () => { assert.quotaUpdateModalField('number', 'Max files', 'max_files', 20, 10, { min: 'Value has to be at least 0 or more', max: 'Value has to be at most 10 or less' }); }); it('shows the right texts', () => { assert.quotaUpdateModalTexts( `Update CephFS files quota for '/a/c/b'`, `The inherited files quota 10 from '/a' is the maximum value to be used.`, `Updated CephFS files quota for '/a/c/b'` ); }); }); describe('max_bytes', () => { beforeEach(() => { mockLib.updateQuotaThroughModal('max_bytes', 512); }); it('should update max_files correctly', () => { expect(cephfsService.quota).toHaveBeenCalledWith(1, '/a/c/b', { max_bytes: 512 }); assert.quotaIsNotInherited('bytes', '512 B', 1024); }); it('uses the correct form field', () => { mockLib.updateQuotaThroughModal('max_bytes', 512); assert.quotaUpdateModalField('binary', 'Max size', 'max_bytes', 2048, 1024); }); it('shows the right texts', () => { assert.quotaUpdateModalTexts( `Update CephFS size quota for '/a/c/b'`, `The inherited size quota 1 KiB from '/a' is the maximum value to be used.`, `Updated CephFS size quota for '/a/c/b'` ); }); }); describe('action behaviour', () => { it('opens with next maximum as maximum if directory holds the current maximum', () => { mockLib.updateQuotaThroughModal('max_bytes', 512); mockLib.updateQuotaThroughModal('max_bytes', 888); assert.quotaUpdateModalField('binary', 'Max size', 'max_bytes', 512, 1024); }); it(`uses 'Set' action instead of 'Update' if the quota is not set (0)`, () => { mockLib.updateQuotaThroughModal('max_bytes', 0); mockLib.updateQuotaThroughModal('max_bytes', 200); assert.quotaUpdateModalTexts( `Set CephFS size quota for '/a/c/b'`, `The inherited size quota 1 KiB from '/a' is the maximum value to be used.`, `Set CephFS size quota for '/a/c/b'` ); }); }); }); describe('unset modal', () => { describe('max_files', () => { beforeEach(() => { mockLib.updateQuotaThroughModal('max_files', 5); // Sets usable quota mockLib.unsetQuotaThroughModal('max_files'); }); it('should unset max_files correctly', () => { expect(cephfsService.quota).toHaveBeenCalledWith(1, '/a/c/b', { max_files: 0 }); assert.dirQuotas(2048, 0); }); it('shows the right texts', () => { assert.quotaUnsetModalTexts( `Unset CephFS files quota for '/a/c/b'`, `Unset files quota 5 from '/a/c/b' in order to inherit files quota 10 from '/a'.`, `Unset CephFS files quota for '/a/c/b'` ); }); }); describe('max_bytes', () => { beforeEach(() => { mockLib.updateQuotaThroughModal('max_bytes', 512); // Sets usable quota mockLib.unsetQuotaThroughModal('max_bytes'); }); it('should unset max_files correctly', () => { expect(cephfsService.quota).toHaveBeenCalledWith(1, '/a/c/b', { max_bytes: 0 }); assert.dirQuotas(0, 20); }); it('shows the right texts', () => { assert.quotaUnsetModalTexts( `Unset CephFS size quota for '/a/c/b'`, `Unset size quota 512 B from '/a/c/b' in order to inherit size quota 1 KiB from '/a'.`, `Unset CephFS size quota for '/a/c/b'` ); }); }); describe('action behaviour', () => { it('uses different Text if no quota is inherited', () => { mockLib.selectNode('/a'); mockLib.unsetQuotaThroughModal('max_bytes'); assert.quotaUnsetModalTexts( `Unset CephFS size quota for '/a'`, `Unset size quota 1 KiB from '/a' in order to have no quota on the directory.`, `Unset CephFS size quota for '/a'` ); }); it('uses different Text if quota is already inherited', () => { mockLib.unsetQuotaThroughModal('max_bytes'); assert.quotaUnsetModalTexts( `Unset CephFS size quota for '/a/c/b'`, `Unset size quota 2 KiB from '/a/c/b' which isn't used because of the inheritance ` + `of size quota 1 KiB from '/a'.`, `Unset CephFS size quota for '/a/c/b'` ); }); }); }); }); describe('table actions', () => { let actions: CdTableAction[]; const empty = (): CdTableSelection => new CdTableSelection(); const select = (value: number): CdTableSelection => { const selection = new CdTableSelection(); selection.selected = [{ dirValue: value }]; return selection; }; beforeEach(() => { actions = component.quota.tableActions; }); it(`shows 'Set' for empty and not set quotas`, () => { const isSetVisible = actions[0].visible; expect(isSetVisible(empty())).toBe(true); expect(isSetVisible(select(0))).toBe(true); expect(isSetVisible(select(1))).toBe(false); }); it(`shows 'Update' for set quotas only`, () => { const isUpdateVisible = actions[1].visible; expect(isUpdateVisible(empty())).toBeFalsy(); expect(isUpdateVisible(select(0))).toBe(false); expect(isUpdateVisible(select(1))).toBe(true); }); it(`only enables 'Unset' for set quotas only`, () => { const isUnsetDisabled = actions[2].disable; expect(isUnsetDisabled(empty())).toBe(true); expect(isUnsetDisabled(select(0))).toBe(true); expect(isUnsetDisabled(select(1))).toBe(false); }); it('should test all quota table actions permission combinations', () => { const permissionHelper: PermissionHelper = new PermissionHelper(component.permission, { single: { dirValue: 0 }, multiple: [{ dirValue: 0 }, {}] }); const tableActions = permissionHelper.setPermissionsAndGetActions( component.quota.tableActions ); expect(tableActions).toEqual({ 'create,update,delete': { actions: ['Set', 'Update', 'Unset'], primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' } }, 'create,update': { actions: ['Set', 'Update', 'Unset'], primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' } }, 'create,delete': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, create: { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, 'update,delete': { actions: ['Set', 'Update', 'Unset'], primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' } }, update: { actions: ['Set', 'Update', 'Unset'], primary: { multiple: 'Set', executing: 'Set', single: 'Set', no: 'Set' } }, delete: { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); }); describe('reload all', () => { const calledPaths = ['/', '/a', '/a/c', '/a/c/a', '/a/c/a/b']; const dirsByPath = (): string[] => get.dirs().map((d) => d.path); beforeEach(() => { mockLib.changeId(1); mockLib.selectNode('/a'); mockLib.selectNode('/a/c'); mockLib.selectNode('/a/c/a'); mockLib.selectNode('/a/c/a/b'); }); it('should reload all requested paths', () => { assert.lsDirHasBeenCalledWith(1, calledPaths); lsDirSpy.calls.reset(); assert.lsDirHasBeenCalledWith(1, []); component.refreshAllDirectories(); assert.lsDirHasBeenCalledWith(1, calledPaths); }); it('should reload all requested paths if not selected anything', () => { lsDirSpy.calls.reset(); mockLib.changeId(2); assert.lsDirHasBeenCalledWith(2, ['/']); lsDirSpy.calls.reset(); component.refreshAllDirectories(); assert.lsDirHasBeenCalledWith(2, ['/']); }); it('should add new directories', () => { // Create two new directories in preparation const dirsBeforeRefresh = dirsByPath(); expect(dirsBeforeRefresh.includes('/a/c/has_dir_now')).toBe(false); mockLib.mkDir('/a/c', 'has_dir_now', 0, 0); mockLib.mkDir('/a/c/a/b', 'has_dir_now_too', 0, 0); // Now the new directories will be fetched component.refreshAllDirectories(); const dirsAfterRefresh = dirsByPath(); expect(dirsAfterRefresh.length - dirsBeforeRefresh.length).toBe(2); expect(dirsAfterRefresh.includes('/a/c/has_dir_now')).toBe(true); expect(dirsAfterRefresh.includes('/a/c/a/b/has_dir_now_too')).toBe(true); }); it('should remove deleted directories', () => { // Create one new directory and refresh in order to have it added to the directories list mockLib.mkDir('/a/c', 'will_be_removed_shortly', 0, 0); component.refreshAllDirectories(); const dirsBeforeRefresh = dirsByPath(); expect(dirsBeforeRefresh.includes('/a/c/will_be_removed_shortly')).toBe(true); mockData.createdDirs = []; // Mocks the deletion of the directory // Now the deleted directory will be missing on refresh component.refreshAllDirectories(); const dirsAfterRefresh = dirsByPath(); expect(dirsAfterRefresh.length - dirsBeforeRefresh.length).toBe(-1); expect(dirsAfterRefresh.includes('/a/c/will_be_removed_shortly')).toBe(false); }); describe('loading indicator', () => { beforeEach(() => { noAsyncUpdate = true; }); it('should have set loading indicator to false after refreshing all dirs', fakeAsync(() => { component.refreshAllDirectories(); expect(component.loadingIndicator).toBe(true); tick(3000); // To resolve all promises expect(component.loadingIndicator).toBe(false); })); it('should only update the tree once and not on every call', fakeAsync(() => { const spy = spyOn(component.treeComponent, 'sizeChanged').and.callThrough(); component.refreshAllDirectories(); expect(spy).toHaveBeenCalledTimes(0); tick(3000); // To resolve all promises // Called during the interval and at the end of timeout expect(spy).toHaveBeenCalledTimes(2); })); it('should have set all loaded dirs as attribute names of "indicators"', () => { noAsyncUpdate = false; component.refreshAllDirectories(); expect(Object.keys(component.loading).sort()).toEqual(calledPaths); }); it('should set an indicator to true during load', () => { lsDirSpy.and.callFake(() => new Observable((): null => null)); component.refreshAllDirectories(); expect(Object.values(component.loading).every((b) => b)).toBe(true); expect(component.loadingIndicator).toBe(true); }); }); describe('disable create snapshot', () => { let actions: CdTableAction[]; beforeEach(() => { actions = component.snapshot.tableActions; mockLib.mkDir('/', 'volumes', 2, 2); mockLib.mkDir('/volumes', 'group1', 2, 2); mockLib.mkDir('/volumes/group1', 'subvol', 2, 2); mockLib.mkDir('/volumes/group1/subvol', 'subfile', 2, 2); }); const empty = (): CdTableSelection => new CdTableSelection(); it('should return a descriptive message to explain why it is disabled', () => { const path = '/volumes/group1/subvol/subfile'; const res = 'Cannot create snapshots for files/folders in the subvolume subvol'; mockLib.selectNode(path); expect(actions[0].disable(empty())).toContain(res); }); it('should return false if it is not a subvolume node', () => { const testCases = [ '/volumes/group1/subvol', '/volumes/group1', '/volumes', '/', '/a', '/a/b' ]; testCases.forEach((testCase) => { mockLib.selectNode(testCase); expect(actions[0].disable(empty())).toBeFalsy(); }); }); }); }); });
38,629
33.739209
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-directories/cephfs-directories.component.ts
import { Component, Input, OnChanges, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { AbstractControl, Validators } from '@angular/forms'; import { ITreeOptions, TreeComponent, TreeModel, TreeNode, TREE_ACTIONS } from '@circlon/angular-tree-component'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import moment from 'moment'; import { CephfsService } from '~/app/shared/api/cephfs.service'; import { ConfirmationModalComponent } from '~/app/shared/components/confirmation-modal/confirmation-modal.component'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { FormModalComponent } from '~/app/shared/components/form-modal/form-modal.component'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdValidators } from '~/app/shared/forms/cd-validators'; import { CdFormModalFieldConfig } from '~/app/shared/models/cd-form-modal-field-config'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { CephfsDir, CephfsQuotas, CephfsSnapshot } from '~/app/shared/models/cephfs-directory-models'; import { Permission } from '~/app/shared/models/permissions'; import { CdDatePipe } from '~/app/shared/pipes/cd-date.pipe'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; class QuotaSetting { row: { // Used in quota table name: string; value: number | string; originPath: string; }; quotaKey: string; dirValue: number; nextTreeMaximum: { value: number; path: string; }; } @Component({ selector: 'cd-cephfs-directories', templateUrl: './cephfs-directories.component.html', styleUrls: ['./cephfs-directories.component.scss'] }) export class CephfsDirectoriesComponent implements OnInit, OnChanges { @ViewChild(TreeComponent) treeComponent: TreeComponent; @ViewChild('origin', { static: true }) originTmpl: TemplateRef<any>; @Input() id: number; private modalRef: NgbModalRef; private dirs: CephfsDir[]; private nodeIds: { [path: string]: CephfsDir }; private requestedPaths: string[]; private loadingTimeout: any; icons = Icons; loadingIndicator = false; loading = {}; treeOptions: ITreeOptions = { useVirtualScroll: true, getChildren: (node: TreeNode): Promise<any[]> => { return this.updateDirectory(node.id); }, actionMapping: { mouse: { click: this.selectAndShowNode.bind(this), expanderClick: this.selectAndShowNode.bind(this) } } }; permission: Permission; selectedDir: CephfsDir; settings: QuotaSetting[]; quota: { columns: CdTableColumn[]; selection: CdTableSelection; tableActions: CdTableAction[]; updateSelection: Function; }; snapshot: { columns: CdTableColumn[]; selection: CdTableSelection; tableActions: CdTableAction[]; updateSelection: Function; }; nodes: any[]; alreadyExists: boolean; constructor( private authStorageService: AuthStorageService, private modalService: ModalService, private cephfsService: CephfsService, private cdDatePipe: CdDatePipe, private actionLabels: ActionLabelsI18n, private notificationService: NotificationService, private dimlessBinaryPipe: DimlessBinaryPipe ) {} private selectAndShowNode(tree: TreeModel, node: TreeNode, $event: any) { TREE_ACTIONS.TOGGLE_EXPANDED(tree, node, $event); this.selectNode(node); } private selectNode(node: TreeNode) { TREE_ACTIONS.TOGGLE_ACTIVE(undefined, node, undefined); this.selectedDir = this.getDirectory(node); if (node.id === '/') { return; } this.setSettings(node); } ngOnInit() { this.permission = this.authStorageService.getPermissions().cephfs; this.setUpQuotaTable(); this.setUpSnapshotTable(); } private setUpQuotaTable() { this.quota = { columns: [ { prop: 'row.name', name: $localize`Name`, flexGrow: 1 }, { prop: 'row.value', name: $localize`Value`, sortable: false, flexGrow: 1 }, { prop: 'row.originPath', name: $localize`Origin`, sortable: false, cellTemplate: this.originTmpl, flexGrow: 1 } ], selection: new CdTableSelection(), updateSelection: (selection: CdTableSelection) => { this.quota.selection = selection; }, tableActions: [ { name: this.actionLabels.SET, icon: Icons.edit, permission: 'update', visible: (selection) => !selection.hasSelection || (selection.first() && selection.first().dirValue === 0), click: () => this.updateQuotaModal() }, { name: this.actionLabels.UPDATE, icon: Icons.edit, permission: 'update', visible: (selection) => selection.first() && selection.first().dirValue > 0, click: () => this.updateQuotaModal() }, { name: this.actionLabels.UNSET, icon: Icons.destroy, permission: 'update', disable: (selection) => !selection.hasSelection || (selection.first() && selection.first().dirValue === 0), click: () => this.unsetQuotaModal() } ] }; } private setUpSnapshotTable() { this.snapshot = { columns: [ { prop: 'name', name: $localize`Name`, flexGrow: 1 }, { prop: 'path', name: $localize`Path`, isHidden: true, flexGrow: 2 }, { prop: 'created', name: $localize`Created`, flexGrow: 1, pipe: this.cdDatePipe } ], selection: new CdTableSelection(), updateSelection: (selection: CdTableSelection) => { this.snapshot.selection = selection; }, tableActions: [ { name: this.actionLabels.CREATE, icon: Icons.add, permission: 'create', canBePrimary: (selection) => !selection.hasSelection, click: () => this.createSnapshot(), disable: () => this.disableCreateSnapshot() }, { name: this.actionLabels.DELETE, icon: Icons.destroy, permission: 'delete', click: () => this.deleteSnapshotModal(), canBePrimary: (selection) => selection.hasSelection, disable: (selection) => !selection.hasSelection } ] }; } private disableCreateSnapshot(): string | boolean { const folders = this.selectedDir.path.split('/').slice(1); // With deph of 4 or more we have the subvolume files/folders for which we cannot create // a snapshot. Somehow, you can create a snapshot of the subvolume but not its files. if (folders.length >= 4 && folders[0] === 'volumes') { return $localize`Cannot create snapshots for files/folders in the subvolume ${folders[2]}`; } return false; } ngOnChanges() { this.selectedDir = undefined; this.dirs = []; this.requestedPaths = []; this.nodeIds = {}; if (this.id) { this.setRootNode(); this.firstCall(); } } private setRootNode() { this.nodes = [ { name: '/', id: '/', isExpanded: true } ]; } private firstCall() { const path = '/'; setTimeout(() => { this.getNode(path).loadNodeChildren(); }, 10); } updateDirectory(path: string): Promise<any[]> { this.unsetLoadingIndicator(); if (!this.requestedPaths.includes(path)) { this.requestedPaths.push(path); } else if (this.loading[path] === true) { return undefined; // Path is currently fetched. } return new Promise((resolve) => { this.setLoadingIndicator(path, true); this.cephfsService.lsDir(this.id, path).subscribe((dirs) => { this.updateTreeStructure(dirs); this.updateQuotaTable(); this.updateTree(); resolve(this.getChildren(path)); this.setLoadingIndicator(path, false); }); }); } private setLoadingIndicator(path: string, loading: boolean) { this.loading[path] = loading; this.unsetLoadingIndicator(); } private getSubDirectories(path: string, tree: CephfsDir[] = this.dirs): CephfsDir[] { return tree.filter((d) => d.parent === path); } private getChildren(path: string): any[] { const subTree = this.getSubTree(path); return _.sortBy(this.getSubDirectories(path), 'path').map((dir) => this.createNode(dir, subTree) ); } private createNode(dir: CephfsDir, subTree?: CephfsDir[]): any { this.nodeIds[dir.path] = dir; if (!subTree) { this.getSubTree(dir.parent); } return { name: dir.name, id: dir.path, hasChildren: this.getSubDirectories(dir.path, subTree).length > 0 }; } private getSubTree(path: string): CephfsDir[] { return this.dirs.filter((d) => d.parent && d.parent.startsWith(path)); } private setSettings(node: TreeNode) { const readable = (value: number, fn?: (arg0: number) => number | string): number | string => value ? (fn ? fn(value) : value) : ''; this.settings = [ this.getQuota(node, 'max_files', readable), this.getQuota(node, 'max_bytes', (value) => readable(value, (v) => this.dimlessBinaryPipe.transform(v)) ) ]; } private getQuota( tree: TreeNode, quotaKey: string, valueConvertFn: (number: number) => number | string ): QuotaSetting { // Get current maximum const currentPath = tree.id; tree = this.getOrigin(tree, quotaKey); const dir = this.getDirectory(tree); const value = dir.quotas[quotaKey]; // Get next tree maximum // => The value that isn't changeable through a change of the current directories quota value let nextMaxValue = value; let nextMaxPath = dir.path; if (tree.id === currentPath) { if (tree.parent.id === '/') { // The value will never inherit any other value, so it has no maximum. nextMaxValue = 0; } else { const nextMaxDir = this.getDirectory(this.getOrigin(tree.parent, quotaKey)); nextMaxValue = nextMaxDir.quotas[quotaKey]; nextMaxPath = nextMaxDir.path; } } return { row: { name: quotaKey === 'max_bytes' ? $localize`Max size` : $localize`Max files`, value: valueConvertFn(value), originPath: value ? dir.path : '' }, quotaKey, dirValue: this.nodeIds[currentPath].quotas[quotaKey], nextTreeMaximum: { value: nextMaxValue, path: nextMaxValue ? nextMaxPath : '' } }; } /** * Get the node where the quota limit originates from in the current node * * Example as it's a recursive method: * * | Path + Value | Call depth | useOrigin? | Output | * |:-------------:|:----------:|:---------------------:|:------:| * | /a/b/c/d (15) | 1st | 2nd (5) < 15 => false | /a/b | * | /a/b/c (20) | 2nd | 3rd (5) < 20 => false | /a/b | * | /a/b (5) | 3rd | 4th (10) < 5 => true | /a/b | * | /a (10) | 4th | 10 => true | /a | * */ private getOrigin(tree: TreeNode, quotaSetting: string): TreeNode { if (tree.parent && tree.parent.id !== '/') { const current = this.getQuotaFromTree(tree, quotaSetting); // Get the next used quota and node above the current one (until it hits the root directory) const originTree = this.getOrigin(tree.parent, quotaSetting); const inherited = this.getQuotaFromTree(originTree, quotaSetting); // Select if the current quota is in use or the above const useOrigin = current === 0 || (inherited !== 0 && inherited < current); return useOrigin ? originTree : tree; } return tree; } private getQuotaFromTree(tree: TreeNode, quotaSetting: string): number { return this.getDirectory(tree).quotas[quotaSetting]; } private getDirectory(node: TreeNode): CephfsDir { const path = node.id as string; return this.nodeIds[path]; } selectOrigin(path: string) { this.selectNode(this.getNode(path)); } private getNode(path: string): TreeNode { return this.treeComponent.treeModel.getNodeById(path); } updateQuotaModal() { const path = this.selectedDir.path; const selection: QuotaSetting = this.quota.selection.first(); const nextMax = selection.nextTreeMaximum; const key = selection.quotaKey; const value = selection.dirValue; this.modalService.show(FormModalComponent, { titleText: this.getModalQuotaTitle( value === 0 ? this.actionLabels.SET : this.actionLabels.UPDATE, path ), message: nextMax.value ? $localize`The inherited ${this.getQuotaValueFromPathMsg( nextMax.value, nextMax.path )} is the maximum value to be used.` : undefined, fields: [this.getQuotaFormField(selection.row.name, key, value, nextMax.value)], submitButtonText: $localize`Save`, onSubmit: (values: CephfsQuotas) => this.updateQuota(values) }); } private getModalQuotaTitle(action: string, path: string): string { return $localize`${action} CephFS ${this.getQuotaName()} quota for '${path}'`; } private getQuotaName(): string { return this.isBytesQuotaSelected() ? $localize`size` : $localize`files`; } private isBytesQuotaSelected(): boolean { return this.quota.selection.first().quotaKey === 'max_bytes'; } private getQuotaValueFromPathMsg(value: number, path: string): string { value = this.isBytesQuotaSelected() ? this.dimlessBinaryPipe.transform(value) : value; return $localize`${this.getQuotaName()} quota ${value} from '${path}'`; } private getQuotaFormField( label: string, name: string, value: number, maxValue: number ): CdFormModalFieldConfig { const isBinary = name === 'max_bytes'; const formValidators = [isBinary ? CdValidators.binaryMin(0) : Validators.min(0)]; if (maxValue) { formValidators.push(isBinary ? CdValidators.binaryMax(maxValue) : Validators.max(maxValue)); } const field: CdFormModalFieldConfig = { type: isBinary ? 'binary' : 'number', label, name, value, validators: formValidators, required: true }; if (!isBinary) { field.errors = { min: $localize`Value has to be at least 0 or more`, max: $localize`Value has to be at most ${maxValue} or less` }; } return field; } private updateQuota(values: CephfsQuotas, onSuccess?: Function) { const path = this.selectedDir.path; const key = this.quota.selection.first().quotaKey; const action = this.selectedDir.quotas[key] === 0 ? this.actionLabels.SET : values[key] === 0 ? this.actionLabels.UNSET : $localize`Updated`; this.cephfsService.quota(this.id, path, values).subscribe(() => { if (onSuccess) { onSuccess(); } this.notificationService.show( NotificationType.success, this.getModalQuotaTitle(action, path) ); this.forceDirRefresh(); }); } unsetQuotaModal() { const path = this.selectedDir.path; const selection: QuotaSetting = this.quota.selection.first(); const key = selection.quotaKey; const nextMax = selection.nextTreeMaximum; const dirValue = selection.dirValue; const quotaValue = this.getQuotaValueFromPathMsg(nextMax.value, nextMax.path); const conclusion = nextMax.value > 0 ? nextMax.value > dirValue ? $localize`in order to inherit ${quotaValue}` : $localize`which isn't used because of the inheritance of ${quotaValue}` : $localize`in order to have no quota on the directory`; this.modalRef = this.modalService.show(ConfirmationModalComponent, { titleText: this.getModalQuotaTitle(this.actionLabels.UNSET, path), buttonText: this.actionLabels.UNSET, description: $localize`${this.actionLabels.UNSET} ${this.getQuotaValueFromPathMsg( dirValue, path )} ${conclusion}.`, onSubmit: () => this.updateQuota({ [key]: 0 }, () => this.modalRef.close()) }); } createSnapshot() { // Create a snapshot. Auto-generate a snapshot name by default. const path = this.selectedDir.path; this.modalService.show(FormModalComponent, { titleText: $localize`Create Snapshot`, message: $localize`Please enter the name of the snapshot.`, fields: [ { type: 'text', name: 'name', value: `${moment().toISOString(true)}`, required: true, validators: [this.validateValue.bind(this)] } ], submitButtonText: $localize`Create Snapshot`, onSubmit: (values: CephfsSnapshot) => { if (!this.alreadyExists) { this.cephfsService.mkSnapshot(this.id, path, values.name).subscribe((name) => { this.notificationService.show( NotificationType.success, $localize`Created snapshot '${name}' for '${path}'` ); this.forceDirRefresh(); }); } else { this.notificationService.show( NotificationType.error, $localize`Snapshot name '${values.name}' is already in use. Please use another name.` ); } } }); } validateValue(control: AbstractControl) { this.alreadyExists = this.selectedDir.snapshots.some((s) => s.name === control.value); } /** * Forces an update of the current selected directory * * As all nodes point by their path on an directory object, the easiest way is to update * the objects by merge with their latest change. */ private forceDirRefresh(path?: string) { if (!path) { const dir = this.selectedDir; if (!dir) { throw new Error('This function can only be called without path if an selection was made'); } // Parent has to be called in order to update the object referring // to the current selected directory path = dir.parent ? dir.parent : dir.path; } const node = this.getNode(path); node.loadNodeChildren(); } private updateTreeStructure(dirs: CephfsDir[]) { const getChildrenAndPaths = ( directories: CephfsDir[], parent: string ): { children: CephfsDir[]; paths: string[] } => { const children = directories.filter((d) => d.parent === parent); const paths = children.map((d) => d.path); return { children, paths }; }; const parents = _.uniq(dirs.map((d) => d.parent).sort()); parents.forEach((p) => { const received = getChildrenAndPaths(dirs, p); const cached = getChildrenAndPaths(this.dirs, p); cached.children.forEach((d) => { if (!received.paths.includes(d.path)) { this.removeOldDirectory(d); } }); received.children.forEach((d) => { if (cached.paths.includes(d.path)) { this.updateExistingDirectory(cached.children, d); } else { this.addNewDirectory(d); } }); }); } private removeOldDirectory(rmDir: CephfsDir) { const path = rmDir.path; // Remove directory from local variables _.remove(this.dirs, (d) => d.path === path); delete this.nodeIds[path]; this.updateDirectoriesParentNode(rmDir); } private updateDirectoriesParentNode(dir: CephfsDir) { const parent = dir.parent; if (!parent) { return; } const node = this.getNode(parent); if (!node) { // Node will not be found for new sub sub directories - this is the intended behaviour return; } const children = this.getChildren(parent); node.data.children = children; node.data.hasChildren = children.length > 0; this.treeComponent.treeModel.update(); } private addNewDirectory(newDir: CephfsDir) { this.dirs.push(newDir); this.nodeIds[newDir.path] = newDir; this.updateDirectoriesParentNode(newDir); } private updateExistingDirectory(source: CephfsDir[], updatedDir: CephfsDir) { const currentDirObject = source.find((sub) => sub.path === updatedDir.path); Object.assign(currentDirObject, updatedDir); } private updateQuotaTable() { const node = this.selectedDir ? this.getNode(this.selectedDir.path) : undefined; if (node && node.id !== '/') { this.setSettings(node); } } private updateTree(force: boolean = false) { if (this.loadingIndicator && !force) { // In order to make the page scrollable during load, the render cycle for each node // is omitted and only be called if all updates were loaded. return; } this.treeComponent.treeModel.update(); this.nodes = [...this.nodes]; this.treeComponent.sizeChanged(); } deleteSnapshotModal() { this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: $localize`CephFs Snapshot`, itemNames: this.snapshot.selection.selected.map((snapshot: CephfsSnapshot) => snapshot.name), submitAction: () => this.deleteSnapshot() }); } deleteSnapshot() { const path = this.selectedDir.path; this.snapshot.selection.selected.forEach((snapshot: CephfsSnapshot) => { const name = snapshot.name; this.cephfsService.rmSnapshot(this.id, path, name).subscribe(() => { this.notificationService.show( NotificationType.success, $localize`Deleted snapshot '${name}' for '${path}'` ); }); }); this.modalRef.close(); this.forceDirRefresh(); } refreshAllDirectories() { // In order to make the page scrollable during load, the render cycle for each node // is omitted and only be called if all updates were loaded. this.loadingIndicator = true; this.requestedPaths.map((path) => this.forceDirRefresh(path)); const interval = setInterval(() => { this.updateTree(true); if (!this.loadingIndicator) { clearInterval(interval); } }, 3000); } unsetLoadingIndicator() { if (!this.loadingIndicator) { return; } clearTimeout(this.loadingTimeout); this.loadingTimeout = setTimeout(() => { const loading = Object.values(this.loading).some((l) => l); if (loading) { return this.unsetLoadingIndicator(); } this.loadingIndicator = false; this.updateTree(); // The problem is that we can't subscribe to an useful updated tree event and the time // between fetching all calls and rebuilding the tree can take some time }, 3000); } }
23,415
30.901907
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-list/cephfs-list.component.html
<cd-table [data]="filesystems" columnMode="flex" [columns]="columns" (fetchData)="loadFilesystems($event)" identifier="id" forceIdentifier="true" selectionType="single" [hasDetails]="true" (setExpandedRow)="setExpandedRow($event)" (updateSelection)="updateSelection($event)"> <cd-cephfs-tabs cdTableDetail [selection]="expandedRow"> </cd-cephfs-tabs> </cd-table>
475
30.733333
54
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-list/cephfs-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { Component, Input } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { CephfsListComponent } from './cephfs-list.component'; @Component({ selector: 'cd-cephfs-tabs', template: '' }) class CephfsTabsStubComponent { @Input() selection: CdTableSelection; } describe('CephfsListComponent', () => { let component: CephfsListComponent; let fixture: ComponentFixture<CephfsListComponent>; configureTestBed({ imports: [BrowserAnimationsModule, SharedModule, HttpClientTestingModule], declarations: [CephfsListComponent, CephfsTabsStubComponent] }); beforeEach(() => { fixture = TestBed.createComponent(CephfsListComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,206
32.527778
79
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-list/cephfs-list.component.ts
import { Component, OnInit } from '@angular/core'; import { CephfsService } from '~/app/shared/api/cephfs.service'; import { ListWithDetails } from '~/app/shared/classes/list-with-details.class'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { CdDatePipe } from '~/app/shared/pipes/cd-date.pipe'; @Component({ selector: 'cd-cephfs-list', templateUrl: './cephfs-list.component.html', styleUrls: ['./cephfs-list.component.scss'] }) export class CephfsListComponent extends ListWithDetails implements OnInit { columns: CdTableColumn[]; filesystems: any = []; selection = new CdTableSelection(); constructor(private cephfsService: CephfsService, private cdDatePipe: CdDatePipe) { super(); } ngOnInit() { this.columns = [ { name: $localize`Name`, prop: 'mdsmap.fs_name', flexGrow: 2 }, { name: $localize`Created`, prop: 'mdsmap.created', flexGrow: 2, pipe: this.cdDatePipe }, { name: $localize`Enabled`, prop: 'mdsmap.enabled', flexGrow: 1, cellTransformation: CellTemplate.checkIcon } ]; } loadFilesystems(context: CdTableFetchDataContext) { this.cephfsService.list().subscribe( (resp: any[]) => { this.filesystems = resp; }, () => { context.error(); } ); } updateSelection(selection: CdTableSelection) { this.selection = selection; } }
1,720
26.758065
90
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-tabs/cephfs-tabs.component.html
<ng-container *ngIf="selection"> <nav ngbNav #nav="ngbNav" (navChange)="softRefresh()" class="nav-tabs" cdStatefulTab="cephfs-tabs"> <ng-container ngbNavItem="details"> <a ngbNavLink i18n>Details</a> <ng-template ngbNavContent> <cd-cephfs-detail [data]="details"> </cd-cephfs-detail> </ng-template> </ng-container> <ng-container ngbNavItem="clients"> <a ngbNavLink> <ng-container i18n>Clients</ng-container> <span class="badge badge-pill badge-tab ms-1">{{ clients.data.length }}</span> </a> <ng-template ngbNavContent> <cd-cephfs-clients [id]="id" [clients]="clients" (triggerApiUpdate)="refresh()"> </cd-cephfs-clients> </ng-template> </ng-container> <ng-container ngbNavItem="directories"> <a ngbNavLink i18n>Directories</a> <ng-template ngbNavContent> <cd-cephfs-directories [id]="id"></cd-cephfs-directories> </ng-template> </ng-container> <ng-container ngbNavItem="performance-details"> <a ngbNavLink i18n>Performance Details</a> <ng-template ngbNavContent> <cd-grafana i18n-title title="CephFS MDS performance" [grafanaPath]="'mds-performance?var-mds_servers=mds.' + grafanaId" [type]="'metrics'" uid="tbO9LAiZz" grafanaStyle="one"> </cd-grafana> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="nav"></div> </ng-container>
1,639
31.156863
86
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-tabs/cephfs-tabs.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { Component, Input } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { TreeModule } from '@circlon/angular-tree-component'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { CephfsService } from '~/app/shared/api/cephfs.service'; import { TableStatusViewCache } from '~/app/shared/classes/table-status-view-cache'; import { ViewCacheStatus } from '~/app/shared/enum/view-cache-status.enum'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { CephfsClientsComponent } from '../cephfs-clients/cephfs-clients.component'; import { CephfsDetailComponent } from '../cephfs-detail/cephfs-detail.component'; import { CephfsDirectoriesComponent } from '../cephfs-directories/cephfs-directories.component'; import { CephfsTabsComponent } from './cephfs-tabs.component'; describe('CephfsTabsComponent', () => { let component: CephfsTabsComponent; let fixture: ComponentFixture<CephfsTabsComponent>; let service: CephfsService; let data: { standbys: string; pools: any[]; ranks: any[]; mdsCounters: object; name: string; clients: { status: ViewCacheStatus; data: any[] }; }; let old: any; const getReload: any = () => component['reloadSubscriber']; const setReload = (sth?: any) => (component['reloadSubscriber'] = sth); const mockRunOutside = () => { component['subscribeInterval'] = () => { // It's mocked because the rxjs timer subscription isn't called through the use of 'tick'. setReload({ unsubscribed: false, unsubscribe: () => { old = getReload(); getReload().unsubscribed = true; setReload(); } }); component.refresh(); }; }; const setSelection = (selection: any) => { component.selection = selection; component.ngOnChanges(); }; const selectFs = (id: number, name: string) => { setSelection({ id, mdsmap: { info: { something: { name } } } }); }; const updateData = () => { component['data'] = _.cloneDeep(data); component.softRefresh(); }; @Component({ selector: 'cd-cephfs-chart', template: '' }) class CephfsChartStubComponent { @Input() mdsCounter: any; } configureTestBed({ imports: [ SharedModule, NgbNavModule, HttpClientTestingModule, TreeModule, ToastrModule.forRoot() ], declarations: [ CephfsTabsComponent, CephfsChartStubComponent, CephfsDetailComponent, CephfsDirectoriesComponent, CephfsClientsComponent ] }); beforeEach(() => { fixture = TestBed.createComponent(CephfsTabsComponent); component = fixture.componentInstance; component.selection = undefined; data = { standbys: 'b', pools: [{}, {}], ranks: [{}, {}, {}], mdsCounters: { a: { name: 'a', x: [], y: [] } }, name: 'someFs', clients: { status: ViewCacheStatus.ValueOk, data: [{}, {}, {}, {}] } }; service = TestBed.inject(CephfsService); spyOn(service, 'getTabs').and.callFake(() => of(data)); fixture.detectChanges(); mockRunOutside(); setReload(); // Clears rxjs timer subscription }); it('should create', () => { expect(component).toBeTruthy(); }); it('should resist invalid mds info', () => { setSelection({ id: 3, mdsmap: { info: {} } }); expect(component.grafanaId).toBe(undefined); }); it('should find out the grafana id', () => { selectFs(2, 'otherMds'); expect(component.grafanaId).toBe('otherMds'); }); it('should set default values on id change before api request', () => { const defaultDetails: Record<string, any> = { standbys: '', pools: [], ranks: [], mdsCounters: {}, name: '' }; const defaultClients: Record<string, any> = { data: [], status: new TableStatusViewCache(ViewCacheStatus.ValueNone) }; component['subscribeInterval'] = () => undefined; updateData(); expect(component.clients).not.toEqual(defaultClients); expect(component.details).not.toEqual(defaultDetails); selectFs(2, 'otherMds'); expect(component.clients).toEqual(defaultClients); expect(component.details).toEqual(defaultDetails); }); it('should force data updates on tab change without api requests', () => { const oldClients = component.clients; const oldDetails = component.details; updateData(); expect(service.getTabs).toHaveBeenCalledTimes(0); expect(component.details).not.toBe(oldDetails); expect(component.clients).not.toBe(oldClients); }); describe('handling of id change', () => { beforeEach(() => { setReload(); // Clears rxjs timer subscription selectFs(2, 'otherMds'); old = getReload(); // Gets current subscription }); it('should have called getDetails once', () => { expect(component.details.pools.length).toBe(2); expect(service.getTabs).toHaveBeenCalledTimes(1); }); it('should not subscribe to an new interval for the same selection', () => { expect(component.id).toBe(2); expect(component.grafanaId).toBe('otherMds'); selectFs(2, 'otherMds'); expect(component.id).toBe(2); expect(component.grafanaId).toBe('otherMds'); expect(getReload()).toBe(old); }); it('should subscribe to an new interval', () => { selectFs(3, 'anotherMds'); expect(getReload()).not.toBe(old); // Holds an new object }); it('should unsubscribe the old interval if it exists', () => { selectFs(3, 'anotherMds'); expect(old.unsubscribed).toBe(true); }); it('should not unsubscribe if no interval exists', () => { expect(() => component.ngOnDestroy()).not.toThrow(); }); it('should request the details of the new id', () => { expect(service.getTabs).toHaveBeenCalledWith(2); }); it('should should unsubscribe on deselect', () => { setSelection(undefined); expect(old.unsubscribed).toBe(true); expect(getReload()).toBe(undefined); // Cleared timer subscription }); }); });
6,457
28.898148
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cephfs/cephfs-tabs/cephfs-tabs.component.ts
import { Component, Input, NgZone, OnChanges, OnDestroy } from '@angular/core'; import _ from 'lodash'; import { Subscription, timer } from 'rxjs'; import { CephfsService } from '~/app/shared/api/cephfs.service'; import { TableStatusViewCache } from '~/app/shared/classes/table-status-view-cache'; import { ViewCacheStatus } from '~/app/shared/enum/view-cache-status.enum'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; @Component({ selector: 'cd-cephfs-tabs', templateUrl: './cephfs-tabs.component.html', styleUrls: ['./cephfs-tabs.component.scss'] }) export class CephfsTabsComponent implements OnChanges, OnDestroy { @Input() selection: any; // Grafana tab grafanaId: any; grafanaPermission: Permission; // Client tab id: number; clients: Record<string, any> = { data: [], status: new TableStatusViewCache(ViewCacheStatus.ValueNone) }; // Details tab details: Record<string, any> = { standbys: '', pools: [], ranks: [], mdsCounters: {}, name: '' }; private data: any; private reloadSubscriber: Subscription; constructor( private ngZone: NgZone, private authStorageService: AuthStorageService, private cephfsService: CephfsService ) { this.grafanaPermission = this.authStorageService.getPermissions().grafana; } ngOnChanges() { if (!this.selection) { this.unsubscribeInterval(); return; } if (this.selection.id !== this.id) { this.setupSelected(this.selection.id, this.selection.mdsmap.info); } } private setupSelected(id: number, mdsInfo: any) { this.id = id; const firstMds: any = _.first(Object.values(mdsInfo)); this.grafanaId = firstMds && firstMds['name']; this.details = { standbys: '', pools: [], ranks: [], mdsCounters: {}, name: '' }; this.clients = { data: [], status: new TableStatusViewCache(ViewCacheStatus.ValueNone) }; this.updateInterval(); } private updateInterval() { this.unsubscribeInterval(); this.subscribeInterval(); } private unsubscribeInterval() { if (this.reloadSubscriber) { this.reloadSubscriber.unsubscribe(); } } private subscribeInterval() { this.ngZone.runOutsideAngular( () => (this.reloadSubscriber = timer(0, 5000).subscribe(() => this.ngZone.run(() => this.refresh()) )) ); } refresh() { this.cephfsService.getTabs(this.id).subscribe( (data: any) => { this.data = data; this.softRefresh(); }, () => { this.clients.status = new TableStatusViewCache(ViewCacheStatus.ValueException); } ); } softRefresh() { const data = _.cloneDeep(this.data); // Forces update of tab tables on tab switch // Clients tab this.clients = data.clients; this.clients.status = new TableStatusViewCache(this.clients.status); // Details tab this.details = { standbys: data.standbys, pools: data.pools, ranks: data.ranks, mdsCounters: data.mds_counters, name: data.name }; } ngOnDestroy() { this.unsubscribeInterval(); } }
3,252
23.832061
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/cluster.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { TreeModule } from '@circlon/angular-tree-component'; import { NgbActiveModal, NgbDatepickerModule, NgbDropdownModule, NgbNavModule, NgbPopoverModule, NgbTimepickerModule, NgbTooltipModule, NgbTypeaheadModule } from '@ng-bootstrap/ng-bootstrap'; import { NgxPipeFunctionModule } from 'ngx-pipe-function'; import { SharedModule } from '~/app/shared/shared.module'; import { PerformanceCounterModule } from '../performance-counter/performance-counter.module'; import { CephSharedModule } from '../shared/ceph-shared.module'; import { ConfigurationDetailsComponent } from './configuration/configuration-details/configuration-details.component'; import { ConfigurationFormComponent } from './configuration/configuration-form/configuration-form.component'; import { ConfigurationComponent } from './configuration/configuration.component'; import { CreateClusterReviewComponent } from './create-cluster/create-cluster-review.component'; import { CreateClusterComponent } from './create-cluster/create-cluster.component'; import { CrushmapComponent } from './crushmap/crushmap.component'; import { HostDetailsComponent } from './hosts/host-details/host-details.component'; import { HostFormComponent } from './hosts/host-form/host-form.component'; import { HostsComponent } from './hosts/hosts.component'; import { InventoryDevicesComponent } from './inventory/inventory-devices/inventory-devices.component'; import { InventoryComponent } from './inventory/inventory.component'; import { LogsComponent } from './logs/logs.component'; import { MgrModulesModule } from './mgr-modules/mgr-modules.module'; import { MonitorComponent } from './monitor/monitor.component'; import { OsdCreationPreviewModalComponent } from './osd/osd-creation-preview-modal/osd-creation-preview-modal.component'; import { OsdDetailsComponent } from './osd/osd-details/osd-details.component'; import { OsdDevicesSelectionGroupsComponent } from './osd/osd-devices-selection-groups/osd-devices-selection-groups.component'; import { OsdDevicesSelectionModalComponent } from './osd/osd-devices-selection-modal/osd-devices-selection-modal.component'; import { OsdFlagsIndivModalComponent } from './osd/osd-flags-indiv-modal/osd-flags-indiv-modal.component'; import { OsdFlagsModalComponent } from './osd/osd-flags-modal/osd-flags-modal.component'; import { OsdFormComponent } from './osd/osd-form/osd-form.component'; import { OsdListComponent } from './osd/osd-list/osd-list.component'; import { OsdPgScrubModalComponent } from './osd/osd-pg-scrub-modal/osd-pg-scrub-modal.component'; import { OsdRecvSpeedModalComponent } from './osd/osd-recv-speed-modal/osd-recv-speed-modal.component'; import { OsdReweightModalComponent } from './osd/osd-reweight-modal/osd-reweight-modal.component'; import { OsdScrubModalComponent } from './osd/osd-scrub-modal/osd-scrub-modal.component'; import { ActiveAlertListComponent } from './prometheus/active-alert-list/active-alert-list.component'; import { PrometheusTabsComponent } from './prometheus/prometheus-tabs/prometheus-tabs.component'; import { RulesListComponent } from './prometheus/rules-list/rules-list.component'; import { SilenceFormComponent } from './prometheus/silence-form/silence-form.component'; import { SilenceListComponent } from './prometheus/silence-list/silence-list.component'; import { SilenceMatcherModalComponent } from './prometheus/silence-matcher-modal/silence-matcher-modal.component'; import { PlacementPipe } from './services/placement.pipe'; import { ServiceDaemonListComponent } from './services/service-daemon-list/service-daemon-list.component'; import { ServiceDetailsComponent } from './services/service-details/service-details.component'; import { ServiceFormComponent } from './services/service-form/service-form.component'; import { ServicesComponent } from './services/services.component'; import { TelemetryComponent } from './telemetry/telemetry.component'; import { UpgradeComponent } from './upgrade/upgrade.component'; @NgModule({ imports: [ CommonModule, PerformanceCounterModule, NgbNavModule, SharedModule, RouterModule, FormsModule, ReactiveFormsModule, NgbTooltipModule, MgrModulesModule, NgbTypeaheadModule, NgbTimepickerModule, TreeModule, CephSharedModule, NgbDatepickerModule, NgbPopoverModule, NgbDropdownModule, NgxPipeFunctionModule ], declarations: [ HostsComponent, MonitorComponent, ConfigurationComponent, OsdListComponent, OsdDetailsComponent, OsdScrubModalComponent, OsdFlagsModalComponent, HostDetailsComponent, ConfigurationDetailsComponent, ConfigurationFormComponent, OsdReweightModalComponent, CrushmapComponent, LogsComponent, OsdRecvSpeedModalComponent, OsdPgScrubModalComponent, OsdRecvSpeedModalComponent, SilenceFormComponent, SilenceListComponent, SilenceMatcherModalComponent, ServicesComponent, InventoryComponent, HostFormComponent, OsdFormComponent, OsdDevicesSelectionModalComponent, InventoryDevicesComponent, OsdDevicesSelectionGroupsComponent, OsdCreationPreviewModalComponent, RulesListComponent, ActiveAlertListComponent, ServiceDetailsComponent, ServiceDaemonListComponent, TelemetryComponent, PrometheusTabsComponent, ServiceFormComponent, OsdFlagsIndivModalComponent, PlacementPipe, CreateClusterComponent, CreateClusterReviewComponent, UpgradeComponent ], providers: [NgbActiveModal] }) export class ClusterModule {}
5,776
44.849206
127
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/configuration/configuration.component.html
<cd-table [data]="data" (fetchData)="getConfigurationList($event)" [columns]="columns" [extraFilterableColumns]="filters" selectionType="single" [hasDetails]="true" (setExpandedRow)="setExpandedRow($event)" (updateSelection)="updateSelection($event)"> <cd-table-actions class="table-actions" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> <cd-configuration-details cdTableDetail [selection]="expandedRow"> </cd-configuration-details> </cd-table> <ng-template #confValTpl let-value="value"> <span *ngIf="value"> <span *ngFor="let conf of value; last as isLast"> {{ conf.section }}: {{ conf.value }}{{ !isLast ? "," : "" }}<br /> </span> </span> </ng-template>
911
32.777778
72
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/configuration/configuration.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { ConfigurationDetailsComponent } from './configuration-details/configuration-details.component'; import { ConfigurationComponent } from './configuration.component'; describe('ConfigurationComponent', () => { let component: ConfigurationComponent; let fixture: ComponentFixture<ConfigurationComponent>; configureTestBed({ declarations: [ConfigurationComponent, ConfigurationDetailsComponent], imports: [ BrowserAnimationsModule, SharedModule, FormsModule, NgbNavModule, HttpClientTestingModule, RouterTestingModule ] }); beforeEach(() => { fixture = TestBed.createComponent(ConfigurationComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should check header text', () => { expect(fixture.debugElement.query(By.css('.datatable-header')).nativeElement.textContent).toBe( ['Name', 'Description', 'Current value', 'Default', 'Editable'].join('') ); }); });
1,619
33.468085
104
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/configuration/configuration.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { ConfigurationService } from '~/app/shared/api/configuration.service'; import { ListWithDetails } from '~/app/shared/classes/list-with-details.class'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; @Component({ selector: 'cd-configuration', templateUrl: './configuration.component.html', styleUrls: ['./configuration.component.scss'] }) export class ConfigurationComponent extends ListWithDetails implements OnInit { permission: Permission; tableActions: CdTableAction[]; data: any[] = []; icons = Icons; columns: CdTableColumn[]; selection = new CdTableSelection(); filters: CdTableColumn[] = [ { name: $localize`Level`, prop: 'level', filterOptions: ['basic', 'advanced', 'dev'], filterInitValue: 'basic', filterPredicate: (row, value) => { enum Level { basic = 0, advanced = 1, dev = 2 } const levelVal = Level[value]; return Level[row.level] <= levelVal; } }, { name: $localize`Service`, prop: 'services', filterOptions: ['mon', 'mgr', 'osd', 'mds', 'common', 'mds_client', 'rgw'], filterPredicate: (row, value) => { return row.services.includes(value); } }, { name: $localize`Source`, prop: 'source', filterOptions: ['mon'], filterPredicate: (row, value) => { if (!row.hasOwnProperty('source')) { return false; } return row.source.includes(value); } }, { name: $localize`Modified`, prop: 'modified', filterOptions: ['yes', 'no'], filterPredicate: (row, value) => { if (value === 'yes' && row.hasOwnProperty('value')) { return true; } if (value === 'no' && !row.hasOwnProperty('value')) { return true; } return false; } } ]; @ViewChild('confValTpl', { static: true }) public confValTpl: TemplateRef<any>; @ViewChild('confFlagTpl') public confFlagTpl: TemplateRef<any>; constructor( private authStorageService: AuthStorageService, private configurationService: ConfigurationService, public actionLabels: ActionLabelsI18n ) { super(); this.permission = this.authStorageService.getPermissions().configOpt; const getConfigOptUri = () => this.selection.first() && `${encodeURIComponent(this.selection.first().name)}`; const editAction: CdTableAction = { permission: 'update', icon: Icons.edit, routerLink: () => `/configuration/edit/${getConfigOptUri()}`, name: this.actionLabels.EDIT, disable: () => !this.isEditable(this.selection) }; this.tableActions = [editAction]; } ngOnInit() { this.columns = [ { canAutoResize: true, prop: 'name', name: $localize`Name` }, { prop: 'desc', name: $localize`Description`, cellClass: 'wrap' }, { prop: 'value', name: $localize`Current value`, cellClass: 'wrap', cellTemplate: this.confValTpl }, { prop: 'default', name: $localize`Default`, cellClass: 'wrap' }, { prop: 'can_update_at_runtime', name: $localize`Editable`, cellTransformation: CellTemplate.checkIcon, flexGrow: 0.4, cellClass: 'text-center' } ]; } updateSelection(selection: CdTableSelection) { this.selection = selection; } getConfigurationList(context: CdTableFetchDataContext) { this.configurationService.getConfigData().subscribe( (data: any) => { this.data = data; }, () => { context.error(); } ); } isEditable(selection: CdTableSelection): boolean { if (selection.selected.length !== 1) { return false; } return selection.selected[0].can_update_at_runtime; } }
4,498
28.993333
90
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/configuration/configuration-details/configuration-details.component.html
<ng-container *ngIf="selection"> <table class="table table-striped table-bordered"> <tbody> <tr> <td i18n class="bold w-25">Name</td> <td class="w-75">{{ selection.name }}</td> </tr> <tr> <td i18n class="bold">Description</td> <td>{{ selection.desc }}</td> </tr> <tr> <td i18n class="bold">Long description</td> <td>{{ selection.long_desc }}</td> </tr> <tr> <td i18n class="bold">Current values</td> <td> <span *ngFor="let conf of selection.value; last as isLast"> {{ conf.section }}: {{ conf.value }}{{ !isLast ? "," : "" }}<br /> </span> </td> </tr> <tr> <td i18n class="bold">Default</td> <td>{{ selection.default }}</td> </tr> <tr> <td i18n class="bold">Daemon default</td> <td>{{ selection.daemon_default }}</td> </tr> <tr> <td i18n class="bold">Type</td> <td>{{ selection.type }}</td> </tr> <tr> <td i18n class="bold">Min</td> <td>{{ selection.min }}</td> </tr> <tr> <td i18n class="bold">Max</td> <td>{{ selection.max }}</td> </tr> <tr> <td i18n class="bold">Flags</td> <td> <span *ngFor="let flag of selection.flags"> <span title="{{ flags[flag] }}"> <span class="badge badge-dark me-2">{{ flag | uppercase }}</span> </span> </span> </td> </tr> <tr> <td i18n class="bold">Services</td> <td> <span *ngFor="let service of selection.services"> <span class="badge badge-dark me-2">{{ service }}</span> </span> </td> </tr> <tr> <td i18n class="bold">Source</td> <td>{{ selection.source }}</td> </tr> <tr> <td i18n class="bold">Level</td> <td>{{ selection.level }}</td> </tr> <tr> <td i18n class="bold">Can be updated at runtime (editable)</td> <td>{{ selection.can_update_at_runtime | booleanText }}</td> </tr> <tr> <td i18n class="bold">Tags</td> <td>{{ selection.tags }}</td> </tr> <tr> <td i18n class="bold">Enum values</td> <td>{{ selection.enum_values }}</td> </tr> <tr> <td i18n class="bold">See also</td> <td>{{ selection.see_also }}</td> </tr> </tbody> </table> </ng-container>
2,727
24.735849
79
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/configuration/configuration-details/configuration-details.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { DataTableModule } from '~/app/shared/datatable/datatable.module'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { ConfigurationDetailsComponent } from './configuration-details.component'; describe('ConfigurationDetailsComponent', () => { let component: ConfigurationDetailsComponent; let fixture: ComponentFixture<ConfigurationDetailsComponent>; configureTestBed({ declarations: [ConfigurationDetailsComponent], imports: [DataTableModule, SharedModule] }); beforeEach(() => { fixture = TestBed.createComponent(ConfigurationDetailsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
882
31.703704
82
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/configuration/configuration-details/configuration-details.component.ts
import { Component, Input, OnChanges } from '@angular/core'; import _ from 'lodash'; @Component({ selector: 'cd-configuration-details', templateUrl: './configuration-details.component.html', styleUrls: ['./configuration-details.component.scss'] }) export class ConfigurationDetailsComponent implements OnChanges { @Input() selection: any; flags = { runtime: $localize`The value can be updated at runtime.`, no_mon_update: $localize`Daemons/clients do not pull this value from the monitor config database. We disallow setting this option via 'ceph config set ...'. This option should be configured via ceph.conf or via the command line.`, startup: $localize`Option takes effect only during daemon startup.`, cluster_create: $localize`Option only affects cluster creation.`, create: $localize`Option only affects daemon creation.` }; ngOnChanges() { if (this.selection) { this.selection.services = _.split(this.selection.services, ','); } } }
1,014
32.833333
79
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/configuration/configuration-form/configuration-form-create-request.model.ts
export class ConfigFormCreateRequestModel { name: string; value: Array<any> = []; }
88
16.8
43
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/configuration/configuration-form/configuration-form.component.html
<div class="cd-col-form" *cdFormLoading="loading"> <form name="configForm" #formDir="ngForm" [formGroup]="configForm" novalidate> <div class="card"> <div class="card-header"> <ng-container i18>Edit</ng-container> {{ configForm.getValue('name') }} </div> <div class="card-body"> <!-- Name --> <div class="form-group row"> <label i18n class="cd-col-form-label">Name</label> <div class="cd-col-form-input"> <input class="form-control" type="text" id="name" formControlName="name" readonly> </div> </div> <!-- Description --> <div class="form-group row" *ngIf="configForm.getValue('desc')"> <label i18n class="cd-col-form-label">Description</label> <div class="cd-col-form-input"> <textarea class="form-control resize-vertical" id="desc" formControlName="desc" readonly> </textarea> </div> </div> <!-- Long description --> <div class="form-group row" *ngIf="configForm.getValue('long_desc')"> <label i18n class="cd-col-form-label">Long description</label> <div class="cd-col-form-input"> <textarea class="form-control resize-vertical" id="long_desc" formControlName="long_desc" readonly> </textarea> </div> </div> <!-- Default --> <div class="form-group row" *ngIf="configForm.getValue('default') !== ''"> <label i18n class="cd-col-form-label">Default</label> <div class="cd-col-form-input"> <input class="form-control" type="text" id="default" formControlName="default" readonly> </div> </div> <!-- Daemon default --> <div class="form-group row" *ngIf="configForm.getValue('daemon_default') !== ''"> <label i18n class="cd-col-form-label">Daemon default</label> <div class="cd-col-form-input"> <input class="form-control" type="text" id="daemon_default" formControlName="daemon_default" readonly> </div> </div> <!-- Services --> <div class="form-group row" *ngIf="configForm.getValue('services').length > 0"> <label i18n class="cd-col-form-label">Services</label> <div class="cd-col-form-input"> <span *ngFor="let service of configForm.getValue('services')" class="form-component-badge"> <span class="badge badge-dark">{{ service }}</span> </span> </div> </div> <!-- Values --> <div formGroupName="values"> <h3 i18n class="cd-header">Values</h3> <ng-container *ngFor="let section of availSections"> <div class="form-group row" *ngIf="type === 'bool'"> <label class="cd-col-form-label" [for]="section">{{ section }} </label> <div class="cd-col-form-input"> <select id="pool" name="pool" class="form-select" [formControlName]="section"> <option [ngValue]="null" i18n>-- Default --</option> <option [ngValue]="true" i18n>true</option> <option [ngValue]="false" i18n>false</option> </select> </div> </div> <div class="form-group row" *ngIf="type !== 'bool'"> <label class="cd-col-form-label" [for]="section">{{ section }} </label> <div class="cd-col-form-input"> <input class="form-control" [type]="inputType" [id]="section" [placeholder]="humanReadableType" [formControlName]="section" [step]="getStep(type, this.configForm.getValue(section))"> <span class="invalid-feedback" *ngIf="configForm.showError(section, formDir, 'pattern')"> {{ patternHelpText }} </span> <span class="invalid-feedback" *ngIf="configForm.showError(section, formDir, 'invalidUuid')"> {{ patternHelpText }} </span> <span class="invalid-feedback" *ngIf="configForm.showError(section, formDir, 'max')" i18n>The entered value is too high! It must not be greater than {{ maxValue }}.</span> <span class="invalid-feedback" *ngIf="configForm.showError(section, formDir, 'min')" i18n>The entered value is too low! It must not be lower than {{ minValue }}.</span> </div> </div> </ng-container> </div> </div> <!-- Footer --> <div class="card-footer"> <cd-form-button-panel (submitActionEvent)="submit()" [form]="configForm" [submitText]="actionLabels.UPDATE" wrappingClass="text-right"></cd-form-button-panel> </div> </div> </form> </div>
5,920
35.776398
108
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/configuration/configuration-form/configuration-form.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { ConfigFormModel } from '~/app/shared/components/config-option/config-option.model'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { ConfigurationFormComponent } from './configuration-form.component'; describe('ConfigurationFormComponent', () => { let component: ConfigurationFormComponent; let fixture: ComponentFixture<ConfigurationFormComponent>; configureTestBed({ imports: [ HttpClientTestingModule, ReactiveFormsModule, RouterTestingModule, ToastrModule.forRoot(), SharedModule ], declarations: [ConfigurationFormComponent] }); beforeEach(() => { fixture = TestBed.createComponent(ConfigurationFormComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); describe('getValidators', () => { it('should return a validator for types float, addr and uuid', () => { const types = ['float', 'addr', 'uuid']; types.forEach((valType) => { const configOption = new ConfigFormModel(); configOption.type = valType; const ret = component.getValidators(configOption); expect(ret).toBeTruthy(); expect(ret.length).toBe(1); }); }); it('should not return a validator for types str and bool', () => { const types = ['str', 'bool']; types.forEach((valType) => { const configOption = new ConfigFormModel(); configOption.type = valType; const ret = component.getValidators(configOption); expect(ret).toBeUndefined(); }); }); it('should return a pattern and a min validator', () => { const configOption = new ConfigFormModel(); configOption.type = 'int'; configOption.min = 2; const ret = component.getValidators(configOption); expect(ret).toBeTruthy(); expect(ret.length).toBe(2); expect(component.minValue).toBe(2); expect(component.maxValue).toBeUndefined(); }); it('should return a pattern and a max validator', () => { const configOption = new ConfigFormModel(); configOption.type = 'int'; configOption.max = 5; const ret = component.getValidators(configOption); expect(ret).toBeTruthy(); expect(ret.length).toBe(2); expect(component.minValue).toBeUndefined(); expect(component.maxValue).toBe(5); }); it('should return multiple validators', () => { const configOption = new ConfigFormModel(); configOption.type = 'float'; configOption.max = 5.2; configOption.min = 1.5; const ret = component.getValidators(configOption); expect(ret).toBeTruthy(); expect(ret.length).toBe(3); expect(component.minValue).toBe(1.5); expect(component.maxValue).toBe(5.2); }); }); });
3,194
30.633663
92
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/configuration/configuration-form/configuration-form.component.ts
import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, ValidatorFn } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import _ from 'lodash'; import { ConfigurationService } from '~/app/shared/api/configuration.service'; import { ConfigFormModel } from '~/app/shared/components/config-option/config-option.model'; import { ConfigOptionTypes } from '~/app/shared/components/config-option/config-option.types'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdForm } from '~/app/shared/forms/cd-form'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { NotificationService } from '~/app/shared/services/notification.service'; import { ConfigFormCreateRequestModel } from './configuration-form-create-request.model'; @Component({ selector: 'cd-configuration-form', templateUrl: './configuration-form.component.html', styleUrls: ['./configuration-form.component.scss'] }) export class ConfigurationFormComponent extends CdForm implements OnInit { configForm: CdFormGroup; response: ConfigFormModel; type: string; inputType: string; humanReadableType: string; minValue: number; maxValue: number; patternHelpText: string; availSections = ['global', 'mon', 'mgr', 'osd', 'mds', 'client']; constructor( public actionLabels: ActionLabelsI18n, private route: ActivatedRoute, private router: Router, private configService: ConfigurationService, private notificationService: NotificationService ) { super(); this.createForm(); } createForm() { const formControls = { name: new FormControl({ value: null }), desc: new FormControl({ value: null }), long_desc: new FormControl({ value: null }), values: new FormGroup({}), default: new FormControl({ value: null }), daemon_default: new FormControl({ value: null }), services: new FormControl([]) }; this.availSections.forEach((section) => { formControls.values.addControl(section, new FormControl(null)); }); this.configForm = new CdFormGroup(formControls); } ngOnInit() { this.route.params.subscribe((params: { name: string }) => { const configName = params.name; this.configService.get(configName).subscribe((resp: ConfigFormModel) => { this.setResponse(resp); this.loadingReady(); }); }); } getValidators(configOption: any): ValidatorFn[] { const typeValidators = ConfigOptionTypes.getTypeValidators(configOption); if (typeValidators) { this.patternHelpText = typeValidators.patternHelpText; if ('max' in typeValidators && typeValidators.max !== '') { this.maxValue = typeValidators.max; } if ('min' in typeValidators && typeValidators.min !== '') { this.minValue = typeValidators.min; } return typeValidators.validators; } return undefined; } getStep(type: string, value: number): number | undefined { return ConfigOptionTypes.getTypeStep(type, value); } setResponse(response: ConfigFormModel) { this.response = response; const validators = this.getValidators(response); this.configForm.get('name').setValue(response.name); this.configForm.get('desc').setValue(response.desc); this.configForm.get('long_desc').setValue(response.long_desc); this.configForm.get('default').setValue(response.default); this.configForm.get('daemon_default').setValue(response.daemon_default); this.configForm.get('services').setValue(response.services); if (this.response.value) { this.response.value.forEach((value) => { // Check value type. If it's a boolean value we need to convert it because otherwise we // would use the string representation. That would cause issues for e.g. checkboxes. let sectionValue = null; if (value.value === 'true') { sectionValue = true; } else if (value.value === 'false') { sectionValue = false; } else { sectionValue = value.value; } this.configForm.get('values').get(value.section).setValue(sectionValue); }); } this.availSections.forEach((section) => { this.configForm.get('values').get(section).setValidators(validators); }); const currentType = ConfigOptionTypes.getType(response.type); this.type = currentType.name; this.inputType = currentType.inputType; this.humanReadableType = currentType.humanReadable; } createRequest(): ConfigFormCreateRequestModel | null { const values: any[] = []; this.availSections.forEach((section) => { const sectionValue = this.configForm.getValue(section); if (sectionValue !== null && sectionValue !== '') { values.push({ section: section, value: sectionValue }); } }); if (!_.isEqual(this.response.value, values)) { const request = new ConfigFormCreateRequestModel(); request.name = this.configForm.getValue('name'); request.value = values; return request; } return null; } submit() { const request = this.createRequest(); if (request) { this.configService.create(request).subscribe( () => { this.notificationService.show( NotificationType.success, $localize`Updated config option ${request.name}` ); this.router.navigate(['/configuration']); }, () => { this.configForm.setErrors({ cdSubmitButton: true }); } ); } this.router.navigate(['/configuration']); } }
5,715
32.040462
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/create-cluster/create-cluster-review.component.html
<div class="row"> <div class="col-lg-3"> <fieldset> <legend class="cd-header" i18n>Cluster Resources</legend> <table class="table table-striped"> <tr> <td i18n class="bold">Hosts</td> <td>{{ hostsCount }}</td> </tr> <tr> <td> <dl> <dt> <p i18n>Storage Capacity</p> </dt> <dd> <p i18n>Number of devices</p> </dd> <dd> <p i18n>Raw capacity</p> </dd> </dl> </td> <td class="pt-5"><p>{{ totalDevices }}</p><p> {{ totalCapacity | dimlessBinary }}</p></td> </tr> <tr> <td i18n class="bold">CPUs</td> <td>{{ totalCPUs | empty }}</td> </tr> <tr> <td i18n class="bold">Memory</td> <td>{{ totalMemory | empty }}</td> </tr> </table> </fieldset> </div> <div class="col-lg-9"> <legend i18n class="cd-header">Host Details</legend> <cd-hosts [hiddenColumns]="['services', 'status']" [hideToolHeader]="true" [hasTableDetails]="false" [showGeneralActionsOnly]="true"> </cd-hosts> </div> </div>
1,314
23.811321
56
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/create-cluster/create-cluster-review.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import _ from 'lodash'; import { ToastrModule } from 'ngx-toastr'; import { CephModule } from '~/app/ceph/ceph.module'; import { CoreModule } from '~/app/core/core.module'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { CreateClusterReviewComponent } from './create-cluster-review.component'; describe('CreateClusterReviewComponent', () => { let component: CreateClusterReviewComponent; let fixture: ComponentFixture<CreateClusterReviewComponent>; configureTestBed({ imports: [HttpClientTestingModule, SharedModule, ToastrModule.forRoot(), CephModule, CoreModule] }); beforeEach(() => { fixture = TestBed.createComponent(CreateClusterReviewComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,024
33.166667
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/create-cluster/create-cluster-review.component.ts
import { Component, OnInit } from '@angular/core'; import _ from 'lodash'; import { CephServiceService } from '~/app/shared/api/ceph-service.service'; import { HostService } from '~/app/shared/api/host.service'; import { OsdService } from '~/app/shared/api/osd.service'; import { CephServiceSpec } from '~/app/shared/models/service.interface'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { WizardStepsService } from '~/app/shared/services/wizard-steps.service'; @Component({ selector: 'cd-create-cluster-review', templateUrl: './create-cluster-review.component.html', styleUrls: ['./create-cluster-review.component.scss'] }) export class CreateClusterReviewComponent implements OnInit { hosts: object[] = []; hostsCount: number; totalDevices: number; totalCapacity = 0; services: Array<CephServiceSpec> = []; totalCPUs = 0; totalMemory = 0; constructor( public wizardStepsService: WizardStepsService, public cephServiceService: CephServiceService, private dimlessBinary: DimlessBinaryPipe, public hostService: HostService, private osdService: OsdService ) {} ngOnInit() { let dataDevices = 0; let dataDeviceCapacity = 0; let walDevices = 0; let walDeviceCapacity = 0; let dbDevices = 0; let dbDeviceCapacity = 0; this.hostService.list('true').subscribe((resp: object[]) => { this.hosts = resp; this.hostsCount = this.hosts.length; _.forEach(this.hosts, (hostKey) => { this.totalCPUs = this.totalCPUs + hostKey['cpu_count']; // convert to bytes this.totalMemory = this.totalMemory + hostKey['memory_total_kb'] * 1024; }); this.totalMemory = this.dimlessBinary.transform(this.totalMemory); }); if (this.osdService.osdDevices['data']) { dataDevices = this.osdService.osdDevices['data']?.length; dataDeviceCapacity = this.osdService.osdDevices['data']['capacity']; } if (this.osdService.osdDevices['wal']) { walDevices = this.osdService.osdDevices['wal']?.length; walDeviceCapacity = this.osdService.osdDevices['wal']['capacity']; } if (this.osdService.osdDevices['db']) { dbDevices = this.osdService.osdDevices['db']?.length; dbDeviceCapacity = this.osdService.osdDevices['db']['capacity']; } this.totalDevices = dataDevices + walDevices + dbDevices; this.osdService.osdDevices['totalDevices'] = this.totalDevices; this.totalCapacity = dataDeviceCapacity + walDeviceCapacity + dbDeviceCapacity; } }
2,551
33.958904
83
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/create-cluster/create-cluster.component.html
<div class="container h-75" *ngIf="!startClusterCreation"> <div class="row h-100 justify-content-center align-items-center"> <div class="blank-page"> <!-- htmllint img-req-src="false" --> <img [src]="projectConstants.cephLogo" alt="Ceph" class="img-fluid mx-auto d-block"> <h3 class="text-center m-2" i18n>Welcome to {{ projectConstants.projectName }}</h3> <div class="m-4"> <h4 class="text-center" i18n>Please expand your cluster first</h4> <div class="text-center"> <button class="btn btn-accent m-2" name="expand-cluster" (click)="createCluster()" aria-label="Expand Cluster" i18n>Expand Cluster</button> <button class="btn btn-light" name="skip-cluster-creation" aria-label="Skip" (click)="skipClusterCreation()" i18n>Skip</button> </div> </div> </div> </div> </div> <div class="card" *ngIf="startClusterCreation"> <div class="card-header" i18n>Expand Cluster</div> <div class="container-fluid"> <cd-wizard [stepsTitle]="stepTitles"></cd-wizard> <div class="card-body vertical-line"> <ng-container [ngSwitch]="currentStep?.stepIndex"> <div *ngSwitchCase="'1'" class="ms-5"> <h4 class="title" i18n>Add Hosts</h4> <br> <cd-hosts [hiddenColumns]="['services']" [hideMaintenance]="true" [hasTableDetails]="false" [showGeneralActionsOnly]="true"></cd-hosts> </div> <div *ngSwitchCase="'2'" class="ms-5"> <h4 class="title" i18n>Create OSDs</h4> <div class="alignForm"> <cd-osd-form [hideTitle]="true" [hideSubmitBtn]="true" (emitDriveGroup)="setDriveGroup($event)" (emitDeploymentOption)="setDeploymentOptions($event)" (emitMode)="setDeploymentMode($event)"></cd-osd-form> </div> </div> <div *ngSwitchCase="'3'" class="ms-5"> <h4 class="title" i18n>Create Services</h4> <br> <cd-services [hasDetails]="false" [hiddenServices]="['mon', 'mgr', 'crash', 'agent']" [hiddenColumns]="['status.running', 'status.size', 'status.last_refresh']" [routedModal]="false"></cd-services> </div> <div *ngSwitchCase="'4'" class="ms-5"> <cd-create-cluster-review></cd-create-cluster-review> </div> </ng-container> </div> </div> <div class="card-footer"> <button class="btn btn-accent m-2 float-end" (click)="onNextStep()" aria-label="Next" i18n>{{ showSubmitButtonLabel() }}</button> <cd-back-button class="m-2 float-end" aria-label="Close" (backAction)="onPreviousStep()" [name]="showCancelButtonLabel()"></cd-back-button> <button class="btn btn-light m-2 me-4 float-end" id="skipStepBtn" (click)="onSkip()" aria-label="Skip this step" *ngIf="stepTitles[currentStep.stepIndex - 1] === 'Create OSDs'" i18n>Skip</button> </div> </div> <ng-template #skipConfirmTpl> <span i18n>You are about to skip the cluster expansion process. You’ll need to <strong>navigate through the menu to add hosts and services.</strong></span> <div class="mt-4" i18n>Are you sure you want to continue?</div> </ng-template>
3,799
35.538462
104
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/create-cluster/create-cluster.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { CephModule } from '~/app/ceph/ceph.module'; import { CoreModule } from '~/app/core/core.module'; import { HostService } from '~/app/shared/api/host.service'; import { OsdService } from '~/app/shared/api/osd.service'; import { ConfirmationModalComponent } from '~/app/shared/components/confirmation-modal/confirmation-modal.component'; import { LoadingPanelComponent } from '~/app/shared/components/loading-panel/loading-panel.component'; import { AppConstants } from '~/app/shared/constants/app.constants'; import { ModalService } from '~/app/shared/services/modal.service'; import { WizardStepsService } from '~/app/shared/services/wizard-steps.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { CreateClusterComponent } from './create-cluster.component'; describe('CreateClusterComponent', () => { let component: CreateClusterComponent; let fixture: ComponentFixture<CreateClusterComponent>; let wizardStepService: WizardStepsService; let hostService: HostService; let osdService: OsdService; let modalServiceShowSpy: jasmine.Spy; const projectConstants: typeof AppConstants = AppConstants; configureTestBed( { imports: [ HttpClientTestingModule, RouterTestingModule, ToastrModule.forRoot(), SharedModule, CoreModule, CephModule ] }, [LoadingPanelComponent] ); beforeEach(() => { fixture = TestBed.createComponent(CreateClusterComponent); component = fixture.componentInstance; wizardStepService = TestBed.inject(WizardStepsService); hostService = TestBed.inject(HostService); osdService = TestBed.inject(OsdService); modalServiceShowSpy = spyOn(TestBed.inject(ModalService), 'show').and.returnValue({ // mock the close function, it might be called if there are async tests. close: jest.fn() }); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should have project name as heading in welcome screen', () => { const heading = fixture.debugElement.query(By.css('h3')).nativeElement; expect(heading.innerHTML).toBe(`Welcome to ${projectConstants.projectName}`); }); it('should show confirmation modal when cluster creation is skipped', () => { component.skipClusterCreation(); expect(modalServiceShowSpy.calls.any()).toBeTruthy(); expect(modalServiceShowSpy.calls.first().args[0]).toBe(ConfirmationModalComponent); }); it('should show the wizard when cluster creation is started', () => { component.createCluster(); fixture.detectChanges(); const nativeEl = fixture.debugElement.nativeElement; expect(nativeEl.querySelector('cd-wizard')).not.toBe(null); }); it('should have title Add Hosts', () => { component.createCluster(); fixture.detectChanges(); const heading = fixture.debugElement.query(By.css('.title')).nativeElement; expect(heading.innerHTML).toBe('Add Hosts'); }); it('should show the host list when cluster creation as first step', () => { component.createCluster(); fixture.detectChanges(); const nativeEl = fixture.debugElement.nativeElement; expect(nativeEl.querySelector('cd-hosts')).not.toBe(null); }); it('should move to next step and show the second page', () => { const wizardStepServiceSpy = spyOn(wizardStepService, 'moveToNextStep').and.callThrough(); component.createCluster(); fixture.detectChanges(); component.onNextStep(); fixture.detectChanges(); expect(wizardStepServiceSpy).toHaveBeenCalledTimes(1); }); it('should show the button labels correctly', () => { component.createCluster(); fixture.detectChanges(); let submitBtnLabel = component.showSubmitButtonLabel(); expect(submitBtnLabel).toEqual('Next'); let cancelBtnLabel = component.showCancelButtonLabel(); expect(cancelBtnLabel).toEqual('Cancel'); component.onNextStep(); fixture.detectChanges(); submitBtnLabel = component.showSubmitButtonLabel(); expect(submitBtnLabel).toEqual('Next'); cancelBtnLabel = component.showCancelButtonLabel(); expect(cancelBtnLabel).toEqual('Back'); component.onNextStep(); fixture.detectChanges(); submitBtnLabel = component.showSubmitButtonLabel(); expect(submitBtnLabel).toEqual('Next'); cancelBtnLabel = component.showCancelButtonLabel(); expect(cancelBtnLabel).toEqual('Back'); // Last page of the wizard component.onNextStep(); fixture.detectChanges(); submitBtnLabel = component.showSubmitButtonLabel(); expect(submitBtnLabel).toEqual('Expand Cluster'); cancelBtnLabel = component.showCancelButtonLabel(); expect(cancelBtnLabel).toEqual('Back'); }); it('should ensure osd creation did not happen when no devices are selected', () => { component.simpleDeployment = false; const osdServiceSpy = spyOn(osdService, 'create').and.callThrough(); component.onSubmit(); fixture.detectChanges(); expect(osdServiceSpy).toBeCalledTimes(0); }); it('should ensure osd creation did happen when devices are selected', () => { const osdServiceSpy = spyOn(osdService, 'create').and.callThrough(); osdService.osdDevices['totalDevices'] = 1; component.onSubmit(); fixture.detectChanges(); expect(osdServiceSpy).toBeCalledTimes(1); }); it('should ensure host list call happened', () => { const hostServiceSpy = spyOn(hostService, 'list').and.callThrough(); component.onSubmit(); expect(hostServiceSpy).toHaveBeenCalledTimes(1); }); it('should show skip button in the Create OSDs Steps', () => { component.createCluster(); fixture.detectChanges(); component.onNextStep(); fixture.detectChanges(); const skipBtn = fixture.debugElement.query(By.css('#skipStepBtn')).nativeElement; expect(skipBtn).not.toBe(null); expect(skipBtn.innerHTML).toBe('Skip'); }); it('should skip the Create OSDs Steps', () => { component.createCluster(); fixture.detectChanges(); component.onNextStep(); fixture.detectChanges(); const skipBtn = fixture.debugElement.query(By.css('#skipStepBtn')).nativeElement; skipBtn.click(); fixture.detectChanges(); expect(component.stepsToSkip['Create OSDs']).toBe(true); }); });
6,659
36.206704
117
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/create-cluster/create-cluster.component.ts
import { Component, EventEmitter, OnDestroy, OnInit, Output, TemplateRef, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { forkJoin, Subscription } from 'rxjs'; import { finalize } from 'rxjs/operators'; import { ClusterService } from '~/app/shared/api/cluster.service'; import { HostService } from '~/app/shared/api/host.service'; import { OsdService } from '~/app/shared/api/osd.service'; import { ConfirmationModalComponent } from '~/app/shared/components/confirmation-modal/confirmation-modal.component'; import { ActionLabelsI18n, AppConstants, URLVerbs } from '~/app/shared/constants/app.constants'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { DeploymentOptions } from '~/app/shared/models/osd-deployment-options'; import { Permissions } from '~/app/shared/models/permissions'; import { WizardStepModel } from '~/app/shared/models/wizard-steps'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { WizardStepsService } from '~/app/shared/services/wizard-steps.service'; import { DriveGroup } from '../osd/osd-form/drive-group.model'; @Component({ selector: 'cd-create-cluster', templateUrl: './create-cluster.component.html', styleUrls: ['./create-cluster.component.scss'] }) export class CreateClusterComponent implements OnInit, OnDestroy { @ViewChild('skipConfirmTpl', { static: true }) skipConfirmTpl: TemplateRef<any>; currentStep: WizardStepModel; currentStepSub: Subscription; permissions: Permissions; projectConstants: typeof AppConstants = AppConstants; stepTitles = ['Add Hosts', 'Create OSDs', 'Create Services', 'Review']; startClusterCreation = false; observables: any = []; modalRef: NgbModalRef; driveGroup = new DriveGroup(); driveGroups: Object[] = []; deploymentOption: DeploymentOptions; selectedOption = {}; simpleDeployment = true; stepsToSkip: { [steps: string]: boolean } = {}; @Output() submitAction = new EventEmitter(); constructor( private authStorageService: AuthStorageService, private wizardStepsService: WizardStepsService, private router: Router, private hostService: HostService, private notificationService: NotificationService, private actionLabels: ActionLabelsI18n, private clusterService: ClusterService, private modalService: ModalService, private taskWrapper: TaskWrapperService, private osdService: OsdService ) { this.permissions = this.authStorageService.getPermissions(); this.currentStepSub = this.wizardStepsService .getCurrentStep() .subscribe((step: WizardStepModel) => { this.currentStep = step; }); this.currentStep.stepIndex = 1; } ngOnInit(): void { this.osdService.getDeploymentOptions().subscribe((options) => { this.deploymentOption = options; this.selectedOption = { option: options.recommended_option, encrypted: false }; }); this.stepTitles.forEach((stepTitle) => { this.stepsToSkip[stepTitle] = false; }); } createCluster() { this.startClusterCreation = true; } skipClusterCreation() { const modalVariables = { titleText: $localize`Warning`, buttonText: $localize`Continue`, warning: true, bodyTpl: this.skipConfirmTpl, showSubmit: true, onSubmit: () => { this.clusterService.updateStatus('POST_INSTALLED').subscribe({ error: () => this.modalRef.close(), complete: () => { this.notificationService.show( NotificationType.info, $localize`Cluster expansion skipped by user` ); this.router.navigate(['/dashboard']); this.modalRef.close(); } }); } }; this.modalRef = this.modalService.show(ConfirmationModalComponent, modalVariables); } onSubmit() { if (!this.stepsToSkip['Add Hosts']) { this.hostService.list('false').subscribe((hosts) => { hosts.forEach((host) => { const index = host['labels'].indexOf('_no_schedule', 0); if (index > -1) { host['labels'].splice(index, 1); this.observables.push(this.hostService.update(host['hostname'], true, host['labels'])); } }); forkJoin(this.observables) .pipe( finalize(() => this.clusterService.updateStatus('POST_INSTALLED').subscribe(() => { this.notificationService.show( NotificationType.success, $localize`Cluster expansion was successful` ); this.router.navigate(['/dashboard']); }) ) ) .subscribe({ error: (error) => error.preventDefault() }); }); } if (!this.stepsToSkip['Create OSDs']) { if (this.driveGroup) { const user = this.authStorageService.getUsername(); this.driveGroup.setName(`dashboard-${user}-${_.now()}`); this.driveGroups.push(this.driveGroup.spec); } if (this.simpleDeployment) { const title = this.deploymentOption?.options[this.selectedOption['option']].title; const trackingId = $localize`${title} deployment`; this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('osd/' + URLVerbs.CREATE, { tracking_id: trackingId }), call: this.osdService.create([this.selectedOption], trackingId, 'predefined') }) .subscribe({ error: (error) => error.preventDefault(), complete: () => { this.submitAction.emit(); } }); } else { if (this.osdService.osdDevices['totalDevices'] > 0) { this.driveGroup.setFeature('encrypted', this.selectedOption['encrypted']); const trackingId = _.join(_.map(this.driveGroups, 'service_id'), ', '); this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('osd/' + URLVerbs.CREATE, { tracking_id: trackingId }), call: this.osdService.create(this.driveGroups, trackingId) }) .subscribe({ error: (error) => error.preventDefault(), complete: () => { this.submitAction.emit(); this.osdService.osdDevices = []; } }); } } } } setDriveGroup(driveGroup: DriveGroup) { this.driveGroup = driveGroup; } setDeploymentOptions(option: object) { this.selectedOption = option; } setDeploymentMode(mode: boolean) { this.simpleDeployment = mode; } onNextStep() { if (!this.wizardStepsService.isLastStep()) { this.wizardStepsService.getCurrentStep().subscribe((step: WizardStepModel) => { this.currentStep = step; }); this.wizardStepsService.moveToNextStep(); } else { this.onSubmit(); } } onPreviousStep() { if (!this.wizardStepsService.isFirstStep()) { this.wizardStepsService.moveToPreviousStep(); } else { this.router.navigate(['/dashboard']); } } onSkip() { const stepTitle = this.stepTitles[this.currentStep.stepIndex - 1]; this.stepsToSkip[stepTitle] = true; this.onNextStep(); } showSubmitButtonLabel() { return !this.wizardStepsService.isLastStep() ? this.actionLabels.NEXT : $localize`Expand Cluster`; } showCancelButtonLabel() { return !this.wizardStepsService.isFirstStep() ? this.actionLabels.BACK : this.actionLabels.CANCEL; } ngOnDestroy(): void { this.currentStepSub.unsubscribe(); } }
8,136
31.94332
117
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/crushmap/crushmap.component.html
<div class="row"> <div class="col-sm-12 col-lg-12"> <div class="card"> <div class="card-header" i18n>CRUSH map viewer</div> <div class="card-body"> <div class="row"> <div class="col-sm-6 col-lg-6 tree-container"> <i *ngIf="loadingIndicator" [ngClass]="[icons.large, icons.spinner, icons.spin]"></i> <tree-root #tree [nodes]="nodes" [options]="treeOptions" (updateData)="onUpdateData()"> <ng-template #treeNodeTemplate let-node> <span *ngIf="node.data.status" class="badge" [ngClass]="{'badge-success': ['in', 'up'].includes(node.data.status), 'badge-danger': ['down', 'out', 'destroyed'].includes(node.data.status)}"> {{ node.data.status }} </span> <span>&nbsp;</span> <span class="node-name" [ngClass]="{'type-osd': node.data.type === 'osd'}" [innerHTML]="node.data.name"></span> </ng-template> </tree-root> </div> <div class="col-sm-6 col-lg-6 metadata" *ngIf="metadata"> <legend>{{ metadataTitle }}</legend> <div> <cd-table-key-value [data]="metadata"></cd-table-key-value> </div> </div> </div> </div> </div> </div> </div>
1,534
35.547619
166
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/crushmap/crushmap.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { DebugElement } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { TreeModule } from '@circlon/angular-tree-component'; import { of } from 'rxjs'; import { CrushRuleService } from '~/app/shared/api/crush-rule.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { CrushmapComponent } from './crushmap.component'; describe('CrushmapComponent', () => { let component: CrushmapComponent; let fixture: ComponentFixture<CrushmapComponent>; let debugElement: DebugElement; let crushRuleService: CrushRuleService; let crushRuleServiceInfoSpy: jasmine.Spy; configureTestBed({ imports: [HttpClientTestingModule, TreeModule, SharedModule], declarations: [CrushmapComponent] }); beforeEach(() => { fixture = TestBed.createComponent(CrushmapComponent); component = fixture.componentInstance; debugElement = fixture.debugElement; crushRuleService = TestBed.inject(CrushRuleService); crushRuleServiceInfoSpy = spyOn(crushRuleService, 'getInfo'); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should display right title', () => { const span = debugElement.nativeElement.querySelector('.card-header'); expect(span.textContent).toBe('CRUSH map viewer'); }); it('should display "No nodes!" if ceph tree nodes is empty array', fakeAsync(() => { crushRuleServiceInfoSpy.and.returnValue(of({ nodes: [] })); fixture.detectChanges(); tick(5000); expect(crushRuleService.getInfo).toHaveBeenCalled(); expect(component.nodes[0].name).toEqual('No nodes!'); component.ngOnDestroy(); })); it('should have two root nodes', fakeAsync(() => { crushRuleServiceInfoSpy.and.returnValue( of({ nodes: [ { children: [-2], type: 'root', name: 'default', id: -1 }, { children: [1, 0, 2], type: 'host', name: 'my-host', id: -2 }, { status: 'up', type: 'osd', name: 'osd.0', id: 0 }, { status: 'down', type: 'osd', name: 'osd.1', id: 1 }, { status: 'up', type: 'osd', name: 'osd.2', id: 2 }, { children: [-4], type: 'datacenter', name: 'site1', id: -3 }, { children: [4], type: 'host', name: 'my-host-2', id: -4 }, { status: 'up', type: 'osd', name: 'osd.0-2', id: 4 } ], roots: [-1, -3, -6] }) ); fixture.detectChanges(); tick(10000); expect(crushRuleService.getInfo).toHaveBeenCalled(); expect(component.nodes).toEqual([ { cdId: -3, children: [ { children: [ { id: component.nodes[0].children[0].children[0].id, cdId: 4, status: 'up', type: 'osd', name: 'osd.0-2 (osd)' } ], id: component.nodes[0].children[0].id, cdId: -4, status: undefined, type: 'host', name: 'my-host-2 (host)' } ], id: component.nodes[0].id, status: undefined, type: 'datacenter', name: 'site1 (datacenter)' }, { children: [ { children: [ { id: component.nodes[1].children[0].children[0].id, cdId: 0, status: 'up', type: 'osd', name: 'osd.0 (osd)' }, { id: component.nodes[1].children[0].children[1].id, cdId: 1, status: 'down', type: 'osd', name: 'osd.1 (osd)' }, { id: component.nodes[1].children[0].children[2].id, cdId: 2, status: 'up', type: 'osd', name: 'osd.2 (osd)' } ], id: component.nodes[1].children[0].id, cdId: -2, status: undefined, type: 'host', name: 'my-host (host)' } ], id: component.nodes[1].id, cdId: -1, status: undefined, type: 'root', name: 'default (root)' } ]); component.ngOnDestroy(); })); });
4,440
31.181159
86
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/crushmap/crushmap.component.ts
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { ITreeOptions, TreeComponent, TreeModel, TreeNode, TREE_ACTIONS } from '@circlon/angular-tree-component'; import { Observable, Subscription } from 'rxjs'; import { CrushRuleService } from '~/app/shared/api/crush-rule.service'; import { Icons } from '~/app/shared/enum/icons.enum'; import { TimerService } from '~/app/shared/services/timer.service'; @Component({ selector: 'cd-crushmap', templateUrl: './crushmap.component.html', styleUrls: ['./crushmap.component.scss'] }) export class CrushmapComponent implements OnDestroy, OnInit { private sub = new Subscription(); @ViewChild('tree') tree: TreeComponent; icons = Icons; loadingIndicator = true; nodes: any[] = []; treeOptions: ITreeOptions = { useVirtualScroll: true, nodeHeight: 22, actionMapping: { mouse: { click: this.onNodeSelected.bind(this) } } }; metadata: any; metadataTitle: string; metadataKeyMap: { [key: number]: any } = {}; data$: Observable<object>; constructor(private crushRuleService: CrushRuleService, private timerService: TimerService) {} ngOnInit() { this.sub = this.timerService .get(() => this.crushRuleService.getInfo(), 5000) .subscribe((data: any) => { this.loadingIndicator = false; this.nodes = this.abstractTreeData(data); }); } ngOnDestroy() { this.sub.unsubscribe(); } private abstractTreeData(data: any): any[] { const nodes = data.nodes || []; const rootNodes = data.roots || []; const treeNodeMap: { [key: number]: any } = {}; if (0 === nodes.length) { return [ { name: 'No nodes!' } ]; } const roots: any[] = []; nodes.reverse().forEach((node: any) => { if (rootNodes.includes(node.id)) { roots.push(node.id); } treeNodeMap[node.id] = this.generateTreeLeaf(node, treeNodeMap); }); const children = roots.map((id) => { return treeNodeMap[id]; }); return children; } private generateTreeLeaf(node: any, treeNodeMap: any) { const cdId = node.id; this.metadataKeyMap[cdId] = node; const name: string = node.name + ' (' + node.type + ')'; const status: string = node.status; const children: any[] = []; const resultNode = { name, status, cdId, type: node.type }; if (node.children) { node.children.sort().forEach((childId: any) => { children.push(treeNodeMap[childId]); }); resultNode['children'] = children; } return resultNode; } onNodeSelected(tree: TreeModel, node: TreeNode) { TREE_ACTIONS.ACTIVATE(tree, node, true); if (node.data.cdId !== undefined) { const { name, type, status, ...remain } = this.metadataKeyMap[node.data.cdId]; this.metadata = remain; this.metadataTitle = name + ' (' + type + ')'; } else { delete this.metadata; delete this.metadataTitle; } } onUpdateData() { this.tree.treeModel.expandAll(); } }
3,080
24.04878
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/hosts/hosts.component.html
<nav ngbNav #nav="ngbNav" class="nav-tabs"> <ng-container ngbNavItem> <a ngbNavLink i18n>Hosts List</a> <ng-template ngbNavContent> <cd-table #table [data]="hosts" [columns]="columns" columnMode="flex" (fetchData)="getHosts($event)" selectionType="single" [searchableObjects]="true" [hasDetails]="hasTableDetails" (setExpandedRow)="setExpandedRow($event)" (updateSelection)="updateSelection($event)" [toolHeader]="!hideToolHeader"> <div class="table-actions btn-toolbar"> <cd-table-actions [permission]="permissions.hosts" [selection]="selection" class="btn-group" id="host-actions" [tableActions]="tableActions"> </cd-table-actions> </div> <cd-host-details cdTableDetail [permissions]="permissions" [selection]="expandedRow"> </cd-host-details> </cd-table> </ng-template> </ng-container> <ng-container ngbNavItem *ngIf="permissions.grafana.read"> </ng-container> <ng-container ngbNavItem *ngIf="permissions.grafana.read"> <a ngbNavLink i18n>Overall Performance</a> <ng-template ngbNavContent> <cd-grafana i18n-title title="Host overview" [grafanaPath]="'host-overview?'" [type]="'metrics'" uid="y0KGL0iZz" grafanaStyle="two"> </cd-grafana> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="nav"></div> <ng-template #servicesTpl let-services="value"> <span *ngFor="let service of services"> <cd-label [key]="service['type']" [value]="service['count']" class="me-1"></cd-label> </span> </ng-template> <ng-template #hostNameTpl let-row="row"> <span [ngClass]="row"> {{ row.hostname }} </span><br> <span class="text-muted fst-italic" *ngIf="row.addr"> ({{ row.addr }}) </span> </ng-template> <ng-template #maintenanceConfirmTpl> <div *ngFor="let msg of errorMessage; let last=last"> <ul *ngIf="!last || errorMessage.length === '1'"> <li i18n>{{ msg }}</li> </ul> </div> <ng-container i18n *ngIf="showSubmit">Are you sure you want to continue?</ng-container> </ng-template> <ng-template #orchTmpl> <span i18n i18n-ngbTooltip ngbTooltip="Data will be available only if Orchestrator is available.">N/A</span> </ng-template> <ng-template #flashTmpl> <span i18n i18n-ngbTooltip ngbTooltip="SSD, NVMEs">Flash</span> </ng-template> <router-outlet name="modal"></router-outlet>
2,920
29.113402
89
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/hosts/hosts.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { CephModule } from '~/app/ceph/ceph.module'; import { CephSharedModule } from '~/app/ceph/shared/ceph-shared.module'; import { CoreModule } from '~/app/core/core.module'; import { HostService } from '~/app/shared/api/host.service'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { OrchestratorFeature } from '~/app/shared/models/orchestrator.enum'; import { Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, OrchestratorHelper, TableActionHelper } from '~/testing/unit-test-helper'; import { HostsComponent } from './hosts.component'; class MockShowForceMaintenanceModal { showModal = false; showModalDialog(msg: string) { if ( msg.includes('WARNING') && !msg.includes('It is NOT safe to stop') && !msg.includes('ALERT') && !msg.includes('unsafe to stop') ) { this.showModal = true; } } } describe('HostsComponent', () => { let component: HostsComponent; let fixture: ComponentFixture<HostsComponent>; let hostListSpy: jasmine.Spy; let orchService: OrchestratorService; let showForceMaintenanceModal: MockShowForceMaintenanceModal; const fakeAuthStorageService = { getPermissions: () => { return new Permissions({ hosts: ['read', 'update', 'create', 'delete'] }); } }; configureTestBed({ imports: [ BrowserAnimationsModule, CephSharedModule, SharedModule, HttpClientTestingModule, RouterTestingModule, ToastrModule.forRoot(), CephModule, CoreModule ], providers: [ { provide: AuthStorageService, useValue: fakeAuthStorageService }, TableActionsComponent ] }); beforeEach(() => { showForceMaintenanceModal = new MockShowForceMaintenanceModal(); fixture = TestBed.createComponent(HostsComponent); component = fixture.componentInstance; hostListSpy = spyOn(TestBed.inject(HostService), 'list'); orchService = TestBed.inject(OrchestratorService); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should render hosts list even with not permission mapped services', () => { const hostname = 'ceph.dev'; const payload = [ { services: [ { type: 'osd', id: '0' }, { type: 'rgw', id: 'rgw' }, { type: 'notPermissionMappedService', id: '1' } ], hostname: hostname, labels: ['foo', 'bar'] } ]; OrchestratorHelper.mockStatus(false); hostListSpy.and.callFake(() => of(payload)); fixture.detectChanges(); component.getHosts(new CdTableFetchDataContext(() => undefined)); fixture.detectChanges(); const spans = fixture.debugElement.nativeElement.querySelectorAll( '.datatable-body-cell-label span' ); expect(spans[0].textContent.trim()).toBe(hostname); }); it('should show the exact count of the repeating daemons', () => { const hostname = 'ceph.dev'; const payload = [ { service_instances: [ { type: 'mgr', count: 2 }, { type: 'osd', count: 3 }, { type: 'rgw', count: 1 } ], hostname: hostname, labels: ['foo', 'bar'] } ]; OrchestratorHelper.mockStatus(false); hostListSpy.and.callFake(() => of(payload)); fixture.detectChanges(); component.getHosts(new CdTableFetchDataContext(() => undefined)); fixture.detectChanges(); const spans = fixture.debugElement.nativeElement.querySelectorAll( '.datatable-body-cell-label span span.badge.badge-background-primary' ); expect(spans[0].textContent).toContain('mgr: 2'); expect(spans[1].textContent).toContain('osd: 3'); expect(spans[2].textContent).toContain('rgw: 1'); }); it('should test if host facts are tranformed correctly if orch available', () => { const features = [OrchestratorFeature.HOST_FACTS]; const payload = [ { hostname: 'host_test', services: [ { type: 'osd', id: '0' } ], cpu_count: 2, cpu_cores: 1, memory_total_kb: 1024, hdd_count: 4, hdd_capacity_bytes: 1024, flash_count: 4, flash_capacity_bytes: 1024, nic_count: 1 } ]; OrchestratorHelper.mockStatus(true, features); hostListSpy.and.callFake(() => of(payload)); fixture.detectChanges(); component.getHosts(new CdTableFetchDataContext(() => undefined)); expect(hostListSpy).toHaveBeenCalled(); expect(component.hosts[0]['cpu_count']).toEqual(2); expect(component.hosts[0]['memory_total_bytes']).toEqual(1048576); expect(component.hosts[0]['raw_capacity']).toEqual(2048); expect(component.hosts[0]['hdd_count']).toEqual(4); expect(component.hosts[0]['flash_count']).toEqual(4); expect(component.hosts[0]['cpu_cores']).toEqual(1); expect(component.hosts[0]['nic_count']).toEqual(1); }); it('should test if host facts are unavailable if no orch available', () => { const payload = [ { hostname: 'host_test', services: [ { type: 'osd', id: '0' } ] } ]; OrchestratorHelper.mockStatus(false); hostListSpy.and.callFake(() => of(payload)); fixture.detectChanges(); component.getHosts(new CdTableFetchDataContext(() => undefined)); fixture.detectChanges(); const spans = fixture.debugElement.nativeElement.querySelectorAll( '.datatable-body-cell-label span' ); expect(spans[7].textContent).toBe('N/A'); }); it('should test if host facts are unavailable if get_fatcs orch feature is not available', () => { const payload = [ { hostname: 'host_test', services: [ { type: 'osd', id: '0' } ] } ]; OrchestratorHelper.mockStatus(true); hostListSpy.and.callFake(() => of(payload)); fixture.detectChanges(); component.getHosts(new CdTableFetchDataContext(() => undefined)); fixture.detectChanges(); const spans = fixture.debugElement.nativeElement.querySelectorAll( '.datatable-body-cell-label span' ); expect(spans[7].textContent).toBe('N/A'); }); it('should test if memory/raw capacity columns shows N/A if facts are available but in fetching state', () => { const features = [OrchestratorFeature.HOST_FACTS]; let hostPayload: any[]; hostPayload = [ { hostname: 'host_test', services: [ { type: 'osd', id: '0' } ], cpu_count: 2, cpu_cores: 1, memory_total_kb: undefined, hdd_count: 4, hdd_capacity_bytes: undefined, flash_count: 4, flash_capacity_bytes: undefined, nic_count: 1 } ]; OrchestratorHelper.mockStatus(true, features); hostListSpy.and.callFake(() => of(hostPayload)); fixture.detectChanges(); component.getHosts(new CdTableFetchDataContext(() => undefined)); expect(component.hosts[0]['memory_total_bytes']).toEqual('N/A'); expect(component.hosts[0]['raw_capacity']).toEqual('N/A'); }); it('should show force maintenance modal when it is safe to stop host', () => { const errorMsg = `WARNING: Stopping 1 out of 1 daemons in Grafana service. Service will not be operational with no daemons left. At least 1 daemon must be running to guarantee service.`; showForceMaintenanceModal.showModalDialog(errorMsg); expect(showForceMaintenanceModal.showModal).toBeTruthy(); }); it('should not show force maintenance modal when error is an ALERT', () => { const errorMsg = `ALERT: Cannot stop active Mgr daemon, Please switch active Mgrs with 'ceph mgr fail ceph-node-00'`; showForceMaintenanceModal.showModalDialog(errorMsg); expect(showForceMaintenanceModal.showModal).toBeFalsy(); }); it('should not show force maintenance modal when it is not safe to stop host', () => { const errorMsg = `WARNING: Stopping 1 out of 1 daemons in Grafana service. Service will not be operational with no daemons left. At least 1 daemon must be running to guarantee service. It is NOT safe to stop ['mon.ceph-node-00']: not enough monitors would be available (ceph-node-02) after stopping mons`; showForceMaintenanceModal.showModalDialog(errorMsg); expect(showForceMaintenanceModal.showModal).toBeFalsy(); }); it('should not show force maintenance modal when it is unsafe to stop host', () => { const errorMsg = 'unsafe to stop osd.0 because of some unknown reason'; showForceMaintenanceModal.showModalDialog(errorMsg); expect(showForceMaintenanceModal.showModal).toBeFalsy(); }); describe('table actions', () => { const fakeHosts = require('./fixtures/host_list_response.json'); beforeEach(() => { hostListSpy.and.callFake(() => of(fakeHosts)); }); const testTableActions = async ( orch: boolean, features: OrchestratorFeature[], tests: { selectRow?: number; expectResults: any }[] ) => { OrchestratorHelper.mockStatus(orch, features); fixture.detectChanges(); await fixture.whenStable(); for (const test of tests) { if (test.selectRow) { component.selection = new CdTableSelection(); component.selection.selected = [test.selectRow]; } await TableActionHelper.verifyTableActions( fixture, component.tableActions, test.expectResults ); } }; it('should have correct states when Orchestrator is enabled', async () => { const tests = [ { expectResults: { Add: { disabled: false, disableDesc: '' }, Edit: { disabled: true, disableDesc: '' }, Remove: { disabled: true, disableDesc: '' } } }, { selectRow: fakeHosts[0], // non-orchestrator host expectResults: { Add: { disabled: false, disableDesc: '' }, Edit: { disabled: true, disableDesc: component.messages.nonOrchHost }, Remove: { disabled: true, disableDesc: component.messages.nonOrchHost } } }, { selectRow: fakeHosts[1], // orchestrator host expectResults: { Add: { disabled: false, disableDesc: '' }, Edit: { disabled: false, disableDesc: '' }, Remove: { disabled: false, disableDesc: '' } } } ]; const features = [ OrchestratorFeature.HOST_ADD, OrchestratorFeature.HOST_LABEL_ADD, OrchestratorFeature.HOST_REMOVE, OrchestratorFeature.HOST_LABEL_REMOVE, OrchestratorFeature.HOST_DRAIN ]; await testTableActions(true, features, tests); }); it('should have correct states when Orchestrator is disabled', async () => { const resultNoOrchestrator = { disabled: true, disableDesc: orchService.disableMessages.noOrchestrator }; const tests = [ { expectResults: { Add: resultNoOrchestrator, Edit: { disabled: true, disableDesc: '' }, Remove: { disabled: true, disableDesc: '' } } }, { selectRow: fakeHosts[0], // non-orchestrator host expectResults: { Add: resultNoOrchestrator, Edit: { disabled: true, disableDesc: component.messages.nonOrchHost }, Remove: { disabled: true, disableDesc: component.messages.nonOrchHost } } }, { selectRow: fakeHosts[1], // orchestrator host expectResults: { Add: resultNoOrchestrator, Edit: resultNoOrchestrator, Remove: resultNoOrchestrator } } ]; await testTableActions(false, [], tests); }); it('should have correct states when Orchestrator features are missing', async () => { const resultMissingFeatures = { disabled: true, disableDesc: orchService.disableMessages.missingFeature }; const tests = [ { expectResults: { Add: resultMissingFeatures, Edit: { disabled: true, disableDesc: '' }, Remove: { disabled: true, disableDesc: '' } } }, { selectRow: fakeHosts[0], // non-orchestrator host expectResults: { Add: resultMissingFeatures, Edit: { disabled: true, disableDesc: component.messages.nonOrchHost }, Remove: { disabled: true, disableDesc: component.messages.nonOrchHost } } }, { selectRow: fakeHosts[1], // orchestrator host expectResults: { Add: resultMissingFeatures, Edit: resultMissingFeatures, Remove: resultMissingFeatures } } ]; await testTableActions(true, [], tests); }); }); });
14,129
31.186788
113
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/hosts/hosts.component.ts
import { Component, Input, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { Subscription } from 'rxjs'; import { mergeMap } from 'rxjs/operators'; import { HostService } from '~/app/shared/api/host.service'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; import { ListWithDetails } from '~/app/shared/classes/list-with-details.class'; import { ConfirmationModalComponent } from '~/app/shared/components/confirmation-modal/confirmation-modal.component'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { FormModalComponent } from '~/app/shared/components/form-modal/form-modal.component'; import { SelectMessages } from '~/app/shared/components/select/select-messages.model'; import { ActionLabelsI18n, URLVerbs } from '~/app/shared/constants/app.constants'; import { TableComponent } from '~/app/shared/datatable/table/table.component'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { OrchestratorFeature } from '~/app/shared/models/orchestrator.enum'; import { OrchestratorStatus } from '~/app/shared/models/orchestrator.interface'; import { Permissions } from '~/app/shared/models/permissions'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { EmptyPipe } from '~/app/shared/pipes/empty.pipe'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { URLBuilderService } from '~/app/shared/services/url-builder.service'; import { HostFormComponent } from './host-form/host-form.component'; const BASE_URL = 'hosts'; @Component({ selector: 'cd-hosts', templateUrl: './hosts.component.html', styleUrls: ['./hosts.component.scss'], providers: [{ provide: URLBuilderService, useValue: new URLBuilderService(BASE_URL) }] }) export class HostsComponent extends ListWithDetails implements OnDestroy, OnInit { private sub = new Subscription(); @ViewChild(TableComponent) table: TableComponent; @ViewChild('servicesTpl', { static: true }) public servicesTpl: TemplateRef<any>; @ViewChild('maintenanceConfirmTpl', { static: true }) maintenanceConfirmTpl: TemplateRef<any>; @ViewChild('orchTmpl', { static: true }) orchTmpl: TemplateRef<any>; @ViewChild('flashTmpl', { static: true }) flashTmpl: TemplateRef<any>; @ViewChild('hostNameTpl', { static: true }) hostNameTpl: TemplateRef<any>; @Input() hiddenColumns: string[] = []; @Input() hideMaintenance = false; @Input() hasTableDetails = true; @Input() hideToolHeader = false; @Input() showGeneralActionsOnly = false; permissions: Permissions; columns: Array<CdTableColumn> = []; hosts: Array<object> = []; isLoadingHosts = false; cdParams = { fromLink: '/hosts' }; tableActions: CdTableAction[]; selection = new CdTableSelection(); modalRef: NgbModalRef; isExecuting = false; errorMessage: string; enableMaintenanceBtn: boolean; enableDrainBtn: boolean; bsModalRef: NgbModalRef; icons = Icons; messages = { nonOrchHost: $localize`The feature is disabled because the selected host is not managed by Orchestrator.` }; orchStatus: OrchestratorStatus; actionOrchFeatures = { add: [OrchestratorFeature.HOST_ADD], edit: [OrchestratorFeature.HOST_LABEL_ADD, OrchestratorFeature.HOST_LABEL_REMOVE], remove: [OrchestratorFeature.HOST_REMOVE], maintenance: [ OrchestratorFeature.HOST_MAINTENANCE_ENTER, OrchestratorFeature.HOST_MAINTENANCE_EXIT ], drain: [OrchestratorFeature.HOST_DRAIN] }; constructor( private authStorageService: AuthStorageService, private dimlessBinary: DimlessBinaryPipe, private emptyPipe: EmptyPipe, private hostService: HostService, private actionLabels: ActionLabelsI18n, private modalService: ModalService, private taskWrapper: TaskWrapperService, private router: Router, private notificationService: NotificationService, private orchService: OrchestratorService ) { super(); this.permissions = this.authStorageService.getPermissions(); this.tableActions = [ { name: this.actionLabels.ADD, permission: 'create', icon: Icons.add, click: () => this.router.url.includes('/hosts') ? this.router.navigate([BASE_URL, { outlets: { modal: [URLVerbs.ADD] } }]) : (this.bsModalRef = this.modalService.show(HostFormComponent, { hideMaintenance: this.hideMaintenance })), disable: (selection: CdTableSelection) => this.getDisable('add', selection) }, { name: this.actionLabels.EDIT, permission: 'update', icon: Icons.edit, click: () => this.editAction(), disable: (selection: CdTableSelection) => this.getDisable('edit', selection) }, { name: this.actionLabels.START_DRAIN, permission: 'update', icon: Icons.exit, click: () => this.hostDrain(), disable: (selection: CdTableSelection) => this.getDisable('drain', selection) || !this.enableDrainBtn, visible: () => !this.showGeneralActionsOnly && this.enableDrainBtn }, { name: this.actionLabels.STOP_DRAIN, permission: 'update', icon: Icons.exit, click: () => this.hostDrain(true), disable: (selection: CdTableSelection) => this.getDisable('drain', selection) || this.enableDrainBtn, visible: () => !this.showGeneralActionsOnly && !this.enableDrainBtn }, { name: this.actionLabels.REMOVE, permission: 'delete', icon: Icons.destroy, click: () => this.deleteAction(), disable: (selection: CdTableSelection) => this.getDisable('remove', selection) }, { name: this.actionLabels.ENTER_MAINTENANCE, permission: 'update', icon: Icons.enter, click: () => this.hostMaintenance(), disable: (selection: CdTableSelection) => this.getDisable('maintenance', selection) || this.isExecuting || this.enableMaintenanceBtn, visible: () => !this.showGeneralActionsOnly && !this.enableMaintenanceBtn }, { name: this.actionLabels.EXIT_MAINTENANCE, permission: 'update', icon: Icons.exit, click: () => this.hostMaintenance(), disable: (selection: CdTableSelection) => this.getDisable('maintenance', selection) || this.isExecuting || !this.enableMaintenanceBtn, visible: () => !this.showGeneralActionsOnly && this.enableMaintenanceBtn } ]; } ngOnInit() { this.columns = [ { name: $localize`Hostname`, prop: 'hostname', flexGrow: 1, cellTemplate: this.hostNameTpl }, { name: $localize`Service Instances`, prop: 'service_instances', flexGrow: 1.5, cellTemplate: this.servicesTpl }, { name: $localize`Labels`, prop: 'labels', flexGrow: 1, cellTransformation: CellTemplate.badge, customTemplateConfig: { class: 'badge-dark' } }, { name: $localize`Status`, prop: 'status', flexGrow: 0.8, cellTransformation: CellTemplate.badge, customTemplateConfig: { map: { maintenance: { class: 'badge-warning' }, available: { class: 'badge-success' } } } }, { name: $localize`Model`, prop: 'model', flexGrow: 1 }, { name: $localize`CPUs`, prop: 'cpu_count', flexGrow: 0.3 }, { name: $localize`Cores`, prop: 'cpu_cores', flexGrow: 0.3 }, { name: $localize`Total Memory`, prop: 'memory_total_bytes', pipe: this.dimlessBinary, flexGrow: 0.4 }, { name: $localize`Raw Capacity`, prop: 'raw_capacity', pipe: this.dimlessBinary, flexGrow: 0.5 }, { name: $localize`HDDs`, prop: 'hdd_count', flexGrow: 0.3 }, { name: $localize`Flash`, prop: 'flash_count', headerTemplate: this.flashTmpl, flexGrow: 0.3 }, { name: $localize`NICs`, prop: 'nic_count', flexGrow: 0.3 } ]; this.columns = this.columns.filter((col: any) => { return !this.hiddenColumns.includes(col.prop); }); } ngOnDestroy() { this.sub.unsubscribe(); } updateSelection(selection: CdTableSelection) { this.selection = selection; this.enableMaintenanceBtn = false; this.enableDrainBtn = false; if (this.selection.hasSelection) { if (this.selection.first().status === 'maintenance') { this.enableMaintenanceBtn = true; } if (!this.selection.first().labels.includes('_no_schedule')) { this.enableDrainBtn = true; } } } editAction() { this.hostService.getLabels().subscribe((resp: string[]) => { const host = this.selection.first(); const labels = new Set(resp.concat(this.hostService.predefinedLabels)); const allLabels = Array.from(labels).map((label) => { return { enabled: true, name: label }; }); this.modalService.show(FormModalComponent, { titleText: $localize`Edit Host: ${host.hostname}`, fields: [ { type: 'select-badges', name: 'labels', value: host['labels'], label: $localize`Labels`, typeConfig: { customBadges: true, options: allLabels, messages: new SelectMessages({ empty: $localize`There are no labels.`, filter: $localize`Filter or add labels`, add: $localize`Add label` }) } } ], submitButtonText: $localize`Edit Host`, onSubmit: (values: any) => { this.hostService.update(host['hostname'], true, values.labels).subscribe(() => { this.notificationService.show( NotificationType.success, $localize`Updated Host "${host.hostname}"` ); // Reload the data table content. this.table.refreshBtn(); }); } }); }); } hostMaintenance() { this.isExecuting = true; const host = this.selection.first(); if (host['status'] !== 'maintenance') { this.hostService.update(host['hostname'], false, [], true).subscribe( () => { this.isExecuting = false; this.notificationService.show( NotificationType.success, $localize`"${host.hostname}" moved to maintenance` ); this.table.refreshBtn(); }, (error) => { this.isExecuting = false; this.errorMessage = error.error['detail'].split(/\n/); error.preventDefault(); if ( error.error['detail'].includes('WARNING') && !error.error['detail'].includes('It is NOT safe to stop') && !error.error['detail'].includes('ALERT') && !error.error['detail'].includes('unsafe to stop') ) { const modalVariables = { titleText: $localize`Warning`, buttonText: $localize`Continue`, warning: true, bodyTpl: this.maintenanceConfirmTpl, showSubmit: true, onSubmit: () => { this.hostService.update(host['hostname'], false, [], true, true).subscribe( () => { this.modalRef.close(); }, () => this.modalRef.close() ); } }; this.modalRef = this.modalService.show(ConfirmationModalComponent, modalVariables); } else { this.notificationService.show( NotificationType.error, $localize`"${host.hostname}" cannot be put into maintenance`, $localize`${error.error['detail']}` ); } } ); } else { this.hostService.update(host['hostname'], false, [], true).subscribe(() => { this.isExecuting = false; this.notificationService.show( NotificationType.success, $localize`"${host.hostname}" has exited maintenance` ); this.table.refreshBtn(); }); } } hostDrain(stop = false) { const host = this.selection.first(); if (stop) { const index = host['labels'].indexOf('_no_schedule', 0); host['labels'].splice(index, 1); this.hostService.update(host['hostname'], true, host['labels']).subscribe(() => { this.notificationService.show( NotificationType.info, $localize`"${host['hostname']}" stopped draining` ); this.table.refreshBtn(); }); } else { this.hostService.update(host['hostname'], false, [], false, false, true).subscribe(() => { this.notificationService.show( NotificationType.info, $localize`"${host['hostname']}" started draining` ); this.table.refreshBtn(); }); } } getDisable( action: 'add' | 'edit' | 'remove' | 'maintenance' | 'drain', selection: CdTableSelection ): boolean | string { if ( action === 'remove' || action === 'edit' || action === 'maintenance' || action === 'drain' ) { if (!selection?.hasSingleSelection) { return true; } if (!_.every(selection.selected, 'sources.orchestrator')) { return this.messages.nonOrchHost; } } return this.orchService.getTableActionDisableDesc( this.orchStatus, this.actionOrchFeatures[action] ); } deleteAction() { const hostname = this.selection.first().hostname; this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: 'Host', itemNames: [hostname], actionDescription: 'remove', submitActionObservable: () => this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('host/remove', { hostname: hostname }), call: this.hostService.delete(hostname) }) }); } checkHostsFactsAvailable() { const orchFeatures = this.orchStatus.features; if (!_.isEmpty(orchFeatures)) { if (orchFeatures.get_facts.available) { return true; } return false; } return false; } transformHostsData() { if (this.checkHostsFactsAvailable()) { _.forEach(this.hosts, (hostKey) => { hostKey['memory_total_bytes'] = this.emptyPipe.transform(hostKey['memory_total_kb'] * 1024); hostKey['raw_capacity'] = this.emptyPipe.transform( hostKey['hdd_capacity_bytes'] + hostKey['flash_capacity_bytes'] ); }); } else { // mark host facts columns unavailable for (let column = 4; column < this.columns.length; column++) { this.columns[column]['cellTemplate'] = this.orchTmpl; } } } getHosts(context: CdTableFetchDataContext) { if (this.isLoadingHosts) { return; } this.isLoadingHosts = true; this.sub = this.orchService .status() .pipe( mergeMap((orchStatus) => { this.orchStatus = orchStatus; const factsAvailable = this.checkHostsFactsAvailable(); return this.hostService.list(`${factsAvailable}`); }) ) .subscribe( (hostList) => { this.hosts = hostList; this.hosts.forEach((host: object) => { if (host['status'] === '') { host['status'] = 'available'; } }); this.transformHostsData(); this.isLoadingHosts = false; }, () => { this.isLoadingHosts = false; context.error(); } ); } }
17,014
31.911025
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/hosts/host-details/host-details.component.html
<ng-container *ngIf="selection"> <nav ngbNav #nav="ngbNav" class="nav-tabs" cdStatefulTab="host-details"> <ng-container ngbNavItem="devices"> <a ngbNavLink i18n>Devices</a> <ng-template ngbNavContent> <cd-device-list [hostname]="selection['hostname']"></cd-device-list> </ng-template> </ng-container> <ng-container ngbNavItem="inventory" *ngIf="permissions.hosts.read"> <a ngbNavLink i18n>Physical Disks</a> <ng-template ngbNavContent> <cd-inventory [hostname]="selectedHostname"></cd-inventory> </ng-template> </ng-container> <ng-container ngbNavItem="daemons" *ngIf="permissions.hosts.read"> <a ngbNavLink i18n>Daemons</a> <ng-template ngbNavContent> <cd-service-daemon-list [hostname]="selectedHostname" flag="hostDetails" [hiddenColumns]="['hostname']"> </cd-service-daemon-list> </ng-template> </ng-container> <ng-container ngbNavItem="performance-details" *ngIf="permissions.grafana.read"> <a ngbNavLink i18n>Performance Details</a> <ng-template ngbNavContent> <cd-grafana i18n-title title="Host details" [grafanaPath]="'host-details?var-ceph_hosts=' + selectedHostname" [type]="'metrics'" uid="rtOg0AiWz" grafanaStyle="four"> </cd-grafana> </ng-template> </ng-container> <ng-container ngbNavItem="device-health"> <a ngbNavLink i18n>Device health</a> <ng-template ngbNavContent> <cd-smart-list *ngIf="selectedHostname; else noHostname" [hostname]="selectedHostname"></cd-smart-list> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="nav"></div> </ng-container> <ng-template #noHostname> <cd-alert-panel type="error" i18n>No hostname found.</cd-alert-panel> </ng-template>
2,108
32.47619
85
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/hosts/host-details/host-details.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { CephModule } from '~/app/ceph/ceph.module'; import { CephSharedModule } from '~/app/ceph/shared/ceph-shared.module'; import { CoreModule } from '~/app/core/core.module'; import { Permissions } from '~/app/shared/models/permissions'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, TabHelper } from '~/testing/unit-test-helper'; import { HostDetailsComponent } from './host-details.component'; describe('HostDetailsComponent', () => { let component: HostDetailsComponent; let fixture: ComponentFixture<HostDetailsComponent>; configureTestBed({ imports: [ BrowserAnimationsModule, HttpClientTestingModule, RouterTestingModule, CephModule, CoreModule, CephSharedModule, SharedModule, ToastrModule.forRoot() ] }); beforeEach(() => { fixture = TestBed.createComponent(HostDetailsComponent); component = fixture.componentInstance; component.selection = undefined; component.permissions = new Permissions({ hosts: ['read'], grafana: ['read'] }); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('Host details tabset', () => { beforeEach(() => { component.selection = { hostname: 'localhost' }; fixture.detectChanges(); }); it('should recognize a tabset child', () => { const tabsetChild = TabHelper.getNgbNav(fixture); expect(tabsetChild).toBeDefined(); }); it('should show tabs', () => { expect(TabHelper.getTextContents(fixture)).toEqual([ 'Devices', 'Physical Disks', 'Daemons', 'Performance Details', 'Device health' ]); }); }); });
2,051
28.73913
79
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/hosts/host-details/host-details.component.ts
import { Component, Input } from '@angular/core'; import { Permissions } from '~/app/shared/models/permissions'; @Component({ selector: 'cd-host-details', templateUrl: './host-details.component.html', styleUrls: ['./host-details.component.scss'] }) export class HostDetailsComponent { @Input() permissions: Permissions; @Input() selection: any; get selectedHostname(): string { return this.selection !== undefined ? this.selection['hostname'] : null; } }
481
21.952381
76
ts