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/cluster/telemetry/telemetry.component.html
<div class="cd-col-form" *cdFormLoading="loading"> <ng-container [ngSwitch]="step"> <!-- Configuration step --> <div *ngSwitchCase="1"> <form name="form" #formDir="ngForm" [formGroup]="configForm" novalidate> <div class="card"> <div class="card-header" i18n>Step {{ step }} of 2: Telemetry report configuration</div> <div class="card-body"> <p i18n>The telemetry module sends anonymous data about this Ceph cluster back to the Ceph developers to help understand how Ceph is used and what problems users may be experiencing.<br/> This data is visualized on <a href="https://telemetry-public.ceph.com/">public dashboards</a> that allow the community to quickly see summary statistics on how many clusters are reporting, their total capacity and OSD count, and version distribution trends.<br/><br/> The data being reported does <b>not</b> contain any sensitive data like pool names, object names, object contents, hostnames, or device serial numbers. It contains counters and statistics on how the cluster has been deployed, the version of Ceph, the distribution of the hosts and other parameters which help the project to gain a better understanding of the way Ceph is used. The data is sent secured to {{ sendToUrl }} and {{ sendToDeviceUrl }} (device report).</p> <div *ngIf="moduleEnabled"> The plugin is already <b>enabled</b>. Click <b>Deactivate</b> to disable it.&nbsp; <button type="button" class="btn btn-light" (click)="disableModule('The Telemetry module has been disabled successfully.')" i18n>Deactivate</button> </div> <legend i18n>Channels</legend> <p i18n>The telemetry report is broken down into several "channels", each with a different type of information that can be configured below.</p> <!-- Channel basic --> <div class="form-group row"> <label class="cd-col-form-label" for="channel_basic"> <ng-container i18n>Basic</ng-container> <cd-helper> <ng-container i18n>Includes basic information about the cluster:</ng-container> <ul> <li i18n>Capacity of the cluster</li> <li i18n>Number of monitors, managers, OSDs, MDSs, object gateways, or other daemons</li> <li i18n>Software version currently being used</li> <li i18n>Number and types of RADOS pools and CephFS file systems</li> <li i18n>Names of configuration options that have been changed from their default (but not their values)</li> </ul> </cd-helper> </label> <div class="cd-col-form-input"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="channel_basic" formControlName="channel_basic"> <label class="custom-control-label" for="channel_basic"></label> </div> </div> </div> <!-- Channel crash --> <div class="form-group row"> <label class="cd-col-form-label" for="channel_crash"> <ng-container i18n>Crash</ng-container> <cd-helper> <ng-container i18n>Includes information about daemon crashes:</ng-container> <ul> <li i18n>Type of daemon</li> <li i18n>Version of the daemon</li> <li i18n>Operating system (OS distribution, kernel version)</li> <li i18n>Stack trace identifying where in the Ceph code the crash occurred</li> </ul> </cd-helper> </label> <div class="cd-col-form-input"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="channel_crash" formControlName="channel_crash"> <label class="custom-control-label" for="channel_crash"></label> </div> </div> </div> <!-- Channel device --> <div class="form-group row"> <label class="cd-col-form-label" for="channel_device"> <ng-container i18n>Device</ng-container> <cd-helper i18n-html html="Includes information about device metrics like anonymized SMART metrics."> </cd-helper> </label> <div class="cd-col-form-input"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="channel_device" formControlName="channel_device"> <label class="custom-control-label" for="channel_device"></label> </div> </div> </div> <!-- Channel ident --> <div class="form-group row"> <label class="cd-col-form-label" for="channel_ident"> <ng-container i18n>Ident</ng-container> <cd-helper> <ng-container i18n>Includes user-provided identifying information about the cluster:</ng-container> <ul> <li>Cluster description</li> <li>Contact email address</li> </ul> </cd-helper> </label> <div class="cd-col-form-input"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="channel_ident" formControlName="channel_ident" (click)="toggleIdent()"> <label class="custom-control-label" for="channel_ident"></label> </div> </div> </div> <!-- Channel perf --> <div class="form-group row"> <label class="cd-col-form-label" for="channel_perf"> <ng-container i18n>Perf</ng-container> <cd-helper> <ng-container i18n>Includes various performance metrics of a cluster.</ng-container> </cd-helper> </label> <div class="cd-col-form-input"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="channel_perf" formControlName="channel_perf"> <label class="custom-control-label" for="channel_perf"></label> </div> </div> </div> <ng-container *ngIf="showContactInfo"> <legend> <ng-container i18n>Contact Information</ng-container> <cd-helper i18n>Submitting any contact information is completely optional and disabled by default.</cd-helper> </legend> <div class="form-group row"> <label class="cd-col-form-label" for="contact" i18n>Contact</label> <div class="cd-col-form-input"> <input id="contact" class="form-control" type="text" formControlName="contact" placeholder="Example User <[email protected]>"> </div> </div> <div class="form-group row"> <label class="cd-col-form-label" for="description" i18n>Description</label> <div class="cd-col-form-input"> <input id="description" class="form-control" type="text" formControlName="description" placeholder="My first Ceph cluster" i18n-placeholder> </div> </div> <div class="form-group row"> <label class="cd-col-form-label" for="organization" i18n>Organization</label> <div class="cd-col-form-input"> <input id="organization" class="form-control" type="text" formControlName="organization" placeholder="Organization name" i18n-placeholder> </div> </div> </ng-container> <legend i18n>Advanced Settings</legend> <div class="form-group row"> <label class="cd-col-form-label" for="interval"> <ng-container i18n>Interval</ng-container> <cd-helper i18n>The module compiles and sends a new report every 24 hours by default. You can adjust this interval by setting a different number of hours.</cd-helper> </label> <div class="cd-col-form-input"> <input id="interval" class="form-control" type="number" formControlName="interval" min="8"> <span class="invalid-feedback" *ngIf="configForm.showError('interval', formDir, 'min')" i18n>The entered value is too low! It must be greater or equal to 8.</span> </div> </div> <div class="form-group row"> <label class="cd-col-form-label" for="proxy"> <ng-container i18n>Proxy</ng-container> <cd-helper> <p i18n>If the cluster cannot directly connect to the configured telemetry endpoint (default telemetry.ceph.com), you can configure a HTTP/HTTPS proxy server by e.g. adding https://10.0.0.1:8080</p> <p i18n>You can also include a user:pass if needed e.g. https://ceph:[email protected]:8080</p> </cd-helper> </label> <div class="cd-col-form-input"> <input id="proxy" class="form-control" type="text" formControlName="proxy" placeholder="https://10.0.0.1:8080"> </div> </div> <br /> <p i18n><b>Note:</b> By clicking 'Next' you will first see a preview of the report content before you can activate the automatic submission of your data.</p> </div> <div class="card-footer"> <div class="button-group text-right"> <button type="button" class="btn btn-light" (click)="next()"> <ng-container>{{ actionLabels.NEXT }}</ng-container> </button> </div> </div> </div> </form> </div> <!-- Preview step --> <div *ngSwitchCase="2"> <form name="previewForm" #frm="ngForm" [formGroup]="previewForm" novalidate> <div class="card"> <div class="card-header" i18n>Step {{ step }} of 2: Telemetry report preview</div> <div class="card-body"> <!-- Telemetry report ID --> <div class="form-group row"> <label i18n for="reportId" class="cd-col-form-label">Report ID <cd-helper i18n-html html="A randomized UUID to identify a particular cluster over the course of several telemetry reports."> </cd-helper> </label> <div class="cd-col-form-input"> <input class="form-control" type="text" id="reportId" formControlName="reportId" readonly> </div> </div> <!-- Telemetry report --> <div class="form-group row"> <label i18n for="report" class="cd-col-form-label">Report preview <cd-helper i18n-html html="The actual telemetry data that will be submitted."><em>Note: Please select 'Download' to view the full report, including metrics from the perf channel.</em> </cd-helper> </label> <div class="cd-col-form-input"> <textarea class="form-control" id="report" formControlName="report" rows="15" readonly></textarea> </div> </div> <div class="form-group row"> <div class="cd-col-form-offset"> <div class="btn-group" role="group"> <cd-download-button [objectItem]="report" fileName="telemetry_report"> </cd-download-button> <cd-copy-2-clipboard-button source="report"> </cd-copy-2-clipboard-button> </div> </div> </div> <!-- License agreement --> <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="licenseAgrmt" name="licenseAgrmt" formControlName="licenseAgrmt"> <label class="custom-control-label" for="licenseAgrmt" i18n>I agree to my telemetry data being submitted under the <a href="https://cdla.io/sharing-1-0/">Community Data License Agreement - Sharing - Version 1.0</a></label> </div> </div> </div> </div> <div class="card-footer"> <div class="button-group text-right"> <cd-form-button-panel (submitActionEvent)="onSubmit()" (backActionEvent)="back()" [form]="previewForm" [submitText]="actionLabels.UPDATE" [cancelText]="actionLabels.BACK"></cd-form-button-panel> </div> </div> </div> </form> </div> </ng-container> </div>
15,628
44.17052
192
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/telemetry/telemetry.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { Router } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import _ from 'lodash'; import { ToastrModule } from 'ngx-toastr'; import { of as observableOf } from 'rxjs'; import { MgrModuleService } from '~/app/shared/api/mgr-module.service'; import { DownloadButtonComponent } from '~/app/shared/components/download-button/download-button.component'; import { LoadingPanelComponent } from '~/app/shared/components/loading-panel/loading-panel.component'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { TelemetryComponent } from './telemetry.component'; describe('TelemetryComponent', () => { let component: TelemetryComponent; let fixture: ComponentFixture<TelemetryComponent>; let mgrModuleService: MgrModuleService; let options: any; let configs: any; let httpTesting: HttpTestingController; let router: Router; const optionsNames = [ 'channel_basic', 'channel_crash', 'channel_device', 'channel_ident', 'channel_perf', 'contact', 'description', 'device_url', 'enabled', 'interval', 'last_opt_revision', 'leaderboard', 'log_level', 'log_to_cluster', 'log_to_cluster_level', 'log_to_file', 'organization', 'proxy', 'url' ]; configureTestBed( { declarations: [TelemetryComponent], imports: [ HttpClientTestingModule, ReactiveFormsModule, RouterTestingModule, SharedModule, ToastrModule.forRoot() ] }, [LoadingPanelComponent, DownloadButtonComponent] ); describe('configForm', () => { beforeEach(() => { fixture = TestBed.createComponent(TelemetryComponent); component = fixture.componentInstance; mgrModuleService = TestBed.inject(MgrModuleService); options = {}; configs = {}; optionsNames.forEach((name) => (options[name] = { name })); optionsNames.forEach((name) => (configs[name] = true)); spyOn(mgrModuleService, 'getOptions').and.callFake(() => observableOf(options)); spyOn(mgrModuleService, 'getConfig').and.callFake(() => observableOf(configs)); fixture.detectChanges(); httpTesting = TestBed.inject(HttpTestingController); router = TestBed.inject(Router); spyOn(router, 'navigate'); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should show/hide ident fields on checking/unchecking', () => { const getContactField = () => fixture.debugElement.nativeElement.querySelector('input[id=contact]'); const getDescriptionField = () => fixture.debugElement.nativeElement.querySelector('input[id=description]'); const checkVisibility = () => { if (component.showContactInfo) { expect(getContactField()).toBeTruthy(); expect(getDescriptionField()).toBeTruthy(); } else { expect(getContactField()).toBeFalsy(); expect(getDescriptionField()).toBeFalsy(); } }; // Initial check. checkVisibility(); // toggle fields. component.toggleIdent(); fixture.detectChanges(); checkVisibility(); // toggle fields again. component.toggleIdent(); fixture.detectChanges(); checkVisibility(); }); it('should set module enability to true correctly', () => { expect(component.moduleEnabled).toBeTruthy(); }); it('should set module enability to false correctly', () => { configs['enabled'] = false; component.ngOnInit(); expect(component.moduleEnabled).toBeFalsy(); }); it('should filter options list correctly', () => { _.forEach(Object.keys(component.options), (option) => { expect(component.requiredFields).toContain(option); }); }); it('should disable the Telemetry module', () => { const message = 'Module disabled message.'; const followUpFunc = function () { return 'followUp'; }; component.disableModule(message, followUpFunc); const req = httpTesting.expectOne('api/telemetry'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ enable: false }); req.flush({}); }); it('should disable the Telemetry module with default parameters', () => { component.disableModule(); const req = httpTesting.expectOne('api/telemetry'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ enable: false }); req.flush({}); expect(router.navigate).toHaveBeenCalledWith(['']); }); }); describe('previewForm', () => { beforeEach(() => { fixture = TestBed.createComponent(TelemetryComponent); component = fixture.componentInstance; fixture.detectChanges(); httpTesting = TestBed.inject(HttpTestingController); router = TestBed.inject(Router); spyOn(router, 'navigate'); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should only replace the ranges and values of a JSON object', () => { expect( JSON.parse( component.replacerTest({ ranges: [ [null, -1], [0, 511], [512, 1023] ], values: [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ], other: [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] }) ) ).toStrictEqual({ ranges: ['[null,-1]', '[0,511]', '[512,1023]'], values: ['[0,0,0]', '[0,0,0]', '[0,0,0]'], other: [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ] }); expect( JSON.parse( component.replacerTest({ ranges: [ [null, -1], [0, 511], [512, 1023] ], values: [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ], other: true }) ) ).toStrictEqual({ ranges: ['[null,-1]', '[0,511]', '[512,1023]'], values: ['[0,0,0]', '[0,0,0]', '[0,0,0]'], other: true }); expect( JSON.parse( component.replacerTest({ ranges: [ [null, -1], [0, 511], [512, 1023] ], values: [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ], other: 1 }) ) ).toStrictEqual({ ranges: ['[null,-1]', '[0,511]', '[512,1023]'], values: ['[0,0,0]', '[0,0,0]', '[0,0,0]'], other: 1 }); expect( JSON.parse( component.replacerTest({ ranges: [ [null, -1], [0, 511], [512, 1023] ], values: [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ], other: { value: 0 } }) ) ).toStrictEqual({ ranges: ['[null,-1]', '[0,511]', '[512,1023]'], values: ['[0,0,0]', '[0,0,0]', '[0,0,0]'], other: { value: 0 } }); }); it('should remove perf channel fields from a report', () => { expect( JSON.parse( component.formatReportTest({ perf_counters: {}, stats_per_pool: {}, stats_per_pg: {}, io_rate: {}, osd_perf_histograms: {}, mempool: {}, heap_stats: {}, rocksdb_stats: {} }) ) ).toStrictEqual({}); expect( JSON.parse( component.formatReportTest({ perf_counters: {}, stats_per_pool: {}, stats_per_pg: {}, io_rate: {}, osd_perf_histograms: {}, mempool: {}, heap_stats: {}, rocksdb_stats: {}, other: {} }) ) ).toStrictEqual({ other: {} }); }); it('should submit', () => { component.onSubmit(); const req1 = httpTesting.expectOne('api/telemetry'); expect(req1.request.method).toBe('PUT'); expect(req1.request.body).toEqual({ enable: true, license_name: 'sharing-1-0' }); req1.flush({}); const req2 = httpTesting.expectOne({ url: 'api/mgr/module/telemetry', method: 'PUT' }); expect(req2.request.body).toEqual({ config: {} }); req2.flush({}); expect(router.url).toBe('/'); }); }); });
9,011
26.900929
108
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/telemetry/telemetry.component.ts
import { Component, OnInit } from '@angular/core'; import { ValidatorFn, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import _ from 'lodash'; import { forkJoin as observableForkJoin } from 'rxjs'; import { MgrModuleService } from '~/app/shared/api/mgr-module.service'; import { TelemetryService } from '~/app/shared/api/telemetry.service'; 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 { CdFormBuilder } from '~/app/shared/forms/cd-form-builder'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { NotificationService } from '~/app/shared/services/notification.service'; import { TelemetryNotificationService } from '~/app/shared/services/telemetry-notification.service'; @Component({ selector: 'cd-telemetry', templateUrl: './telemetry.component.html', styleUrls: ['./telemetry.component.scss'] }) export class TelemetryComponent extends CdForm implements OnInit { configForm: CdFormGroup; licenseAgrmt = false; moduleEnabled: boolean; options: Object = {}; newConfig: Object = {}; configResp: object = {}; previewForm: CdFormGroup; requiredFields = [ 'channel_basic', 'channel_crash', 'channel_device', 'channel_ident', 'channel_perf', 'interval', 'proxy', 'contact', 'description', 'organization' ]; contactInfofields = ['contact', 'description', 'organization']; report: object = undefined; reportId: number = undefined; sendToUrl = ''; sendToDeviceUrl = ''; step = 1; showContactInfo: boolean; constructor( public actionLabels: ActionLabelsI18n, private formBuilder: CdFormBuilder, private mgrModuleService: MgrModuleService, private notificationService: NotificationService, private router: Router, private telemetryService: TelemetryService, private telemetryNotificationService: TelemetryNotificationService ) { super(); } ngOnInit() { const observables = [ this.mgrModuleService.getOptions('telemetry'), this.mgrModuleService.getConfig('telemetry') ]; observableForkJoin(observables).subscribe( (resp: object) => { const configResp = resp[1]; this.moduleEnabled = configResp['enabled']; this.sendToUrl = configResp['url']; this.sendToDeviceUrl = configResp['device_url']; this.showContactInfo = configResp['channel_ident']; this.options = _.pick(resp[0], this.requiredFields); this.configResp = _.pick(configResp, this.requiredFields); this.createConfigForm(); this.configForm.setValue(this.configResp); this.loadingReady(); }, (_error) => { this.loadingError(); } ); } private createConfigForm() { const controlsConfig = {}; _.forEach(Object.values(this.options), (option) => { controlsConfig[option.name] = [option.default_value, this.getValidators(option)]; }); this.configForm = this.formBuilder.group(controlsConfig); } private replacer(key: string, value: any) { // Display the arrays of keys 'ranges' and 'values' horizontally as they take up too much space // and Stringify displays it in vertical by default. if ((key === 'ranges' || key === 'values') && Array.isArray(value)) { const elements = []; for (let i = 0; i < value.length; i++) { elements.push(JSON.stringify(value[i])); } return elements; } // Else, just return the value as is, without any formatting. return value; } replacerTest(report: object) { return JSON.stringify(report, this.replacer, 2); } private formatReport() { let copy = {}; copy = JSON.parse(JSON.stringify(this.report)); const perf_keys = [ 'perf_counters', 'stats_per_pool', 'stats_per_pg', 'io_rate', 'osd_perf_histograms', 'mempool', 'heap_stats', 'rocksdb_stats' ]; for (let i = 0; i < perf_keys.length; i++) { const key = perf_keys[i]; if (key in copy['report']) { delete copy['report'][key]; } } return JSON.stringify(copy, null, 2); } formatReportTest(report: object) { let copy = {}; copy = JSON.parse(JSON.stringify(report)); const perf_keys = [ 'perf_counters', 'stats_per_pool', 'stats_per_pg', 'io_rate', 'osd_perf_histograms', 'mempool', 'heap_stats', 'rocksdb_stats' ]; for (let i = 0; i < perf_keys.length; i++) { const key = perf_keys[i]; if (key in copy) { delete copy[key]; } } return JSON.stringify(copy, null, 2); } private createPreviewForm() { const controls = { report: this.formatReport(), reportId: this.reportId, licenseAgrmt: [this.licenseAgrmt, Validators.requiredTrue] }; this.previewForm = this.formBuilder.group(controls); } private getValidators(option: any): ValidatorFn[] { const result = []; switch (option.type) { case 'int': result.push(Validators.required); break; case 'str': if (_.isNumber(option.min)) { result.push(Validators.minLength(option.min)); } if (_.isNumber(option.max)) { result.push(Validators.maxLength(option.max)); } break; } return result; } private updateReportFromConfig(updatedConfig: Object = {}) { // update channels const availableChannels: string[] = this.report['report']['channels_available']; const updatedChannels = []; for (const channel of availableChannels) { const key = `channel_${channel}`; if (updatedConfig[key]) { updatedChannels.push(channel); } } this.report['report']['channels'] = updatedChannels; // update contactInfo for (const contactInfofield of this.contactInfofields) { this.report['report'][contactInfofield] = updatedConfig[contactInfofield]; } } private getReport() { this.loadingStart(); this.telemetryService.getReport().subscribe( (resp: object) => { this.report = resp; this.reportId = resp['report']['report_id']; this.updateReportFromConfig(this.newConfig); this.createPreviewForm(); this.loadingReady(); this.step++; }, (_error) => { this.loadingError(); } ); } toggleIdent() { this.showContactInfo = !this.showContactInfo; } buildReport() { this.newConfig = {}; for (const option of Object.values(this.options)) { const control = this.configForm.get(option.name); // Append the option only if they are valid if (control.valid) { this.newConfig[option.name] = control.value; } else { this.configForm.setErrors({ cdSubmitButton: true }); return; } } // reset contact info field if ident channel is off if (!this.newConfig['channel_ident']) { for (const contactInfofield of this.contactInfofields) { this.newConfig[contactInfofield] = ''; } } this.getReport(); } disableModule(message: string = null, followUpFunc: Function = null) { this.telemetryService.enable(false).subscribe(() => { this.telemetryNotificationService.setVisibility(true); if (message) { this.notificationService.show(NotificationType.success, message); } if (followUpFunc) { followUpFunc(); } else { this.router.navigate(['']); } }); } next() { this.buildReport(); } back() { this.step--; } getChangedConfig() { const updatedConfig = {}; _.forEach(this.requiredFields, (configField) => { if (!_.isEqual(this.configResp[configField], this.newConfig[configField])) { updatedConfig[configField] = this.newConfig[configField]; } }); return updatedConfig; } onSubmit() { const updatedConfig = this.getChangedConfig(); const observables = [ this.telemetryService.enable(), this.mgrModuleService.updateConfig('telemetry', updatedConfig) ]; observableForkJoin(observables).subscribe( () => { this.telemetryNotificationService.setVisibility(false); this.notificationService.show( NotificationType.success, $localize`The Telemetry module has been configured and activated successfully.` ); }, () => { this.telemetryNotificationService.setVisibility(false); this.notificationService.show( NotificationType.error, $localize`An Error occurred while updating the Telemetry module configuration.\ Please Try again` ); // Reset the 'Update' button. this.previewForm.setErrors({ cdSubmitButton: true }); }, () => { this.newConfig = {}; this.router.navigate(['']); } ); } }
9,037
28.344156
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/upgrade/upgrade.component.html
<ng-container *ngIf="{upgradeInfo: upgradeInfo$ | async, error: upgradeInfoError$ } as upgrade"> <div class="row h-25 ms-1" *ngIf="!upgrade.upgradeInfoError && upgrade.upgradeInfo as upgradeInfo; else checkUpgrade"> <ng-container *ngIf="healthData$ | async as healthData"> <div class="col-lg-3 h-50 d-flex flex-column border justify-content-center align-items-center"> <span class="bold">Current Version</span> <span class="mt-1">{{ version }}</span> </div> <div class="col-lg-3 h-50 d-flex flex-column border justify-content-center align-items-center"> <span class="bold">Cluster Status</span> <ng-template #healthChecks> <ul> <li *ngFor="let check of healthData.health.checks"> <span [ngStyle]="check.severity | healthColor" [class.health-warn-description]="check.severity === 'HEALTH_WARN'"> {{ check.type }}</span>: {{ check.summary.message }} </li> </ul> </ng-template> <div class="info-card-content-clickable mt-1" [ngStyle]="healthData.health.status | healthColor" [ngbPopover]="healthChecks" popoverClass="info-card-popover-cluster-status"> {{ healthData.health.status | healthLabel | uppercase }} <i *ngIf="healthData.health?.status !== 'HEALTH_OK'" class="fa fa-exclamation-triangle"></i> </div> </div> <div class="col-lg-3 h-50 d-flex flex-column border justify-content-center align-items-center"> <span class="bold">Upgrade Status</span> <ng-container *ngIf="upgradeInfo.versions.length > 0; else noUpgradesAvailable"> <span class="mt-2" i18n> <i [ngClass]="[icons.up]" class="text-info"></i> Upgrade available</span> <div i18n-ngbTooltip [ngbTooltip]="(healthData.mgr_map | mgrSummary).total <= 1 ? 'To upgrade, you need minimum 2 mgr daemons.' : ''"> <button class="btn btn-accent mt-2" id="upgrade" aria-label="Upgrade now" [disabled]="(healthData.mgr_map | mgrSummary).total <= 1" i18n>Upgrade now</button> </div> </ng-container> </div> <div class="col-lg-3 h-50 d-flex flex-column border justify-content-center align-items-center"> <span class="bold">MGR Count</span> <span class="mt-1"> <i class="text-success" [ngClass]="[icons.success]" *ngIf="(healthData.mgr_map | mgrSummary).total > 1; else warningIcon"> </i> {{ (healthData.mgr_map | mgrSummary).total }} </span> </div> <div class="d-flex mt-3 p-0"> <dl class="w-50" *ngIf="fsid$ | async as fsid"> <dt class="bold mt-5" i18n>Cluster FSID</dt> <dd class="mt-2">{{ fsid }}</dd> <dt class="bold mt-5" i18n>Release Image</dt> <dd class="mt-2">{{ upgradeInfo.image }}</dd> <dt class="bold mt-5" i18n>Registry</dt> <dd class="mt-2">{{ upgradeInfo.registry }}</dd> </dl> </div> </ng-container> </div> </ng-container> <ng-template #checkUpgrade> <div class="row h-75 justify-content-center align-items-center"> <h3 class="mt-1 bold text-center" id="checking-for-upgrades" i18n>Checking for upgrades <i [ngClass]="[icons.spin, icons.spinner]"></i> </h3> </div> </ng-template> <ng-template #noUpgradesAvailable> <span class="mt-1" id="no-upgrades-available" i18n> <i [ngClass]="[icons.success]" class="text-success"></i> Cluster is up-to-date </span> </ng-template> <ng-template #warningIcon> <i class="text-warning" [ngClass]="[icons.warning]" title="To upgrade, you need minimum 2 mgr daemons."> </i> </ng-template>
3,993
38.156863
128
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/upgrade/upgrade.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { UpgradeComponent } from './upgrade.component'; import { configureTestBed } from '~/testing/unit-test-helper'; import { SummaryService } from '~/app/shared/services/summary.service'; import { BehaviorSubject, of } from 'rxjs'; import { UpgradeService } from '~/app/shared/api/upgrade.service'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { UpgradeInfoInterface } from '~/app/shared/models/upgrade.interface'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { HealthService } from '~/app/shared/api/health.service'; import { SharedModule } from '~/app/shared/shared.module'; export class SummaryServiceMock { summaryDataSource = new BehaviorSubject({ version: 'ceph version 17.0.0-12222-gcd0cd7cb ' + '(b8193bb4cda16ccc5b028c3e1df62bc72350a15d) quincy (dev)' }); summaryData$ = this.summaryDataSource.asObservable(); subscribe(call: any) { return this.summaryData$.subscribe(call); } } describe('UpgradeComponent', () => { let component: UpgradeComponent; let fixture: ComponentFixture<UpgradeComponent>; let upgradeInfoSpy: jasmine.Spy; let getHealthSpy: jasmine.Spy; const healthPayload: Record<string, any> = { health: { status: 'HEALTH_OK' }, mon_status: { monmap: { mons: [] }, quorum: [] }, osd_map: { osds: [] }, mgr_map: { active_name: 'test_mgr', standbys: [] }, hosts: 0, rgw: 0, fs_map: { filesystems: [], standbys: [] }, iscsi_daemons: 1, client_perf: {}, scrub_status: 'Inactive', pools: [], df: { stats: {} }, pg_info: { object_stats: { num_objects: 1 } } }; configureTestBed({ imports: [HttpClientTestingModule, SharedModule], schemas: [NO_ERRORS_SCHEMA], declarations: [UpgradeComponent], providers: [UpgradeService, { provide: SummaryService, useClass: SummaryServiceMock }] }); beforeEach(() => { fixture = TestBed.createComponent(UpgradeComponent); component = fixture.componentInstance; upgradeInfoSpy = spyOn(TestBed.inject(UpgradeService), 'list'); getHealthSpy = spyOn(TestBed.inject(HealthService), 'getMinimalHealth'); getHealthSpy.and.returnValue(of(healthPayload)); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should load the view once check for upgrade is done', () => { const upgradeInfoPayload = { image: 'quay.io/ceph-test/ceph', registry: 'quay.io', versions: ['18.1.0', '18.1.1', '18.1.2'] }; upgradeInfoSpy.and.returnValue(of(upgradeInfoPayload)); component.ngOnInit(); fixture.detectChanges(); const firstCellSpan = fixture.debugElement.nativeElement.querySelector('span'); expect(firstCellSpan.textContent).toBe('Current Version'); }); it('should show button to Upgrade if a new version is available', () => { const upgradeInfoPayload = { image: 'quay.io/ceph-test/ceph', registry: 'quay.io', versions: ['18.1.0', '18.1.1', '18.1.2'] }; upgradeInfoSpy.and.returnValue(of(upgradeInfoPayload)); component.ngOnInit(); fixture.detectChanges(); const upgradeNowBtn = fixture.debugElement.nativeElement.querySelector('#upgrade'); expect(upgradeNowBtn).not.toBeNull(); }); it('should not show the upgrade button if there are no new version available', () => { const upgradeInfoPayload: UpgradeInfoInterface = { image: 'quay.io/ceph-test/ceph', registry: 'quay.io', versions: [] }; upgradeInfoSpy.and.returnValue(of(upgradeInfoPayload)); component.ngOnInit(); fixture.detectChanges(); const noUpgradesSpan = fixture.debugElement.nativeElement.querySelector( '#no-upgrades-available' ); expect(noUpgradesSpan.textContent).toBe(' Cluster is up-to-date '); }); it('should show the loading screen while the api call is pending', () => { const loading = fixture.debugElement.nativeElement.querySelector('h3'); expect(loading.textContent).toBe('Checking for upgrades '); }); it('should upgrade only when there are more than 1 mgr', () => { const upgradeInfoPayload = { image: 'quay.io/ceph-test/ceph', registry: 'quay.io', versions: ['18.1.0', '18.1.1', '18.1.2'] }; upgradeInfoSpy.and.returnValue(of(upgradeInfoPayload)); component.ngOnInit(); fixture.detectChanges(); const upgradeBtn = fixture.debugElement.nativeElement.querySelector('#upgrade'); expect(upgradeBtn.disabled).toBeTruthy(); // Add a standby mgr to the payload const healthPayload2: Record<string, any> = { health: { status: 'HEALTH_OK' }, mon_status: { monmap: { mons: [] }, quorum: [] }, osd_map: { osds: [] }, mgr_map: { active_name: 'test_mgr', standbys: ['mgr1'] }, hosts: 0, rgw: 0, fs_map: { filesystems: [], standbys: [] }, iscsi_daemons: 1, client_perf: {}, scrub_status: 'Inactive', pools: [], df: { stats: {} }, pg_info: { object_stats: { num_objects: 1 } } }; getHealthSpy.and.returnValue(of(healthPayload2)); component.ngOnInit(); fixture.detectChanges(); expect(upgradeBtn.disabled).toBeFalsy(); }); });
5,272
34.153333
90
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/upgrade/upgrade.component.ts
import { Component, OnInit } from '@angular/core'; import { Observable, of } from 'rxjs'; import { catchError, ignoreElements } from 'rxjs/operators'; import { HealthService } from '~/app/shared/api/health.service'; import { UpgradeService } from '~/app/shared/api/upgrade.service'; import { Icons } from '~/app/shared/enum/icons.enum'; import { Permission } from '~/app/shared/models/permissions'; import { UpgradeInfoInterface } from '~/app/shared/models/upgrade.interface'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { SummaryService } from '~/app/shared/services/summary.service'; @Component({ selector: 'cd-upgrade', templateUrl: './upgrade.component.html', styleUrls: ['./upgrade.component.scss'] }) export class UpgradeComponent implements OnInit { version: string; upgradeInfo$: Observable<UpgradeInfoInterface>; upgradeInfoError$: Observable<any>; permission: Permission; healthData$: Observable<any>; fsid$: Observable<any>; icons = Icons; constructor( private summaryService: SummaryService, private upgradeService: UpgradeService, private authStorageService: AuthStorageService, private healthService: HealthService ) { this.permission = this.authStorageService.getPermissions().configOpt; } ngOnInit(): void { this.summaryService.subscribe((summary) => { const version = summary.version.replace('ceph version ', '').split('-'); this.version = version[0]; }); this.upgradeInfo$ = this.upgradeService.list(); this.upgradeInfoError$ = this.upgradeInfo$?.pipe( ignoreElements(), catchError((error) => of(error)) ); this.healthData$ = this.healthService.getMinimalHealth(); this.fsid$ = this.healthService.getClusterFsid(); } }
1,787
34.76
80
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard-v3.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { NgbNavModule, NgbPopoverModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'; import { ChartsModule } from 'ng2-charts'; import { SimplebarAngularModule } from 'simplebar-angular'; import { SharedModule } from '~/app/shared/shared.module'; import { CephSharedModule } from '../shared/ceph-shared.module'; import { CardComponent } from './card/card.component'; import { DashboardAreaChartComponent } from './dashboard-area-chart/dashboard-area-chart.component'; import { DashboardPieComponent } from './dashboard-pie/dashboard-pie.component'; import { DashboardTimeSelectorComponent } from './dashboard-time-selector/dashboard-time-selector.component'; import { DashboardV3Component } from './dashboard/dashboard-v3.component'; import { CardRowComponent } from './card-row/card-row.component'; import { PgSummaryPipe } from './pg-summary.pipe'; @NgModule({ imports: [ CephSharedModule, CommonModule, NgbNavModule, SharedModule, ChartsModule, RouterModule, NgbPopoverModule, NgbTooltipModule, FormsModule, ReactiveFormsModule, SimplebarAngularModule ], declarations: [ DashboardV3Component, CardComponent, DashboardPieComponent, CardRowComponent, PgSummaryPipe, DashboardAreaChartComponent, DashboardTimeSelectorComponent ], exports: [DashboardV3Component] }) export class DashboardV3Module {}
1,601
32.375
109
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/pg-summary.pipe.spec.ts
import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { PgCategoryService } from '../shared/pg-category.service'; import { PgSummaryPipe } from './pg-summary.pipe'; describe('OsdSummaryPipe', () => { let pipe: PgSummaryPipe; configureTestBed({ providers: [PgSummaryPipe, PgCategoryService] }); beforeEach(() => { pipe = TestBed.inject(PgSummaryPipe); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('tranforms value', () => { const value = { statuses: { 'active+clean': 241 }, pgs_per_osd: 241 }; expect(pipe.transform(value)).toEqual({ categoryPgAmount: { clean: 241 }, total: 241 }); }); });
786
20.27027
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/pg-summary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; import { PgCategoryService } from '~/app/ceph/shared/pg-category.service'; @Pipe({ name: 'pgSummary' }) export class PgSummaryPipe implements PipeTransform { constructor(private pgCategoryService: PgCategoryService) {} transform(value: any): any { const categoryPgAmount: Record<string, number> = {}; let total = 0; _.forEach(value.statuses, (pgAmount, pgStatesText) => { const categoryType = this.pgCategoryService.getTypeByStates(pgStatesText); if (_.isUndefined(categoryPgAmount[categoryType])) { categoryPgAmount[categoryType] = 0; } categoryPgAmount[categoryType] += pgAmount; total += pgAmount; }); return { categoryPgAmount, total }; } }
806
27.821429
80
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/card-row/card-row.component.html
<div class="d-flex pl-1 pb-2 pt-2"> <div class="ms-2 me-auto"> <a [routerLink]="link" *ngIf="link && total > 0; else noLinkTitle" [ngPlural]="total" i18n> {{ total }} <ng-template ngPluralCase="=0">{{ title }}</ng-template> <ng-template ngPluralCase="=1">{{ title }}</ng-template> <ng-template ngPluralCase="other">{{ title }}s</ng-template> </a> </div> <ng-container [ngSwitch]="summaryType"> <ng-container *ngSwitchCase="'iscsi'"> <ng-container *ngTemplateOutlet="iscsiSummary"></ng-container> </ng-container> <ng-container *ngSwitchCase="'osd'"> <ng-container *ngTemplateOutlet="osdSummary"></ng-container> </ng-container> <ng-container *ngSwitchCase="'simplified'"> <ng-container *ngTemplateOutlet="simplifiedSummary"></ng-container> </ng-container> <ng-container *ngSwitchDefault> <ng-container *ngTemplateOutlet="defaultSummary"></ng-container> </ng-container> </ng-container> </div> <ng-template #defaultSummary> <span *ngIf="data.success || data.categoryPgAmount?.clean || (data.success === 0 && data.total === 0)"> <span *ngIf="data.success || (data.success === 0 && data.total === 0)"> {{ data.success }} </span> <span *ngIf="data.categoryPgAmount?.clean"> {{ data.categoryPgAmount?.clean }} </span> <i class="text-success" [ngClass]="[icons.success]"> </i> </span> <span *ngIf="data.info" class="ms-2"> <span *ngIf="data.info"> {{ data.info }} </span> <i class="text-info" [ngClass]="[icons.danger]"> </i> </span> <span *ngIf="data.warn || data.categoryPgAmount?.warning" class="ms-2"> <span *ngIf="data.warn"> {{ data.warn }} </span> <span *ngIf="data.categoryPgAmount?.warning"> {{ data.categoryPgAmount?.warning }} </span> <i class="text-warning" [ngClass]="[icons.warning]"> </i> </span> <span *ngIf="data.error || data.categoryPgAmount?.unknown" class="ms-2"> <span *ngIf="data.error"> {{ data.error }} </span> <span *ngIf="data.categoryPgAmount?.unknown"> {{ data.categoryPgAmount?.unknown }} </span> <i class="text-danger" [ngClass]="[icons.danger]"> </i> </span> <span *ngIf="data.categoryPgAmount?.working" class="ms-2"> <span *ngIf="data.categoryPgAmount?.working"> {{ data.categoryPgAmount?.working }} </span> <i class="text-warning" [ngClass]="[icons.spinner, icons.spin]"> </i> </span> </ng-template> <ng-template #osdSummary> <span *ngIf="data.up === data.in"> {{ data.up }} <i class="text-success" [ngClass]="[icons.success]"> </i> </span> <span *ngIf="data.up !== data.in"> {{ data.up }} <span class="fw-bold text-success"> up </span> </span> <span *ngIf="data.in !== data.up" class="ms-2"> {{ data.in }} <span class="fw-bold text-success"> in </span> </span> <span *ngIf="data.down" class="ms-2"> {{ data.down }} <span class="fw-bold text-danger me-2"> down </span> </span> <span *ngIf="data.out" class="ms-2"> {{ data.out }} <span class="fw-bold text-danger me-2"> out </span> </span> <span *ngIf="data.nearfull" class="ms-2"> {{ data.nearfull }} <span class="fw-bold text-warning me-2"> nearfull</span></span> <span *ngIf="data.full" class="ms-2"> {{ data.full }} <span class="fw-bold text-danger"> full </span> </span> </ng-template> <ng-template #iscsiSummary> <span> {{ data.up }} <i class="text-success" *ngIf="data.up || data.up === 0" [ngClass]="[icons.success]"> </i> </span> <span *ngIf="data.down" class="ms-2"> {{ data.down }} <i class="text-danger" [ngClass]="[icons.danger]"> </i> </span> </ng-template> <ng-template #simplifiedSummary> <span> {{ data }} <i class="text-success" [ngClass]="[icons.success]"></i> </span> </ng-template> <ng-template #noLinkTitle> <span *ngIf="total || total === 0" [ngPlural]="total"> {{ total }} <ng-template ngPluralCase="=0">{{ title }}</ng-template> <ng-template ngPluralCase="=1">{{ title }}</ng-template> <ng-template ngPluralCase="other">{{ title }}s</ng-template> </span> </ng-template>
4,450
25.494048
105
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/card-row/card-row.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { CardRowComponent } from './card-row.component'; describe('CardRowComponent', () => { let component: CardRowComponent; let fixture: ComponentFixture<CardRowComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [CardRowComponent] }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(CardRowComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); });
598
23.958333
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/card-row/card-row.component.ts
import { Component, Input, OnChanges } from '@angular/core'; import { Icons } from '~/app/shared/enum/icons.enum'; @Component({ selector: 'cd-card-row', templateUrl: './card-row.component.html', styleUrls: ['./card-row.component.scss'] }) export class CardRowComponent implements OnChanges { @Input() title: string; @Input() link: string; @Input() data: any; @Input() summaryType = 'default'; icons = Icons; total: number; ngOnChanges(): void { if (this.data.total || this.data.total === 0) { this.total = this.data.total; } else if (this.summaryType === 'iscsi') { this.total = this.data.up + this.data.down || 0; } else { this.total = this.data; } } }
724
19.714286
60
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/card/card.component.html
<div class="card shadow-sm flex-fill"> <h4 class="card-title mt-4 ms-4 mb-0"> {{ cardTitle }} </h4> <div class="card-body ps-0 pe-0"> <ng-content></ng-content> </div> </div>
190
20.222222
40
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/card/card.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { CardComponent } from './card.component'; describe('CardComponent', () => { let component: CardComponent; let fixture: ComponentFixture<CardComponent>; configureTestBed({ imports: [RouterTestingModule], declarations: [CardComponent] }); beforeEach(() => { fixture = TestBed.createComponent(CardComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); it('Setting cards title makes title visible', () => { const title = 'Card Title'; component.cardTitle = title; fixture.detectChanges(); const titleDiv = fixture.debugElement.nativeElement.querySelector('.card-title'); expect(titleDiv.textContent).toContain(title); }); });
954
27.088235
85
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/card/card.component.ts
import { Component, Input } from '@angular/core'; @Component({ selector: 'cd-card', templateUrl: './card.component.html', styleUrls: ['./card.component.scss'] }) export class CardComponent { @Input() cardTitle: string; }
232
18.416667
49
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard-area-chart/dashboard-area-chart.component.html
<div class="row"> <div class="col-3 center-text"> <br> <b class="chartTitle" i18n>{{ chartTitle }}</b> <br> <span [ngbTooltip]="label" i18n>{{currentData}} {{ currentDataUnits }}</span> <br> <span [ngbTooltip]="label2" i18n>{{currentData2}} {{ currentDataUnits2 }}</span> </div> <div class="col-9"> <div class="chart"> <canvas baseChart [datasets]="chartData.dataset" [options]="options" [chartType]="'line'" [plugins]="chartAreaBorderPlugin"> </canvas> </div> </div> </div>
610
24.458333
62
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard-area-chart/dashboard-area-chart.component.spec.ts
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { DimlessBinaryPerSecondPipe } from '~/app/shared/pipes/dimless-binary-per-second.pipe'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { DimlessPipe } from '~/app/shared/pipes/dimless.pipe'; import { FormatterService } from '~/app/shared/services/formatter.service'; import { configureTestBed } from '~/testing/unit-test-helper'; import { DashboardAreaChartComponent } from './dashboard-area-chart.component'; describe('DashboardAreaChartComponent', () => { let component: DashboardAreaChartComponent; let fixture: ComponentFixture<DashboardAreaChartComponent>; configureTestBed({ schemas: [NO_ERRORS_SCHEMA], declarations: [DashboardAreaChartComponent], providers: [ CssHelper, DimlessBinaryPipe, DimlessBinaryPerSecondPipe, DimlessPipe, FormatterService ] }); beforeEach(() => { fixture = TestBed.createComponent(DashboardAreaChartComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,257
33
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard-area-chart/dashboard-area-chart.component.ts
import { AfterViewInit, Component, Input, OnChanges, ViewChild } from '@angular/core'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { DimlessBinaryPerSecondPipe } from '~/app/shared/pipes/dimless-binary-per-second.pipe'; import { FormatterService } from '~/app/shared/services/formatter.service'; import { BaseChartDirective, PluginServiceGlobalRegistrationAndOptions } from 'ng2-charts'; import { DimlessPipe } from '~/app/shared/pipes/dimless.pipe'; import { NumberFormatterService } from '~/app/shared/services/number-formatter.service'; @Component({ selector: 'cd-dashboard-area-chart', templateUrl: './dashboard-area-chart.component.html', styleUrls: ['./dashboard-area-chart.component.scss'] }) export class DashboardAreaChartComponent implements OnChanges, AfterViewInit { @ViewChild(BaseChartDirective) chart: BaseChartDirective; @Input() chartTitle: string; @Input() maxValue?: number; @Input() dataUnits: string; @Input() data: Array<[number, string]>; @Input() data2?: Array<[number, string]>; @Input() label: string; @Input() label2?: string; @Input() decimals?: number = 1; currentDataUnits: string; currentData: number; currentDataUnits2?: string; currentData2?: number; chartDataUnits: string; chartData: any = { dataset: [ { label: '', data: [{ x: 0, y: 0 }], tension: 0, pointBackgroundColor: this.cssHelper.propertyValue('chart-color-strong-blue'), backgroundColor: this.cssHelper.propertyValue('chart-color-translucent-blue'), borderColor: this.cssHelper.propertyValue('chart-color-strong-blue') }, { label: '', data: [], tension: 0, pointBackgroundColor: this.cssHelper.propertyValue('chart-color-orange'), backgroundColor: this.cssHelper.propertyValue('chart-color-yellow'), borderColor: this.cssHelper.propertyValue('chart-color-orange') } ] }; options: any = { responsive: true, maintainAspectRatio: false, elements: { point: { radius: 0 } }, legend: { display: false }, tooltips: { intersect: false, displayColors: true, backgroundColor: this.cssHelper.propertyValue('chart-color-tooltip-background'), callbacks: { title: function (tooltipItem: any): any { return tooltipItem[0].xLabel; } } }, hover: { intersect: false }, scales: { xAxes: [ { display: false, type: 'time', gridLines: { display: false }, time: { tooltipFormat: 'YYYY/MM/DD hh:mm:ss' } } ], yAxes: [ { gridLines: { display: false }, ticks: { beginAtZero: true, maxTicksLimit: 3, callback: (value: any) => { if (value === 0) { return null; } return this.fillString(this.convertUnits(value)); } } } ] }, plugins: { borderArea: true, chartAreaBorder: { borderColor: this.cssHelper.propertyValue('chart-color-slight-dark-gray'), borderWidth: 2 } } }; public chartAreaBorderPlugin: PluginServiceGlobalRegistrationAndOptions[] = [ { beforeDraw(chart: Chart) { if (!chart.options.plugins.borderArea) { return; } const { ctx, chartArea: { left, top, right, bottom } } = chart; ctx.save(); ctx.strokeStyle = chart.options.plugins.chartAreaBorder.borderColor; ctx.lineWidth = chart.options.plugins.chartAreaBorder.borderWidth; ctx.setLineDash(chart.options.plugins.chartAreaBorder.borderDash || []); ctx.lineDashOffset = chart.options.plugins.chartAreaBorder.borderDashOffset; ctx.strokeRect(left, top, right - left - 1, bottom); ctx.restore(); } } ]; constructor( private cssHelper: CssHelper, private dimlessBinary: DimlessBinaryPipe, private dimlessBinaryPerSecond: DimlessBinaryPerSecondPipe, private dimlessPipe: DimlessPipe, private formatter: FormatterService, private numberFormatter: NumberFormatterService ) {} ngOnChanges(): void { this.updateChartData(); } ngAfterViewInit(): void { this.updateChartData(); } private updateChartData(): void { if (this.data) { this.setChartTicks(); this.chartData.dataset[0].data = this.formatData(this.data); this.chartData.dataset[0].label = this.label; [this.currentData, this.currentDataUnits] = this.convertUnits( this.data[this.data.length - 1][1] ).split(' '); } if (this.data2) { this.chartData.dataset[1].data = this.formatData(this.data2); this.chartData.dataset[1].label = this.label2; [this.currentData2, this.currentDataUnits2] = this.convertUnits( this.data2[this.data2.length - 1][1] ).split(' '); } if (this.chart) { this.chart.chart.update(); } } private formatData(array: Array<any>): any { let formattedData = {}; formattedData = array.map((data: any) => ({ x: data[0] * 1000, y: Number(this.convertToChartDataUnits(data[1]).replace(/[^\d,.]+/g, '')) })); return formattedData; } private convertToChartDataUnits(data: any): any { let dataWithUnits: string = ''; if (this.chartDataUnits) { if (this.dataUnits === 'B') { dataWithUnits = this.numberFormatter.formatBytesFromTo( data, this.dataUnits, this.chartDataUnits ); } else if (this.dataUnits === 'B/s') { dataWithUnits = this.numberFormatter.formatBytesPerSecondFromTo( data, this.dataUnits, this.chartDataUnits ); } else if (this.dataUnits === 'ms') { dataWithUnits = this.numberFormatter.formatSecondsFromTo( data, this.dataUnits, this.chartDataUnits, this.decimals ); } else { dataWithUnits = this.numberFormatter.formatUnitlessFromTo( data, this.dataUnits, this.chartDataUnits ); } } return dataWithUnits; } private convertUnits(data: any): any { let dataWithUnits: string = ''; if (this.dataUnits === 'B') { dataWithUnits = this.dimlessBinary.transform(data); } else if (this.dataUnits === 'B/s') { dataWithUnits = this.dimlessBinaryPerSecond.transform(data); } else if (this.dataUnits === 'ms') { dataWithUnits = this.formatter.format_number(data, 1000, ['ms', 's'], this.decimals); } else { dataWithUnits = this.dimlessPipe.transform(data); } return dataWithUnits; } private fillString(str: string): string { let maxNumberOfChar: number = 8; let numberOfChars: number = str.length; if (str.length < 4) { maxNumberOfChar = 11; } for (; numberOfChars < maxNumberOfChar; numberOfChars++) { str = '\u00A0' + str; } return str + '\u00A0\u00A0'; } private setChartTicks() { if (!this.chart) { return; } let maxValue = 0; let maxValueDataUnits = ''; let extraRoom = 1.2; if (this.maxValue) { extraRoom = 1.0; [maxValue, maxValueDataUnits] = this.convertUnits(this.maxValue).split(' '); } else if (this.data) { extraRoom = 1.2; let maxValueData = Math.max(...this.data.map((values: any) => values[1])); if (this.data2) { let maxValueData2 = Math.max(...this.data2.map((values: any) => values[1])); maxValue = Math.max(maxValueData, maxValueData2); } else { maxValue = maxValueData; } [maxValue, maxValueDataUnits] = this.convertUnits(maxValue).split(' '); } const yAxesTicks = this.chart.chart.options.scales.yAxes[0].ticks; yAxesTicks.suggestedMax = maxValue * extraRoom; yAxesTicks.suggestedMin = 0; yAxesTicks.stepSize = Number((yAxesTicks.suggestedMax / 2).toFixed(0)); yAxesTicks.callback = (value: any) => { if (value === 0) { return null; } if (!maxValueDataUnits) { return this.fillString(`${value}`); } return this.fillString(`${value} ${maxValueDataUnits}`); }; this.chartDataUnits = maxValueDataUnits || ''; this.chart.chart.update(); } }
8,586
28.010135
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard-pie/dashboard-pie.component.html
<div class="chart-container"> <canvas baseChart #chartCanvas [datasets]="chartConfig.dataset" [chartType]="chartConfig.chartType" [options]="chartConfig.options" [labels]="chartConfig.labels" [colors]="chartConfig.colors" [plugins]="doughnutChartPlugins" class="chart-canvas"> </canvas> <div class="chartjs-tooltip" #chartTooltip> <table></table> </div> </div>
460
26.117647
45
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard-pie/dashboard-pie.component.spec.ts
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { configureTestBed } from '~/testing/unit-test-helper'; import { DashboardPieComponent } from './dashboard-pie.component'; describe('DashboardPieComponent', () => { let component: DashboardPieComponent; let fixture: ComponentFixture<DashboardPieComponent>; configureTestBed({ schemas: [NO_ERRORS_SCHEMA], declarations: [DashboardPieComponent], providers: [CssHelper, DimlessBinaryPipe] }); beforeEach(() => { fixture = TestBed.createComponent(DashboardPieComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); });
884
30.607143
75
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard-pie/dashboard-pie.component.ts
import { Component, Input, OnChanges, OnInit } from '@angular/core'; import * as Chart from 'chart.js'; import _ from 'lodash'; import { PluginServiceGlobalRegistrationAndOptions } from 'ng2-charts'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; @Component({ selector: 'cd-dashboard-pie', templateUrl: './dashboard-pie.component.html', styleUrls: ['./dashboard-pie.component.scss'] }) export class DashboardPieComponent implements OnChanges, OnInit { @Input() data: any; @Input() highThreshold: number; @Input() lowThreshold: number; color: string; chartConfig: any = { chartType: 'doughnut', labels: ['', '', ''], dataset: [ { label: null, backgroundColor: [ this.cssHelper.propertyValue('chart-color-light-gray'), this.cssHelper.propertyValue('chart-color-slight-dark-gray'), this.cssHelper.propertyValue('chart-color-dark-gray') ] }, { label: null, borderWidth: 0, backgroundColor: [ this.cssHelper.propertyValue('chart-color-blue'), this.cssHelper.propertyValue('chart-color-white') ] } ], options: { cutoutPercentage: 70, events: ['click', 'mouseout', 'touchstart'], legend: { display: true, position: 'right', labels: { boxWidth: 10, usePointStyle: false, generateLabels: (chart: any) => { const labels = { 0: {}, 1: {}, 2: {} }; labels[0] = { text: $localize`Used: ${chart.data.datasets[1].data[2]}`, fillStyle: chart.data.datasets[1].backgroundColor[0], strokeStyle: chart.data.datasets[1].backgroundColor[0] }; labels[1] = { text: $localize`Warning: ${chart.data.datasets[0].data[0]}%`, fillStyle: chart.data.datasets[0].backgroundColor[1], strokeStyle: chart.data.datasets[0].backgroundColor[1] }; labels[2] = { text: $localize`Danger: ${ chart.data.datasets[0].data[0] + chart.data.datasets[0].data[1] }%`, fillStyle: chart.data.datasets[0].backgroundColor[2], strokeStyle: chart.data.datasets[0].backgroundColor[2] }; return labels; } } }, plugins: { center_text: true }, tooltips: { enabled: true, displayColors: false, backgroundColor: this.cssHelper.propertyValue('chart-color-tooltip-background'), cornerRadius: 0, bodyFontSize: 14, bodyFontStyle: '600', position: 'nearest', xPadding: 12, yPadding: 12, filter: (tooltipItem: any) => { return tooltipItem.datasetIndex === 1; }, callbacks: { label: (item: Record<string, any>, data: Record<string, any>) => { let text = data.labels[item.index]; if (!text.includes('%')) { text = `${text} (${data.datasets[item.datasetIndex].data[item.index]}%)`; } return text; } } }, title: { display: false } } }; public doughnutChartPlugins: PluginServiceGlobalRegistrationAndOptions[] = [ { id: 'center_text', beforeDraw(chart: Chart) { const cssHelper = new CssHelper(); const defaultFontFamily = 'Helvetica Neue, Helvetica, Arial, sans-serif'; Chart.defaults.global.defaultFontFamily = defaultFontFamily; const ctx = chart.ctx; if (!chart.options.plugins.center_text || !chart.data.datasets[0].label) { return; } ctx.save(); const label = chart.data.datasets[0].label[0].split('\n'); const centerX = (chart.chartArea.left + chart.chartArea.right) / 2; const centerY = (chart.chartArea.top + chart.chartArea.bottom) / 2; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.font = `24px ${defaultFontFamily}`; ctx.fillText(label[0], centerX, centerY - 10); if (label.length > 1) { ctx.font = `14px ${defaultFontFamily}`; ctx.fillStyle = cssHelper.propertyValue('chart-color-center-text-description'); ctx.fillText(label[1], centerX, centerY + 10); } ctx.restore(); } } ]; constructor(private cssHelper: CssHelper, private dimlessBinary: DimlessBinaryPipe) {} ngOnInit() { this.prepareRawUsage(this.chartConfig, this.data); } ngOnChanges() { this.prepareRawUsage(this.chartConfig, this.data); } private prepareRawUsage(chart: Record<string, any>, data: Record<string, any>) { const nearFullRatioPercent = this.lowThreshold * 100; const fullRatioPercent = this.highThreshold * 100; const percentAvailable = this.calcPercentage(data.max - data.current, data.max); const percentUsed = this.calcPercentage(data.current, data.max); if (percentUsed >= fullRatioPercent) { this.color = 'chart-color-red'; } else if (percentUsed >= nearFullRatioPercent) { this.color = 'chart-color-yellow'; } else { this.color = 'chart-color-blue'; } chart.dataset[0].data = [ Math.round(nearFullRatioPercent), Math.round(Math.abs(nearFullRatioPercent - fullRatioPercent)), Math.round(100 - fullRatioPercent) ]; chart.dataset[1].data = [ percentUsed, percentAvailable, this.dimlessBinary.transform(data.current) ]; chart.dataset[1].backgroundColor[0] = this.cssHelper.propertyValue(this.color); chart.dataset[0].label = [`${percentUsed}%\nof ${this.dimlessBinary.transform(data.max)}`]; } private calcPercentage(dividend: number, divisor: number) { if (!_.isNumber(dividend) || !_.isNumber(divisor) || divisor === 0) { return 0; } return Math.ceil((dividend / divisor) * 100 * 100) / 100; } }
6,071
30.957895
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard-time-selector/dashboard-time-selector.component.html
<div class="timeSelector"> <select id="timepicker" name="timepicker" [(ngModel)]="time" (ngModelChange)="emitTime()" class="form-select"> <option *ngFor="let key of times" [ngValue]="key.value">{{ key.name }} </option> </select> </div>
300
24.083333
48
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard-time-selector/dashboard-time-selector.component.spec.ts
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { DashboardTimeSelectorComponent } from './dashboard-time-selector.component'; describe('DashboardTimeSelectorComponent', () => { let component: DashboardTimeSelectorComponent; let fixture: ComponentFixture<DashboardTimeSelectorComponent>; configureTestBed({ schemas: [NO_ERRORS_SCHEMA], declarations: [DashboardTimeSelectorComponent] }); beforeEach(() => { fixture = TestBed.createComponent(DashboardTimeSelectorComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); });
764
29.6
85
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard-time-selector/dashboard-time-selector.component.ts
import { Component, EventEmitter, Output } from '@angular/core'; import moment from 'moment'; @Component({ selector: 'cd-dashboard-time-selector', templateUrl: './dashboard-time-selector.component.html', styleUrls: ['./dashboard-time-selector.component.scss'] }) export class DashboardTimeSelectorComponent { @Output() selectedTime = new EventEmitter<any>(); times: any; time: any; constructor() { this.times = [ { name: $localize`Last 5 minutes`, value: this.timeToDate(5 * 60, 1) }, { name: $localize`Last 15 minutes`, value: this.timeToDate(15 * 60, 3) }, { name: $localize`Last 30 minutes`, value: this.timeToDate(30 * 60, 6) }, { name: $localize`Last 1 hour`, value: this.timeToDate(3600, 12) }, { name: $localize`Last 3 hours`, value: this.timeToDate(3 * 3600, 36) }, { name: $localize`Last 6 hours`, value: this.timeToDate(6 * 3600, 72) }, { name: $localize`Last 12 hours`, value: this.timeToDate(12 * 3600, 144) }, { name: $localize`Last 24 hours`, value: this.timeToDate(24 * 3600, 288) }, { name: $localize`Last 2 days`, value: this.timeToDate(48 * 3600, 576) }, { name: $localize`Last 7 days`, value: this.timeToDate(168 * 3600, 2016) } ]; this.time = this.times[3].value; } emitTime() { this.selectedTime.emit(this.timeToDate(this.time.end - this.time.start, this.time.step)); } private timeToDate(secondsAgo: number, step: number): any { const date: number = moment().unix() - secondsAgo; const dateNow: number = moment().unix(); const formattedDate: any = { start: date, end: dateNow, step: step }; return formattedDate; } }
1,905
23.435897
93
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard/dashboard-v3.component.html
<div class="container-fluid" *ngIf="healthData && enabledFeature$ | async as enabledFeature"> <div class="row mx-0"> <cd-card cardTitle="Details" i18n-title class="col-sm-3 px-3" [ngClass]="{'d-flex': flexHeight}" aria-label="Details card"> <dl class="ms-4 me-4"> <dt>FSID</dt> <dd>{{ detailsCardData.fsid }}</dd> <dt>Orchestrator</dt> <dd i18n>{{ detailsCardData.orchestrator || 'Orchestrator is not available' }}</dd> <dt>Ceph version</dt> <dd>{{ detailsCardData.cephVersion }}</dd> </dl> </cd-card> <cd-card cardTitle="Status" i18n-title class="col-sm-6 px-3 d-flex" aria-label="Status card"> <div class="d-flex ms-4 me-4 mb-5 center-content"> <ng-template #healthChecks> <ng-container *ngTemplateOutlet="logsLink"></ng-container> <ul> <li *ngFor="let check of healthData.health.checks"> <span [ngStyle]="check.severity | healthColor" [class.health-warn-description]="check.severity === 'HEALTH_WARN'"> {{ check.type }}</span>: {{ check.summary.message }} </li> </ul> </ng-template> <i *ngIf="healthData.health?.status" [ngClass]="[healthData.health.status | healthIcon, icons.large2x]" [ngStyle]="healthData.health.status | healthColor" [title]="healthData.health.status"></i> <a class="ms-2 mt-n1 lead text-primary" [ngbPopover]="healthChecks" popoverClass="info-card-popover-cluster-status" *ngIf="healthData.health?.checks?.length" i18n>Cluster</a> <span class="ms-2 mt-n1 lead" *ngIf="!healthData.health?.checks?.length" i18n>Cluster</span> </div> <section class="border-top mt-5" *ngIf="isAlertmanagerConfigured && (prometheusAlertService.activeCriticalAlerts || prometheusAlertService.activeWarningAlerts)"> <div class="d-flex flex-wrap ms-4 me-4"> <span class="pt-2" i18n>Alerts</span> <!-- Potentially make widget component --> <button class="btn btn-outline-danger rounded-pill ms-2" [ngClass]="{'active': showAlerts && alertType === 'critical'}" title="Danger" (click)="toggleAlertsWindow('danger')" id="dangerAlerts" i18n-title *ngIf="prometheusAlertService?.activeCriticalAlerts > 0"> <i [ngClass]="[icons.danger]"></i> <span>{{ prometheusAlertService.activeCriticalAlerts }}</span> </button> <button class="btn btn-outline-warning rounded-pill ms-2" [ngClass]="{'active': showAlerts && alertType === 'warning'}" title="Warning" (click)="toggleAlertsWindow('warning')" id="warningAlerts" i18n-title *ngIf="prometheusAlertService?.activeWarningAlerts > 0"> <i [ngClass]="[icons.infoCircle]"></i> <span>{{ prometheusAlertService.activeWarningAlerts }}</span> </button> <div class="pt-0 position-right"> <button class="btn btn-block dropdown-toggle" data-toggle="collapse" aria-label="toggle alert window" [attr.aria-expanded]="showAlerts" (click)="toggleAlertsWindow('danger', 'true')"></button> </div> </div> <div class="alerts pt-0" *ngIf="showAlerts"> <hr class="mt-4"> <ngx-simplebar [options]="simplebar"> <div class="card-body ps-0 pe-1 pt-1"> <ng-container *ngTemplateOutlet="alertsCard"></ng-container> </div> </ngx-simplebar> </div> </section> </cd-card> <cd-card cardTitle="Capacity" i18n-title class="col-sm-3 px-3" [ngClass]="{'d-flex': flexHeight}" aria-label="Capacity card"> <ng-container class="ms-4 me-4" *ngIf="capacity && osdSettings"> <cd-dashboard-pie [data]="{max: capacity.total_bytes, current: capacity.total_used_raw_bytes}" [lowThreshold]="osdSettings.nearfull_ratio" [highThreshold]="osdSettings.full_ratio"> </cd-dashboard-pie> </ng-container> </cd-card> </div> <!-- Second row --> <div class="row mx-0"> <!-- Inventory Card --> <cd-card cardTitle="Inventory" i18n-title class="col-sm-3 px-3 d-flex" aria-label="Inventory card"> <hr> <!-- Hosts --> <li class="list-group-item"> <cd-card-row [data]="healthData.hosts" link="/hosts" title="Host" summaryType="simplified" *ngIf="healthData.hosts != null"></cd-card-row> </li> <hr> <!-- Monitors --> <li class="list-group-item"> <cd-card-row [data]="healthData.mon_status.monmap.mons.length" link="/monitor" title="Monitor" summaryType="simplified" *ngIf="healthData.mon_status"></cd-card-row> </li> <hr> <!-- Managers --> <li *ngIf="healthData.mgr_map" class="list-group-item"> <cd-card-row [data]="healthData.mgr_map | mgrSummary" title="Manager" *ngIf="healthData.mgr_map"></cd-card-row> </li> <hr> <!-- OSDs --> <li class="list-group-item"> <cd-card-row [data]="healthData.osd_map | osdSummary" link="/osd" title="OSD" summaryType="osd" *ngIf="healthData.osd_map"></cd-card-row> </li> <hr> <!-- Pools --> <li *ngIf="healthData.pools" class="list-group-item"> <cd-card-row [data]="healthData.pools.length" link="/pool" title="Pool" summaryType="simplified" *ngIf="healthData.pools"></cd-card-row> </li> <hr> <!-- PG Info --> <li class="list-group-item"> <cd-card-row [data]="healthData.pg_info | pgSummary" title="PG" *ngIf="healthData.pg_info"></cd-card-row> </li> <hr> <!-- Object gateways --> <li *ngIf="enabledFeature.rgw && healthData.rgw != null" class="list-group-item" id="rgw-item"> <cd-card-row [data]="healthData.rgw" link="/rgw/daemon" title="Object Gateway" summaryType="simplified" *ngIf="healthData.rgw || healthData.rgw === 0 "></cd-card-row> </li> <hr> <!-- Metadata Servers --> <li *ngIf="enabledFeature.cephfs && healthData.fs_map" class="list-group-item" id="mds-item"> <cd-card-row [data]="healthData.fs_map | mdsSummary" title="Metadata Server" *ngIf="healthData.fs_map"></cd-card-row> </li> <hr> <!-- iSCSI Gateways --> <li *ngIf="enabledFeature.iscsi && healthData.iscsi_daemons != null" class="list-group-item" id="iscsi-item"> <cd-card-row [data]="healthData.iscsi_daemons" link="/iscsi/daemon" title="iSCSI Gateway" summaryType="iscsi" *ngIf="healthData.iscsi_daemons"></cd-card-row> </li> </cd-card> <cd-card cardTitle="Cluster utilization" i18n-title class="col-sm-9 px-3 d-flex" aria-label="Cluster utilization card"> <div class="ms-4 me-4 mt-0"> <cd-dashboard-time-selector (selectedTime)="getPrometheusData($event)"> </cd-dashboard-time-selector> <ng-container *ngIf="capacity"> <cd-dashboard-area-chart chartTitle="Used Capacity" [maxValue]="capacity.total_bytes" dataUnits="B" label="Used Capacity" [data]="queriesResults.USEDCAPACITY"> </cd-dashboard-area-chart> </ng-container> <cd-dashboard-area-chart chartTitle="IOPS" dataUnits="" label="OPS" label2="IPS" [data]="queriesResults.OPS" [data2]="queriesResults.IPS"> </cd-dashboard-area-chart> <cd-dashboard-area-chart chartTitle="Latency" dataUnits="ms" decimals="3" label="Read" label2="Write" [data]="queriesResults.READLATENCY" [data2]="queriesResults.WRITELATENCY"> </cd-dashboard-area-chart> <cd-dashboard-area-chart chartTitle="Client Throughput" dataUnits="B/s" label="Read" label2="Write" [data]="queriesResults.READCLIENTTHROUGHPUT" [data2]="queriesResults.WRITECLIENTTHROUGHPUT"> </cd-dashboard-area-chart> <cd-dashboard-area-chart chartTitle="Recovery Throughput" dataUnits="B/s" label="Recovery Throughput" [data]="queriesResults.RECOVERYBYTES"> </cd-dashboard-area-chart> </div> </cd-card> </div> </div> <ng-template #alertsCard> <ng-container *ngFor="let alert of alerts; let i = index"> <div [ngClass]="borderClass" *ngIf="alertType === alert.labels.severity"> <div class="card tc_alerts border-0 pt-3"> <div class="row no-gutters"> <div class="col-sm-1 text-center"> <span [ngClass]="[icons.stack, icons.large, textClass]"> <i [ngClass]="[icons.circle, icons.stack2x]"></i> <i [ngClass]="[icons.stack1x, icons.inverse, icons.warning]"></i> </span> </div> <div class="col-md-11"> <div class="card-body ps-0 pe-1 pt-1"> <h6 class="card-title bold">{{ alert.labels.alertname }}</h6> <p class="card-text me-3" [innerHtml]="alert.annotations.summary"></p> <p class="card-text text-muted me-3"> <small class="date" [title]="alert.startsAt | cdDate" i18n>Active since: {{ alert.startsAt | relativeDate }}</small> </p> </div> </div> </div> </div> <hr> </div> </ng-container> </ng-template> <ng-template #logsLink> <ng-container *ngIf="permissions.log.read"> <p class="logs-link" i18n><i [ngClass]="[icons.infoCircle]"></i> See <a routerLink="/logs">Logs</a> for more details.</p> </ng-container> </ng-template>
11,511
39.251748
143
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard/dashboard-v3.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { RouterTestingModule } from '@angular/router/testing'; import _ from 'lodash'; import { ToastrModule } from 'ngx-toastr'; import { BehaviorSubject, of } from 'rxjs'; import { HealthService } from '~/app/shared/api/health.service'; import { PrometheusService } from '~/app/shared/api/prometheus.service'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { AlertmanagerAlert } from '~/app/shared/models/prometheus-alerts'; import { FeatureTogglesService } from '~/app/shared/services/feature-toggles.service'; import { PrometheusAlertService } from '~/app/shared/services/prometheus-alert.service'; import { SummaryService } from '~/app/shared/services/summary.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { PgCategoryService } from '../../shared/pg-category.service'; import { CardRowComponent } from '../card-row/card-row.component'; import { CardComponent } from '../card/card.component'; import { DashboardPieComponent } from '../dashboard-pie/dashboard-pie.component'; import { PgSummaryPipe } from '../pg-summary.pipe'; import { DashboardV3Component } from './dashboard-v3.component'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; export class SummaryServiceMock { summaryDataSource = new BehaviorSubject({ version: 'ceph version 17.0.0-12222-gcd0cd7cb ' + '(b8193bb4cda16ccc5b028c3e1df62bc72350a15d) quincy (dev)' }); summaryData$ = this.summaryDataSource.asObservable(); subscribe(call: any) { return this.summaryData$.subscribe(call); } } describe('Dashbord Component', () => { let component: DashboardV3Component; let fixture: ComponentFixture<DashboardV3Component>; let healthService: HealthService; let orchestratorService: OrchestratorService; let getHealthSpy: jasmine.Spy; let getAlertsSpy: jasmine.Spy; let fakeFeatureTogglesService: jasmine.Spy; const healthPayload: Record<string, any> = { health: { status: 'HEALTH_OK' }, mon_status: { monmap: { mons: [] }, quorum: [] }, osd_map: { osds: [] }, mgr_map: { standbys: [] }, hosts: 0, rgw: 0, fs_map: { filesystems: [], standbys: [] }, iscsi_daemons: 1, client_perf: {}, scrub_status: 'Inactive', pools: [], df: { stats: {} }, pg_info: { object_stats: { num_objects: 1 } } }; const alertsPayload: AlertmanagerAlert[] = [ { labels: { alertname: 'CephMgrPrometheusModuleInactive', instance: 'ceph2:9283', job: 'ceph', severity: 'critical' }, annotations: { description: 'The mgr/prometheus module at ceph2:9283 is unreachable.', summary: 'The mgr/prometheus module is not available' }, startsAt: '2022-09-28T08:23:41.152Z', endsAt: '2022-09-28T15:28:01.152Z', generatorURL: 'http://prometheus:9090/testUrl', status: { state: 'active', silencedBy: null, inhibitedBy: null }, receivers: ['ceph2'], fingerprint: 'fingerprint' }, { labels: { alertname: 'CephOSDDownHigh', instance: 'ceph:9283', job: 'ceph', severity: 'critical' }, annotations: { description: '66.67% or 2 of 3 OSDs are down (>= 10%).', summary: 'More than 10% of OSDs are down' }, startsAt: '2022-09-28T14:17:22.665Z', endsAt: '2022-09-28T15:28:32.665Z', generatorURL: 'http://prometheus:9090/testUrl', status: { state: 'active', silencedBy: null, inhibitedBy: null }, receivers: ['default'], fingerprint: 'fingerprint' }, { labels: { alertname: 'CephHealthWarning', instance: 'ceph:9283', job: 'ceph', severity: 'warning' }, annotations: { description: 'The cluster state has been HEALTH_WARN for more than 15 minutes.', summary: 'Ceph is in the WARNING state' }, startsAt: '2022-09-28T08:41:38.454Z', endsAt: '2022-09-28T15:28:38.454Z', generatorURL: 'http://prometheus:9090/testUrl', status: { state: 'active', silencedBy: null, inhibitedBy: null }, receivers: ['ceph'], fingerprint: 'fingerprint' } ]; const configValueData: any = 'e90a0d58-658e-4148-8f61-e896c86f0696'; const orchName: any = 'Cephadm'; configureTestBed({ imports: [RouterTestingModule, HttpClientTestingModule, ToastrModule.forRoot(), SharedModule], declarations: [ DashboardV3Component, CardComponent, DashboardPieComponent, CardRowComponent, PgSummaryPipe ], schemas: [NO_ERRORS_SCHEMA], providers: [ { provide: SummaryService, useClass: SummaryServiceMock }, { provide: PrometheusAlertService, useValue: { activeCriticalAlerts: 2, activeWarningAlerts: 1 } }, CssHelper, PgCategoryService ] }); beforeEach(() => { fakeFeatureTogglesService = spyOn(TestBed.inject(FeatureTogglesService), 'get').and.returnValue( of({ rbd: true, mirroring: true, iscsi: true, cephfs: true, rgw: true }) ); fixture = TestBed.createComponent(DashboardV3Component); component = fixture.componentInstance; healthService = TestBed.inject(HealthService); orchestratorService = TestBed.inject(OrchestratorService); getHealthSpy = spyOn(TestBed.inject(HealthService), 'getMinimalHealth'); getHealthSpy.and.returnValue(of(healthPayload)); spyOn(TestBed.inject(PrometheusService), 'ifAlertmanagerConfigured').and.callFake((fn) => fn()); getAlertsSpy = spyOn(TestBed.inject(PrometheusService), 'getAlerts'); getAlertsSpy.and.returnValue(of(alertsPayload)); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should render all cards', () => { fixture.detectChanges(); const dashboardCards = fixture.debugElement.nativeElement.querySelectorAll('cd-card'); expect(dashboardCards.length).toBe(5); }); it('should get corresponding data into detailsCardData', () => { spyOn(healthService, 'getClusterFsid').and.returnValue(of(configValueData)); spyOn(orchestratorService, 'getName').and.returnValue(of(orchName)); component.ngOnInit(); expect(component.detailsCardData.fsid).toBe('e90a0d58-658e-4148-8f61-e896c86f0696'); expect(component.detailsCardData.orchestrator).toBe('Cephadm'); expect(component.detailsCardData.cephVersion).toBe('17.0.0-12222-gcd0cd7cb quincy (dev)'); }); it('should check if the respective icon is shown for each status', () => { const payload = _.cloneDeep(healthPayload); // HEALTH_WARN payload.health['status'] = 'HEALTH_WARN'; payload.health['checks'] = [ { severity: 'HEALTH_WARN', type: 'WRN', summary: { message: 'fake warning' } } ]; getHealthSpy.and.returnValue(of(payload)); fixture.detectChanges(); const clusterStatusCard = fixture.debugElement.query(By.css('cd-card[cardTitle="Status"] i')); expect(clusterStatusCard.nativeElement.title).toEqual(`${payload.health.status}`); // HEALTH_ERR payload.health['status'] = 'HEALTH_ERR'; payload.health['checks'] = [ { severity: 'HEALTH_ERR', type: 'ERR', summary: { message: 'fake error' } } ]; getHealthSpy.and.returnValue(of(payload)); fixture.detectChanges(); expect(clusterStatusCard.nativeElement.title).toEqual(`${payload.health.status}`); // HEALTH_OK payload.health['status'] = 'HEALTH_OK'; payload.health['checks'] = [ { severity: 'HEALTH_OK', type: 'OK', summary: { message: 'fake success' } } ]; getHealthSpy.and.returnValue(of(payload)); fixture.detectChanges(); expect(clusterStatusCard.nativeElement.title).toEqual(`${payload.health.status}`); }); it('should show the actual alert count on each alerts pill', () => { fixture.detectChanges(); const warningAlerts = fixture.debugElement.query(By.css('button[id=warningAlerts] span')); const dangerAlerts = fixture.debugElement.query(By.css('button[id=dangerAlerts] span')); expect(warningAlerts.nativeElement.textContent).toBe('1'); expect(dangerAlerts.nativeElement.textContent).toBe('2'); }); it('should show the critical alerts window and its content', () => { const payload = _.cloneDeep(alertsPayload[0]); component.toggleAlertsWindow('danger'); fixture.detectChanges(); const cardTitle = fixture.debugElement.query(By.css('.tc_alerts h6.card-title')); expect(cardTitle.nativeElement.textContent).toBe(payload.labels.alertname); expect(component.alertType).not.toBe('warning'); }); it('should show the warning alerts window and its content', () => { const payload = _.cloneDeep(alertsPayload[2]); component.toggleAlertsWindow('warning'); fixture.detectChanges(); const cardTitle = fixture.debugElement.query(By.css('.tc_alerts h6.card-title')); expect(cardTitle.nativeElement.textContent).toBe(payload.labels.alertname); expect(component.alertType).not.toBe('critical'); }); it('should only show the pills when the alerts are not empty', () => { spyOn(TestBed.inject(PrometheusAlertService), 'activeCriticalAlerts').and.returnValue(0); spyOn(TestBed.inject(PrometheusAlertService), 'activeWarningAlerts').and.returnValue(0); fixture.detectChanges(); const warningAlerts = fixture.debugElement.query(By.css('button[id=warningAlerts]')); const dangerAlerts = fixture.debugElement.query(By.css('button[id=dangerAlerts]')); expect(warningAlerts).toBe(null); expect(dangerAlerts).toBe(null); }); it('should render "Status" card text that is not clickable', () => { fixture.detectChanges(); const clusterStatusCard = fixture.debugElement.query(By.css('cd-card[cardTitle="Status"]')); const clickableContent = clusterStatusCard.query(By.css('.lead.text-primary')); expect(clickableContent).toBeNull(); }); it('should render "Status" card text that is clickable (popover)', () => { const payload = _.cloneDeep(healthPayload); payload.health['status'] = 'HEALTH_WARN'; payload.health['checks'] = [ { severity: 'HEALTH_WARN', type: 'WRN', summary: { message: 'fake warning' } } ]; getHealthSpy.and.returnValue(of(payload)); fixture.detectChanges(); const clusterStatusCard = fixture.debugElement.query(By.css('cd-card[cardTitle="Status"]')); const clickableContent = clusterStatusCard.query(By.css('.lead.text-primary')); expect(clickableContent).not.toBeNull(); }); describe('features disabled', () => { beforeEach(() => { fakeFeatureTogglesService.and.returnValue( of({ rbd: false, mirroring: false, iscsi: false, cephfs: false, rgw: false }) ); fixture = TestBed.createComponent(DashboardV3Component); component = fixture.componentInstance; }); it('should not render items related to disabled features', () => { fixture.detectChanges(); const iscsiCard = fixture.debugElement.query(By.css('li[id=iscsi-item]')); const rgwCard = fixture.debugElement.query(By.css('li[id=rgw-item]')); const mds = fixture.debugElement.query(By.css('li[id=mds-item]')); expect(iscsiCard).toBeFalsy(); expect(rgwCard).toBeFalsy(); expect(mds).toBeFalsy(); }); }); });
11,780
34.167164
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard-v3/dashboard/dashboard-v3.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import _ from 'lodash'; import { Observable, Subscription, timer } from 'rxjs'; import { take } from 'rxjs/operators'; import moment from 'moment'; import { HealthService } from '~/app/shared/api/health.service'; import { OsdService } from '~/app/shared/api/osd.service'; import { PrometheusService } from '~/app/shared/api/prometheus.service'; import { Promqls as queries } from '~/app/shared/enum/dashboard-promqls.enum'; import { Icons } from '~/app/shared/enum/icons.enum'; import { DashboardDetails } from '~/app/shared/models/cd-details'; import { Permissions } from '~/app/shared/models/permissions'; import { AlertmanagerAlert } from '~/app/shared/models/prometheus-alerts'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { FeatureTogglesMap$, FeatureTogglesService } from '~/app/shared/services/feature-toggles.service'; import { RefreshIntervalService } from '~/app/shared/services/refresh-interval.service'; import { SummaryService } from '~/app/shared/services/summary.service'; import { PrometheusListHelper } from '~/app/shared/helpers/prometheus-list-helper'; import { PrometheusAlertService } from '~/app/shared/services/prometheus-alert.service'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; @Component({ selector: 'cd-dashboard-v3', templateUrl: './dashboard-v3.component.html', styleUrls: ['./dashboard-v3.component.scss'] }) export class DashboardV3Component extends PrometheusListHelper implements OnInit, OnDestroy { detailsCardData: DashboardDetails = {}; osdSettingsService: any; osdSettings: any; interval = new Subscription(); permissions: Permissions; enabledFeature$: FeatureTogglesMap$; color: string; capacityService: any; capacity: any; healthData$: Observable<Object>; prometheusAlerts$: Observable<AlertmanagerAlert[]>; icons = Icons; showAlerts = false; flexHeight = true; simplebar = { autoHide: false }; textClass: string; borderClass: string; alertType: string; alerts: AlertmanagerAlert[]; healthData: any; categoryPgAmount: Record<string, number> = {}; totalPgs = 0; queriesResults: any = { USEDCAPACITY: '', IPS: '', OPS: '', READLATENCY: '', WRITELATENCY: '', READCLIENTTHROUGHPUT: '', WRITECLIENTTHROUGHPUT: '', RECOVERYBYTES: '' }; timerGetPrometheusDataSub: Subscription; timerTime = 30000; readonly lastHourDateObject = { start: moment().unix() - 3600, end: moment().unix(), step: 12 }; constructor( private summaryService: SummaryService, private orchestratorService: OrchestratorService, private osdService: OsdService, private authStorageService: AuthStorageService, private featureToggles: FeatureTogglesService, private healthService: HealthService, public prometheusService: PrometheusService, private refreshIntervalService: RefreshIntervalService, public prometheusAlertService: PrometheusAlertService ) { super(prometheusService); this.permissions = this.authStorageService.getPermissions(); this.enabledFeature$ = this.featureToggles.get(); } ngOnInit() { super.ngOnInit(); this.interval = this.refreshIntervalService.intervalData$.subscribe(() => { this.getHealth(); this.getCapacityCardData(); }); this.getPrometheusData(this.lastHourDateObject); this.getDetailsCardData(); } ngOnDestroy() { this.interval.unsubscribe(); if (this.timerGetPrometheusDataSub) { this.timerGetPrometheusDataSub.unsubscribe(); } } getHealth() { this.healthService.getMinimalHealth().subscribe((data: any) => { this.healthData = data; }); } toggleAlertsWindow(type: string, isToggleButton: boolean = false) { this.triggerPrometheusAlerts(); if (isToggleButton) { this.showAlerts = !this.showAlerts; this.flexHeight = !this.flexHeight; } else if ( !this.showAlerts || (this.alertType === type && type !== 'danger') || (this.alertType !== 'warning' && type === 'danger') ) { this.showAlerts = !this.showAlerts; this.flexHeight = !this.flexHeight; } type === 'danger' ? (this.alertType = 'critical') : (this.alertType = type); this.textClass = `text-${type}`; this.borderClass = `border-${type}`; } getDetailsCardData() { this.healthService.getClusterFsid().subscribe((data: string) => { this.detailsCardData.fsid = data; }); this.orchestratorService.getName().subscribe((data: string) => { this.detailsCardData.orchestrator = data; }); this.summaryService.subscribe((summary) => { const version = summary.version.replace('ceph version ', '').split(' '); this.detailsCardData.cephVersion = version[0] + ' ' + version.slice(2, version.length).join(' '); }); } getCapacityCardData() { this.osdSettingsService = this.osdService .getOsdSettings() .pipe(take(1)) .subscribe((data: any) => { this.osdSettings = data; }); this.capacityService = this.healthService.getClusterCapacity().subscribe((data: any) => { this.capacity = data; }); } triggerPrometheusAlerts() { this.prometheusService.ifAlertmanagerConfigured(() => { this.prometheusService.getAlerts().subscribe((alerts) => { this.alerts = alerts; }); }); } getPrometheusData(selectedTime: any) { this.prometheusService.ifPrometheusConfigured(() => { if (this.timerGetPrometheusDataSub) { this.timerGetPrometheusDataSub.unsubscribe(); } this.timerGetPrometheusDataSub = timer(0, this.timerTime).subscribe(() => { selectedTime = this.updateTimeStamp(selectedTime); for (const queryName in queries) { if (queries.hasOwnProperty(queryName)) { const query = queries[queryName]; let interval = selectedTime.step; if (query.includes('rate') && selectedTime.step < 20) { interval = 20; } else if (query.includes('rate')) { interval = selectedTime.step * 2; } const intervalAdjustedQuery = query.replace(/\[(.*?)\]/g, `[${interval}s]`); this.prometheusService .getPrometheusData({ params: intervalAdjustedQuery, start: selectedTime['start'], end: selectedTime['end'], step: selectedTime['step'] }) .subscribe((data: any) => { if (data.result.length) { this.queriesResults[queryName] = data.result[0].values; } }); } } }); }); } private updateTimeStamp(selectedTime: any): any { let formattedDate = {}; const date: number = selectedTime['start'] + this.timerTime / 1000; const dateNow: number = selectedTime['end'] + this.timerTime / 1000; formattedDate = { start: date, end: dateNow, step: selectedTime['step'] }; return formattedDate; } }
7,153
31.666667
93
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/dashboard.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { NgbNavModule, NgbPopoverModule } from '@ng-bootstrap/ng-bootstrap'; import { ChartsModule } from 'ng2-charts'; import { SharedModule } from '~/app/shared/shared.module'; import { DashboardV3Module } from '../dashboard-v3/dashboard-v3.module'; import { CephSharedModule } from '../shared/ceph-shared.module'; import { FeedbackComponent } from '../shared/feedback/feedback.component'; import { DashboardComponent } from './dashboard/dashboard.component'; import { HealthPieComponent } from './health-pie/health-pie.component'; import { HealthComponent } from './health/health.component'; import { InfoCardComponent } from './info-card/info-card.component'; import { InfoGroupComponent } from './info-group/info-group.component'; import { MdsSummaryPipe } from './mds-summary.pipe'; import { MgrSummaryPipe } from './mgr-summary.pipe'; import { MonSummaryPipe } from './mon-summary.pipe'; import { OsdSummaryPipe } from './osd-summary.pipe'; @NgModule({ imports: [ CephSharedModule, CommonModule, NgbNavModule, SharedModule, ChartsModule, RouterModule, NgbPopoverModule, FormsModule, ReactiveFormsModule, DashboardV3Module ], declarations: [ HealthComponent, DashboardComponent, MonSummaryPipe, OsdSummaryPipe, MgrSummaryPipe, MdsSummaryPipe, HealthPieComponent, InfoCardComponent, InfoGroupComponent, FeedbackComponent ] }) export class DashboardModule {}
1,660
31.568627
76
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/mds-summary.pipe.spec.ts
import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { MdsSummaryPipe } from './mds-summary.pipe'; describe('MdsSummaryPipe', () => { let pipe: MdsSummaryPipe; configureTestBed({ providers: [MdsSummaryPipe] }); beforeEach(() => { pipe = TestBed.inject(MdsSummaryPipe); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms with 0 active and 2 standy', () => { const payload = { standbys: [{ name: 'a' }], filesystems: [{ mdsmap: { info: [{ state: 'up:standby-replay' }] } }] }; const expected = [ { class: 'popover-info', content: '0 active', titleText: '1 standbyReplay' }, { class: 'card-text-line-break', content: '', titleText: '' }, { class: 'popover-info', content: '2 standby', titleText: 'standby daemons: a' } ]; expect(pipe.transform(payload)).toEqual(expected); }); it('transforms with 1 active and 1 standy', () => { const payload = { standbys: [{ name: 'b' }], filesystems: [{ mdsmap: { info: [{ state: 'up:active', name: 'a' }] } }] }; const expected = [ { class: 'popover-info', content: '1 active', titleText: 'active daemon: a' }, { class: 'card-text-line-break', content: '', titleText: '' }, { class: 'popover-info', content: '1 standby', titleText: 'standby daemons: b' } ]; expect(pipe.transform(payload)).toEqual(expected); }); it('transforms with 0 filesystems', () => { const payload: Record<string, any> = { standbys: [0], filesystems: [] }; const expected = [{ class: 'popover-info', content: 'no filesystems', titleText: '' }]; expect(pipe.transform(payload)).toEqual(expected); }); it('transforms without filesystem', () => { const payload = { standbys: [{ name: 'a' }] }; const expected = [ { class: 'popover-info', content: '1 up', titleText: '' }, { class: 'card-text-line-break', content: '', titleText: '' }, { class: 'popover-info', content: 'no filesystems', titleText: 'standby daemons: a' } ]; expect(pipe.transform(payload)).toEqual(expected); }); it('transforms without value', () => { expect(pipe.transform(undefined)).toBe(''); }); });
2,297
30.479452
91
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/mds-summary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'mdsSummary' }) export class MdsSummaryPipe implements PipeTransform { transform(value: any): any { if (!value) { return ''; } let contentLine1 = ''; let contentLine2 = ''; let standbys = 0; let active = 0; let standbyReplay = 0; _.each(value.standbys, () => { standbys += 1; }); if (value.standbys && !value.filesystems) { contentLine1 = `${standbys} ${$localize`up`}`; contentLine2 = $localize`no filesystems`; } else if (value.filesystems.length === 0) { contentLine1 = $localize`no filesystems`; } else { _.each(value.filesystems, (fs) => { _.each(fs.mdsmap.info, (mds) => { if (mds.state === 'up:standby-replay') { standbyReplay += 1; } else { active += 1; } }); }); contentLine1 = `${active} ${$localize`active`}`; contentLine2 = `${standbys + standbyReplay} ${$localize`standby`}`; } const standbyHoverText = value.standbys.map((s: any): string => s.name).join(', '); const standbyTitleText = !standbyHoverText ? '' : `${$localize`standby daemons`}: ${standbyHoverText}`; const fsLength = value.filesystems ? value.filesystems.length : 0; const infoObject = fsLength > 0 ? value.filesystems[0].mdsmap.info : {}; const activeHoverText = Object.values(infoObject) .map((info: any): string => info.name) .join(', '); let activeTitleText = !activeHoverText ? '' : `${$localize`active daemon`}: ${activeHoverText}`; // There is always one standbyreplay to replace active daemon, if active one is down if (!active && fsLength > 0) { activeTitleText = `${standbyReplay} ${$localize`standbyReplay`}`; } const mgrSummary = [ { content: contentLine1, class: 'popover-info', titleText: activeTitleText } ]; if (contentLine2) { mgrSummary.push({ content: '', class: 'card-text-line-break', titleText: '' }); mgrSummary.push({ content: contentLine2, class: 'popover-info', titleText: standbyTitleText }); } return mgrSummary; } }
2,297
28.088608
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/mgr-summary.pipe.spec.ts
import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { MgrSummaryPipe } from './mgr-summary.pipe'; describe('MgrSummaryPipe', () => { let pipe: MgrSummaryPipe; configureTestBed({ providers: [MgrSummaryPipe] }); beforeEach(() => { pipe = TestBed.inject(MgrSummaryPipe); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms without value', () => { expect(pipe.transform(undefined)).toBe(''); }); it('transforms with active_name undefined', () => { const payload: Record<string, any> = { active_name: undefined, standbys: [] }; const expected = [ { class: 'popover-info', content: 'n/a active', titleText: '' }, { class: 'card-text-line-break', content: '', titleText: '' }, { class: 'popover-info', content: '0 standby', titleText: '' } ]; expect(pipe.transform(payload)).toEqual(expected); }); it('transforms with 1 active and 2 standbys', () => { const payload = { active_name: 'x', standbys: [{ name: 'y' }, { name: 'z' }] }; const expected = [ { class: 'popover-info', content: '1 active', titleText: 'active daemon: x' }, { class: 'card-text-line-break', content: '', titleText: '' }, { class: 'popover-info', content: '2 standby', titleText: 'standby daemons: y, z' } ]; expect(pipe.transform(payload)).toEqual(expected); }); });
1,482
26.981132
89
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/mgr-summary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'mgrSummary' }) export class MgrSummaryPipe implements PipeTransform { transform(value: any): any { if (!value) { return ''; } let activeCount = $localize`n/a`; const activeTitleText = _.isUndefined(value.active_name) ? '' : `${$localize`active daemon`}: ${value.active_name}`; // There is always one standbyreplay to replace active daemon, if active one is down if (activeTitleText.length > 0) { activeCount = '1'; } const standbyHoverText = value.standbys.map((s: any): string => s.name).join(', '); const standbyTitleText = !standbyHoverText ? '' : `${$localize`standby daemons`}: ${standbyHoverText}`; const standbyCount = value.standbys.length; const mgrSummary = [ { content: `${activeCount} ${$localize`active`}`, class: 'popover-info', titleText: activeTitleText } ]; mgrSummary.push({ content: '', class: 'card-text-line-break', titleText: '' }); mgrSummary.push({ content: `${standbyCount} ${$localize`standby`}`, class: 'popover-info', titleText: standbyTitleText }); return mgrSummary; } }
1,280
25.142857
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/mon-summary.pipe.spec.ts
import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { MonSummaryPipe } from './mon-summary.pipe'; describe('MonSummaryPipe', () => { let pipe: MonSummaryPipe; configureTestBed({ providers: [MonSummaryPipe] }); beforeEach(() => { pipe = TestBed.inject(MonSummaryPipe); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms without value', () => { expect(pipe.transform(undefined)).toBe(''); }); it('transforms with 3 mons in quorum', () => { const value = { monmap: { mons: [0, 1, 2] }, quorum: [0, 1, 2] }; expect(pipe.transform(value)).toBe('3 (quorum 0, 1, 2)'); }); it('transforms with 2/3 mons in quorum', () => { const value = { monmap: { mons: [0, 1, 2] }, quorum: [0, 1] }; expect(pipe.transform(value)).toBe('3 (quorum 0, 1)'); }); });
938
21.902439
62
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/mon-summary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'monSummary' }) export class MonSummaryPipe implements PipeTransform { transform(value: any): any { if (!value) { return ''; } const result = $localize`${value.monmap.mons.length.toString()} (quorum \ ${value.quorum.join(', ')})`; return result; } }
348
18.388889
77
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/osd-summary.pipe.spec.ts
import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { OsdSummaryPipe } from './osd-summary.pipe'; describe('OsdSummaryPipe', () => { let pipe: OsdSummaryPipe; configureTestBed({ providers: [OsdSummaryPipe] }); beforeEach(() => { pipe = TestBed.inject(OsdSummaryPipe); }); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms without value', () => { expect(pipe.transform(undefined)).toBe(''); }); it('transforms having 3 osd with 3 up, 3 in, 0 down, 0 out', () => { const value = { osds: [ { up: 1, in: 1, state: ['up', 'exists'] }, { up: 1, in: 1, state: ['up', 'exists'] }, { up: 1, in: 1, state: ['up', 'exists'] } ] }; expect(pipe.transform(value)).toEqual([ { content: '3 total', class: '' }, { content: '', class: 'card-text-line-break' }, { content: '3 up, 3 in', class: '' } ]); }); it('transforms having 3 osd with 2 up, 1 in, 1 down, 2 out', () => { const value = { osds: [ { up: 1, in: 1, state: ['up', 'exists'] }, { up: 1, in: 0, state: ['up', 'exists'] }, { up: 0, in: 0, state: ['exists'] } ] }; expect(pipe.transform(value)).toEqual([ { content: '3 total', class: '' }, { content: '', class: 'card-text-line-break' }, { content: '2 up, 1 in', class: '' }, { content: '', class: 'card-text-line-break' }, { content: '1 down, 2 out', class: 'card-text-error' } ]); }); it('transforms having 3 osd with 2 up, 3 in, 1 full, 1 nearfull, 1 down, 0 out', () => { const value = { osds: [ { up: 1, in: 1, state: ['up', 'nearfull'] }, { up: 1, in: 1, state: ['up', 'exists'] }, { up: 0, in: 1, state: ['full'] } ] }; expect(pipe.transform(value)).toEqual([ { content: '3 total', class: '' }, { content: '', class: 'card-text-line-break' }, { content: '2 up, 3 in', class: '' }, { content: '', class: 'card-text-line-break' }, { content: '1 down', class: 'card-text-error' }, { content: '', class: 'card-text-line-break' }, { content: '1 near full', class: 'card-text-error' }, { content: '', class: 'card-text-line-break' }, { content: '1 full', class: 'card-text-error' } ]); }); it('transforms having 3 osd with 3 up, 2 in, 0 down, 1 out', () => { const value = { osds: [ { up: 1, in: 1, state: ['up', 'exists'] }, { up: 1, in: 1, state: ['up', 'exists'] }, { up: 1, in: 0, state: ['up', 'exists'] } ] }; expect(pipe.transform(value)).toEqual([ { content: '3 total', class: '' }, { content: '', class: 'card-text-line-break' }, { content: '3 up, 2 in', class: '' }, { content: '', class: 'card-text-line-break' }, { content: '1 out', class: 'card-text-error' } ]); }); it('transforms having 4 osd with 3 up, 2 in, 1 down, another 2 out', () => { const value = { osds: [ { up: 1, in: 1, state: ['up', 'exists'] }, { up: 1, in: 0, state: ['up', 'exists'] }, { up: 1, in: 0, state: ['up', 'exists'] }, { up: 0, in: 1, state: ['exists'] } ] }; expect(pipe.transform(value)).toEqual([ { content: '4 total', class: '' }, { content: '', class: 'card-text-line-break' }, { content: '3 up, 2 in', class: '' }, { content: '', class: 'card-text-line-break' }, { content: '1 down, 2 out', class: 'card-text-error' } ]); }); });
4,206
20.685567
90
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/osd-summary.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'osdSummary' }) export class OsdSummaryPipe implements PipeTransform { transform(value: any): any { if (!value) { return ''; } let inCount = 0; let upCount = 0; let nearFullCount = 0; let fullCount = 0; _.each(value.osds, (osd) => { if (osd.in) { inCount++; } if (osd.up) { upCount++; } if (osd.state.includes('nearfull')) { nearFullCount++; } if (osd.state.includes('full')) { fullCount++; } }); const osdSummary = [ { content: `${value.osds.length} ${$localize`total`}`, class: '' } ]; osdSummary.push({ content: '', class: 'card-text-line-break' }); osdSummary.push({ content: `${upCount} ${$localize`up`}, ${inCount} ${$localize`in`}`, class: '' }); const downCount = value.osds.length - upCount; const outCount = value.osds.length - inCount; if (downCount > 0 || outCount > 0) { osdSummary.push({ content: '', class: 'card-text-line-break' }); const downText = downCount > 0 ? `${downCount} ${$localize`down`}` : ''; const separator = downCount > 0 && outCount > 0 ? ', ' : ''; const outText = outCount > 0 ? `${outCount} ${$localize`out`}` : ''; osdSummary.push({ content: `${downText}${separator}${outText}`, class: 'card-text-error' }); } if (nearFullCount > 0) { osdSummary.push( { content: '', class: 'card-text-line-break' }, { content: `${nearFullCount} ${$localize`near full`}`, class: 'card-text-error' }, { content: '', class: 'card-text-line-break' } ); } if (fullCount > 0) { osdSummary.push({ content: `${fullCount} ${$localize`full`}`, class: 'card-text-error' }); } return osdSummary; } }
2,067
21.478261
78
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/dashboard/dashboard.component.html
<main aria-label="Dashboard"> <a href="#main" class="sr-only">skip to content</a> <ng-container *ngIf="(enabledFeature$ | async)?.dashboard === false; else dashboardV3" class="main-padding"> <cd-refresh-selector></cd-refresh-selector> <cd-health id="main"></cd-health> </ng-container> <ng-template #dashboardV3> <cd-dashboard-v3></cd-dashboard-v3> </ng-template> </main>
417
25.125
88
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/dashboard/dashboard.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { FeatureTogglesService } from '~/app/shared/services/feature-toggles.service'; import { configureTestBed } from '~/testing/unit-test-helper'; import { DashboardComponent } from './dashboard.component'; describe('DashboardComponent', () => { let component: DashboardComponent; let fixture: ComponentFixture<DashboardComponent>; configureTestBed({ imports: [NgbNavModule, HttpClientTestingModule], declarations: [DashboardComponent], providers: [FeatureTogglesService], schemas: [NO_ERRORS_SCHEMA] }); beforeEach(() => { fixture = TestBed.createComponent(DashboardComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,020
30.90625
86
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/dashboard/dashboard.component.ts
import { Component } from '@angular/core'; import { Observable } from 'rxjs'; import { FeatureTogglesService } from '~/app/shared/services/feature-toggles.service'; @Component({ selector: 'cd-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.scss'] }) export class DashboardComponent { enabledFeature$: Observable<Object>; constructor(private featureToggles: FeatureTogglesService) { this.enabledFeature$ = this.featureToggles.get(); } }
496
28.235294
86
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/health-pie/health-pie.component.html
<div class="chart-container"> <canvas baseChart #chartCanvas [datasets]="chartConfig.dataset" [chartType]="chartConfig.chartType" [options]="chartConfig.options" [labels]="chartConfig.labels" [colors]="chartConfig.colors" [plugins]="doughnutChartPlugins" class="chart-canvas"> </canvas> <div class="chartjs-tooltip" #chartTooltip> </div> </div>
440
26.5625
45
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/health-pie/health-pie.component.spec.ts
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { DimlessPipe } from '~/app/shared/pipes/dimless.pipe'; import { FormatterService } from '~/app/shared/services/formatter.service'; import { configureTestBed } from '~/testing/unit-test-helper'; import { HealthPieComponent } from './health-pie.component'; describe('HealthPieComponent', () => { let component: HealthPieComponent; let fixture: ComponentFixture<HealthPieComponent>; configureTestBed({ schemas: [NO_ERRORS_SCHEMA], declarations: [HealthPieComponent], providers: [DimlessBinaryPipe, DimlessPipe, FormatterService, CssHelper] }); beforeEach(() => { fixture = TestBed.createComponent(HealthPieComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); it('Add slice border if there is more than one slice with numeric non zero value', () => { component.chartConfig.dataset[0].data = [48, 0, 1, 0]; component.ngOnChanges(); expect(component.chartConfig.dataset[0].borderWidth).toEqual(1); }); it('Remove slice border if there is only one slice with numeric non zero value', () => { component.chartConfig.dataset[0].data = [48, 0, undefined, 0]; component.ngOnChanges(); expect(component.chartConfig.dataset[0].borderWidth).toEqual(0); }); it('Remove slice border if there is no slice with numeric non zero value', () => { component.chartConfig.dataset[0].data = [undefined, 0]; component.ngOnChanges(); expect(component.chartConfig.dataset[0].borderWidth).toEqual(0); }); it('should not hide any slice if there is no user click on legend item', () => { const initialData = [8, 15]; component.chartConfig.dataset[0].data = initialData; component.ngOnChanges(); expect(component.chartConfig.dataset[0].data).toEqual(initialData); }); describe('tooltip body', () => { const tooltipBody = ['text: 10000']; it('should return amount converted to appropriate units', () => { component.isBytesData = false; expect(component['getChartTooltipBody'](tooltipBody)).toEqual('text: 10 k'); component.isBytesData = true; expect(component['getChartTooltipBody'](tooltipBody)).toEqual('text: 9.8 KiB'); }); it('should not return amount when showing label as tooltip', () => { component.showLabelAsTooltip = true; expect(component['getChartTooltipBody'](tooltipBody)).toEqual('text'); }); }); });
2,695
34.473684
92
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/health-pie/health-pie.component.ts
import { Component, ElementRef, EventEmitter, Input, OnChanges, OnInit, Output, ViewChild } from '@angular/core'; import * as Chart from 'chart.js'; import _ from 'lodash'; import { PluginServiceGlobalRegistrationAndOptions } from 'ng2-charts'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { ChartTooltip } from '~/app/shared/models/chart-tooltip'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { DimlessPipe } from '~/app/shared/pipes/dimless.pipe'; @Component({ selector: 'cd-health-pie', templateUrl: './health-pie.component.html', styleUrls: ['./health-pie.component.scss'] }) export class HealthPieComponent implements OnChanges, OnInit { @ViewChild('chartCanvas', { static: true }) chartCanvasRef: ElementRef; @ViewChild('chartTooltip', { static: true }) chartTooltipRef: ElementRef; @Input() data: any; @Input() config = {}; @Input() isBytesData = false; @Input() tooltipFn: any; @Input() showLabelAsTooltip = false; @Output() prepareFn = new EventEmitter(); chartConfig: any = { chartType: 'doughnut', dataset: [ { label: null, borderWidth: 0 } ], colors: [ { backgroundColor: [ this.cssHelper.propertyValue('chart-color-green'), this.cssHelper.propertyValue('chart-color-yellow'), this.cssHelper.propertyValue('chart-color-orange'), this.cssHelper.propertyValue('chart-color-red'), this.cssHelper.propertyValue('chart-color-blue') ] } ], options: { cutoutPercentage: 90, events: ['click', 'mouseout', 'touchstart'], legend: { display: true, position: 'right', labels: { boxWidth: 10, usePointStyle: false } }, plugins: { center_text: true }, tooltips: { enabled: true, displayColors: false, backgroundColor: this.cssHelper.propertyValue('chart-color-tooltip-background'), cornerRadius: 0, bodyFontSize: 14, bodyFontStyle: '600', position: 'nearest', xPadding: 12, yPadding: 12, callbacks: { label: (item: Record<string, any>, data: Record<string, any>) => { let text = data.labels[item.index]; if (!text.includes('%')) { text = `${text} (${data.datasets[item.datasetIndex].data[item.index]}%)`; } return text; } } }, title: { display: false } } }; public doughnutChartPlugins: PluginServiceGlobalRegistrationAndOptions[] = [ { id: 'center_text', beforeDraw(chart: Chart) { const cssHelper = new CssHelper(); const defaultFontFamily = 'Helvetica Neue, Helvetica, Arial, sans-serif'; Chart.defaults.global.defaultFontFamily = defaultFontFamily; const ctx = chart.ctx; if (!chart.options.plugins.center_text || !chart.data.datasets[0].label) { return; } ctx.save(); const label = chart.data.datasets[0].label.split('\n'); const centerX = (chart.chartArea.left + chart.chartArea.right) / 2; const centerY = (chart.chartArea.top + chart.chartArea.bottom) / 2; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.font = `24px ${defaultFontFamily}`; ctx.fillStyle = cssHelper.propertyValue('chart-color-center-text'); ctx.fillText(label[0], centerX, centerY - 10); if (label.length > 1) { ctx.font = `14px ${defaultFontFamily}`; ctx.fillStyle = cssHelper.propertyValue('chart-color-center-text-description'); ctx.fillText(label[1], centerX, centerY + 10); } ctx.restore(); } } ]; constructor( private dimlessBinary: DimlessBinaryPipe, private dimless: DimlessPipe, private cssHelper: CssHelper ) {} ngOnInit() { const getStyleTop = (tooltip: any, positionY: number) => { return positionY + tooltip.caretY - tooltip.height - 10 + 'px'; }; const getStyleLeft = (tooltip: any, positionX: number) => { return positionX + tooltip.caretX + 'px'; }; const chartTooltip = new ChartTooltip( this.chartCanvasRef, this.chartTooltipRef, getStyleLeft, getStyleTop ); chartTooltip.getBody = (body: any) => { return this.getChartTooltipBody(body); }; _.merge(this.chartConfig, this.config); this.prepareFn.emit([this.chartConfig, this.data]); } ngOnChanges() { this.prepareFn.emit([this.chartConfig, this.data]); this.setChartSliceBorderWidth(); } private getChartTooltipBody(body: string[]) { const bodySplit = body[0].split(': '); if (this.showLabelAsTooltip) { return bodySplit[0]; } bodySplit[1] = this.isBytesData ? this.dimlessBinary.transform(bodySplit[1]) : this.dimless.transform(bodySplit[1]); return bodySplit.join(': '); } private setChartSliceBorderWidth() { let nonZeroValueSlices = 0; _.forEach(this.chartConfig.dataset[0].data, function (slice) { if (slice > 0) { nonZeroValueSlices += 1; } }); this.chartConfig.dataset[0].borderWidth = nonZeroValueSlices > 1 ? 1 : 0; } }
5,367
25.974874
89
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/health/health.component.html
<div *ngIf="healthData && enabledFeature$ | async as enabledFeature" class="container-fluid"> <cd-info-group groupTitle="Status" i18n-groupTitle *ngIf="healthData.health?.status || healthData.mon_status || healthData.osd_map || healthData.mgr_map || healthData.hosts != null || healthData.rgw != null || healthData.fs_map || healthData.iscsi_daemons != null"> <cd-info-card cardTitle="Cluster Status" i18n-cardTitle class="cd-status-card" contentClass="content-highlight" *ngIf="healthData.health?.status"> <ng-container *ngIf="healthData.health?.checks?.length > 0"> <ng-template #healthChecks> <ng-container *ngTemplateOutlet="logsLink"></ng-container> <ul> <li *ngFor="let check of healthData.health.checks"> <span [ngStyle]="check.severity | healthColor" [class.health-warn-description]="check.severity === 'HEALTH_WARN'"> {{ check.type }}</span>: {{ check.summary.message }} </li> </ul> </ng-template> <div class="info-card-content-clickable" [ngStyle]="healthData.health.status | healthColor" [ngbPopover]="healthChecks" popoverClass="info-card-popover-cluster-status"> {{ healthData.health.status | healthLabel | uppercase }} <i *ngIf="healthData.health?.status !== 'HEALTH_OK'" class="fa fa-exclamation-triangle"></i> </div> </ng-container> <ng-container *ngIf="!healthData.health?.checks?.length"> <div [ngStyle]="healthData.health.status | healthColor"> {{ healthData.health.status | healthLabel | uppercase }} </div> </ng-container> </cd-info-card> <cd-info-card cardTitle="Hosts" i18n-cardTitle link="/hosts" class="cd-status-card" contentClass="content-highlight" *ngIf="healthData.hosts != null"> {{ healthData.hosts }} total </cd-info-card> <cd-info-card cardTitle="Monitors" i18n-cardTitle link="/monitor" class="cd-status-card" contentClass="content-highlight" *ngIf="healthData.mon_status"> {{ healthData.mon_status | monSummary }} </cd-info-card> <cd-info-card cardTitle="OSDs" i18n-cardTitle link="/osd" class="cd-status-card" *ngIf="(healthData.osd_map | osdSummary) as transformedResult" contentClass="content-highlight"> <span *ngFor="let result of transformedResult" [ngClass]="result.class"> {{ result.content }} </span> </cd-info-card> <cd-info-card cardTitle="Managers" i18n-cardTitle class="cd-status-card" contentClass="content-highlight" *ngIf="healthData.mgr_map"> <span *ngFor="let result of (healthData.mgr_map | mgrSummary)" [ngClass]="result.class" [title]="result.titleText != null ? result.titleText : ''"> {{ result.content }} </span> </cd-info-card> <cd-info-card cardTitle="Object Gateways" i18n-cardTitle link="/rgw/daemon" class="cd-status-card" contentClass="content-highlight" *ngIf="enabledFeature.rgw && healthData?.rgw != null"> {{ healthData.rgw }} total </cd-info-card> <cd-info-card cardTitle="Metadata Servers" i18n-cardTitle class="cd-status-card" *ngIf="(enabledFeature.cephfs && healthData.fs_map | mdsSummary) as transformedResult" [contentClass]="(transformedResult.length > 1 ? 'text-area-size-2' : '') + ' content-highlight'"> <!-- TODO: check text-area-size-2 --> <span *ngFor="let result of transformedResult" [ngClass]="result.class" [title]="result.titleText !== null ? result.titleText : ''"> {{ result.content }} </span> </cd-info-card> <cd-info-card cardTitle="iSCSI Gateways" i18n-cardTitle link="/block/iscsi" class="cd-status-card" contentClass="content-highlight" *ngIf="enabledFeature.iscsi && healthData?.iscsi_daemons != null"> {{ healthData.iscsi_daemons.up + healthData.iscsi_daemons.down }} total <span class="card-text-line-break"></span> {{ healthData.iscsi_daemons.up }} up, <span [ngClass]="{'card-text-error': healthData.iscsi_daemons.down > 0}">{{ healthData.iscsi_daemons.down }} down</span> </cd-info-card> </cd-info-group> <cd-info-group groupTitle="Capacity" i18n-groupTitle *ngIf="healthData.pools || healthData.df || healthData.pg_info"> <cd-info-card cardTitle="Raw Capacity" i18n-cardTitle class="cd-capacity-card cd-chart-card" contentClass="content-chart" *ngIf="healthData.df"> <cd-health-pie [data]="healthData" [config]="rawCapacityChartConfig" [isBytesData]="true" (prepareFn)="prepareRawUsage($event[0], $event[1])"> </cd-health-pie> </cd-info-card> <cd-info-card cardTitle="Objects" i18n-cardTitle class="cd-capacity-card cd-chart-card" contentClass="content-chart" *ngIf="healthData.pg_info?.object_stats?.num_objects != null"> <cd-health-pie [data]="healthData" (prepareFn)="prepareObjects($event[0], $event[1])"> </cd-health-pie> </cd-info-card> <cd-info-card cardTitle="PG Status" i18n-cardTitle class="cd-capacity-card cd-chart-card" contentClass="content-chart" *ngIf="healthData.pg_info"> <ng-template #pgStatus> <ng-container *ngTemplateOutlet="logsLink"></ng-container> <ul> <li *ngFor="let pgStatesText of healthData.pg_info.statuses | keyvalue"> {{ pgStatesText.key }}: {{ pgStatesText.value }} </li> </ul> </ng-template> <div class="pg-status-popover-wrapper"> <div [ngbPopover]="pgStatus"> <cd-health-pie [data]="healthData" [config]="pgStatusChartConfig" (prepareFn)="preparePgStatus($event[0], $event[1])"> </cd-health-pie> </div> </div> </cd-info-card> <cd-info-card cardTitle="Pools" i18n-cardTitle link="/pool" class="cd-capacity-card" contentClass="content-highlight" *ngIf="healthData.pools"> {{ healthData.pools.length }} </cd-info-card> <cd-info-card cardTitle="PGs per OSD" i18n-cardTitle class="cd-capacity-card" contentClass="content-highlight" *ngIf="healthData.pg_info"> {{ healthData.pg_info.pgs_per_osd | dimless }} </cd-info-card> </cd-info-group> <cd-info-group groupTitle="Performance" i18n-groupTitle *ngIf="healthData.client_perf || healthData.scrub_status"> <cd-info-card cardTitle="Client Read/Write" i18n-cardTitle class="cd-performance-card cd-chart-card" contentClass="content-chart" *ngIf="healthData.client_perf"> <cd-health-pie [data]="healthData" [config]="clientStatsConfig" (prepareFn)="prepareReadWriteRatio($event[0], $event[1])"> </cd-health-pie> </cd-info-card> <cd-info-card cardTitle="Client Throughput" i18n-cardTitle class="cd-performance-card cd-chart-card" contentClass="content-chart" *ngIf="healthData.client_perf"> <cd-health-pie [data]="healthData" [config]="clientStatsConfig" (prepareFn)="prepareClientThroughput($event[0], $event[1])"> </cd-health-pie> </cd-info-card> <cd-info-card cardTitle="Recovery Throughput" i18n-cardTitle class="cd-performance-card" contentClass="content-highlight" *ngIf="healthData.client_perf"> {{ (healthData.client_perf.recovering_bytes_per_sec | dimlessBinary) + '/s' }} </cd-info-card> <cd-info-card cardTitle="Scrubbing" i18n-cardTitle class="cd-performance-card" contentClass="content-highlight" *ngIf="healthData.scrub_status"> {{ healthData.scrub_status }} </cd-info-card> </cd-info-group> <ng-template #logsLink> <ng-container *ngIf="permissions.log.read"> <p class="logs-link" i18n><i [ngClass]="[icons.infoCircle]"></i> See <a routerLink="/logs">Logs</a> for more details.</p> </ng-container> </ng-template> </div>
9,536
38.572614
115
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/health/health.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import _ from 'lodash'; import { of } from 'rxjs'; import { PgCategoryService } from '~/app/ceph/shared/pg-category.service'; import { HealthService } from '~/app/shared/api/health.service'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { FeatureTogglesService } from '~/app/shared/services/feature-toggles.service'; import { RefreshIntervalService } from '~/app/shared/services/refresh-interval.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { HealthPieComponent } from '../health-pie/health-pie.component'; import { MdsSummaryPipe } from '../mds-summary.pipe'; import { MgrSummaryPipe } from '../mgr-summary.pipe'; import { MonSummaryPipe } from '../mon-summary.pipe'; import { OsdSummaryPipe } from '../osd-summary.pipe'; import { HealthComponent } from './health.component'; describe('HealthComponent', () => { let component: HealthComponent; let fixture: ComponentFixture<HealthComponent>; let getHealthSpy: jasmine.Spy; const healthPayload: Record<string, any> = { health: { status: 'HEALTH_OK' }, mon_status: { monmap: { mons: [] }, quorum: [] }, osd_map: { osds: [] }, mgr_map: { standbys: [] }, hosts: 0, rgw: 0, fs_map: { filesystems: [], standbys: [] }, iscsi_daemons: 0, client_perf: {}, scrub_status: 'Inactive', pools: [], df: { stats: {} }, pg_info: { object_stats: { num_objects: 0 } } }; const fakeAuthStorageService = { getPermissions: () => { return new Permissions({ log: ['read'] }); } }; let fakeFeatureTogglesService: jasmine.Spy; configureTestBed({ imports: [SharedModule, HttpClientTestingModule], declarations: [ HealthComponent, HealthPieComponent, MonSummaryPipe, OsdSummaryPipe, MdsSummaryPipe, MgrSummaryPipe ], schemas: [NO_ERRORS_SCHEMA], providers: [ { provide: AuthStorageService, useValue: fakeAuthStorageService }, PgCategoryService, RefreshIntervalService, CssHelper ] }); beforeEach(() => { fakeFeatureTogglesService = spyOn(TestBed.inject(FeatureTogglesService), 'get').and.returnValue( of({ rbd: true, mirroring: true, iscsi: true, cephfs: true, rgw: true }) ); fixture = TestBed.createComponent(HealthComponent); component = fixture.componentInstance; getHealthSpy = spyOn(TestBed.inject(HealthService), 'getMinimalHealth'); getHealthSpy.and.returnValue(of(healthPayload)); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should render all info groups and all info cards', () => { fixture.detectChanges(); const infoGroups = fixture.debugElement.nativeElement.querySelectorAll('cd-info-group'); expect(infoGroups.length).toBe(3); const infoCards = fixture.debugElement.nativeElement.querySelectorAll('cd-info-card'); expect(infoCards.length).toBe(17); }); describe('features disabled', () => { beforeEach(() => { fakeFeatureTogglesService.and.returnValue( of({ rbd: false, mirroring: false, iscsi: false, cephfs: false, rgw: false }) ); fixture = TestBed.createComponent(HealthComponent); component = fixture.componentInstance; }); it('should not render cards related to disabled features', () => { fixture.detectChanges(); const infoGroups = fixture.debugElement.nativeElement.querySelectorAll('cd-info-group'); expect(infoGroups.length).toBe(3); const infoCards = fixture.debugElement.nativeElement.querySelectorAll('cd-info-card'); expect(infoCards.length).toBe(14); }); }); it('should render all except "Status" group and cards', () => { const payload = _.cloneDeep(healthPayload); payload.health.status = ''; payload.mon_status = null; payload.osd_map = null; payload.mgr_map = null; payload.hosts = null; payload.rgw = null; payload.fs_map = null; payload.iscsi_daemons = null; getHealthSpy.and.returnValue(of(payload)); fixture.detectChanges(); const infoGroups = fixture.debugElement.nativeElement.querySelectorAll('cd-info-group'); expect(infoGroups.length).toBe(2); const infoCards = fixture.debugElement.nativeElement.querySelectorAll('cd-info-card'); expect(infoCards.length).toBe(9); }); it('should render all except "Performance" group and cards', () => { const payload = _.cloneDeep(healthPayload); payload.scrub_status = ''; payload.client_perf = null; getHealthSpy.and.returnValue(of(payload)); fixture.detectChanges(); const infoGroups = fixture.debugElement.nativeElement.querySelectorAll('cd-info-group'); expect(infoGroups.length).toBe(2); const infoCards = fixture.debugElement.nativeElement.querySelectorAll('cd-info-card'); expect(infoCards.length).toBe(13); }); it('should render all except "Capacity" group and cards', () => { const payload = _.cloneDeep(healthPayload); payload.pools = null; payload.df = null; payload.pg_info = null; getHealthSpy.and.returnValue(of(payload)); fixture.detectChanges(); const infoGroups = fixture.debugElement.nativeElement.querySelectorAll('cd-info-group'); expect(infoGroups.length).toBe(2); const infoCards = fixture.debugElement.nativeElement.querySelectorAll('cd-info-card'); expect(infoCards.length).toBe(12); }); it('should render all groups and 1 card per group', () => { const payload: Record<string, any> = { hosts: 0, scrub_status: 'Inactive', pools: [] }; getHealthSpy.and.returnValue(of(payload)); fixture.detectChanges(); const infoGroups = fixture.debugElement.nativeElement.querySelectorAll('cd-info-group'); expect(infoGroups.length).toBe(3); _.each(infoGroups, (infoGroup) => { expect(infoGroup.querySelectorAll('cd-info-card').length).toBe(1); }); }); it('should render "Cluster Status" card text that is not clickable', () => { fixture.detectChanges(); const clusterStatusCard = fixture.debugElement.query( By.css('cd-info-card[cardTitle="Cluster Status"]') ); const clickableContent = clusterStatusCard.query(By.css('.info-card-content-clickable')); expect(clickableContent).toBeNull(); expect(clusterStatusCard.nativeElement.textContent).toEqual(' OK '); }); it('should render "Cluster Status" card text that is clickable (popover)', () => { const payload = _.cloneDeep(healthPayload); payload.health['status'] = 'HEALTH_WARN'; payload.health['checks'] = [ { severity: 'HEALTH_WARN', type: 'WRN', summary: { message: 'fake warning' } } ]; getHealthSpy.and.returnValue(of(payload)); fixture.detectChanges(); expect(component.permissions.log.read).toBeTruthy(); const clusterStatusCard = fixture.debugElement.query( By.css('cd-info-card[cardTitle="Cluster Status"]') ); const clickableContent = clusterStatusCard.query(By.css('.info-card-content-clickable')); expect(clickableContent.nativeElement.textContent).toEqual(' WARNING '); }); it('event binding "prepareReadWriteRatio" is called', () => { const prepareReadWriteRatio = spyOn(component, 'prepareReadWriteRatio').and.callThrough(); const payload = _.cloneDeep(healthPayload); payload.client_perf['read_op_per_sec'] = 1; payload.client_perf['write_op_per_sec'] = 3; getHealthSpy.and.returnValue(of(payload)); fixture.detectChanges(); expect(prepareReadWriteRatio).toHaveBeenCalled(); expect(prepareReadWriteRatio.calls.mostRecent().args[0].dataset[0].data).toEqual([25, 75]); }); it('event binding "prepareRawUsage" is called', () => { const prepareRawUsage = spyOn(component, 'prepareRawUsage'); fixture.detectChanges(); expect(prepareRawUsage).toHaveBeenCalled(); }); it('event binding "preparePgStatus" is called', () => { const preparePgStatus = spyOn(component, 'preparePgStatus'); fixture.detectChanges(); expect(preparePgStatus).toHaveBeenCalled(); }); it('event binding "prepareObjects" is called', () => { const prepareObjects = spyOn(component, 'prepareObjects'); fixture.detectChanges(); expect(prepareObjects).toHaveBeenCalled(); }); describe('preparePgStatus', () => { const expectedChart = (data: number[], label: string = null) => ({ labels: [ `Clean: ${component['dimless'].transform(data[0])}`, `Working: ${component['dimless'].transform(data[1])}`, `Warning: ${component['dimless'].transform(data[2])}`, `Unknown: ${component['dimless'].transform(data[3])}` ], options: {}, dataset: [ { data: data.map((i) => component['calcPercentage']( i, data.reduce((j, k) => j + k) ) ), label: label } ] }); it('gets no data', () => { const chart = { dataset: [{}], options: {} }; component.preparePgStatus(chart, { pg_info: {} }); expect(chart).toEqual(expectedChart([0, 0, 0, 0], '0\nPGs')); }); it('gets data from all categories', () => { const chart = { dataset: [{}], options: {} }; component.preparePgStatus(chart, { pg_info: { statuses: { 'clean+active+scrubbing+nonMappedState': 4, 'clean+active+scrubbing': 2, 'clean+active': 1, 'clean+active+scrubbing+down': 3 } } }); expect(chart).toEqual(expectedChart([1, 2, 3, 4], '10\nPGs')); }); }); describe('isClientReadWriteChartShowable', () => { beforeEach(() => { component.healthData = healthPayload; }); it('returns false', () => { component.healthData['client_perf'] = {}; expect(component.isClientReadWriteChartShowable()).toBeFalsy(); }); it('returns false', () => { component.healthData['client_perf'] = { read_op_per_sec: undefined, write_op_per_sec: 0 }; expect(component.isClientReadWriteChartShowable()).toBeFalsy(); }); it('returns true', () => { component.healthData['client_perf'] = { read_op_per_sec: 1, write_op_per_sec: undefined }; expect(component.isClientReadWriteChartShowable()).toBeTruthy(); }); it('returns true', () => { component.healthData['client_perf'] = { read_op_per_sec: 2, write_op_per_sec: 3 }; expect(component.isClientReadWriteChartShowable()).toBeTruthy(); }); }); describe('calcPercentage', () => { it('returns correct value', () => { expect(component['calcPercentage'](1, undefined)).toEqual(0); expect(component['calcPercentage'](1, null)).toEqual(0); expect(component['calcPercentage'](1, 0)).toEqual(0); expect(component['calcPercentage'](undefined, 1)).toEqual(0); expect(component['calcPercentage'](null, 1)).toEqual(0); expect(component['calcPercentage'](0, 1)).toEqual(0); expect(component['calcPercentage'](1, 100000)).toEqual(0.01); expect(component['calcPercentage'](2.346, 10)).toEqual(23.46); expect(component['calcPercentage'](2.56, 10)).toEqual(25.6); }); }); });
11,713
32.56447
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/health/health.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import _ from 'lodash'; import { Subscription } from 'rxjs'; import { take } from 'rxjs/operators'; import { PgCategoryService } from '~/app/ceph/shared/pg-category.service'; import { HealthService } from '~/app/shared/api/health.service'; import { OsdService } from '~/app/shared/api/osd.service'; import { CssHelper } from '~/app/shared/classes/css-helper'; import { Icons } from '~/app/shared/enum/icons.enum'; import { OsdSettings } from '~/app/shared/models/osd-settings'; import { Permissions } from '~/app/shared/models/permissions'; 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 { FeatureTogglesMap$, FeatureTogglesService } from '~/app/shared/services/feature-toggles.service'; import { RefreshIntervalService } from '~/app/shared/services/refresh-interval.service'; @Component({ selector: 'cd-health', templateUrl: './health.component.html', styleUrls: ['./health.component.scss'] }) export class HealthComponent implements OnInit, OnDestroy { healthData: any; osdSettings = new OsdSettings(); interval = new Subscription(); permissions: Permissions; enabledFeature$: FeatureTogglesMap$; icons = Icons; color: string; clientStatsConfig = { colors: [ { backgroundColor: [ this.cssHelper.propertyValue('chart-color-cyan'), this.cssHelper.propertyValue('chart-color-purple') ] } ] }; rawCapacityChartConfig = { colors: [ { backgroundColor: [ this.cssHelper.propertyValue('chart-color-blue'), this.cssHelper.propertyValue('chart-color-gray') ] } ] }; pgStatusChartConfig = { options: { events: [''] } }; constructor( private healthService: HealthService, private osdService: OsdService, private authStorageService: AuthStorageService, private pgCategoryService: PgCategoryService, private featureToggles: FeatureTogglesService, private refreshIntervalService: RefreshIntervalService, private dimlessBinary: DimlessBinaryPipe, private dimless: DimlessPipe, private cssHelper: CssHelper ) { this.permissions = this.authStorageService.getPermissions(); this.enabledFeature$ = this.featureToggles.get(); } ngOnInit() { this.interval = this.refreshIntervalService.intervalData$.subscribe(() => { this.getHealth(); }); this.osdService .getOsdSettings() .pipe(take(1)) .subscribe((data: any) => { this.osdSettings = data; }); } ngOnDestroy() { this.interval.unsubscribe(); } getHealth() { this.healthService.getMinimalHealth().subscribe((data: any) => { this.healthData = data; }); } prepareReadWriteRatio(chart: Record<string, any>) { const ratioLabels = []; const ratioData = []; const total = this.healthData.client_perf.write_op_per_sec + this.healthData.client_perf.read_op_per_sec; ratioLabels.push( `${$localize`Reads`}: ${this.dimless.transform( this.healthData.client_perf.read_op_per_sec )} ${$localize`/s`}` ); ratioData.push(this.calcPercentage(this.healthData.client_perf.read_op_per_sec, total)); ratioLabels.push( `${$localize`Writes`}: ${this.dimless.transform( this.healthData.client_perf.write_op_per_sec )} ${$localize`/s`}` ); ratioData.push(this.calcPercentage(this.healthData.client_perf.write_op_per_sec, total)); chart.labels = ratioLabels; chart.dataset[0].data = ratioData; chart.dataset[0].label = `${this.dimless.transform(total)}\n${$localize`IOPS`}`; } prepareClientThroughput(chart: Record<string, any>) { const ratioLabels = []; const ratioData = []; const total = this.healthData.client_perf.read_bytes_sec + this.healthData.client_perf.write_bytes_sec; ratioLabels.push( `${$localize`Reads`}: ${this.dimlessBinary.transform( this.healthData.client_perf.read_bytes_sec )}${$localize`/s`}` ); ratioData.push(this.calcPercentage(this.healthData.client_perf.read_bytes_sec, total)); ratioLabels.push( `${$localize`Writes`}: ${this.dimlessBinary.transform( this.healthData.client_perf.write_bytes_sec )}${$localize`/s`}` ); ratioData.push(this.calcPercentage(this.healthData.client_perf.write_bytes_sec, total)); chart.labels = ratioLabels; chart.dataset[0].data = ratioData; chart.dataset[0].label = `${this.dimlessBinary .transform(total) .replace(' ', '\n')}${$localize`/s`}`; } prepareRawUsage(chart: Record<string, any>, data: Record<string, any>) { const percentAvailable = this.calcPercentage( data.df.stats.total_bytes - data.df.stats.total_used_raw_bytes, data.df.stats.total_bytes ); const percentUsed = this.calcPercentage( data.df.stats.total_used_raw_bytes, data.df.stats.total_bytes ); if (percentUsed / 100 >= this.osdSettings.nearfull_ratio) { this.color = 'chart-color-red'; } else if (percentUsed / 100 >= this.osdSettings.full_ratio) { this.color = 'chart-color-yellow'; } else { this.color = 'chart-color-blue'; } this.rawCapacityChartConfig.colors[0].backgroundColor[0] = this.cssHelper.propertyValue( this.color ); chart.dataset[0].data = [percentUsed, percentAvailable]; chart.labels = [ `${$localize`Used`}: ${this.dimlessBinary.transform(data.df.stats.total_used_raw_bytes)}`, `${$localize`Avail.`}: ${this.dimlessBinary.transform( data.df.stats.total_bytes - data.df.stats.total_used_raw_bytes )}` ]; chart.dataset[0].label = `${percentUsed}%\nof ${this.dimlessBinary.transform( data.df.stats.total_bytes )}`; } preparePgStatus(chart: Record<string, any>, data: Record<string, any>) { const categoryPgAmount: Record<string, number> = {}; let totalPgs = 0; _.forEach(data.pg_info.statuses, (pgAmount, pgStatesText) => { const categoryType = this.pgCategoryService.getTypeByStates(pgStatesText); if (_.isUndefined(categoryPgAmount[categoryType])) { categoryPgAmount[categoryType] = 0; } categoryPgAmount[categoryType] += pgAmount; totalPgs += pgAmount; }); for (const categoryType of this.pgCategoryService.getAllTypes()) { if (_.isUndefined(categoryPgAmount[categoryType])) { categoryPgAmount[categoryType] = 0; } } chart.dataset[0].data = this.pgCategoryService .getAllTypes() .map((categoryType) => this.calcPercentage(categoryPgAmount[categoryType], totalPgs)); chart.labels = [ `${$localize`Clean`}: ${this.dimless.transform(categoryPgAmount['clean'])}`, `${$localize`Working`}: ${this.dimless.transform(categoryPgAmount['working'])}`, `${$localize`Warning`}: ${this.dimless.transform(categoryPgAmount['warning'])}`, `${$localize`Unknown`}: ${this.dimless.transform(categoryPgAmount['unknown'])}` ]; chart.dataset[0].label = `${totalPgs}\n${$localize`PGs`}`; } prepareObjects(chart: Record<string, any>, data: Record<string, any>) { const objectCopies = data.pg_info.object_stats.num_object_copies; const healthy = objectCopies - data.pg_info.object_stats.num_objects_misplaced - data.pg_info.object_stats.num_objects_degraded - data.pg_info.object_stats.num_objects_unfound; const healthyPercentage = this.calcPercentage(healthy, objectCopies); const misplacedPercentage = this.calcPercentage( data.pg_info.object_stats.num_objects_misplaced, objectCopies ); const degradedPercentage = this.calcPercentage( data.pg_info.object_stats.num_objects_degraded, objectCopies ); const unfoundPercentage = this.calcPercentage( data.pg_info.object_stats.num_objects_unfound, objectCopies ); chart.labels = [ `${$localize`Healthy`}: ${healthyPercentage}%`, `${$localize`Misplaced`}: ${misplacedPercentage}%`, `${$localize`Degraded`}: ${degradedPercentage}%`, `${$localize`Unfound`}: ${unfoundPercentage}%` ]; chart.dataset[0].data = [ healthyPercentage, misplacedPercentage, degradedPercentage, unfoundPercentage ]; chart.dataset[0].label = `${this.dimless.transform( data.pg_info.object_stats.num_objects )}\n${$localize`objects`}`; } isClientReadWriteChartShowable() { const readOps = this.healthData.client_perf.read_op_per_sec || 0; const writeOps = this.healthData.client_perf.write_op_per_sec || 0; return readOps + writeOps > 0; } private calcPercentage(dividend: number, divisor: number) { if (!_.isNumber(dividend) || !_.isNumber(divisor) || divisor === 0) { return 0; } return Math.ceil((dividend / divisor) * 100 * 100) / 100; } }
9,069
31.508961
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/info-card/info-card.component.html
<div class="card shadow-sm" [ngClass]="cardClass"> <div class="card-body d-flex align-items-center justify-content-center"> <h4 class="card-title m-4"> <a *ngIf="link; else noLinkTitle" [routerLink]="link">{{ cardTitle }}</a> <ng-template #noLinkTitle> {{ cardTitle }} </ng-template> </h4> <div class="card-text text-center" [ngClass]="contentClass"> <ng-content></ng-content> </div> </div> </div>
475
24.052632
74
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/info-card/info-card.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { InfoCardComponent } from './info-card.component'; describe('InfoCardComponent', () => { let component: InfoCardComponent; let fixture: ComponentFixture<InfoCardComponent>; configureTestBed({ imports: [RouterTestingModule], declarations: [InfoCardComponent] }); beforeEach(() => { fixture = TestBed.createComponent(InfoCardComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); it('Setting cardTitle makes title visible', () => { const cardTitle = 'Card Title'; component.cardTitle = cardTitle; fixture.detectChanges(); const titleDiv = fixture.debugElement.nativeElement.querySelector('.card-title'); expect(titleDiv.textContent).toContain(cardTitle); }); it('Setting link makes anchor visible', () => { const cardTitle = 'Card Title'; const link = '/dashboard'; component.cardTitle = cardTitle; component.link = link; fixture.detectChanges(); const anchor = fixture.debugElement.nativeElement .querySelector('.card-title') .querySelector('a'); expect(anchor.textContent).toContain(cardTitle); expect(anchor.href).toBe(`http://localhost${link}`); }); it('Setting cardClass makes class set', () => { const cardClass = 'my-css-card-class'; component.cardClass = cardClass; fixture.detectChanges(); const card = fixture.debugElement.nativeElement.querySelector(`.card.${cardClass}`); expect(card).toBeTruthy(); }); it('Setting contentClass makes class set', () => { const contentClass = 'my-css-content-class'; component.contentClass = contentClass; fixture.detectChanges(); const card = fixture.debugElement.nativeElement.querySelector(`.card-body .${contentClass}`); expect(card).toBeTruthy(); }); });
2,036
29.863636
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/info-card/info-card.component.ts
import { Component, Input } from '@angular/core'; @Component({ selector: 'cd-info-card', templateUrl: './info-card.component.html', styleUrls: ['./info-card.component.scss'] }) export class InfoCardComponent { @Input() cardTitle: string; @Input() link: string; @Input() cardClass = ''; @Input() contentClass: string; }
342
18.055556
49
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/info-group/info-group.component.html
<div class="row"> <div class="info-group-title"> <span>{{ groupTitle }}</span> <cd-helper iconClass="fa fa-info-circle fa-2xs"> <div class="text-center" i18n>For an overview of {{ groupTitle|lowercase }} widgets click <cd-doc section="dashboard-landing-page-{{ groupTitle|lowercase }}" docText="here" i18n-docText></cd-doc> </div> </cd-helper> </div> </div> <div class="row"> <ng-content></ng-content> </div>
491
26.333333
75
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/info-group/info-group.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { NgbPopoverModule } from '@ng-bootstrap/ng-bootstrap'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { InfoGroupComponent } from './info-group.component'; describe('InfoGroupComponent', () => { let component: InfoGroupComponent; let fixture: ComponentFixture<InfoGroupComponent>; configureTestBed({ imports: [NgbPopoverModule, SharedModule, HttpClientTestingModule], declarations: [InfoGroupComponent] }); beforeEach(() => { fixture = TestBed.createComponent(InfoGroupComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); it('Setting groupTitle makes title visible', () => { const groupTitle = 'Group Title'; component.groupTitle = groupTitle; fixture.detectChanges(); const titleDiv = fixture.debugElement.nativeElement.querySelector('.info-group-title'); expect(titleDiv.textContent).toContain(groupTitle); }); });
1,180
30.918919
91
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/dashboard/info-group/info-group.component.ts
import { Component, Input } from '@angular/core'; import { Icons } from '~/app/shared/enum/icons.enum'; @Component({ selector: 'cd-info-group', templateUrl: './info-group.component.html', styleUrls: ['./info-group.component.scss'] }) export class InfoGroupComponent { icons = Icons; @Input() groupTitle: string; }
328
20.933333
53
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { NgbNavModule, NgbTooltipModule, NgbTypeaheadModule } from '@ng-bootstrap/ng-bootstrap'; import { SharedModule } from '~/app/shared/shared.module'; import { NfsDetailsComponent } from './nfs-details/nfs-details.component'; import { NfsFormClientComponent } from './nfs-form-client/nfs-form-client.component'; import { NfsFormComponent } from './nfs-form/nfs-form.component'; import { NfsListComponent } from './nfs-list/nfs-list.component'; @NgModule({ imports: [ ReactiveFormsModule, RouterModule, SharedModule, NgbNavModule, CommonModule, NgbTypeaheadModule, NgbTooltipModule ], declarations: [NfsListComponent, NfsDetailsComponent, NfsFormComponent, NfsFormClientComponent] }) export class NfsModule {}
943
33.962963
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/models/nfs.fsal.ts
export interface NfsFSAbstractionLayer { value: string; descr: string; disabled: boolean; }
98
15.5
40
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-details/nfs-details.component.html
<ng-container *ngIf="selection"> <nav ngbNav #nav="ngbNav" class="nav-tabs" cdStatefulTab="nfs-details"> <ng-container ngbNavItem="details"> <a ngbNavLink i18n>Details</a> <ng-template ngbNavContent> <cd-table-key-value [data]="data"> </cd-table-key-value> </ng-template> </ng-container> <ng-container ngbNavItem="clients"> <a ngbNavLink i18n>Clients ({{ clients.length }})</a> <ng-template ngbNavContent> <cd-table #table [data]="clients" columnMode="flex" [columns]="clientsColumns" identifier="addresses" forceIdentifier="true" selectionType=""> </cd-table> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="nav"></div> </ng-container>
887
25.909091
48
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-details/nfs-details.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 { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { NfsDetailsComponent } from './nfs-details.component'; describe('NfsDetailsComponent', () => { let component: NfsDetailsComponent; let fixture: ComponentFixture<NfsDetailsComponent>; const elem = (css: string) => fixture.debugElement.query(By.css(css)); configureTestBed({ declarations: [NfsDetailsComponent], imports: [BrowserAnimationsModule, SharedModule, HttpClientTestingModule, NgbNavModule] }); beforeEach(() => { fixture = TestBed.createComponent(NfsDetailsComponent); component = fixture.componentInstance; component.selection = { export_id: 1, path: '/qwe', fsal: { name: 'CEPH', user_id: 'fs', fs_name: 1 }, cluster_id: 'cluster1', pseudo: '/qwe', access_type: 'RW', squash: 'no_root_squash', protocols: [4], transports: ['TCP', 'UDP'], clients: [ { addresses: ['192.168.0.10', '192.168.1.0/8'], access_type: 'RW', squash: 'root_id_squash' } ] }; component.ngOnChanges(); fixture.detectChanges(); }); it('should create', () => { expect(component.data).toBeTruthy(); }); it('should prepare data', () => { expect(component.data).toEqual({ 'Access Type': 'RW', 'CephFS Filesystem': 1, 'CephFS User': 'fs', Cluster: 'cluster1', 'NFS Protocol': ['NFSv4'], Path: '/qwe', Pseudo: '/qwe', 'Security Label': undefined, Squash: 'no_root_squash', 'Storage Backend': 'CephFS', Transport: ['TCP', 'UDP'] }); }); it('should prepare data if RGW', () => { const newData = _.assignIn(component.selection, { fsal: { name: 'RGW', user_id: 'user-id' } }); component.selection = newData; component.ngOnChanges(); expect(component.data).toEqual({ 'Access Type': 'RW', Cluster: 'cluster1', 'NFS Protocol': ['NFSv4'], 'Object Gateway User': 'user-id', Path: '/qwe', Pseudo: '/qwe', Squash: 'no_root_squash', 'Storage Backend': 'Object Gateway', Transport: ['TCP', 'UDP'] }); }); it('should have 1 client', () => { expect(elem('nav.nav-tabs a:nth-of-type(2)').nativeElement.textContent).toBe('Clients (1)'); expect(component.clients).toEqual([ { access_type: 'RW', addresses: ['192.168.0.10', '192.168.1.0/8'], squash: 'root_id_squash' } ]); }); });
2,933
27.485437
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-details/nfs-details.component.ts
import { Component, Input, OnChanges } from '@angular/core'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; @Component({ selector: 'cd-nfs-details', templateUrl: './nfs-details.component.html', styleUrls: ['./nfs-details.component.scss'] }) export class NfsDetailsComponent implements OnChanges { @Input() selection: any; selectedItem: any; data: any; clientsColumns: CdTableColumn[]; clients: any[] = []; constructor() { this.clientsColumns = [ { name: $localize`Addresses`, prop: 'addresses', flexGrow: 2 }, { name: $localize`Access Type`, prop: 'access_type', flexGrow: 1 }, { name: $localize`Squash`, prop: 'squash', flexGrow: 1 } ]; } ngOnChanges() { if (this.selection) { this.selectedItem = this.selection; this.clients = this.selectedItem.clients; this.data = {}; this.data[$localize`Cluster`] = this.selectedItem.cluster_id; this.data[$localize`NFS Protocol`] = this.selectedItem.protocols.map( (protocol: string) => 'NFSv' + protocol ); this.data[$localize`Pseudo`] = this.selectedItem.pseudo; this.data[$localize`Access Type`] = this.selectedItem.access_type; this.data[$localize`Squash`] = this.selectedItem.squash; this.data[$localize`Transport`] = this.selectedItem.transports; this.data[$localize`Path`] = this.selectedItem.path; if (this.selectedItem.fsal.name === 'CEPH') { this.data[$localize`Storage Backend`] = $localize`CephFS`; this.data[$localize`CephFS User`] = this.selectedItem.fsal.user_id; this.data[$localize`CephFS Filesystem`] = this.selectedItem.fsal.fs_name; this.data[$localize`Security Label`] = this.selectedItem.fsal.sec_label_xattr; } else { this.data[$localize`Storage Backend`] = $localize`Object Gateway`; this.data[$localize`Object Gateway User`] = this.selectedItem.fsal.user_id; } } } }
2,052
28.753623
86
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-form-client/nfs-form-client.component.html
<div class="form-group row"> <label class="cd-col-form-label" i18n>Clients</label> <div class="cd-col-form-input" [formGroup]="form" #formDir="ngForm"> <span *ngIf="form.get('clients').value.length === 0" class="no-border text-muted"> <span class="form-text text-muted" i18n>Any client can access</span> </span> <ng-container formArrayName="clients"> <div *ngFor="let item of clientsFormArray.controls; let index = index; trackBy: trackByFn"> <div class="card" [formGroup]="item"> <div class="card-header"> {{ (index + 1) | ordinal }} <span class="float-end clickable" name="remove_client" (click)="removeClient(index)" ngbTooltip="Remove">&times;</span> </div> <div class="card-body"> <!-- Addresses --> <div class="form-group row"> <label i18n class="cd-col-form-label required" for="addresses">Addresses</label> <div class="cd-col-form-input"> <input type="text" class="form-control" name="addresses" id="addresses" formControlName="addresses" placeholder="192.168.0.10, 192.168.1.0/8"> <span class="invalid-feedback"> <span *ngIf="showError(index, 'addresses', formDir, 'required')" i18n>This field is required.</span> <span *ngIf="showError(index, 'addresses', formDir, 'pattern')"> <ng-container i18n>Must contain one or more comma-separated values</ng-container> <br> <ng-container i18n>For example:</ng-container> 192.168.0.10, 192.168.1.0/8 </span> </span> </div> </div> <!-- Access Type--> <div class="form-group row"> <label i18n class="cd-col-form-label" for="access_type">Access Type</label> <div class="cd-col-form-input"> <select class="form-select" name="access_type" id="access_type" formControlName="access_type"> <option value="">{{ getNoAccessTypeDescr() }}</option> <option *ngFor="let item of nfsAccessType" [value]="item.value">{{ item.value }}</option> </select> <span class="form-text text-muted" *ngIf="getValue(index, 'access_type')"> {{ getAccessTypeHelp(index) }} </span> </div> </div> <!-- Squash --> <div class="form-group row"> <label class="cd-col-form-label" for="squash"> <span i18n>Squash</span> <ng-container *ngTemplateOutlet="squashHelperTpl"></ng-container> </label> <div class="cd-col-form-input"> <select class="form-select" name="squash" id="squash" formControlName="squash"> <option value="">{{ getNoSquashDescr() }}</option> <option *ngFor="let squash of nfsSquash" [value]="squash">{{ squash }}</option> </select> </div> </div> </div> </div> </div> </ng-container> <div class="row my-2"> <div class="col-12"> <div class="float-end"> <button class="btn btn-light " (click)="addClient()" name="add_client"> <i [ngClass]="[icons.add]"></i> <ng-container i18n>Add clients</ng-container> </button> </div> </div> </div> </div> </div>
4,119
36.454545
101
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-form-client/nfs-form-client.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { NfsFormClientComponent } from './nfs-form-client.component'; describe('NfsFormClientComponent', () => { let component: NfsFormClientComponent; let fixture: ComponentFixture<NfsFormClientComponent>; configureTestBed({ declarations: [NfsFormClientComponent], imports: [ReactiveFormsModule, SharedModule, HttpClientTestingModule] }); beforeEach(() => { fixture = TestBed.createComponent(NfsFormClientComponent); const formBuilder = TestBed.inject(CdFormBuilder); component = fixture.componentInstance; component.form = new CdFormGroup({ access_type: new FormControl(''), clients: formBuilder.array([]), squash: new FormControl('') }); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should add a client', () => { expect(component.form.getValue('clients')).toEqual([]); component.addClient(); expect(component.form.getValue('clients')).toEqual([ { access_type: '', addresses: '', squash: '' } ]); }); it('should return form access_type', () => { expect(component.getNoAccessTypeDescr()).toBe('-- Select the access type --'); component.form.patchValue({ access_type: 'RW' }); expect(component.getNoAccessTypeDescr()).toBe('RW (inherited from global config)'); }); it('should return form squash', () => { expect(component.getNoSquashDescr()).toBe( '-- Select what kind of user id squashing is performed --' ); component.form.patchValue({ squash: 'root_id_squash' }); expect(component.getNoSquashDescr()).toBe('root_id_squash (inherited from global config)'); }); it('should remove client', () => { component.addClient(); expect(component.form.getValue('clients')).toEqual([ { access_type: '', addresses: '', squash: '' } ]); component.removeClient(0); expect(component.form.getValue('clients')).toEqual([]); }); });
2,410
32.486111
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-form-client/nfs-form-client.component.ts
import { Component, ContentChild, Input, OnInit, TemplateRef } from '@angular/core'; import { FormArray, FormControl, NgForm, Validators } from '@angular/forms'; import _ from 'lodash'; import { NfsService } from '~/app/shared/api/nfs.service'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; @Component({ selector: 'cd-nfs-form-client', templateUrl: './nfs-form-client.component.html', styleUrls: ['./nfs-form-client.component.scss'] }) export class NfsFormClientComponent implements OnInit { @Input() form: CdFormGroup; @Input() clients: any[]; @ContentChild('squashHelper', { static: true }) squashHelperTpl: TemplateRef<any>; nfsSquash: any[] = Object.keys(this.nfsService.nfsSquash); nfsAccessType: any[] = this.nfsService.nfsAccessType; icons = Icons; clientsFormArray: FormArray; constructor(private nfsService: NfsService) {} ngOnInit() { _.forEach(this.clients, (client) => { const fg = this.addClient(); fg.patchValue(client); }); this.clientsFormArray = this.form.get('clients') as FormArray; } getNoAccessTypeDescr() { if (this.form.getValue('access_type')) { return `${this.form.getValue('access_type')} ${$localize`(inherited from global config)`}`; } return $localize`-- Select the access type --`; } getAccessTypeHelp(index: number) { const accessTypeItem = this.nfsAccessType.find((currentAccessTypeItem) => { return this.getValue(index, 'access_type') === currentAccessTypeItem.value; }); return _.isObjectLike(accessTypeItem) ? accessTypeItem.help : ''; } getNoSquashDescr() { if (this.form.getValue('squash')) { return `${this.form.getValue('squash')} (${$localize`inherited from global config`})`; } return $localize`-- Select what kind of user id squashing is performed --`; } addClient() { this.clientsFormArray = this.form.get('clients') as FormArray; const REGEX_IP = `(([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\.([0-9]{1,3})([/](\\d|[1-2]\\d|3[0-2]))?)`; const REGEX_LIST_IP = `${REGEX_IP}([ ,]{1,2}${REGEX_IP})*`; const fg = new CdFormGroup({ addresses: new FormControl('', { validators: [Validators.required, Validators.pattern(REGEX_LIST_IP)] }), access_type: new FormControl(''), squash: new FormControl('') }); this.clientsFormArray.push(fg); return fg; } removeClient(index: number) { this.clientsFormArray = this.form.get('clients') as FormArray; this.clientsFormArray.removeAt(index); } showError(index: number, control: string, formDir: NgForm, x: string) { return (<any>this.form.controls.clients).controls[index].showError(control, formDir, x); } getValue(index: number, control: string) { this.clientsFormArray = this.form.get('clients') as FormArray; const client = this.clientsFormArray.at(index) as CdFormGroup; return client.getValue(control); } trackByFn(index: number) { return index; } }
3,050
30.78125
109
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-form/nfs-form.component.html
<div class="cd-col-form" *cdFormLoading="loading"> <form name="nfsForm" #formDir="ngForm" [formGroup]="nfsForm" novalidate> <div class="card"> <div i18n="form title" class="card-header">{{ action | titlecase }} {{ resource | upperFirst }}</div> <div class="card-body"> <!-- cluster_id --> <div class="form-group row"> <label class="cd-col-form-label" for="cluster_id"> <span class="required" i18n>Cluster</span> <cd-helper> <p i18n>This is the ID of an NFS Service.</p> </cd-helper> </label> <div class="cd-col-form-input"> <select class="form-select" formControlName="cluster_id" name="cluster_id" id="cluster_id"> <option *ngIf="allClusters === null" value="" i18n>Loading...</option> <option *ngIf="allClusters !== null && allClusters.length === 0" value="" i18n>-- No cluster available --</option> <option *ngIf="allClusters !== null && allClusters.length > 0" value="" i18n>-- Select the cluster --</option> <option *ngFor="let cluster of allClusters" [value]="cluster.cluster_id">{{ cluster.cluster_id }}</option> </select> <span class="invalid-feedback" *ngIf="nfsForm.showError('cluster_id', formDir, 'required') || allClusters?.length === 0" i18n>This field is required. To create a new NFS cluster, <a [routerLink]="['/services', {outlets: {modal: ['create']}}]" class="btn-link">add a new NFS Service</a>.</span> </div> </div> <!-- FSAL --> <div formGroupName="fsal"> <!-- Name --> <div class="form-group row"> <label class="cd-col-form-label required" for="name" i18n>Storage Backend</label> <div class="cd-col-form-input"> <select class="form-select" formControlName="name" name="name" id="name" (change)="fsalChangeHandler()"> <option *ngIf="allFsals === null" value="" i18n>Loading...</option> <option *ngIf="allFsals !== null && allFsals.length === 0" value="" i18n>-- No data pools available --</option> <option *ngIf="allFsals !== null && allFsals.length > 0" value="" i18n>-- Select the storage backend --</option> <option *ngFor="let fsal of allFsals" [value]="fsal.value" [disabled]="fsal.disabled">{{ fsal.descr }}</option> </select> <span class="invalid-feedback" *ngIf="nfsForm.showError('name', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="fsalAvailabilityError" i18n>{{ fsalAvailabilityError }}</span> </div> </div> <!-- CephFS Volume --> <div class="form-group row" *ngIf="nfsForm.getValue('name') === 'CEPH'"> <label class="cd-col-form-label required" for="fs_name" i18n>Volume</label> <div class="cd-col-form-input"> <select class="form-select" formControlName="fs_name" name="fs_name" id="fs_name" (change)="pathChangeHandler()"> <option *ngIf="allFsNames === null" value="" i18n>Loading...</option> <option *ngIf="allFsNames !== null && allFsNames.length === 0" value="" i18n>-- No CephFS filesystem available --</option> <option *ngIf="allFsNames !== null && allFsNames.length > 0" value="" i18n>-- Select the CephFS filesystem --</option> <option *ngFor="let filesystem of allFsNames" [value]="filesystem.name">{{ filesystem.name }}</option> </select> <span class="invalid-feedback" *ngIf="nfsForm.showError('fs_name', formDir, 'required')" i18n>This field is required.</span> </div> </div> </div> <!-- Security Label --> <div class="form-group row" *ngIf="nfsForm.getValue('name') === 'CEPH'"> <label class="cd-col-form-label" [ngClass]="{'required': nfsForm.getValue('security_label')}" for="security_label" i18n>Security Label</label> <div class="cd-col-form-input"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" formControlName="security_label" name="security_label" id="security_label"> <label for="security_label" class="custom-control-label" i18n>Enable security label</label> </div> <br> <input type="text" *ngIf="nfsForm.getValue('security_label')" class="form-control" name="sec_label_xattr" id="sec_label_xattr" formControlName="sec_label_xattr"> <span class="invalid-feedback" *ngIf="nfsForm.showError('sec_label_xattr', formDir, 'required')" i18n>This field is required.</span> </div> </div> <!-- Path --> <div class="form-group row" *ngIf="nfsForm.getValue('name') === 'CEPH'"> <label class="cd-col-form-label" for="path"> <span class="required" i18n>CephFS Path</span> <cd-helper> <p i18n>A path in a CephFS file system.</p> </cd-helper> </label> <div class="cd-col-form-input"> <input type="text" class="form-control" name="path" id="path" data-testid="fs_path" formControlName="path" [ngbTypeahead]="pathDataSource" (selectItem)="pathChangeHandler()" (blur)="pathChangeHandler()"> <span class="invalid-feedback" *ngIf="nfsForm.showError('path', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="nfsForm.showError('path', formDir, 'pattern')" i18n>Path need to start with a '/' and can be followed by a word</span> <span class="invalid-feedback" *ngIf="nfsForm.showError('path', formDir, 'pathNameNotAllowed')" i18n>The path does not exist in the selected volume.</span> </div> </div> <!-- Bucket --> <div class="form-group row" *ngIf="nfsForm.getValue('name') === 'RGW'"> <label class="cd-col-form-label" for="path"> <span class="required" i18n>Bucket</span> </label> <div class="cd-col-form-input"> <input type="text" class="form-control" name="path" id="path" data-testid="rgw_path" formControlName="path" [ngbTypeahead]="bucketDataSource"> <span class="invalid-feedback" *ngIf="nfsForm.showError('path', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="nfsForm.showError('path', formDir, 'bucketNameNotAllowed')" i18n>The bucket does not exist or is not in the default realm (if multiple realms are configured). To continue, <a routerLink="/rgw/bucket/create" class="btn-link">create a new bucket</a>.</span> </div> </div> <!-- NFS Protocol --> <div class="form-group row"> <label class="cd-col-form-label required" for="protocols" i18n>NFS Protocol</label> <div class="cd-col-form-input"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" formControlName="protocolNfsv4" name="protocolNfsv4" id="protocolNfsv4" disabled> <label i18n class="custom-control-label" for="protocolNfsv4">NFSv4</label> </div> <span class="invalid-feedback" *ngIf="nfsForm.showError('protocolNfsv4', formDir, 'required')" i18n>This field is required.</span> </div> </div> <!-- Pseudo --> <div class="form-group row" *ngIf="nfsForm.getValue('protocolNfsv4')"> <label class="cd-col-form-label" for="pseudo"> <span class="required" i18n>Pseudo</span> <cd-helper> <p i18n>The position that this <strong>NFS v4</strong> export occupies in the <strong>Pseudo FS</strong> (it must be unique).</p> <p i18n>By using different Pseudo options, the same Path may be exported multiple times.</p> </cd-helper> </label> <div class="cd-col-form-input"> <input type="text" class="form-control" name="pseudo" id="pseudo" formControlName="pseudo"> <span class="invalid-feedback" *ngIf="nfsForm.showError('pseudo', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="nfsForm.showError('pseudo', formDir, 'pseudoAlreadyExists')" i18n>The pseudo is already in use by another export.</span> <span class="invalid-feedback" *ngIf="nfsForm.showError('pseudo', formDir, 'pattern')" i18n>Pseudo needs to start with a '/' and can't contain any of the following: &gt;, &lt;, |, &, ( or ).</span> </div> </div> <!-- Access Type --> <div class="form-group row"> <label class="cd-col-form-label required" for="access_type" i18n>Access Type</label> <div class="cd-col-form-input"> <select class="form-select" formControlName="access_type" name="access_type" id="access_type" (change)="accessTypeChangeHandler()"> <option *ngIf="nfsAccessType === null" value="" i18n>Loading...</option> <option *ngIf="nfsAccessType !== null && nfsAccessType.length === 0" value="" i18n>-- No access type available --</option> <option *ngFor="let accessType of nfsAccessType" [value]="accessType.value">{{ accessType.value }}</option> </select> <span class="form-text text-muted" *ngIf="nfsForm.getValue('access_type')"> {{ getAccessTypeHelp(nfsForm.getValue('access_type')) }} </span> <span class="form-text text-warning" *ngIf="nfsForm.getValue('access_type') === 'RW' && nfsForm.getValue('name') === 'RGW'" i18n>The Object Gateway NFS backend has a number of limitations which will seriously affect applications writing to the share. Please consult the <cd-doc section="rgw-nfs"></cd-doc> for details before enabling write access.</span> <span class="invalid-feedback" *ngIf="nfsForm.showError('access_type', formDir, 'required')" i18n>This field is required.</span> </div> </div> <!-- Squash --> <div class="form-group row"> <label class="cd-col-form-label" for="squash"> <span i18n>Squash</span> <ng-container *ngTemplateOutlet="squashHelper"></ng-container> </label> <div class="cd-col-form-input"> <select class="form-select" name="squash" formControlName="squash" id="squash"> <option *ngIf="nfsSquash === null" value="" i18n>Loading...</option> <option *ngIf="nfsSquash !== null && nfsSquash.length === 0" value="" i18n>-- No squash available --</option> <option *ngFor="let squash of nfsSquash" [value]="squash">{{ squash }}</option> </select> <span class="invalid-feedback" *ngIf="nfsForm.showError('squash', formDir,'required')" i18n>This field is required.</span> </div> </div> <!-- Transport Protocol --> <div class="form-group row"> <label class="cd-col-form-label required" for="transports" i18n>Transport Protocol</label> <div class="cd-col-form-input"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" formControlName="transportUDP" name="transportUDP" id="transportUDP"> <label for="transportUDP" class="custom-control-label" i18n>UDP</label> </div> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" formControlName="transportTCP" name="transportTCP" id="transportTCP"> <label for="transportTCP" class="custom-control-label" i18n>TCP</label> </div> <span class="invalid-feedback" *ngIf="nfsForm.showError('transportUDP', formDir, 'required') || nfsForm.showError('transportTCP', formDir, 'required')" i18n>This field is required.</span> <hr> </div> </div> <!-- Clients --> <cd-nfs-form-client [form]="nfsForm" [clients]="clients" #nfsClients> <ng-template #squashHelper> <cd-helper> <ul class="squash-helper"> <li> <span class="squash-helper-item-value">no_root_squash: </span> <span i18n>No user id squashing is performed.</span> </li> <li> <span class="squash-helper-item-value">root_id_squash: </span> <span i18n>uid 0 and gid 0 are squashed to the Anonymous_Uid and Anonymous_Gid gid 0 in alt_groups lists is also squashed.</span> </li> <li> <span class="squash-helper-item-value">root_squash: </span> <span i18n>uid 0 and gid of any value are squashed to the Anonymous_Uid and Anonymous_Gid alt_groups lists is discarded.</span> </li> <li> <span class="squash-helper-item-value">all_squash: </span> <span i18n>All users are squashed.</span> </li> </ul> </cd-helper> </ng-template> </cd-nfs-form-client> </div> <div class="card-footer"> <cd-form-button-panel (submitActionEvent)="submitAction()" [form]="nfsForm" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)" wrappingClass="text-right"></cd-form-button-panel> </div> </div> </form> </div>
17,215
41.932668
147
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-form/nfs-form.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { ActivatedRoute } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbTypeaheadModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { Observable, of } from 'rxjs'; import { NfsFormClientComponent } from '~/app/ceph/nfs/nfs-form-client/nfs-form-client.component'; import { NfsFormComponent } from '~/app/ceph/nfs/nfs-form/nfs-form.component'; import { Directory } from '~/app/shared/api/nfs.service'; import { LoadingPanelComponent } from '~/app/shared/components/loading-panel/loading-panel.component'; import { SharedModule } from '~/app/shared/shared.module'; import { ActivatedRouteStub } from '~/testing/activated-route-stub'; import { configureTestBed, RgwHelper } from '~/testing/unit-test-helper'; describe('NfsFormComponent', () => { let component: NfsFormComponent; let fixture: ComponentFixture<NfsFormComponent>; let httpTesting: HttpTestingController; let activatedRoute: ActivatedRouteStub; configureTestBed( { declarations: [NfsFormComponent, NfsFormClientComponent], imports: [ HttpClientTestingModule, ReactiveFormsModule, RouterTestingModule, SharedModule, ToastrModule.forRoot(), NgbTypeaheadModule ], providers: [ { provide: ActivatedRoute, useValue: new ActivatedRouteStub({ cluster_id: 'mynfs', export_id: '1' }) } ] }, [LoadingPanelComponent] ); const matchSquash = (backendSquashValue: string, uiSquashValue: string) => { component.ngOnInit(); httpTesting.expectOne('ui-api/nfs-ganesha/fsals').flush(['CEPH', 'RGW']); httpTesting.expectOne('ui-api/nfs-ganesha/cephfs/filesystems').flush([{ id: 1, name: 'a' }]); httpTesting.expectOne('api/nfs-ganesha/cluster').flush(['mynfs']); httpTesting.expectOne('api/nfs-ganesha/export/mynfs/1').flush({ fsal: { name: 'RGW' }, export_id: 1, transports: ['TCP', 'UDP'], protocols: [4], clients: [], squash: backendSquashValue }); httpTesting.verify(); expect(component.nfsForm.value).toMatchObject({ squash: uiSquashValue }); }; beforeEach(() => { fixture = TestBed.createComponent(NfsFormComponent); component = fixture.componentInstance; httpTesting = TestBed.inject(HttpTestingController); activatedRoute = <ActivatedRouteStub>TestBed.inject(ActivatedRoute); RgwHelper.selectDaemon(); fixture.detectChanges(); httpTesting.expectOne('ui-api/nfs-ganesha/fsals').flush(['CEPH', 'RGW']); httpTesting.expectOne('ui-api/nfs-ganesha/cephfs/filesystems').flush([{ id: 1, name: 'a' }]); httpTesting.expectOne('api/nfs-ganesha/cluster').flush(['mynfs']); httpTesting.verify(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should process all data', () => { expect(component.allFsals).toEqual([ { descr: 'CephFS', value: 'CEPH', disabled: false }, { descr: 'Object Gateway', value: 'RGW', disabled: false } ]); expect(component.allFsNames).toEqual([{ id: 1, name: 'a' }]); expect(component.allClusters).toEqual([{ cluster_id: 'mynfs' }]); }); it('should create the form', () => { expect(component.nfsForm.value).toEqual({ access_type: 'RW', clients: [], cluster_id: 'mynfs', fsal: { fs_name: 'a', name: 'CEPH' }, path: '/', protocolNfsv4: true, pseudo: '', sec_label_xattr: 'security.selinux', security_label: false, squash: 'no_root_squash', transportTCP: true, transportUDP: true }); expect(component.nfsForm.get('cluster_id').disabled).toBeFalsy(); }); it('should prepare data when selecting an cluster', () => { component.nfsForm.patchValue({ cluster_id: 'cluster1' }); component.nfsForm.patchValue({ cluster_id: 'cluster2' }); }); it('should not allow changing cluster in edit mode', () => { component.isEdit = true; component.ngOnInit(); expect(component.nfsForm.get('cluster_id').disabled).toBeTruthy(); }); it('should mark NFSv4 protocol as enabled always', () => { expect(component.nfsForm.get('protocolNfsv4')).toBeTruthy(); }); it('should match backend squash values with ui values', () => { component.isEdit = true; matchSquash('none', 'no_root_squash'); matchSquash('all', 'all_squash'); matchSquash('rootid', 'root_id_squash'); matchSquash('root', 'root_squash'); }); describe('should submit request', () => { beforeEach(() => { component.nfsForm.patchValue({ access_type: 'RW', clients: [], cluster_id: 'cluster1', fsal: { name: 'CEPH', fs_name: 1 }, path: '/foo', protocolNfsv4: true, pseudo: '/baz', squash: 'no_root_squash', transportTCP: true, transportUDP: true }); }); it('should call update', () => { activatedRoute.setParams({ cluster_id: 'cluster1', export_id: '1' }); component.isEdit = true; component.cluster_id = 'cluster1'; component.export_id = '1'; component.nfsForm.patchValue({ export_id: 1 }); component.submitAction(); const req = httpTesting.expectOne('api/nfs-ganesha/export/cluster1/1'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ access_type: 'RW', clients: [], cluster_id: 'cluster1', export_id: 1, fsal: { fs_name: 1, name: 'CEPH', sec_label_xattr: null }, path: '/foo', protocols: [4], pseudo: '/baz', security_label: false, squash: 'no_root_squash', transports: ['TCP', 'UDP'] }); }); it('should call create', () => { activatedRoute.setParams({ cluster_id: undefined, export_id: undefined }); component.submitAction(); const req = httpTesting.expectOne('api/nfs-ganesha/export'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ access_type: 'RW', clients: [], cluster_id: 'cluster1', fsal: { fs_name: 1, name: 'CEPH', sec_label_xattr: null }, path: '/foo', protocols: [4], pseudo: '/baz', security_label: false, squash: 'no_root_squash', transports: ['TCP', 'UDP'] }); }); }); describe('pathExistence', () => { beforeEach(() => { component['nfsService']['lsDir'] = jest.fn( (): Observable<Directory> => of({ paths: ['/path1'] }) ); component.nfsForm.get('name').setValue('CEPH'); component.setPathValidation(); }); const testValidator = (pathName: string, valid: boolean, expectedError?: string) => { const path = component.nfsForm.get('path'); path.setValue(pathName); path.markAsDirty(); path.updateValueAndValidity(); if (valid) { expect(path.errors).toBe(null); } else { expect(path.hasError(expectedError)).toBeTruthy(); } }; it('path cannot be empty', () => { testValidator('', false, 'required'); }); it('path that does not exist should be invalid', () => { testValidator('/path2', false, 'pathNameNotAllowed'); expect(component['nfsService']['lsDir']).toHaveBeenCalledTimes(1); }); it('path that exists should be valid', () => { testValidator('/path1', true); expect(component['nfsService']['lsDir']).toHaveBeenCalledTimes(1); }); }); });
7,819
31.719665
102
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-form/nfs-form.component.ts
import { ChangeDetectorRef, Component, OnInit, ViewChild } from '@angular/core'; import { AbstractControl, AsyncValidatorFn, FormControl, ValidationErrors, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import _ from 'lodash'; import { forkJoin, Observable, of } from 'rxjs'; import { catchError, debounceTime, distinctUntilChanged, map, mergeMap } from 'rxjs/operators'; import { NfsFSAbstractionLayer } from '~/app/ceph/nfs/models/nfs.fsal'; import { Directory, NfsService } from '~/app/shared/api/nfs.service'; import { RgwBucketService } from '~/app/shared/api/rgw-bucket.service'; import { RgwSiteService } from '~/app/shared/api/rgw-site.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 { 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 { FinishedTask } from '~/app/shared/models/finished-task'; import { Permission } from '~/app/shared/models/permissions'; import { CdHttpErrorResponse } from '~/app/shared/services/api-interceptor.service'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { NfsFormClientComponent } from '../nfs-form-client/nfs-form-client.component'; @Component({ selector: 'cd-nfs-form', templateUrl: './nfs-form.component.html', styleUrls: ['./nfs-form.component.scss'] }) export class NfsFormComponent extends CdForm implements OnInit { @ViewChild('nfsClients', { static: true }) nfsClients: NfsFormClientComponent; clients: any[] = []; permission: Permission; nfsForm: CdFormGroup; isEdit = false; cluster_id: string = null; export_id: string = null; allClusters: { cluster_id: string }[] = null; icons = Icons; allFsals: any[] = []; allFsNames: any[] = null; fsalAvailabilityError: string = null; defaultAccessType = { RGW: 'RO' }; nfsAccessType: any[] = this.nfsService.nfsAccessType; nfsSquash: any[] = Object.keys(this.nfsService.nfsSquash); action: string; resource: string; pathDataSource = (text$: Observable<string>) => { return text$.pipe( debounceTime(200), distinctUntilChanged(), mergeMap((token: string) => this.getPathTypeahead(token)), map((val: string[]) => val) ); }; bucketDataSource = (text$: Observable<string>) => { return text$.pipe( debounceTime(200), distinctUntilChanged(), mergeMap((token: string) => this.getBucketTypeahead(token)) ); }; constructor( private authStorageService: AuthStorageService, private nfsService: NfsService, private route: ActivatedRoute, private router: Router, private rgwBucketService: RgwBucketService, private rgwSiteService: RgwSiteService, private formBuilder: CdFormBuilder, private taskWrapper: TaskWrapperService, private cdRef: ChangeDetectorRef, public actionLabels: ActionLabelsI18n ) { super(); this.permission = this.authStorageService.getPermissions().pool; this.resource = $localize`NFS export`; this.createForm(); } ngOnInit() { const promises: Observable<any>[] = [ this.nfsService.listClusters(), this.nfsService.fsals(), this.nfsService.filesystems() ]; if (this.router.url.startsWith('/nfs/edit')) { this.isEdit = true; } if (this.isEdit) { this.action = this.actionLabels.EDIT; this.route.params.subscribe((params: { cluster_id: string; export_id: string }) => { this.cluster_id = decodeURIComponent(params.cluster_id); this.export_id = decodeURIComponent(params.export_id); promises.push(this.nfsService.get(this.cluster_id, this.export_id)); this.getData(promises); }); this.nfsForm.get('cluster_id').disable(); } else { this.action = this.actionLabels.CREATE; this.getData(promises); } } getData(promises: Observable<any>[]) { forkJoin(promises).subscribe((data: any[]) => { this.resolveClusters(data[0]); this.resolveFsals(data[1]); this.resolveFilesystems(data[2]); if (data[3]) { this.resolveModel(data[3]); } this.loadingReady(); }); } createForm() { this.nfsForm = new CdFormGroup({ cluster_id: new FormControl('', { validators: [Validators.required] }), fsal: new CdFormGroup({ name: new FormControl('', { validators: [Validators.required] }), fs_name: new FormControl('', { validators: [ CdValidators.requiredIf({ name: 'CEPH' }) ] }) }), path: new FormControl('/'), protocolNfsv4: new FormControl(true), pseudo: new FormControl('', { validators: [ CdValidators.requiredIf({ protocolNfsv4: true }), Validators.pattern('^/[^><|&()]*$') ] }), access_type: new FormControl('RW'), squash: new FormControl(this.nfsSquash[0]), transportUDP: new FormControl(true, { validators: [ CdValidators.requiredIf({ transportTCP: false }, (value: boolean) => { return !value; }) ] }), transportTCP: new FormControl(true, { validators: [ CdValidators.requiredIf({ transportUDP: false }, (value: boolean) => { return !value; }) ] }), clients: this.formBuilder.array([]), security_label: new FormControl(false), sec_label_xattr: new FormControl( 'security.selinux', CdValidators.requiredIf({ security_label: true, 'fsal.name': 'CEPH' }) ) }); } resolveModel(res: any) { if (res.fsal.name === 'CEPH') { res.sec_label_xattr = res.fsal.sec_label_xattr; } res.protocolNfsv4 = res.protocols.indexOf(4) !== -1; delete res.protocols; res.transportTCP = res.transports.indexOf('TCP') !== -1; res.transportUDP = res.transports.indexOf('UDP') !== -1; delete res.transports; Object.entries(this.nfsService.nfsSquash).forEach(([key, value]) => { if (value.includes(res.squash)) { res.squash = key; } }); res.clients.forEach((client: any) => { let addressStr = ''; client.addresses.forEach((address: string) => { addressStr += address + ', '; }); if (addressStr.length >= 2) { addressStr = addressStr.substring(0, addressStr.length - 2); } client.addresses = addressStr; }); this.nfsForm.patchValue(res); this.setPathValidation(); this.clients = res.clients; } resolveClusters(clusters: string[]) { this.allClusters = []; for (const cluster of clusters) { this.allClusters.push({ cluster_id: cluster }); } if (!this.isEdit && this.allClusters.length > 0) { this.nfsForm.get('cluster_id').setValue(this.allClusters[0].cluster_id); } } resolveFsals(res: string[]) { res.forEach((fsal) => { const fsalItem = this.nfsService.nfsFsal.find((currentFsalItem) => { return fsal === currentFsalItem.value; }); if (_.isObjectLike(fsalItem)) { this.allFsals.push(fsalItem); } }); if (!this.isEdit && this.allFsals.length > 0) { this.nfsForm.patchValue({ fsal: { name: this.allFsals[0].value } }); } } resolveFilesystems(filesystems: any[]) { this.allFsNames = filesystems; if (!this.isEdit && filesystems.length > 0) { this.nfsForm.patchValue({ fsal: { fs_name: filesystems[0].name } }); } } fsalChangeHandler() { this.setPathValidation(); const fsalValue = this.nfsForm.getValue('name'); const checkAvailability = fsalValue === 'RGW' ? this.rgwSiteService.get('realms').pipe( mergeMap((realms: string[]) => realms.length === 0 ? of(true) : this.rgwSiteService.isDefaultRealm().pipe( mergeMap((isDefaultRealm) => { if (!isDefaultRealm) { throw new Error('Selected realm is not the default.'); } return of(true); }) ) ) ) : this.nfsService.filesystems(); checkAvailability.subscribe({ next: () => { this.setFsalAvailability(fsalValue, true); if (!this.isEdit) { this.nfsForm.patchValue({ path: fsalValue === 'RGW' ? '' : '/', pseudo: this.generatePseudo(), access_type: this.updateAccessType() }); } this.cdRef.detectChanges(); }, error: (error) => { this.setFsalAvailability(fsalValue, false, error); this.nfsForm.get('name').setValue(''); } }); } private setFsalAvailability(fsalValue: string, available: boolean, errorMessage: string = '') { this.allFsals = this.allFsals.map((fsalItem: NfsFSAbstractionLayer) => { if (fsalItem.value === fsalValue) { fsalItem.disabled = !available; this.fsalAvailabilityError = fsalItem.disabled ? $localize`${fsalItem.descr} backend is not available. ${errorMessage}` : null; } return fsalItem; }); } accessTypeChangeHandler() { const name = this.nfsForm.getValue('name'); const accessType = this.nfsForm.getValue('access_type'); this.defaultAccessType[name] = accessType; } setPathValidation() { const path = this.nfsForm.get('path'); path.setValidators([Validators.required]); if (this.nfsForm.getValue('name') === 'RGW') { path.setAsyncValidators([CdValidators.bucketExistence(true, this.rgwBucketService)]); } else { path.setAsyncValidators([this.pathExistence(true)]); } if (this.isEdit) { path.markAsDirty(); } } getAccessTypeHelp(accessType: string) { const accessTypeItem = this.nfsAccessType.find((currentAccessTypeItem) => { if (accessType === currentAccessTypeItem.value) { return currentAccessTypeItem; } }); return _.isObjectLike(accessTypeItem) ? accessTypeItem.help : ''; } getId() { if ( _.isString(this.nfsForm.getValue('cluster_id')) && _.isString(this.nfsForm.getValue('path')) ) { return this.nfsForm.getValue('cluster_id') + ':' + this.nfsForm.getValue('path'); } return ''; } private getPathTypeahead(path: any) { if (!_.isString(path) || path === '/') { return of([]); } const fsName = this.nfsForm.getValue('fsal').fs_name; return this.nfsService.lsDir(fsName, path).pipe( map((result: Directory) => result.paths.filter((dirName: string) => dirName.toLowerCase().includes(path)).slice(0, 15) ), catchError(() => of([$localize`Error while retrieving paths.`])) ); } pathChangeHandler() { if (!this.isEdit) { this.nfsForm.patchValue({ pseudo: this.generatePseudo() }); } } private getBucketTypeahead(path: string): Observable<any> { if (_.isString(path) && path !== '/' && path !== '') { return this.rgwBucketService.list().pipe( map((bucketList) => bucketList .filter((bucketName: string) => bucketName.toLowerCase().includes(path)) .slice(0, 15) ), catchError(() => of([$localize`Error while retrieving bucket names.`])) ); } else { return of([]); } } private generatePseudo() { let newPseudo = this.nfsForm.getValue('pseudo'); if (this.nfsForm.get('pseudo') && !this.nfsForm.get('pseudo').dirty) { newPseudo = undefined; if (this.nfsForm.getValue('fsal') === 'CEPH') { newPseudo = '/cephfs'; if (_.isString(this.nfsForm.getValue('path'))) { newPseudo += this.nfsForm.getValue('path'); } } } return newPseudo; } private updateAccessType() { const name = this.nfsForm.getValue('name'); let accessType = this.defaultAccessType[name]; if (!accessType) { accessType = 'RW'; } return accessType; } submitAction() { let action: Observable<any>; const requestModel = this.buildRequest(); if (this.isEdit) { action = this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('nfs/edit', { cluster_id: this.cluster_id, export_id: _.parseInt(this.export_id) }), call: this.nfsService.update(this.cluster_id, _.parseInt(this.export_id), requestModel) }); } else { // Create action = this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('nfs/create', { path: requestModel.path, fsal: requestModel.fsal, cluster_id: requestModel.cluster_id }), call: this.nfsService.create(requestModel) }); } action.subscribe({ error: (errorResponse: CdHttpErrorResponse) => this.setFormErrors(errorResponse), complete: () => this.router.navigate(['/nfs']) }); } private setFormErrors(errorResponse: CdHttpErrorResponse) { if ( errorResponse.error.detail && errorResponse.error.detail .toString() .includes(`Pseudo ${this.nfsForm.getValue('pseudo')} is already in use`) ) { this.nfsForm.get('pseudo').setErrors({ pseudoAlreadyExists: true }); } this.nfsForm.setErrors({ cdSubmitButton: true }); } private buildRequest() { const requestModel: any = _.cloneDeep(this.nfsForm.value); if (this.isEdit) { requestModel.export_id = _.parseInt(this.export_id); } if (requestModel.fsal.name === 'RGW') { delete requestModel.fsal.fs_name; } requestModel.protocols = []; if (requestModel.protocolNfsv4) { requestModel.protocols.push(4); } else { requestModel.pseudo = null; } delete requestModel.protocolNfsv4; requestModel.transports = []; if (requestModel.transportTCP) { requestModel.transports.push('TCP'); } delete requestModel.transportTCP; if (requestModel.transportUDP) { requestModel.transports.push('UDP'); } delete requestModel.transportUDP; requestModel.clients.forEach((client: any) => { if (_.isString(client.addresses)) { client.addresses = _(client.addresses) .split(/[ ,]+/) .uniq() .filter((address) => address !== '') .value(); } else { client.addresses = []; } if (!client.squash) { client.squash = requestModel.squash; } if (!client.access_type) { client.access_type = requestModel.access_type; } }); if (requestModel.security_label === false || requestModel.fsal.name === 'RGW') { requestModel.fsal.sec_label_xattr = null; } else { requestModel.fsal.sec_label_xattr = requestModel.sec_label_xattr; } delete requestModel.sec_label_xattr; return requestModel; } private pathExistence(requiredExistenceResult: boolean): AsyncValidatorFn { return (control: AbstractControl): Observable<ValidationErrors | null> => { if (control.pristine || !control.value) { return of({ required: true }); } const fsName = this.nfsForm.getValue('fsal').fs_name; return this.nfsService.lsDir(fsName, control.value).pipe( map((directory: Directory) => directory.paths.includes(control.value) === requiredExistenceResult ? null : { pathNameNotAllowed: true } ), catchError(() => of({ pathNameNotAllowed: true })) ); }; } }
15,995
28.843284
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-list/nfs-list.component.html
<cd-table #table [data]="exports" columnMode="flex" [columns]="columns" identifier="id" forceIdentifier="true" selectionType="single" [hasDetails]="true" (setExpandedRow)="setExpandedRow($event)" (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-nfs-details cdTableDetail [selection]="expandedRow"> </cd-nfs-details> </cd-table> <ng-template #nfsFsal let-value="value"> <ng-container *ngIf="value.name==='CEPH'" i18n>CephFS</ng-container> <ng-container *ngIf="value.name==='RGW'" i18n>Object Gateway</ng-container> </ng-template>
954
29.806452
54
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-list/nfs-list.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } 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 { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { NfsService } from '~/app/shared/api/nfs.service'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; 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, PermissionHelper } from '~/testing/unit-test-helper'; import { NfsDetailsComponent } from '../nfs-details/nfs-details.component'; import { NfsListComponent } from './nfs-list.component'; describe('NfsListComponent', () => { let component: NfsListComponent; let fixture: ComponentFixture<NfsListComponent>; let summaryService: SummaryService; let nfsService: NfsService; let httpTesting: HttpTestingController; const refresh = (data: Summary) => { summaryService['summaryDataSource'].next(data); }; configureTestBed({ declarations: [NfsListComponent, NfsDetailsComponent], imports: [ BrowserAnimationsModule, HttpClientTestingModule, RouterTestingModule, SharedModule, NgbNavModule, ToastrModule.forRoot() ], providers: [TaskListService] }); beforeEach(() => { fixture = TestBed.createComponent(NfsListComponent); component = fixture.componentInstance; summaryService = TestBed.inject(SummaryService); nfsService = TestBed.inject(NfsService); httpTesting = TestBed.inject(HttpTestingController); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('after ngOnInit', () => { beforeEach(() => { fixture.detectChanges(); spyOn(nfsService, 'list').and.callThrough(); }); afterEach(() => { httpTesting.verify(); }); it('should load exports on init', () => { refresh(new Summary()); httpTesting.expectOne('api/nfs-ganesha/export'); expect(nfsService.list).toHaveBeenCalled(); }); it('should not load images on init because no data', () => { refresh(undefined); expect(nfsService.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 executing tasks', () => { let exports: any[]; const addExport = (export_id: string) => { const model = { export_id: export_id, path: 'path_' + export_id, fsal: 'fsal_' + export_id, cluster_id: 'cluster_' + export_id }; exports.push(model); }; const addTask = (name: string, export_id: string) => { const task = new ExecutingTask(); task.name = name; switch (task.name) { case 'nfs/create': task.metadata = { path: 'path_' + export_id, fsal: 'fsal_' + export_id, cluster_id: 'cluster_' + export_id }; break; default: task.metadata = { cluster_id: 'cluster_' + export_id, export_id: export_id }; break; } summaryService.addRunningTask(task); }; beforeEach(() => { exports = []; addExport('a'); addExport('b'); addExport('c'); component.exports = exports; refresh(new Summary()); spyOn(nfsService, 'list').and.callFake(() => of(exports)); fixture.detectChanges(); }); it('should gets all exports without tasks', () => { expect(component.exports.length).toBe(3); expect(component.exports.every((expo) => !expo.cdExecuting)).toBeTruthy(); }); it('should add a new export from a task', fakeAsync(() => { addTask('nfs/create', 'd'); tick(); expect(component.exports.length).toBe(4); expectItemTasks(component.exports[0], undefined); expectItemTasks(component.exports[1], undefined); expectItemTasks(component.exports[2], undefined); expectItemTasks(component.exports[3], 'Creating'); })); it('should show when an existing export is being modified', () => { addTask('nfs/edit', 'a'); addTask('nfs/delete', 'b'); expect(component.exports.length).toBe(3); expectItemTasks(component.exports[0], 'Updating'); expectItemTasks(component.exports[1], 'Deleting'); }); }); 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', 'Delete'], primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,update': { actions: ['Create', 'Edit'], primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,delete': { actions: ['Create', 'Delete'], primary: { multiple: 'Create', executing: 'Delete', single: 'Delete', no: 'Create' } }, create: { actions: ['Create'], primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' } }, 'update,delete': { actions: ['Edit', 'Delete'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, update: { actions: ['Edit'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, delete: { actions: ['Delete'], primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); });
6,608
32.719388
101
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/nfs/nfs-list/nfs-list.component.ts
import { Component, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { Subscription } from 'rxjs'; import { NfsService } from '~/app/shared/api/nfs.service'; import { ListWithDetails } from '~/app/shared/classes/list-with-details.class'; 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 { FinishedTask } from '~/app/shared/models/finished-task'; import { Permission } from '~/app/shared/models/permissions'; import { Task } from '~/app/shared/models/task'; 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'; @Component({ selector: 'cd-nfs-list', templateUrl: './nfs-list.component.html', styleUrls: ['./nfs-list.component.scss'], providers: [TaskListService] }) export class NfsListComponent extends ListWithDetails implements OnInit, OnDestroy { @ViewChild('nfsState') nfsState: TemplateRef<any>; @ViewChild('nfsFsal', { static: true }) nfsFsal: TemplateRef<any>; @ViewChild('table', { static: true }) table: TableComponent; columns: CdTableColumn[]; permission: Permission; selection = new CdTableSelection(); summaryDataSubscription: Subscription; viewCacheStatus: any; exports: any[]; tableActions: CdTableAction[]; isDefaultCluster = false; modalRef: NgbModalRef; builders = { 'nfs/create': (metadata: any) => { return { path: metadata['path'], cluster_id: metadata['cluster_id'], fsal: metadata['fsal'] }; } }; constructor( private authStorageService: AuthStorageService, private modalService: ModalService, private nfsService: NfsService, private taskListService: TaskListService, private taskWrapper: TaskWrapperService, public actionLabels: ActionLabelsI18n ) { super(); this.permission = this.authStorageService.getPermissions().nfs; const getNfsUri = () => this.selection.first() && `${encodeURI(this.selection.first().cluster_id)}/${encodeURI( this.selection.first().export_id )}`; const createAction: CdTableAction = { permission: 'create', icon: Icons.add, routerLink: () => '/nfs/create', canBePrimary: (selection: CdTableSelection) => !selection.hasSingleSelection, name: this.actionLabels.CREATE }; const editAction: CdTableAction = { permission: 'update', icon: Icons.edit, routerLink: () => `/nfs/edit/${getNfsUri()}`, name: this.actionLabels.EDIT }; const deleteAction: CdTableAction = { permission: 'delete', icon: Icons.destroy, click: () => this.deleteNfsModal(), name: this.actionLabels.DELETE }; this.tableActions = [createAction, editAction, deleteAction]; } ngOnInit() { this.columns = [ { name: $localize`Path`, prop: 'path', flexGrow: 2, cellTransformation: CellTemplate.executing }, { name: $localize`Pseudo`, prop: 'pseudo', flexGrow: 2 }, { name: $localize`Cluster`, prop: 'cluster_id', flexGrow: 2 }, { name: $localize`Storage Backend`, prop: 'fsal', flexGrow: 2, cellTemplate: this.nfsFsal }, { name: $localize`Access Type`, prop: 'access_type', flexGrow: 2 } ]; this.taskListService.init( () => this.nfsService.list(), (resp) => this.prepareResponse(resp), (exports) => (this.exports = exports), () => this.onFetchError(), this.taskFilter, this.itemFilter, this.builders ); } ngOnDestroy() { if (this.summaryDataSubscription) { this.summaryDataSubscription.unsubscribe(); } } prepareResponse(resp: any): any[] { let result: any[] = []; resp.forEach((nfs: any) => { nfs.id = `${nfs.cluster_id}:${nfs.export_id}`; nfs.state = 'LOADING'; result = result.concat(nfs); }); return result; } onFetchError() { this.table.reset(); // Disable loading indicator. this.viewCacheStatus = { status: ViewCacheStatus.ValueException }; } itemFilter(entry: any, task: Task) { return ( entry.cluster_id === task.metadata['cluster_id'] && entry.export_id === task.metadata['export_id'] ); } taskFilter(task: Task) { return ['nfs/create', 'nfs/delete', 'nfs/edit'].includes(task.name); } updateSelection(selection: CdTableSelection) { this.selection = selection; } deleteNfsModal() { const cluster_id = this.selection.first().cluster_id; const export_id = this.selection.first().export_id; this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: $localize`NFS export`, itemNames: [`${cluster_id}:${export_id}`], submitActionObservable: () => this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('nfs/delete', { cluster_id: cluster_id, export_id: export_id }), call: this.nfsService.delete(cluster_id, export_id) }) }); } }
6,066
29.335
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/performance-counter/performance-counter.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { SharedModule } from '~/app/shared/shared.module'; import { PerformanceCounterComponent } from './performance-counter/performance-counter.component'; import { TablePerformanceCounterComponent } from './table-performance-counter/table-performance-counter.component'; @NgModule({ imports: [CommonModule, SharedModule, RouterModule], declarations: [TablePerformanceCounterComponent, PerformanceCounterComponent], exports: [TablePerformanceCounterComponent] }) export class PerformanceCounterModule {}
652
42.533333
115
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/performance-counter/performance-counter/performance-counter.component.html
<legend>{{ serviceType }}.{{ serviceId }}</legend> <cd-table-performance-counter [serviceType]="serviceType" [serviceId]="serviceId"> </cd-table-performance-counter>
196
38.4
57
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/performance-counter/performance-counter/performance-counter.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 { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { TablePerformanceCounterComponent } from '../table-performance-counter/table-performance-counter.component'; import { PerformanceCounterComponent } from './performance-counter.component'; describe('PerformanceCounterComponent', () => { let component: PerformanceCounterComponent; let fixture: ComponentFixture<PerformanceCounterComponent>; configureTestBed({ declarations: [PerformanceCounterComponent, TablePerformanceCounterComponent], imports: [RouterTestingModule, SharedModule, HttpClientTestingModule, BrowserAnimationsModule] }); beforeEach(() => { fixture = TestBed.createComponent(PerformanceCounterComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,213
39.466667
116
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/performance-counter/performance-counter/performance-counter.component.ts
import { Component } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'cd-performance-counter', templateUrl: './performance-counter.component.html', styleUrls: ['./performance-counter.component.scss'] }) export class PerformanceCounterComponent { static defaultFromLink = '/hosts'; serviceId: string; serviceType: string; fromLink: string; constructor(private route: ActivatedRoute) { this.route.queryParams.subscribe((params: { fromLink: string }) => { this.fromLink = params.fromLink || PerformanceCounterComponent.defaultFromLink; }); this.route.params.subscribe((params: { type: string; id: string }) => { this.serviceId = decodeURIComponent(params.id); this.serviceType = params.type; }); } }
799
29.769231
85
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/performance-counter/table-performance-counter/table-performance-counter.component.html
<cd-table *ngIf="counters; else warning" [data]="counters" [columns]="columns" columnMode="flex" [autoSave]="false" (fetchData)="getCounters($event)"> <ng-template #valueTpl let-row="row"> {{ row.value | dimless }} {{ row.unit }} </ng-template> </cd-table> <ng-template #warning> <cd-alert-panel type="warning" i18n>Performance counters not available</cd-alert-panel> </ng-template>
476
28.8125
74
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/performance-counter/table-performance-counter/table-performance-counter.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { AppModule } from '~/app/app.module'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { configureTestBed } from '~/testing/unit-test-helper'; import { TablePerformanceCounterComponent } from './table-performance-counter.component'; describe('TablePerformanceCounterComponent', () => { let component: TablePerformanceCounterComponent; let fixture: ComponentFixture<TablePerformanceCounterComponent>; let httpTesting: HttpTestingController; configureTestBed({ imports: [AppModule, HttpClientTestingModule] }); beforeEach(() => { fixture = TestBed.createComponent(TablePerformanceCounterComponent); component = fixture.componentInstance; httpTesting = TestBed.inject(HttpTestingController); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); expect(component.counters).toEqual([]); }); it('should have columns that are sortable', () => { expect(component.columns.every((column) => Boolean(column.prop))).toBeTruthy(); }); describe('Error handling', () => { const context = new CdTableFetchDataContext(() => undefined); beforeEach(() => { spyOn(context, 'error'); component.serviceType = 'osd'; component.serviceId = '3'; component.getCounters(context); }); it('should display 404 warning', () => { httpTesting .expectOne('api/perf_counters/osd/3') .error(new ErrorEvent('osd.3 not found'), { status: 404 }); httpTesting.verify(); expect(component.counters).toBeNull(); expect(context.error).not.toHaveBeenCalled(); }); it('should call error function of context', () => { httpTesting .expectOne('api/perf_counters/osd/3') .error(new ErrorEvent('Unknown error'), { status: 500 }); httpTesting.verify(); expect(component.counters).toEqual([]); expect(context.error).toHaveBeenCalled(); }); }); });
2,150
33.142857
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/performance-counter/table-performance-counter/table-performance-counter.component.ts
import { Component, Input, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { PerformanceCounterService } from '~/app/shared/api/performance-counter.service'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; /** * Display the specified performance counters in a datatable. */ @Component({ selector: 'cd-table-performance-counter', templateUrl: './table-performance-counter.component.html', styleUrls: ['./table-performance-counter.component.scss'] }) export class TablePerformanceCounterComponent implements OnInit { columns: Array<CdTableColumn> = []; counters: Array<object> = []; @ViewChild('valueTpl') public valueTpl: TemplateRef<any>; /** * The service type, e.g. 'rgw', 'mds', 'mon', 'osd', ... */ @Input() serviceType: string; /** * The service identifier. */ @Input() serviceId: string; constructor(private performanceCounterService: PerformanceCounterService) {} ngOnInit() { this.columns = [ { name: $localize`Name`, prop: 'name', flexGrow: 1 }, { name: $localize`Description`, prop: 'description', flexGrow: 1 }, { name: $localize`Value`, prop: 'value', cellTemplate: this.valueTpl, flexGrow: 1 } ]; } getCounters(context: CdTableFetchDataContext) { this.performanceCounterService.get(this.serviceType, this.serviceId).subscribe( (resp: object[]) => { this.counters = resp; }, (error) => { if (error.status === 404) { error.preventDefault(); this.counters = null; } else { context.error(); } } ); } }
1,813
23.849315
90
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool-stat.ts
export class PoolStat { latest: number; rate: number; rates: number[]; } export class PoolStats { bytes_used?: PoolStat; max_avail?: PoolStat; avail_raw?: PoolStat; percent_used?: PoolStat; rd_bytes?: PoolStat; wr_bytes?: PoolStat; rd?: PoolStat; wr?: PoolStat; }
287
15.941176
26
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterModule, Routes } from '@angular/router'; import { NgbNavModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'; import { ActionLabels, URLVerbs } from '~/app/shared/constants/app.constants'; import { SharedModule } from '~/app/shared/shared.module'; import { BlockModule } from '../block/block.module'; import { CephSharedModule } from '../shared/ceph-shared.module'; import { CrushRuleFormModalComponent } from './crush-rule-form-modal/crush-rule-form-modal.component'; import { ErasureCodeProfileFormModalComponent } from './erasure-code-profile-form/erasure-code-profile-form-modal.component'; import { PoolDetailsComponent } from './pool-details/pool-details.component'; import { PoolFormComponent } from './pool-form/pool-form.component'; import { PoolListComponent } from './pool-list/pool-list.component'; @NgModule({ imports: [ CephSharedModule, CommonModule, NgbNavModule, SharedModule, RouterModule, ReactiveFormsModule, NgbTooltipModule, BlockModule ], exports: [PoolListComponent, PoolFormComponent], declarations: [ PoolListComponent, PoolFormComponent, ErasureCodeProfileFormModalComponent, CrushRuleFormModalComponent, PoolDetailsComponent ] }) export class PoolModule {} const routes: Routes = [ { path: '', component: PoolListComponent }, { path: URLVerbs.CREATE, component: PoolFormComponent, data: { breadcrumbs: ActionLabels.CREATE } }, { path: `${URLVerbs.EDIT}/:name`, component: PoolFormComponent, data: { breadcrumbs: ActionLabels.EDIT } } ]; @NgModule({ imports: [PoolModule, RouterModule.forChild(routes)] }) export class RoutedPoolModule {}
1,836
30.672414
125
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool.ts
import { ExecutingTask } from '~/app/shared/models/executing-task'; import { PoolStats } from './pool-stat'; export class Pool { cache_target_full_ratio_micro: number; fast_read: boolean; stripe_width: number; flags_names: string; tier_of: number; hit_set_grade_decay_rate: number; use_gmt_hitset: boolean; last_force_op_resend_preluminous: string; quota_max_bytes: number; erasure_code_profile: string; expected_num_objects: number; size: number; snap_seq: number; auid: number; cache_min_flush_age: number; hit_set_period: number; min_read_recency_for_promote: number; target_max_objects: number; pg_num: number; pg_num_target: number; pg_num_pending: number; pg_placement_num: number; pg_placement_num_target: number; pg_autoscale_mode: string; pg_status: string; type: string; pool_name: string; cache_min_evict_age: number; cache_mode: string; min_size: number; cache_target_dirty_high_ratio_micro: number; object_hash: number; application_metadata: string[]; write_tier: number; cache_target_dirty_ratio_micro: number; pool: number; removed_snaps: string; cdExecuting?: string; executingTasks?: ExecutingTask[]; crush_rule: string; tiers: any[]; hit_set_params: { type: string; }; last_force_op_resend: string; pool_snaps: any[]; quota_max_objects: number; options: { compression_algorithm?: string; compression_max_blob_size?: number; compression_min_blob_size?: number; compression_mode?: string; compression_required_ratio?: number; }; hit_set_count: number; flags: number; target_max_bytes: number; hit_set_search_last_n: number; last_change: string; min_write_recency_for_promote: number; read_tier: number; stats?: PoolStats; cdIsBinary?: boolean; configuration: { source: number; name: string; value: string }[]; constructor(name: string) { this.pool_name = name; } }
1,931
25.108108
67
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/crush-rule-form-modal/crush-rule-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 #frm="ngForm" [formGroup]="form" novalidate> <div class="modal-body"> <div class="form-group row"> <label for="name" class="cd-col-form-label"> <ng-container i18n>Name</ng-container> <span class="required"></span> </label> <div class="cd-col-form-input"> <input type="text" id="name" name="name" class="form-control" placeholder="Name..." formControlName="name" autofocus> <span class="invalid-feedback" *ngIf="form.showError('name', frm, 'required')" i18n>This field is required!</span> <span class="invalid-feedback" *ngIf="form.showError('name', frm, 'pattern')" i18n>The name can only consist of alphanumeric characters, dashes and underscores.</span> <span class="invalid-feedback" *ngIf="form.showError('name', frm, 'uniqueName')" i18n>The chosen erasure code profile name is already in use.</span> </div> </div> <!-- Root --> <div class="form-group row"> <label for="root" class="cd-col-form-label"> <ng-container i18n>Root</ng-container> <cd-helper [html]="tooltips.root"> </cd-helper> <span class="required"></span> </label> <div class="cd-col-form-input"> <select class="form-select" id="root" name="root" formControlName="root"> <option *ngIf="!buckets" ngValue="" i18n>Loading...</option> <option *ngFor="let bucket of buckets" [ngValue]="bucket"> {{ bucket.name }} </option> </select> <span class="invalid-feedback" *ngIf="form.showError('root', frm, 'required')" i18n>This field is required!</span> </div> </div> <!-- Failure Domain Type --> <div class="form-group row"> <label for="failure_domain" class="cd-col-form-label"> <ng-container i18n>Failure domain type</ng-container> <cd-helper [html]="tooltips.failure_domain"> </cd-helper> <span class="required"></span> </label> <div class="cd-col-form-input"> <select class="form-select" id="failure_domain" name="failure_domain" formControlName="failure_domain"> <option *ngIf="!failureDomains" ngValue="" i18n>Loading...</option> <option *ngFor="let domain of failureDomainKeys" [ngValue]="domain"> {{ domain }} ( {{failureDomains[domain].length}} ) </option> </select> <span class="invalid-feedback" *ngIf="form.showError('failure_domain', frm, 'required')" i18n>This field is required!</span> </div> </div> <!-- Class --> <div class="form-group row"> <label for="device_class" class="cd-col-form-label"> <ng-container i18n>Device class</ng-container> <cd-helper [html]="tooltips.device_class"> </cd-helper> </label> <div class="cd-col-form-input"> <select class="form-select" id="device_class" name="device_class" formControlName="device_class"> <option ngValue="" i18n>Let Ceph decide</option> <option *ngFor="let deviceClass of devices" [ngValue]="deviceClass"> {{ deviceClass }} </option> </select> </div> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="onSubmit()" [form]="form" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
4,708
36.975806
121
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/crush-rule-form-modal/crush-rule-form-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { CrushRuleService } from '~/app/shared/api/crush-rule.service'; import { CrushNode } from '~/app/shared/models/crush-node'; import { CrushRuleConfig } from '~/app/shared/models/crush-rule'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { configureTestBed, FixtureHelper, FormHelper, Mocks } from '~/testing/unit-test-helper'; import { PoolModule } from '../pool.module'; import { CrushRuleFormModalComponent } from './crush-rule-form-modal.component'; describe('CrushRuleFormComponent', () => { let component: CrushRuleFormModalComponent; let crushRuleService: CrushRuleService; let fixture: ComponentFixture<CrushRuleFormModalComponent>; let formHelper: FormHelper; let fixtureHelper: FixtureHelper; let data: { names: string[]; nodes: CrushNode[] }; // Object contains functions to get something const get = { nodeByName: (name: string): CrushNode => data.nodes.find((node) => node.name === name), nodesByNames: (names: string[]): CrushNode[] => names.map(get.nodeByName) }; // Expects that are used frequently const assert = { failureDomains: (nodes: CrushNode[], types: string[]) => { const expectation = {}; types.forEach((type) => (expectation[type] = nodes.filter((node) => node.type === type))); const keys = component.failureDomainKeys; expect(keys).toEqual(types); keys.forEach((key) => { expect(component.failureDomains[key].length).toBe(expectation[key].length); }); }, formFieldValues: (root: CrushNode, failureDomain: string, device: string) => { expect(component.form.value).toEqual({ name: '', root, failure_domain: failureDomain, device_class: device }); }, valuesOnRootChange: ( rootName: string, expectedFailureDomain: string, expectedDevice: string ) => { const node = get.nodeByName(rootName); formHelper.setValue('root', node); assert.formFieldValues(node, expectedFailureDomain, expectedDevice); }, creation: (rule: CrushRuleConfig) => { formHelper.setValue('name', rule.name); fixture.detectChanges(); component.onSubmit(); expect(crushRuleService.create).toHaveBeenCalledWith(rule); } }; configureTestBed({ imports: [HttpClientTestingModule, RouterTestingModule, ToastrModule.forRoot(), PoolModule], providers: [CrushRuleService, NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(CrushRuleFormModalComponent); fixtureHelper = new FixtureHelper(fixture); component = fixture.componentInstance; formHelper = new FormHelper(component.form); crushRuleService = TestBed.inject(CrushRuleService); data = { names: ['rule1', 'rule2'], /** * Create the following test crush map: * > default * --> ssd-host * ----> 3x osd with ssd * --> mix-host * ----> hdd-rack * ------> 2x osd-rack with hdd * ----> ssd-rack * ------> 2x osd-rack with ssd */ nodes: Mocks.getCrushMap() }; spyOn(crushRuleService, 'getInfo').and.callFake(() => of(data)); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('calls listing to get rules on ngInit', () => { expect(crushRuleService.getInfo).toHaveBeenCalled(); expect(component.names.length).toBe(2); expect(component.buckets.length).toBe(5); }); describe('lists', () => { afterEach(() => { // The available buckets should not change expect(component.buckets).toEqual( get.nodesByNames(['default', 'hdd-rack', 'mix-host', 'ssd-host', 'ssd-rack']) ); }); it('has the following lists after init', () => { assert.failureDomains(data.nodes, ['host', 'osd', 'osd-rack', 'rack']); // Not root as root only exist once expect(component.devices).toEqual(['hdd', 'ssd']); }); it('has the following lists after selection of ssd-host', () => { formHelper.setValue('root', get.nodeByName('ssd-host')); assert.failureDomains(get.nodesByNames(['osd.0', 'osd.1', 'osd.2']), ['osd']); // Not host as it only exist once expect(component.devices).toEqual(['ssd']); }); it('has the following lists after selection of mix-host', () => { formHelper.setValue('root', get.nodeByName('mix-host')); expect(component.devices).toEqual(['hdd', 'ssd']); assert.failureDomains( get.nodesByNames(['hdd-rack', 'ssd-rack', 'osd2.0', 'osd2.1', 'osd2.0', 'osd2.1']), ['osd-rack', 'rack'] ); }); }); describe('selection', () => { it('selects the first root after init automatically', () => { assert.formFieldValues(get.nodeByName('default'), 'osd-rack', ''); }); it('should select all values automatically by selecting "ssd-host" as root', () => { assert.valuesOnRootChange('ssd-host', 'osd', 'ssd'); }); it('selects automatically the most common failure domain', () => { // Select mix-host as mix-host has multiple failure domains (osd-rack and rack) assert.valuesOnRootChange('mix-host', 'osd-rack', ''); }); it('should override automatic selections', () => { assert.formFieldValues(get.nodeByName('default'), 'osd-rack', ''); assert.valuesOnRootChange('ssd-host', 'osd', 'ssd'); assert.valuesOnRootChange('mix-host', 'osd-rack', ''); }); it('should not override manual selections if possible', () => { formHelper.setValue('failure_domain', 'rack', true); formHelper.setValue('device_class', 'ssd', true); assert.valuesOnRootChange('mix-host', 'rack', 'ssd'); }); it('should preselect device by domain selection', () => { formHelper.setValue('failure_domain', 'osd', true); assert.formFieldValues(get.nodeByName('default'), 'osd', 'ssd'); }); }); describe('form validation', () => { it(`isn't valid if name is not set`, () => { expect(component.form.invalid).toBeTruthy(); formHelper.setValue('name', 'someProfileName'); expect(component.form.valid).toBeTruthy(); }); it('sets name invalid', () => { component.names = ['awesomeProfileName']; formHelper.expectErrorChange('name', 'awesomeProfileName', 'uniqueName'); formHelper.expectErrorChange('name', 'some invalid text', 'pattern'); formHelper.expectErrorChange('name', null, 'required'); }); it(`should show all default form controls`, () => { // name // root (preselected(first root)) // failure_domain (preselected=type that is most common) // device_class (preselected=any if multiple or some type if only one device type) fixtureHelper.expectIdElementsVisible( ['name', 'root', 'failure_domain', 'device_class'], true ); }); }); describe('submission', () => { beforeEach(() => { const taskWrapper = TestBed.inject(TaskWrapperService); spyOn(taskWrapper, 'wrapTaskAroundCall').and.callThrough(); spyOn(crushRuleService, 'create').and.stub(); }); it('creates a rule with only required fields', () => { assert.creation(Mocks.getCrushRuleConfig('default-rule', 'default', 'osd-rack')); }); it('creates a rule with all fields', () => { assert.valuesOnRootChange('ssd-host', 'osd', 'ssd'); assert.creation(Mocks.getCrushRuleConfig('ssd-host-rule', 'ssd-host', 'osd', 'ssd')); }); }); });
7,849
36.203791
118
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/crush-rule-form-modal/crush-rule-form-modal.component.ts
import { Component, EventEmitter, OnInit, Output } from '@angular/core'; import { Validators } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { CrushRuleService } from '~/app/shared/api/crush-rule.service'; import { CrushNodeSelectionClass } from '~/app/shared/classes/crush.node.selection.class'; 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 { CrushNode } from '~/app/shared/models/crush-node'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; @Component({ selector: 'cd-crush-rule-form-modal', templateUrl: './crush-rule-form-modal.component.html', styleUrls: ['./crush-rule-form-modal.component.scss'] }) export class CrushRuleFormModalComponent extends CrushNodeSelectionClass implements OnInit { @Output() submitAction = new EventEmitter(); tooltips = this.crushRuleService.formTooltips; form: CdFormGroup; names: string[]; action: string; resource: string; constructor( private formBuilder: CdFormBuilder, public activeModal: NgbActiveModal, private taskWrapper: TaskWrapperService, private crushRuleService: CrushRuleService, public actionLabels: ActionLabelsI18n ) { super(); this.action = this.actionLabels.CREATE; this.resource = $localize`Crush Rule`; this.createForm(); } createForm() { this.form = this.formBuilder.group({ // name: string name: [ '', [ Validators.required, Validators.pattern('[A-Za-z0-9_-]+'), CdValidators.custom( 'uniqueName', (value: any) => this.names && this.names.indexOf(value) !== -1 ) ] ], // root: CrushNode root: null, // Replaced with first root // failure_domain: string failure_domain: '', // Replaced with most common type // device_class: string device_class: '' // Replaced with device type if only one exists beneath domain }); } ngOnInit() { this.crushRuleService .getInfo() .subscribe(({ names, nodes }: { names: string[]; nodes: CrushNode[] }) => { this.initCrushNodeSelection( nodes, this.form.get('root'), this.form.get('failure_domain'), this.form.get('device_class') ); this.names = names; }); } onSubmit() { if (this.form.invalid) { this.form.setErrors({ cdSubmitButton: true }); return; } const rule = _.cloneDeep(this.form.value); rule.root = rule.root.name; if (rule.device_class === '') { delete rule.device_class; } this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('crushRule/create', rule), call: this.crushRuleService.create(rule) }) .subscribe({ error: () => { this.form.setErrors({ cdSubmitButton: true }); }, complete: () => { this.activeModal.close(); this.submitAction.emit(rule); } }); } }
3,338
29.633028
92
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/erasure-code-profile-form/erasure-code-profile-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 #frm="ngForm" [formGroup]="form" novalidate> <div class="modal-body"> <div class="form-group row"> <label class="cd-col-form-label" for="name" i18n>Name</label> <div class="cd-col-form-input"> <input type="text" id="name" name="name" class="form-control" placeholder="Name..." formControlName="name" autofocus> <span class="invalid-feedback" *ngIf="form.showError('name', frm, 'required')" i18n>This field is required!</span> <span class="invalid-feedback" *ngIf="form.showError('name', frm, 'pattern')" i18n>The name can only consist of alphanumeric characters, dashes and underscores.</span> <span class="invalid-feedback" *ngIf="form.showError('name', frm, 'uniqueName')" i18n>The chosen erasure code profile name is already in use.</span> </div> </div> <div class="form-group row"> <label for="plugin" class="cd-col-form-label"> <span class="required" i18n>Plugin</span> <cd-helper [html]="tooltips.plugins[plugin].description"> </cd-helper> </label> <div class="cd-col-form-input"> <select class="form-select" id="plugin" name="plugin" formControlName="plugin"> <option *ngIf="!plugins" ngValue="" i18n>Loading...</option> <option *ngFor="let plugin of plugins" [ngValue]="plugin"> {{ plugin }} </option> </select> <span class="invalid-feedback" *ngIf="form.showError('name', frm, 'required')" i18n>This field is required!</span> </div> </div> <div class="form-group row"> <label for="k" class="cd-col-form-label"> <span class="required" i18n>Data chunks (k)</span> <cd-helper [html]="tooltips.k"> </cd-helper> </label> <div class="cd-col-form-input"> <input type="number" id="k" name="k" class="form-control" ng-model="$ctrl.erasureCodeProfile.k" placeholder="Data chunks..." formControlName="k" min="2"> <span class="invalid-feedback" *ngIf="form.showError('k', frm, 'required')" i18n>This field is required!</span> <span class="invalid-feedback" *ngIf="form.showError('k', frm, 'min')" i18n>Must be equal to or greater than 2.</span> <span class="invalid-feedback" *ngIf="form.showError('k', frm, 'max')" i18n>Chunks (k+m) have exceeded the available OSDs of {{deviceCount}}.</span> <span class="invalid-feedback" *ngIf="form.showError('k', frm, 'unequal')" i18n>For an equal distribution k has to be a multiple of (k+m)/l.</span> <span class="invalid-feedback" *ngIf="form.showError('k', frm, 'kLowerM')" i18n>K has to be equal to or greater than m in order to recover data correctly through c.</span> <span *ngIf="plugin === 'lrc'" class="form-text text-muted" i18n>Distribution factor: {{lrcMultiK}}</span> </div> </div> <div class="form-group row"> <label for="m" class="cd-col-form-label"> <span class="required" i18n>Coding chunks (m)</span> <cd-helper [html]="tooltips.m"> </cd-helper> </label> <div class="cd-col-form-input"> <input type="number" id="m" name="m" class="form-control" placeholder="Coding chunks..." formControlName="m" min="1"> <span class="invalid-feedback" *ngIf="form.showError('m', frm, 'required')" i18n>This field is required!</span> <span class="invalid-feedback" *ngIf="form.showError('m', frm, 'min')" i18n>Must be equal to or greater than 1.</span> <span class="invalid-feedback" *ngIf="form.showError('m', frm, 'max')" i18n>Chunks (k+m) have exceeded the available OSDs of {{deviceCount}}.</span> </div> </div> <div class="form-group row" *ngIf="plugin === 'shec'"> <label for="c" class="cd-col-form-label"> <span class="required" i18n>Durability estimator (c)</span> <cd-helper [html]="tooltips.plugins.shec.c"> </cd-helper> </label> <div class="cd-col-form-input"> <input type="number" id="c" name="c" class="form-control" placeholder="Coding chunks..." formControlName="c" min="1"> <span class="invalid-feedback" *ngIf="form.showError('c', frm, 'min')" i18n>Must be equal to or greater than 1.</span> <span class="invalid-feedback" *ngIf="form.showError('c', frm, 'cGreaterM')" i18n>C has to be equal to or lower than m as m defines the amount of chunks that can be used.</span> </div> </div> <div class="form-group row" *ngIf="plugin === 'clay'"> <label for="d" class="cd-col-form-label"> <span class="required" i18n>Helper chunks (d)</span> <cd-helper [html]="tooltips.plugins.clay.d"> </cd-helper> </label> <div class="cd-col-form-input"> <div class="input-group"> <input type="number" id="d" name="d" class="form-control" placeholder="Helper chunks..." formControlName="d"> <button class="btn btn-light" id="d-calc-btn" ngbTooltip="Set d manually or use the plugin's default calculation that maximizes d." i18n-ngbTooltip type="button" (click)="toggleDCalc()"> <i [ngClass]="dCalc ? icons.unlock : icons.lock" aria-hidden="true"></i> </button> </div> <span class="form-text text-muted" *ngIf="dCalc" i18n>D is automatically updated on k and m changes</span> <ng-container *ngIf="!dCalc"> <span class="form-text text-muted" *ngIf="getDMin() < getDMax()" i18n>D can be set from {{getDMin()}} to {{getDMax()}}</span> <span class="form-text text-muted" *ngIf="getDMin() === getDMax()" i18n>D can only be set to {{getDMax()}}</span> </ng-container> <span class="invalid-feedback" *ngIf="form.showError('d', frm, 'dMin')" i18n>D has to be greater than k ({{getDMin()}}).</span> <span class="invalid-feedback" *ngIf="form.showError('d', frm, 'dMax')" i18n>D has to be lower than k + m ({{getDMax()}}).</span> </div> </div> <div class="form-group row" *ngIf="plugin === PLUGIN.LRC"> <label class="cd-col-form-label" for="l"> <span class="required" i18n>Locality (l)</span> <cd-helper [html]="tooltips.plugins.lrc.l"> </cd-helper> </label> <div class="cd-col-form-input"> <input type="number" id="l" name="l" class="form-control" placeholder="Coding chunks..." formControlName="l" min="1"> <span class="invalid-feedback" *ngIf="form.showError('l', frm, 'required')" i18n>This field is required!</span> <span class="invalid-feedback" *ngIf="form.showError('l', frm, 'min')" i18n>Must be equal to or greater than 1.</span> <span class="invalid-feedback" *ngIf="form.showError('l', frm, 'unequal')" i18n>Can't split up chunks (k+m) correctly with the current locality.</span> <span class="form-text text-muted" i18n>Locality groups: {{lrcGroups}}</span> </div> </div> <div class="form-group row"> <label for="crushFailureDomain" class="cd-col-form-label"> <ng-container i18n>Crush failure domain</ng-container> <cd-helper [html]="tooltips.crushFailureDomain"> </cd-helper> </label> <div class="cd-col-form-input"> <select class="form-select" id="crushFailureDomain" name="crushFailureDomain" formControlName="crushFailureDomain"> <option *ngIf="!failureDomains" ngValue="" i18n>Loading...</option> <option *ngFor="let domain of failureDomainKeys" [ngValue]="domain"> {{ domain }} ( {{failureDomains[domain].length}} ) </option> </select> </div> </div> <div class="form-group row" *ngIf="plugin === PLUGIN.LRC"> <label for="crushLocality" class="cd-col-form-label"> <ng-container i18n>Crush Locality</ng-container> <cd-helper [html]="tooltips.plugins.lrc.crushLocality"> </cd-helper> </label> <div class="cd-col-form-input"> <select class="form-select" id="crushLocality" name="crushLocality" formControlName="crushLocality"> <option *ngIf="!failureDomains" ngValue="" i18n>Loading...</option> <option *ngIf="failureDomainKeys.length > 0" ngValue="" i18n>None</option> <option *ngFor="let domain of failureDomainKeys" [ngValue]="domain"> {{ domain }} ( {{failureDomains[domain].length}} ) </option> </select> </div> </div> <div class="form-group row" *ngIf="PLUGIN.CLAY === plugin"> <label for="scalar_mds" class="cd-col-form-label"> <ng-container i18n>Scalar mds</ng-container> <cd-helper [html]="tooltips.plugins.clay.scalar_mds"> </cd-helper> </label> <div class="cd-col-form-input"> <select class="form-select" id="scalar_mds" name="scalar_mds" formControlName="scalar_mds"> <option *ngFor="let plugin of [PLUGIN.JERASURE, PLUGIN.ISA, PLUGIN.SHEC]" [ngValue]="plugin"> {{ plugin }} </option> </select> </div> </div> <div class="form-group row" *ngIf="[PLUGIN.JERASURE, PLUGIN.ISA, PLUGIN.CLAY].includes(plugin)"> <label for="technique" class="cd-col-form-label"> <ng-container i18n>Technique</ng-container> <cd-helper [html]="tooltips.plugins[plugin].technique"> </cd-helper> </label> <div class="cd-col-form-input"> <select class="form-select" id="technique" name="technique" formControlName="technique"> <option *ngFor="let technique of techniques" [ngValue]="technique"> {{ technique }} </option> </select> </div> </div> <div class="form-group row" *ngIf="plugin === PLUGIN.JERASURE"> <label for="packetSize" class="cd-col-form-label"> <ng-container i18n>Packetsize</ng-container> <cd-helper [html]="tooltips.plugins.jerasure.packetSize"> </cd-helper> </label> <div class="cd-col-form-input"> <input type="number" id="packetSize" name="packetSize" class="form-control" placeholder="Packetsize..." formControlName="packetSize" min="1"> <span class="invalid-feedback" *ngIf="form.showError('packetSize', frm, 'min')" i18n>Must be equal to or greater than 1.</span> </div> </div> <div class="form-group row"> <label for="crushRoot" class="cd-col-form-label"> <ng-container i18n>Crush root</ng-container> <cd-helper [html]="tooltips.crushRoot"> </cd-helper> </label> <div class="cd-col-form-input"> <select class="form-select" id="crushRoot" name="crushRoot" formControlName="crushRoot"> <option *ngIf="!buckets" ngValue="" i18n>Loading...</option> <option *ngFor="let bucket of buckets" [ngValue]="bucket"> {{ bucket.name }} </option> </select> </div> </div> <div class="form-group row"> <label for="crushDeviceClass" class="cd-col-form-label"> <ng-container i18n>Crush device class</ng-container> <cd-helper [html]="tooltips.crushDeviceClass"> </cd-helper> </label> <div class="cd-col-form-input"> <select class="form-select" id="crushDeviceClass" name="crushDeviceClass" formControlName="crushDeviceClass"> <option ngValue="" i18n>Let Ceph decide</option> <option *ngFor="let deviceClass of devices" [ngValue]="deviceClass"> {{ deviceClass }} </option> </select> <span class="form-text text-muted" i18n>Available OSDs: {{deviceCount}}</span> </div> </div> <div class="form-group row"> <label for="directory" class="cd-col-form-label"> <ng-container i18n>Directory</ng-container> <cd-helper [html]="tooltips.directory"> </cd-helper> </label> <div class="cd-col-form-input"> <input type="text" id="directory" name="directory" class="form-control" placeholder="Path..." formControlName="directory"> </div> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="onSubmit()" [form]="form" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
16,589
38.594272
121
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/erasure-code-profile-form/erasure-code-profile-form-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { ErasureCodeProfileService } from '~/app/shared/api/erasure-code-profile.service'; import { CrushNode } from '~/app/shared/models/crush-node'; import { ErasureCodeProfile } from '~/app/shared/models/erasure-code-profile'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { configureTestBed, FixtureHelper, FormHelper, Mocks } from '~/testing/unit-test-helper'; import { PoolModule } from '../pool.module'; import { ErasureCodeProfileFormModalComponent } from './erasure-code-profile-form-modal.component'; describe('ErasureCodeProfileFormModalComponent', () => { let component: ErasureCodeProfileFormModalComponent; let ecpService: ErasureCodeProfileService; let fixture: ComponentFixture<ErasureCodeProfileFormModalComponent>; let formHelper: FormHelper; let fixtureHelper: FixtureHelper; let data: { plugins: string[]; names: string[]; nodes: CrushNode[] }; const expectTechnique = (current: string) => expect(component.form.getValue('technique')).toBe(current); const expectTechniques = (techniques: string[], current: string) => { expect(component.techniques).toEqual(techniques); expectTechnique(current); }; const expectRequiredControls = (controlNames: string[]) => { controlNames.forEach((name) => { const value = component.form.getValue(name); formHelper.expectValid(name); formHelper.expectErrorChange(name, null, 'required'); // This way other fields won't fail through getting invalid. formHelper.expectValidChange(name, value); }); fixtureHelper.expectIdElementsVisible(controlNames, true); }; configureTestBed({ imports: [HttpClientTestingModule, RouterTestingModule, ToastrModule.forRoot(), PoolModule], providers: [ErasureCodeProfileService, NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(ErasureCodeProfileFormModalComponent); fixtureHelper = new FixtureHelper(fixture); component = fixture.componentInstance; formHelper = new FormHelper(component.form); ecpService = TestBed.inject(ErasureCodeProfileService); data = { plugins: ['isa', 'jerasure', 'shec', 'lrc'], names: ['ecp1', 'ecp2'], /** * Create the following test crush map: * > default * --> ssd-host * ----> 3x osd with ssd * --> mix-host * ----> hdd-rack * ------> 5x osd-rack with hdd * ----> ssd-rack * ------> 5x osd-rack with ssd */ nodes: [ // Root node Mocks.getCrushNode('default', -1, 'root', 11, [-2, -3]), // SSD host Mocks.getCrushNode('ssd-host', -2, 'host', 1, [1, 0, 2]), Mocks.getCrushNode('osd.0', 0, 'osd', 0, undefined, 'ssd'), Mocks.getCrushNode('osd.1', 1, 'osd', 0, undefined, 'ssd'), Mocks.getCrushNode('osd.2', 2, 'osd', 0, undefined, 'ssd'), // SSD and HDD mixed devices host Mocks.getCrushNode('mix-host', -3, 'host', 1, [-4, -5]), // HDD rack Mocks.getCrushNode('hdd-rack', -4, 'rack', 3, [3, 4, 5, 6, 7]), Mocks.getCrushNode('osd2.0', 3, 'osd-rack', 0, undefined, 'hdd'), Mocks.getCrushNode('osd2.1', 4, 'osd-rack', 0, undefined, 'hdd'), Mocks.getCrushNode('osd2.2', 5, 'osd-rack', 0, undefined, 'hdd'), Mocks.getCrushNode('osd2.3', 6, 'osd-rack', 0, undefined, 'hdd'), Mocks.getCrushNode('osd2.4', 7, 'osd-rack', 0, undefined, 'hdd'), // SSD rack Mocks.getCrushNode('ssd-rack', -5, 'rack', 3, [8, 9, 10, 11, 12]), Mocks.getCrushNode('osd3.0', 8, 'osd-rack', 0, undefined, 'ssd'), Mocks.getCrushNode('osd3.1', 9, 'osd-rack', 0, undefined, 'ssd'), Mocks.getCrushNode('osd3.2', 10, 'osd-rack', 0, undefined, 'ssd'), Mocks.getCrushNode('osd3.3', 11, 'osd-rack', 0, undefined, 'ssd'), Mocks.getCrushNode('osd3.4', 12, 'osd-rack', 0, undefined, 'ssd') ] }; spyOn(ecpService, 'getInfo').and.callFake(() => of(data)); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('calls listing to get ecps on ngInit', () => { expect(ecpService.getInfo).toHaveBeenCalled(); expect(component.names.length).toBe(2); }); describe('form validation', () => { it(`isn't valid if name is not set`, () => { expect(component.form.invalid).toBeTruthy(); formHelper.setValue('name', 'someProfileName'); expect(component.form.valid).toBeTruthy(); }); it('sets name invalid', () => { component.names = ['awesomeProfileName']; formHelper.expectErrorChange('name', 'awesomeProfileName', 'uniqueName'); formHelper.expectErrorChange('name', 'some invalid text', 'pattern'); formHelper.expectErrorChange('name', null, 'required'); }); it('sets k to min error', () => { formHelper.expectErrorChange('k', 1, 'min'); }); it('sets m to min error', () => { formHelper.expectErrorChange('m', 0, 'min'); }); it(`should show all default form controls`, () => { const showDefaults = (plugin: string) => { formHelper.setValue('plugin', plugin); fixtureHelper.expectIdElementsVisible( [ 'name', 'plugin', 'k', 'm', 'crushFailureDomain', 'crushRoot', 'crushDeviceClass', 'directory' ], true ); }; showDefaults('jerasure'); showDefaults('shec'); showDefaults('lrc'); showDefaults('isa'); }); it('should change technique to default if not available in other plugin', () => { expectTechnique('reed_sol_van'); formHelper.setValue('technique', 'blaum_roth'); expectTechnique('blaum_roth'); formHelper.setValue('plugin', 'isa'); expectTechnique('reed_sol_van'); formHelper.setValue('plugin', 'clay'); formHelper.expectValidChange('scalar_mds', 'shec'); expectTechnique('single'); }); describe(`for 'jerasure' plugin (default)`, () => { it(`requires 'm' and 'k'`, () => { expectRequiredControls(['k', 'm']); }); it(`should show 'packetSize' and 'technique'`, () => { fixtureHelper.expectIdElementsVisible(['packetSize', 'technique'], true); }); it('should show available techniques', () => { expectTechniques( [ 'reed_sol_van', 'reed_sol_r6_op', 'cauchy_orig', 'cauchy_good', 'liberation', 'blaum_roth', 'liber8tion' ], 'reed_sol_van' ); }); it(`should not show any other plugin specific form control`, () => { fixtureHelper.expectIdElementsVisible( ['c', 'l', 'crushLocality', 'd', 'scalar_mds'], false ); }); it('should not allow "k" to be changed more than possible', () => { formHelper.expectErrorChange('k', 10, 'max'); }); it('should not allow "m" to be changed more than possible', () => { formHelper.expectErrorChange('m', 10, 'max'); }); }); describe(`for 'isa' plugin`, () => { beforeEach(() => { formHelper.setValue('plugin', 'isa'); }); it(`does require 'm' and 'k'`, () => { expectRequiredControls(['k', 'm']); }); it(`should show 'technique'`, () => { fixtureHelper.expectIdElementsVisible(['technique'], true); }); it('should show available techniques', () => { expectTechniques(['reed_sol_van', 'cauchy'], 'reed_sol_van'); }); it(`should not show any other plugin specific form control`, () => { fixtureHelper.expectIdElementsVisible( ['c', 'l', 'crushLocality', 'packetSize', 'd', 'scalar_mds'], false ); }); it('should not allow "k" to be changed more than possible', () => { formHelper.expectErrorChange('k', 10, 'max'); }); it('should not allow "m" to be changed more than possible', () => { formHelper.expectErrorChange('m', 10, 'max'); }); }); describe(`for 'lrc' plugin`, () => { beforeEach(() => { formHelper.setValue('plugin', 'lrc'); formHelper.expectValid('k'); formHelper.expectValid('l'); formHelper.expectValid('m'); }); it(`requires 'm', 'l' and 'k'`, () => { expectRequiredControls(['k', 'm', 'l']); }); it(`should show 'l' and 'crushLocality'`, () => { fixtureHelper.expectIdElementsVisible(['l', 'crushLocality'], true); }); it(`should not show any other plugin specific form control`, () => { fixtureHelper.expectIdElementsVisible( ['c', 'packetSize', 'technique', 'd', 'scalar_mds'], false ); }); it('should not allow "k" to be changed more than possible', () => { formHelper.expectErrorChange('k', 10, 'max'); }); it('should not allow "m" to be changed more than possible', () => { formHelper.expectErrorChange('m', 10, 'max'); }); it('should not allow "l" to be changed so that (k+m) is not a multiple of "l"', () => { formHelper.expectErrorChange('l', 4, 'unequal'); }); it('should update validity of k and l on m change', () => { formHelper.expectValidChange('m', 3); formHelper.expectError('k', 'unequal'); formHelper.expectError('l', 'unequal'); }); describe('lrc calculation', () => { const expectCorrectCalculation = ( k: number, m: number, l: number, failedControl: string[] = [] ) => { formHelper.setValue('k', k); formHelper.setValue('m', m); formHelper.setValue('l', l); ['k', 'l'].forEach((name) => { if (failedControl.includes(name)) { formHelper.expectError(name, 'unequal'); } else { formHelper.expectValid(name); } }); }; const tests = { kFails: [ [2, 1, 1], [2, 2, 1], [3, 1, 1], [3, 2, 1], [3, 1, 2], [3, 3, 1], [3, 3, 3], [4, 1, 1], [4, 2, 1], [4, 2, 2], [4, 3, 1], [4, 4, 1] ], lFails: [ [2, 1, 2], [3, 2, 2], [3, 1, 3], [3, 2, 3], [4, 1, 2], [4, 3, 2], [4, 3, 3], [4, 1, 3], [4, 4, 3], [4, 1, 4], [4, 2, 4], [4, 3, 4] ], success: [ [2, 2, 2], [2, 2, 4], [3, 3, 2], [3, 3, 6], [4, 2, 3], [4, 2, 6], [4, 4, 2], [4, 4, 8], [4, 4, 4] ] }; it('tests all cases where k fails', () => { tests.kFails.forEach((testCase) => { expectCorrectCalculation(testCase[0], testCase[1], testCase[2], ['k']); }); }); it('tests all cases where l fails', () => { tests.lFails.forEach((testCase) => { expectCorrectCalculation(testCase[0], testCase[1], testCase[2], ['k', 'l']); }); }); it('tests all cases where everything is valid', () => { tests.success.forEach((testCase) => { expectCorrectCalculation(testCase[0], testCase[1], testCase[2]); }); }); }); }); describe(`for 'shec' plugin`, () => { beforeEach(() => { formHelper.setValue('plugin', 'shec'); formHelper.expectValid('c'); formHelper.expectValid('m'); formHelper.expectValid('k'); }); it(`does require 'm', 'c' and 'k'`, () => { expectRequiredControls(['k', 'm', 'c']); }); it(`should not show any other plugin specific form control`, () => { fixtureHelper.expectIdElementsVisible( ['l', 'crushLocality', 'packetSize', 'technique', 'd', 'scalar_mds'], false ); }); it('should make sure that k has to be equal or greater than m', () => { formHelper.expectValidChange('k', 3); formHelper.expectErrorChange('k', 2, 'kLowerM'); }); it('should make sure that c has to be equal or less than m', () => { formHelper.expectValidChange('c', 3); formHelper.expectErrorChange('c', 4, 'cGreaterM'); }); it('should update validity of k and c on m change', () => { formHelper.expectValidChange('m', 5); formHelper.expectError('k', 'kLowerM'); formHelper.expectValid('c'); formHelper.expectValidChange('m', 1); formHelper.expectError('c', 'cGreaterM'); formHelper.expectValid('k'); }); }); describe(`for 'clay' plugin`, () => { beforeEach(() => { formHelper.setValue('plugin', 'clay'); // Through this change d has a valid range from 4 to 7 formHelper.expectValidChange('k', 3); formHelper.expectValidChange('m', 5); }); it(`does require 'm', 'c', 'd', 'scalar_mds' and 'k'`, () => { fixtureHelper.clickElement('#d-calc-btn'); expectRequiredControls(['k', 'm', 'd', 'scalar_mds']); }); it(`should not show any other plugin specific form control`, () => { fixtureHelper.expectIdElementsVisible(['l', 'crushLocality', 'packetSize', 'c'], false); }); it('should show default values for d and scalar_mds', () => { expect(component.form.getValue('d')).toBe(7); // (k+m-1) expect(component.form.getValue('scalar_mds')).toBe('jerasure'); }); it('should auto change d if auto calculation is enabled (default)', () => { formHelper.expectValidChange('k', 4); expect(component.form.getValue('d')).toBe(8); }); it('should have specific techniques for scalar_mds jerasure', () => { expectTechniques( ['reed_sol_van', 'reed_sol_r6_op', 'cauchy_orig', 'cauchy_good', 'liber8tion'], 'reed_sol_van' ); }); it('should have specific techniques for scalar_mds isa', () => { formHelper.expectValidChange('scalar_mds', 'isa'); expectTechniques(['reed_sol_van', 'cauchy'], 'reed_sol_van'); }); it('should have specific techniques for scalar_mds shec', () => { formHelper.expectValidChange('scalar_mds', 'shec'); expectTechniques(['single', 'multiple'], 'single'); }); describe('Validity of d', () => { beforeEach(() => { // Don't automatically change d - the only way to get d invalid fixtureHelper.clickElement('#d-calc-btn'); }); it('should not automatically change d if k or m have been changed', () => { formHelper.expectValidChange('m', 4); formHelper.expectValidChange('k', 5); expect(component.form.getValue('d')).toBe(7); }); it('should trigger dMin through change of d', () => { formHelper.expectErrorChange('d', 3, 'dMin'); }); it('should trigger dMax through change of d', () => { formHelper.expectErrorChange('d', 8, 'dMax'); }); it('should trigger dMin through change of k and m', () => { formHelper.expectValidChange('m', 2); formHelper.expectValidChange('k', 7); formHelper.expectError('d', 'dMin'); }); it('should trigger dMax through change of m', () => { formHelper.expectValidChange('m', 3); formHelper.expectError('d', 'dMax'); }); it('should remove dMax through change of k', () => { formHelper.expectValidChange('m', 3); formHelper.expectError('d', 'dMax'); formHelper.expectValidChange('k', 5); formHelper.expectValid('d'); }); }); }); }); describe('submission', () => { let ecp: ErasureCodeProfile; let submittedEcp: ErasureCodeProfile; const testCreation = () => { fixture.detectChanges(); component.onSubmit(); expect(ecpService.create).toHaveBeenCalledWith(submittedEcp); }; const ecpChange = (attribute: string, value: string | number) => { ecp[attribute] = value; submittedEcp[attribute] = value; }; beforeEach(() => { ecp = new ErasureCodeProfile(); submittedEcp = new ErasureCodeProfile(); submittedEcp['crush-root'] = 'default'; submittedEcp['crush-failure-domain'] = 'osd-rack'; submittedEcp['packetsize'] = 2048; submittedEcp['technique'] = 'reed_sol_van'; const taskWrapper = TestBed.inject(TaskWrapperService); spyOn(taskWrapper, 'wrapTaskAroundCall').and.callThrough(); spyOn(ecpService, 'create').and.stub(); }); describe(`'jerasure' usage`, () => { beforeEach(() => { submittedEcp['plugin'] = 'jerasure'; ecpChange('name', 'jerasureProfile'); submittedEcp.k = 4; submittedEcp.m = 2; }); it('should be able to create a profile with only required fields', () => { formHelper.setMultipleValues(ecp, true); testCreation(); }); it(`does not create with missing 'k' or invalid form`, () => { ecpChange('k', 0); formHelper.setMultipleValues(ecp, true); component.onSubmit(); expect(ecpService.create).not.toHaveBeenCalled(); }); it('should be able to create a profile with m, k, name, directory and packetSize', () => { ecpChange('m', 3); ecpChange('directory', '/different/ecp/path'); formHelper.setMultipleValues(ecp, true); formHelper.setValue('packetSize', 8192, true); ecpChange('packetsize', 8192); testCreation(); }); it('should not send the profile with unsupported fields', () => { formHelper.setMultipleValues(ecp, true); formHelper.setValue('crushLocality', 'osd', true); testCreation(); }); }); describe(`'isa' usage`, () => { beforeEach(() => { ecpChange('name', 'isaProfile'); ecpChange('plugin', 'isa'); submittedEcp.k = 7; submittedEcp.m = 3; delete submittedEcp.packetsize; }); it('should be able to create a profile with only plugin and name', () => { formHelper.setMultipleValues(ecp, true); testCreation(); }); it('should send profile with plugin, name, failure domain and technique only', () => { ecpChange('technique', 'cauchy'); formHelper.setMultipleValues(ecp, true); formHelper.setValue('crushFailureDomain', 'osd', true); submittedEcp['crush-failure-domain'] = 'osd'; submittedEcp['crush-device-class'] = 'ssd'; testCreation(); }); it('should not send the profile with unsupported fields', () => { formHelper.setMultipleValues(ecp, true); formHelper.setValue('packetSize', 'osd', true); testCreation(); }); }); describe(`'lrc' usage`, () => { beforeEach(() => { ecpChange('name', 'lrcProfile'); ecpChange('plugin', 'lrc'); submittedEcp.k = 4; submittedEcp.m = 2; submittedEcp.l = 3; delete submittedEcp.packetsize; delete submittedEcp.technique; }); it('should be able to create a profile with only required fields', () => { formHelper.setMultipleValues(ecp, true); testCreation(); }); it('should send profile with all required fields and crush root and locality', () => { ecpChange('l', '6'); formHelper.setMultipleValues(ecp, true); formHelper.setValue('crushRoot', component.buckets[2], true); submittedEcp['crush-root'] = 'mix-host'; formHelper.setValue('crushLocality', 'osd-rack', true); submittedEcp['crush-locality'] = 'osd-rack'; testCreation(); }); it('should not send the profile with unsupported fields', () => { formHelper.setMultipleValues(ecp, true); formHelper.setValue('c', 4, true); testCreation(); }); }); describe(`'shec' usage`, () => { beforeEach(() => { ecpChange('name', 'shecProfile'); ecpChange('plugin', 'shec'); submittedEcp.k = 4; submittedEcp.m = 3; submittedEcp.c = 2; delete submittedEcp.packetsize; delete submittedEcp.technique; }); it('should be able to create a profile with only plugin and name', () => { formHelper.setMultipleValues(ecp, true); testCreation(); }); it('should send profile with plugin, name, c and crush device class only', () => { ecpChange('c', '3'); formHelper.setMultipleValues(ecp, true); formHelper.setValue('crushDeviceClass', 'ssd', true); submittedEcp['crush-device-class'] = 'ssd'; testCreation(); }); it('should not send the profile with unsupported fields', () => { formHelper.setMultipleValues(ecp, true); formHelper.setValue('l', 8, true); testCreation(); }); }); describe(`'clay' usage`, () => { beforeEach(() => { ecpChange('name', 'clayProfile'); ecpChange('plugin', 'clay'); // Setting expectations submittedEcp.k = 4; submittedEcp.m = 2; submittedEcp.d = 5; submittedEcp.scalar_mds = 'jerasure'; delete submittedEcp.packetsize; }); it('should be able to create a profile with only plugin and name', () => { formHelper.setMultipleValues(ecp, true); testCreation(); }); it('should send profile with a changed d', () => { formHelper.setMultipleValues(ecp, true); ecpChange('d', '5'); submittedEcp.d = 5; testCreation(); }); it('should send profile with a changed k which automatically changes d', () => { ecpChange('k', 5); formHelper.setMultipleValues(ecp, true); submittedEcp.d = 6; testCreation(); }); it('should send profile with a changed sclara_mds', () => { ecpChange('scalar_mds', 'shec'); formHelper.setMultipleValues(ecp, true); submittedEcp.scalar_mds = 'shec'; submittedEcp.technique = 'single'; testCreation(); }); it('should not send the profile with unsupported fields', () => { formHelper.setMultipleValues(ecp, true); formHelper.setValue('l', 8, true); testCreation(); }); }); }); });
23,142
32.58926
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/erasure-code-profile-form/erasure-code-profile-form-modal.component.ts
import { Component, EventEmitter, OnInit, Output } from '@angular/core'; import { Validators } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ErasureCodeProfileService } from '~/app/shared/api/erasure-code-profile.service'; import { CrushNodeSelectionClass } from '~/app/shared/classes/crush.node.selection.class'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { Icons } from '~/app/shared/enum/icons.enum'; 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 { CrushNode } from '~/app/shared/models/crush-node'; import { ErasureCodeProfile } from '~/app/shared/models/erasure-code-profile'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; @Component({ selector: 'cd-erasure-code-profile-form-modal', templateUrl: './erasure-code-profile-form-modal.component.html', styleUrls: ['./erasure-code-profile-form-modal.component.scss'] }) export class ErasureCodeProfileFormModalComponent extends CrushNodeSelectionClass implements OnInit { @Output() submitAction = new EventEmitter(); tooltips = this.ecpService.formTooltips; PLUGIN = { LRC: 'lrc', // Locally Repairable Erasure Code SHEC: 'shec', // Shingled Erasure Code CLAY: 'clay', // Coupled LAYer JERASURE: 'jerasure', // default ISA: 'isa' // Intel Storage Acceleration }; plugin = this.PLUGIN.JERASURE; icons = Icons; form: CdFormGroup; plugins: string[]; names: string[]; techniques: string[]; action: string; resource: string; dCalc: boolean; lrcGroups: number; lrcMultiK: number; constructor( private formBuilder: CdFormBuilder, public activeModal: NgbActiveModal, private taskWrapper: TaskWrapperService, private ecpService: ErasureCodeProfileService, public actionLabels: ActionLabelsI18n ) { super(); this.action = this.actionLabels.CREATE; this.resource = $localize`EC Profile`; this.createForm(); this.setJerasureDefaults(); } createForm() { this.form = this.formBuilder.group({ name: [ null, [ Validators.required, Validators.pattern('[A-Za-z0-9_-]+'), CdValidators.custom( 'uniqueName', (value: string) => this.names && this.names.indexOf(value) !== -1 ) ] ], plugin: [this.PLUGIN.JERASURE, [Validators.required]], k: [ 4, // Will be overwritten with plugin defaults [ Validators.required, CdValidators.custom('max', () => this.baseValueValidation(true)), CdValidators.custom('unequal', (v: number) => this.lrcDataValidation(v)), CdValidators.custom('kLowerM', (v: number) => this.shecDataValidation(v)) ] ], m: [ 2, // Will be overwritten with plugin defaults [Validators.required, CdValidators.custom('max', () => this.baseValueValidation())] ], crushFailureDomain: '', // Will be preselected crushRoot: null, // Will be preselected crushDeviceClass: '', // Will be preselected directory: '', // Only for 'jerasure', 'clay' and 'isa' use technique: 'reed_sol_van', // Only for 'jerasure' use packetSize: [2048], // Only for 'lrc' use l: [ 3, // Will be overwritten with plugin defaults [ Validators.required, CdValidators.custom('unequal', (v: number) => this.lrcLocalityValidation(v)) ] ], crushLocality: '', // set to none at the end (same list as for failure domains) // Only for 'shec' use c: [ 2, // Will be overwritten with plugin defaults [ Validators.required, CdValidators.custom('cGreaterM', (v: number) => this.shecDurabilityValidation(v)) ] ], // Only for 'clay' use d: [ 5, // Will be overwritten with plugin defaults (k+m-1) = k+1 <= d <= k+m-1 [ Validators.required, CdValidators.custom('dMin', (v: number) => this.dMinValidation(v)), CdValidators.custom('dMax', (v: number) => this.dMaxValidation(v)) ] ], scalar_mds: [this.PLUGIN.JERASURE, [Validators.required]] // jerasure or isa or shec }); this.toggleDCalc(); this.form.get('k').valueChanges.subscribe(() => this.updateValidityOnChange(['m', 'l', 'd'])); this.form .get('m') .valueChanges.subscribe(() => this.updateValidityOnChange(['k', 'l', 'c', 'd'])); this.form.get('l').valueChanges.subscribe(() => this.updateValidityOnChange(['k', 'm'])); this.form.get('plugin').valueChanges.subscribe((plugin) => this.onPluginChange(plugin)); this.form.get('scalar_mds').valueChanges.subscribe(() => this.setClayDefaultsForScalar()); } private baseValueValidation(dataChunk: boolean = false): boolean { return this.validValidation(() => { return ( this.getKMSum() > this.deviceCount && this.form.getValue('k') > this.form.getValue('m') === dataChunk ); }); } private validValidation(fn: () => boolean, plugin?: string): boolean { if (!this.form || plugin ? this.plugin !== plugin : false) { return false; } return fn(); } private getKMSum(): number { return this.form.getValue('k') + this.form.getValue('m'); } private lrcDataValidation(k: number): boolean { return this.validValidation(() => { const m = this.form.getValue('m'); const l = this.form.getValue('l'); const km = k + m; this.lrcMultiK = k / (km / l); return k % (km / l) !== 0; }, 'lrc'); } private shecDataValidation(k: number): boolean { return this.validValidation(() => { const m = this.form.getValue('m'); return m > k; }, 'shec'); } private lrcLocalityValidation(l: number) { return this.validValidation(() => { const value = this.getKMSum(); this.lrcGroups = l > 0 ? value / l : 0; return l > 0 && value % l !== 0; }, 'lrc'); } private shecDurabilityValidation(c: number): boolean { return this.validValidation(() => { const m = this.form.getValue('m'); return c > m; }, 'shec'); } private dMinValidation(d: number): boolean { return this.validValidation(() => this.getDMin() > d, 'clay'); } getDMin(): number { return this.form.getValue('k') + 1; } private dMaxValidation(d: number): boolean { return this.validValidation(() => d > this.getDMax(), 'clay'); } getDMax(): number { const m = this.form.getValue('m'); const k = this.form.getValue('k'); return k + m - 1; } toggleDCalc() { this.dCalc = !this.dCalc; this.form.get('d')[this.dCalc ? 'disable' : 'enable'](); this.calculateD(); } private calculateD() { if (this.plugin !== this.PLUGIN.CLAY || !this.dCalc) { return; } this.form.silentSet('d', this.getDMax()); } private updateValidityOnChange(names: string[]) { names.forEach((name) => { if (name === 'd') { this.calculateD(); } this.form.get(name).updateValueAndValidity({ emitEvent: false }); }); } private onPluginChange(plugin: string) { this.plugin = plugin; if (plugin === this.PLUGIN.JERASURE) { this.setJerasureDefaults(); } else if (plugin === this.PLUGIN.LRC) { this.setLrcDefaults(); } else if (plugin === this.PLUGIN.ISA) { this.setIsaDefaults(); } else if (plugin === this.PLUGIN.SHEC) { this.setShecDefaults(); } else if (plugin === this.PLUGIN.CLAY) { this.setClayDefaults(); } this.updateValidityOnChange(['m']); // Triggers k, m, c, d and l } private setJerasureDefaults() { this.techniques = [ 'reed_sol_van', 'reed_sol_r6_op', 'cauchy_orig', 'cauchy_good', 'liberation', 'blaum_roth', 'liber8tion' ]; this.setDefaults({ k: 4, m: 2, technique: 'reed_sol_van' }); } private setLrcDefaults() { this.setDefaults({ k: 4, m: 2, l: 3 }); } private setIsaDefaults() { /** * Actually k and m are not required - but they will be set to the default values in case * if they are not set, therefore it's fine to mark them as required in order to get * strange values that weren't set. */ this.techniques = ['reed_sol_van', 'cauchy']; this.setDefaults({ k: 7, m: 3, technique: 'reed_sol_van' }); } private setShecDefaults() { /** * Actually k, c and m are not required - but they will be set to the default values in case * if they are not set, therefore it's fine to mark them as required in order to get * strange values that weren't set. */ this.setDefaults({ k: 4, m: 3, c: 2 }); } private setClayDefaults() { /** * Actually d and scalar_mds are not required - but they will be set to show the default values * in case if they are not set, therefore it's fine to mark them as required in order to not get * strange values that weren't set. * * As d would be set to the value k+m-1 for the greatest savings, the form will * automatically update d if the automatic calculation is activated (default). */ this.setDefaults({ k: 4, m: 2, // d: 5, <- Will be automatically update to 5 scalar_mds: this.PLUGIN.JERASURE }); this.setClayDefaultsForScalar(); } private setClayDefaultsForScalar() { const plugin = this.form.getValue('scalar_mds'); let defaultTechnique = 'reed_sol_van'; if (plugin === this.PLUGIN.JERASURE) { this.techniques = [ 'reed_sol_van', 'reed_sol_r6_op', 'cauchy_orig', 'cauchy_good', 'liber8tion' ]; } else if (plugin === this.PLUGIN.ISA) { this.techniques = ['reed_sol_van', 'cauchy']; } else { // this.PLUGIN.SHEC defaultTechnique = 'single'; this.techniques = ['single', 'multiple']; } this.setDefaults({ technique: defaultTechnique }); } private setDefaults(defaults: object) { Object.keys(defaults).forEach((controlName) => { const control = this.form.get(controlName); const value = control.value; /** * As k, m, c and l are now set touched and dirty on the beginning, plugin change will * overwrite their values as we can't determine if the user has changed anything. * k and m can have two default values where as l and c can only have one, * so there is no need to overwrite them. */ const overwrite = control.pristine || (controlName === 'technique' && !this.techniques.includes(value)) || (controlName === 'k' && [4, 7].includes(value)) || (controlName === 'm' && [2, 3].includes(value)); if (overwrite) { control.setValue(defaults[controlName]); // also validates new value } else { control.updateValueAndValidity(); } }); } ngOnInit() { this.ecpService .getInfo() .subscribe( ({ plugins, names, directory, nodes }: { plugins: string[]; names: string[]; directory: string; nodes: CrushNode[]; }) => { this.initCrushNodeSelection( nodes, this.form.get('crushRoot'), this.form.get('crushFailureDomain'), this.form.get('crushDeviceClass') ); this.plugins = plugins; this.names = names; this.form.silentSet('directory', directory); this.preValidateNumericInputFields(); } ); } /** * This allows k, m, l and c to be validated instantly on change, before the * fields got changed before by the user. */ private preValidateNumericInputFields() { const kml = ['k', 'm', 'l', 'c', 'd'].map((name) => this.form.get(name)); kml.forEach((control) => { control.markAsTouched(); control.markAsDirty(); }); kml[1].updateValueAndValidity(); // Update validity of k, m, c, d and l } onSubmit() { if (this.form.invalid) { this.form.setErrors({ cdSubmitButton: true }); return; } const profile = this.createJson(); this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('ecp/create', { name: profile.name }), call: this.ecpService.create(profile) }) .subscribe({ error: () => { this.form.setErrors({ cdSubmitButton: true }); }, complete: () => { this.activeModal.close(); this.submitAction.emit(profile); } }); } private createJson() { const pluginControls = { technique: [this.PLUGIN.ISA, this.PLUGIN.JERASURE, this.PLUGIN.CLAY], packetSize: [this.PLUGIN.JERASURE], l: [this.PLUGIN.LRC], crushLocality: [this.PLUGIN.LRC], c: [this.PLUGIN.SHEC], d: [this.PLUGIN.CLAY], scalar_mds: [this.PLUGIN.CLAY] }; const ecp = new ErasureCodeProfile(); const plugin = this.form.getValue('plugin'); Object.keys(this.form.controls) .filter((name) => { const pluginControl = pluginControls[name]; const value = this.form.getValue(name); const usable = (pluginControl && pluginControl.includes(plugin)) || !pluginControl; return usable && value && value !== ''; }) .forEach((name) => { this.extendJson(name, ecp); }); return ecp; } private extendJson(name: string, ecp: ErasureCodeProfile) { const differentApiAttributes = { crushFailureDomain: 'crush-failure-domain', crushRoot: 'crush-root', crushDeviceClass: 'crush-device-class', packetSize: 'packetsize', crushLocality: 'crush-locality' }; const value = this.form.getValue(name); ecp[differentApiAttributes[name] || name] = name === 'crushRoot' ? value.name : value; } }
14,256
29.993478
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool-details/pool-details.component.html
<ng-container *ngIf="selection" cdTableDetail> <nav ngbNav #nav="ngbNav" class="nav-tabs" cdStatefulTab="pool-details"> <ng-container ngbNavItem="details"> <a ngbNavLink i18n>Details</a> <ng-template ngbNavContent> <cd-table-key-value [renderObjects]="true" [data]="poolDetails" [autoReload]="false"> </cd-table-key-value> </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="Pool details" grafanaPath="ceph-pool-detail?var-pool_name={{selection.pool_name}}" [type]="'metrics'" uid="-xyV8KCiz" grafanaStyle="three"> </cd-grafana> </ng-template> </ng-container> <ng-container ngbNavItem="configuration" *ngIf="selection.type === 'replicated'"> <a ngbNavLink i18n>Configuration</a> <ng-template ngbNavContent> <cd-rbd-configuration-table [data]="selectedPoolConfiguration"></cd-rbd-configuration-table> </ng-template> </ng-container> <ng-container ngbNavItem="cache-tiers-details" *ngIf="selection['tiers']?.length > 0"> <a ngbNavLink i18n>Cache Tiers Details</a> <ng-template ngbNavContent> <cd-table [data]="cacheTiers" [columns]="cacheTierColumns" [autoSave]="false" columnMode="flex"> </cd-table> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="nav"></div> </ng-container>
1,848
32.618182
100
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool-details/pool-details.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ChangeDetectorRef } from '@angular/core'; 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 { RbdConfigurationListComponent } from '~/app/ceph/block/rbd-configuration-list/rbd-configuration-list.component'; import { Permissions } from '~/app/shared/models/permissions'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, Mocks, TabHelper } from '~/testing/unit-test-helper'; import { PoolDetailsComponent } from './pool-details.component'; describe('PoolDetailsComponent', () => { let poolDetailsComponent: PoolDetailsComponent; let fixture: ComponentFixture<PoolDetailsComponent>; // Needed because of ChangeDetectionStrategy.OnPush // https://github.com/angular/angular/issues/12313#issuecomment-444623173 let changeDetector: ChangeDetectorRef; const detectChanges = () => { poolDetailsComponent.ngOnChanges(); changeDetector.detectChanges(); // won't call ngOnChanges on it's own but updates fixture }; const updatePoolSelection = (selection: any) => { poolDetailsComponent.selection = selection; detectChanges(); }; const currentPoolUpdate = () => { updatePoolSelection(poolDetailsComponent.selection); }; configureTestBed({ imports: [ BrowserAnimationsModule, NgbNavModule, SharedModule, HttpClientTestingModule, RouterTestingModule ], declarations: [PoolDetailsComponent, RbdConfigurationListComponent] }); beforeEach(() => { fixture = TestBed.createComponent(PoolDetailsComponent); // Needed because of ChangeDetectionStrategy.OnPush // https://github.com/angular/angular/issues/12313#issuecomment-444623173 changeDetector = fixture.componentRef.injector.get(ChangeDetectorRef); poolDetailsComponent = fixture.componentInstance; poolDetailsComponent.selection = undefined; poolDetailsComponent.permissions = new Permissions({ grafana: ['read'] }); updatePoolSelection({ tiers: [0], pool: 0, pool_name: 'micro_pool' }); }); it('should create', () => { expect(poolDetailsComponent).toBeTruthy(); }); describe('Pool details tabset', () => { it('should recognize a tabset child', () => { detectChanges(); const ngbNav = TabHelper.getNgbNav(fixture); expect(ngbNav).toBeDefined(); }); it('should not change the tabs active status when selection is the same as before', () => { const tabs = TabHelper.getNgbNavItems(fixture); expect(tabs[0].active).toBeTruthy(); currentPoolUpdate(); expect(tabs[0].active).toBeTruthy(); const ngbNav = TabHelper.getNgbNav(fixture); ngbNav.select(tabs[1].id); expect(tabs[1].active).toBeTruthy(); currentPoolUpdate(); expect(tabs[1].active).toBeTruthy(); }); it('should filter out cdExecuting, cdIsBinary and all stats', () => { updatePoolSelection({ prop1: 1, cdIsBinary: true, prop2: 2, cdExecuting: true, prop3: 3, stats: { anyStat: 3, otherStat: [1, 2, 3] } }); const expectedPool = { prop1: 1, prop2: 2, prop3: 3 }; expect(poolDetailsComponent.poolDetails).toEqual(expectedPool); }); describe('Updates of shown data', () => { const expectedChange = ( expected: { selectedPoolConfiguration?: object; poolDetails?: object; }, newSelection: object, doesNotEqualOld = true ) => { const getData = () => { const data = {}; Object.keys(expected).forEach((key) => (data[key] = poolDetailsComponent[key])); return data; }; const oldData = getData(); updatePoolSelection(newSelection); const newData = getData(); if (doesNotEqualOld) { expect(expected).not.toEqual(oldData); } else { expect(expected).toEqual(oldData); } expect(expected).toEqual(newData); }; it('should update shown data on change', () => { expectedChange( { poolDetails: { pg_num: 256, pg_num_target: 256, pg_placement_num: 256, pg_placement_num_target: 256, pool: 2, pool_name: 'somePool', type: 'replicated', size: 3 } }, Mocks.getPool('somePool', 2) ); }); it('should not update shown data if no detail has changed on pool refresh', () => { expectedChange( { poolDetails: { pool: 0, pool_name: 'micro_pool', tiers: [0] } }, poolDetailsComponent.selection, false ); }); it('should show "Cache Tiers Details" tab if selected pool has "tiers"', () => { const tabsItem = TabHelper.getNgbNavItems(fixture); const tabsText = TabHelper.getTextContents(fixture); expect(poolDetailsComponent.selection['tiers'].length).toBe(1); expect(tabsItem.length).toBe(3); expect(tabsText[2]).toBe('Cache Tiers Details'); expect(tabsItem[0].active).toBeTruthy(); }); it('should not show "Cache Tiers Details" tab if selected pool has no "tiers"', () => { updatePoolSelection({ tiers: [] }); const tabs = TabHelper.getNgbNavItems(fixture); expect(tabs.length).toEqual(2); expect(tabs[0].active).toBeTruthy(); }); }); }); });
5,809
32.77907
121
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool-details/pool-details.component.ts
import { ChangeDetectionStrategy, Component, Input, OnChanges } from '@angular/core'; import _ from 'lodash'; import { PoolService } from '~/app/shared/api/pool.service'; import { CdHelperClass } from '~/app/shared/classes/cd-helper.class'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { RbdConfigurationEntry } from '~/app/shared/models/configuration'; import { Permissions } from '~/app/shared/models/permissions'; @Component({ selector: 'cd-pool-details', templateUrl: './pool-details.component.html', styleUrls: ['./pool-details.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class PoolDetailsComponent implements OnChanges { @Input() cacheTiers: any[]; @Input() permissions: Permissions; @Input() selection: any; cacheTierColumns: Array<CdTableColumn> = []; // 'stats' won't be shown as the pure stat numbers won't tell the user much, // if they are not converted or used in a chart (like the ones available in the pool listing) omittedPoolAttributes = ['cdExecuting', 'cdIsBinary', 'stats']; poolDetails: object; selectedPoolConfiguration: RbdConfigurationEntry[]; constructor(private poolService: PoolService) { this.cacheTierColumns = [ { prop: 'pool_name', name: $localize`Name`, flexGrow: 3 }, { prop: 'cache_mode', name: $localize`Cache Mode`, flexGrow: 2 }, { prop: 'cache_min_evict_age', name: $localize`Min Evict Age`, flexGrow: 2 }, { prop: 'cache_min_flush_age', name: $localize`Min Flush Age`, flexGrow: 2 }, { prop: 'target_max_bytes', name: $localize`Target Max Bytes`, flexGrow: 2 }, { prop: 'target_max_objects', name: $localize`Target Max Objects`, flexGrow: 2 } ]; } ngOnChanges() { if (this.selection) { this.poolService .getConfiguration(this.selection.pool_name) .subscribe((poolConf: RbdConfigurationEntry[]) => { CdHelperClass.updateChanged(this, { selectedPoolConfiguration: poolConf }); }); CdHelperClass.updateChanged(this, { poolDetails: _.omit(this.selection, this.omittedPoolAttributes) }); } } }
2,330
27.777778
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool-form/pool-form-data.ts
import { Validators } from '@angular/forms'; import { SelectMessages } from '~/app/shared/components/select/select-messages.model'; import { Pool } from '../pool'; export class PoolFormData { poolTypes: string[]; erasureInfo = false; crushInfo = false; applications: any; constructor() { this.poolTypes = ['erasure', 'replicated']; this.applications = { selected: [], default: ['cephfs', 'rbd', 'rgw'], available: [], // Filled during runtime validators: [Validators.pattern('[A-Za-z0-9_]+'), Validators.maxLength(128)], messages: new SelectMessages({ empty: $localize`No applications added`, selectionLimit: { text: $localize`Applications limit reached`, tooltip: $localize`A pool can only have up to four applications definitions.` }, customValidations: { pattern: $localize`Allowed characters '_a-zA-Z0-9'`, maxlength: $localize`Maximum length is 128 characters` }, filter: $localize`Filter or add applications'`, add: $localize`Add application` }) }; } pgs = 1; pool: Pool; // Only available during edit mode }
1,179
30.052632
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool-form/pool-form.component.html
<div class="cd-col-form" *cdFormLoading="loading"> <form name="form" #formDir="ngForm" [formGroup]="form" novalidate> <div class="card"> <div i18n="form title|Example: Create Pool@@formTitle" class="card-header">{{ action | titlecase }} {{ resource | upperFirst }}</div> <div class="card-body"> <!-- 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 id="name" name="name" type="text" class="form-control" placeholder="Name..." i18n-placeholder formControlName="name" autofocus> <span class="invalid-feedback" *ngIf="form.showError('name', formDir, 'required')" i18n>This field is required!</span> <span class="invalid-feedback" *ngIf="form.showError('name', formDir, 'uniqueName')" i18n>The chosen Ceph pool name is already in use.</span> <span *ngIf="form.showError('name', formDir, 'rbdPool')" class="invalid-feedback" i18n>It's not possible to create an RBD pool with '/' in the name. Please change the name or remove 'rbd' from the applications list.</span> <span *ngIf="form.showError('name', formDir, 'pattern')" class="invalid-feedback" i18n>Pool name can only contain letters, numbers, '.', '-', '_' or '/'.</span> </div> </div> <!-- Pool type selection --> <div class="form-group row"> <label class="cd-col-form-label required" for="poolType" i18n>Pool type</label> <div class="cd-col-form-input"> <select class="form-select" id="poolType" formControlName="poolType" name="poolType"> <option ngValue="" i18n>-- Select a pool type --</option> <option *ngFor="let poolType of data.poolTypes" [value]="poolType"> {{ poolType }} </option> </select> <span class="invalid-feedback" *ngIf="form.showError('poolType', formDir, 'required')" i18n>This field is required!</span> </div> </div> <div *ngIf="isReplicated || isErasure"> <!-- PG Autoscale Mode --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="pgAutoscaleMode">PG Autoscale</label> <div class="cd-col-form-input"> <select class="form-select" id="pgAutoscaleMode" name="pgAutoscaleMode" formControlName="pgAutoscaleMode"> <option *ngFor="let mode of pgAutoscaleModes" [value]="mode"> {{ mode }} </option> </select> </div> </div> <!-- Pg number --> <div class="form-group row" *ngIf="form.getValue('pgAutoscaleMode') !== 'on'"> <label class="cd-col-form-label required" for="pgNum" i18n>Placement groups</label> <div class="cd-col-form-input"> <input class="form-control" id="pgNum" name="pgNum" formControlName="pgNum" min="1" type="number" (focus)="externalPgChange = false" (blur)="alignPgs()" required> <span class="invalid-feedback" *ngIf="form.showError('pgNum', formDir, 'required')" i18n>This field is required!</span> <span class="invalid-feedback" *ngIf="form.showError('pgNum', formDir, 'min')" i18n>At least one placement group is needed!</span> <span class="invalid-feedback" *ngIf="form.showError('pgNum', formDir, '34')" i18n>Your cluster can't handle this many PGs. Please recalculate the PG amount needed.</span> <span class="form-text text-muted"> <cd-doc section="pgs" docText="Calculation help" i18n-docText></cd-doc> </span> <span class="form-text text-muted" *ngIf="externalPgChange" i18n>The current PGs settings were calculated for you, you should make sure the values suit your needs before submit.</span> </div> </div> <!-- Replica Size --> <div class="form-group row" *ngIf="isReplicated"> <label class="cd-col-form-label required" for="size" i18n>Replicated size</label> <div class="cd-col-form-input"> <input class="form-control" id="size" [max]="getMaxSize()" [min]="getMinSize()" name="size" type="number" formControlName="size"> <span class="invalid-feedback" *ngIf="form.showError('size', formDir)"> <ul class="list-inline"> <li i18n>Minimum: {{ getMinSize() }}</li> <li i18n>Maximum: {{ getMaxSize() }}</li> </ul> </span> <span class="invalid-feedback" *ngIf="form.showError('size', formDir)" i18n>The size specified is out of range. A value from {{ getMinSize() }} to {{ getMaxSize() }} is usable.</span> <span class="text-warning-dark" *ngIf="form.getValue('size') === 1" i18n>A size of 1 will not create a replication of the object. The 'Replicated size' includes the object itself.</span> </div> </div> <!-- Flags --> <div class="form-group row" *ngIf="info.is_all_bluestore && isErasure"> <label i18n class="cd-col-form-label">Flags</label> <div class="cd-col-form-input"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="ec-overwrites" formControlName="ecOverwrites"> <label class="custom-control-label" for="ec-overwrites" i18n>EC Overwrites</label> </div> </div> </div> </div> <!-- Applications --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="applications">Applications</label> <div class="cd-col-form-input"> <cd-select-badges id="applications" [customBadges]="true" [customBadgeValidators]="data.applications.validators" [messages]="data.applications.messages" [data]="data.applications.selected" [options]="data.applications.available" [selectionLimit]="4" (selection)="appSelection()"> </cd-select-badges> <i *ngIf="data.applications.selected <= 0" i18n-title title="Pools should be associated with an application tag" class="{{icons.warning}} icon-warning-color"> </i> </div> </div> <!-- CRUSH --> <div *ngIf="isErasure || isReplicated"> <legend i18n>CRUSH</legend> <!-- Erasure Profile select --> <div class="form-group row" *ngIf="isErasure"> <label i18n class="cd-col-form-label" for="erasureProfile">Erasure code profile</label> <div class="cd-col-form-input"> <div class="input-group mb-1"> <select class="form-select" id="erasureProfile" name="erasureProfile" formControlName="erasureProfile"> <option *ngIf="!ecProfiles" ngValue="" i18n>Loading...</option> <option *ngIf="ecProfiles && ecProfiles.length === 0" [ngValue]="null" i18n>-- No erasure code profile available --</option> <option *ngIf="ecProfiles && ecProfiles.length > 0" [ngValue]="null" i18n>-- Select an erasure code profile --</option> <option *ngFor="let ecp of ecProfiles" [ngValue]="ecp"> {{ ecp.name }} </option> </select> <button class="btn btn-light" [ngClass]="{'active': data.erasureInfo}" id="ecp-info-button" type="button" (click)="data.erasureInfo = !data.erasureInfo"> <i [ngClass]="[icons.questionCircle]" aria-hidden="true"></i> </button> <button class="btn btn-light" type="button" *ngIf="!editing" (click)="addErasureCodeProfile()"> <i [ngClass]="[icons.add]" aria-hidden="true"></i> </button> <button class="btn btn-light" type="button" *ngIf="!editing" ngbTooltip="This profile can't be deleted as it is in use." i18n-ngbTooltip triggers="manual" #ecpDeletionBtn="ngbTooltip" (click)="deleteErasureCodeProfile()"> <i [ngClass]="[icons.trash]" aria-hidden="true"></i> </button> </div> <span class="form-text text-muted" id="ecp-info-block" *ngIf="data.erasureInfo && form.getValue('erasureProfile')"> <nav ngbNav #ecpInfoTabs="ngbNav" class="nav-tabs"> <ng-container ngbNavItem="ecp-info"> <a ngbNavLink i18n>Profile</a> <ng-template ngbNavContent> <cd-table-key-value [renderObjects]="true" [hideKeys]="['name']" [data]="form.getValue('erasureProfile')" [autoReload]="false"> </cd-table-key-value> </ng-template> </ng-container> <ng-container ngbNavItem="used-by-pools"> <a ngbNavLink i18n>Used by pools</a> <ng-template ngbNavContent> <ng-template #ecpIsNotUsed> <span i18n>Profile is not in use.</span> </ng-template> <ul *ngIf="ecpUsage; else ecpIsNotUsed"> <li *ngFor="let pool of ecpUsage"> {{ pool }} </li> </ul> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="ecpInfoTabs"></div> </span> </div> </div> <!-- Crush ruleset selection --> <div class="form-group row" *ngIf="isErasure && !editing"> <label class="cd-col-form-label" for="crushRule" i18n>Crush ruleset</label> <div class="cd-col-form-input"> <span class="form-text text-muted" i18n>A new crush ruleset will be implicitly created.</span> </div> </div> <div class="form-group row" *ngIf="isReplicated || editing"> <label class="cd-col-form-label" for="crushRule" i18n>Crush ruleset</label> <div class="cd-col-form-input"> <ng-template #noRules> <span class="form-text text-muted"> <span i18n>There are no rules.</span>&nbsp; </span> </ng-template> <div *ngIf="current.rules.length > 0; else noRules"> <div class="input-group"> <select class="form-select" id="crushRule" formControlName="crushRule" name="crushSet"> <option [ngValue]="null" i18n>-- Select a crush rule --</option> <option *ngFor="let rule of current.rules" [ngValue]="rule"> {{ rule.rule_name }} </option> </select> <button class="btn btn-light" [ngClass]="{'active': data.crushInfo}" id="crush-info-button" type="button" ngbTooltip="Placement and replication strategies or distribution policies that allow to specify how CRUSH places data replicas." i18n-ngbTooltip (click)="data.crushInfo = !data.crushInfo"> <i [ngClass]="[icons.questionCircle]" aria-hidden="true"></i> </button> <button class="btn btn-light" type="button" *ngIf="isReplicated && !editing" (click)="addCrushRule()"> <i [ngClass]="[icons.add]" aria-hidden="true"></i> </button> <button class="btn btn-light" *ngIf="isReplicated && !editing" type="button" ngbTooltip="This rule can't be deleted as it is in use." i18n-ngbTooltip triggers="manual" #crushDeletionBtn="ngbTooltip" (click)="deleteCrushRule()"> <i [ngClass]="[icons.trash]" aria-hidden="true"></i> </button> </div> <div class="form-text text-muted" id="crush-info-block" *ngIf="data.crushInfo && form.getValue('crushRule')"> <nav ngbNav #crushInfoTabs="ngbNav" class="nav-tabs"> <ng-container ngbNavItem="crush-rule-info"> <a ngbNavLink i18n>Crush rule</a> <ng-template ngbNavContent> <cd-table-key-value [renderObjects]="false" [hideKeys]="['steps', 'type', 'rule_name']" [data]="form.getValue('crushRule')" [autoReload]="false"> </cd-table-key-value> </ng-template> </ng-container> <ng-container ngbNavItem="crush-rule-steps"> <a ngbNavLink i18n>Crush steps</a> <ng-template ngbNavContent> <ol> <li *ngFor="let step of form.get('crushRule').value.steps"> {{ describeCrushStep(step) }} </li> </ol> </ng-template> </ng-container> <ng-container ngbNavItem="used-by-pools"> <a ngbNavLink i18n>Used by pools</a> <ng-template ngbNavContent> <ng-template #ruleIsNotUsed> <span i18n>Rule is not in use.</span> </ng-template> <ul *ngIf="crushUsage; else ruleIsNotUsed"> <li *ngFor="let pool of crushUsage"> {{ pool }} </li> </ul> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="crushInfoTabs"></div> </div> <span class="invalid-feedback" *ngIf="form.showError('crushRule', formDir, 'required')" i18n>This field is required!</span> <span class="invalid-feedback" *ngIf="form.showError('crushRule', formDir, 'tooFewOsds')" i18n>The rule can't be used in the current cluster as it has too few OSDs to meet the minimum required OSD by this rule.</span> </div> </div> </div> </div> <!-- Compression --> <div *ngIf="info.is_all_bluestore" formGroupName="compression"> <legend i18n>Compression</legend> <!-- Compression Mode --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="mode">Mode</label> <div class="cd-col-form-input"> <select class="form-select" id="mode" name="mode" formControlName="mode"> <option *ngFor="let mode of info.compression_modes" [value]="mode"> {{ mode }} </option> </select> </div> </div> <div *ngIf="hasCompressionEnabled()"> <!-- Compression algorithm selection --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="algorithm">Algorithm</label> <div class="cd-col-form-input"> <select class="form-select" id="algorithm" name="algorithm" formControlName="algorithm"> <option *ngIf="!info.compression_algorithms" ngValue="" i18n>Loading...</option> <option *ngIf="info.compression_algorithms && info.compression_algorithms.length === 0" i18n ngValue="">-- No erasure compression algorithm available --</option> <option *ngFor="let algorithm of info.compression_algorithms" [value]="algorithm"> {{ algorithm }} </option> </select> </div> </div> <!-- Compression min blob size --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="minBlobSize">Minimum blob size</label> <div class="cd-col-form-input"> <input id="minBlobSize" name="minBlobSize" formControlName="minBlobSize" type="text" min="0" class="form-control" i18n-placeholder placeholder="e.g., 128KiB" defaultUnit="KiB" cdDimlessBinary> <span class="invalid-feedback" *ngIf="form.showError('minBlobSize', formDir, 'min')" i18n>Value should be greater than 0</span> <span class="invalid-feedback" *ngIf="form.showError('minBlobSize', formDir, 'maximum')" i18n>Value should be less than the maximum blob size</span> </div> </div> <!-- Compression max blob size --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="maxBlobSize">Maximum blob size</label> <div class="cd-col-form-input"> <input id="maxBlobSize" type="text" min="0" formControlName="maxBlobSize" class="form-control" i18n-placeholder placeholder="e.g., 512KiB" defaultUnit="KiB" cdDimlessBinary> <span class="invalid-feedback" *ngIf="form.showError('maxBlobSize', formDir, 'min')" i18n>Value should be greater than 0</span> <span class="invalid-feedback" *ngIf="form.showError('maxBlobSize', formDir, 'minimum')" i18n>Value should be greater than the minimum blob size</span> </div> </div> <!-- Compression ratio --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="ratio">Ratio</label> <div class="cd-col-form-input"> <input id="ratio" name="ratio" formControlName="ratio" type="number" min="0" max="1" step="0.1" class="form-control" i18n-placeholder placeholder="Compression ratio"> <span class="invalid-feedback" *ngIf="form.showError('ratio', formDir, 'min') || form.showError('ratio', formDir, 'max')" i18n>Value should be between 0.0 and 1.0</span> </div> </div> </div> </div> <!-- Quotas --> <div> <legend i18n>Quotas</legend> <!-- Max Bytes --> <div class="form-group row"> <label class="cd-col-form-label" for="max_bytes"> <ng-container i18n>Max bytes</ng-container> <cd-helper> <span i18n>Leave it blank or specify 0 to disable this quota.</span> <br> <span i18n>A valid quota should be greater than 0.</span> </cd-helper> </label> <div class="cd-col-form-input"> <input class="form-control" id="max_bytes" name="max_bytes" type="text" formControlName="max_bytes" i18n-placeholder placeholder="e.g., 10GiB" defaultUnit="GiB" cdDimlessBinary> </div> </div> <!-- Max Objects --> <div class="form-group row"> <label class="cd-col-form-label" for="max_objects"> <ng-container i18n>Max objects</ng-container> <cd-helper> <span i18n>Leave it blank or specify 0 to disable this quota.</span> <br> <span i18n>A valid quota should be greater than 0.</span> </cd-helper> </label> <div class="cd-col-form-input"> <input class="form-control" id="max_objects" min="0" name="max_objects" type="number" formControlName="max_objects"> <span class="invalid-feedback" *ngIf="form.showError('max_objects', formDir, 'min')" i18n>The value should be greater or equal to 0</span> </div> </div> </div> <!-- Pool configuration --> <div [hidden]="isErasure || data.applications.selected.indexOf('rbd') === -1"> <cd-rbd-configuration-form [form]="form" [initializeData]="initializeConfigData" (changes)="currentConfigurationValues = $event()"> </cd-rbd-configuration-form> </div> </div> <div class="card-footer"> <cd-form-button-panel (submitActionEvent)="submit()" [form]="form" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)" wrappingClass="text-right"></cd-form-button-panel> </div> </div> </form> </div>
26,023
41.662295
113
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool-form/pool-form.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { AbstractControl } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ActivatedRoute, Router, Routes } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal, NgbModalModule, NgbModalRef, NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { DashboardNotFoundError } from '~/app/core/error/error'; import { ErrorComponent } from '~/app/core/error/error.component'; import { CrushRuleService } from '~/app/shared/api/crush-rule.service'; import { ErasureCodeProfileService } from '~/app/shared/api/erasure-code-profile.service'; import { PoolService } from '~/app/shared/api/pool.service'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { SelectBadgesComponent } from '~/app/shared/components/select-badges/select-badges.component'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { ErasureCodeProfile } from '~/app/shared/models/erasure-code-profile'; import { Permission } from '~/app/shared/models/permissions'; import { PoolFormInfo } from '~/app/shared/models/pool-form-info'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FixtureHelper, FormHelper, Mocks, modalServiceShow } from '~/testing/unit-test-helper'; import { Pool } from '../pool'; import { PoolModule } from '../pool.module'; import { PoolFormComponent } from './pool-form.component'; describe('PoolFormComponent', () => { let OSDS = 15; let formHelper: FormHelper; let fixtureHelper: FixtureHelper; let component: PoolFormComponent; let fixture: ComponentFixture<PoolFormComponent>; let poolService: PoolService; let form: CdFormGroup; let router: Router; let ecpService: ErasureCodeProfileService; let crushRuleService: CrushRuleService; let poolPermissions: Permission; let authStorageService: AuthStorageService; const setPgNum = (pgs: number): AbstractControl => { const control = formHelper.setValue('pgNum', pgs); fixture.debugElement.query(By.css('#pgNum')).nativeElement.dispatchEvent(new Event('blur')); return control; }; const testPgUpdate = (pgs: number, jump: number, returnValue: number) => { if (pgs) { setPgNum(pgs); } if (jump) { setPgNum(form.getValue('pgNum') + jump); } expect(form.getValue('pgNum')).toBe(returnValue); }; const expectValidSubmit = ( pool: any, taskName = 'pool/create', poolServiceMethod: 'create' | 'update' = 'create' ) => { spyOn(poolService, poolServiceMethod).and.stub(); const taskWrapper = TestBed.inject(TaskWrapperService); spyOn(taskWrapper, 'wrapTaskAroundCall').and.callThrough(); component.submit(); expect(poolService[poolServiceMethod]).toHaveBeenCalledWith(pool); expect(taskWrapper.wrapTaskAroundCall).toHaveBeenCalledWith({ task: { name: taskName, metadata: { pool_name: pool.pool } }, call: undefined // because of stub }); }; let infoReturn: PoolFormInfo; const setInfo = () => { const ecp1 = new ErasureCodeProfile(); ecp1.name = 'ecp1'; infoReturn = { pool_names: ['someExistingPoolName'], osd_count: OSDS, is_all_bluestore: true, bluestore_compression_algorithm: 'snappy', compression_algorithms: ['snappy'], compression_modes: ['none', 'passive'], crush_rules_replicated: [ Mocks.getCrushRule({ id: 0, name: 'rep1', type: 'replicated' }), Mocks.getCrushRule({ id: 1, name: 'rep2', type: 'replicated' }), Mocks.getCrushRule({ id: 2, name: 'used_rule', type: 'replicated' }) ], crush_rules_erasure: [Mocks.getCrushRule({ id: 3, name: 'ecp1', type: 'erasure' })], erasure_code_profiles: [ecp1], pg_autoscale_default_mode: 'off', pg_autoscale_modes: ['off', 'warn', 'on'], used_rules: { used_rule: ['some.pool.uses.it'] }, used_profiles: { ecp1: ['some.other.pool.uses.it'] }, nodes: Mocks.generateSimpleCrushMap(3, 5) }; }; const setUpPoolComponent = () => { fixture = TestBed.createComponent(PoolFormComponent); component = fixture.componentInstance; fixture.detectChanges(); fixtureHelper = new FixtureHelper(fixture); form = component.form; formHelper = new FormHelper(form); }; const routes: Routes = [{ path: '404', component: ErrorComponent }]; configureTestBed( { declarations: [ErrorComponent], imports: [ BrowserAnimationsModule, HttpClientTestingModule, RouterTestingModule.withRoutes(routes), ToastrModule.forRoot(), NgbNavModule, PoolModule, SharedModule, NgbModalModule ], providers: [ ErasureCodeProfileService, NgbActiveModal, SelectBadgesComponent, { provide: ActivatedRoute, useValue: { params: of({ name: 'somePoolName' }) } } ] }, [CriticalConfirmationModalComponent] ); let navigationSpy: jasmine.Spy; beforeEach(() => { poolService = TestBed.inject(PoolService); setInfo(); spyOn(poolService, 'getInfo').and.callFake(() => of(infoReturn)); ecpService = TestBed.inject(ErasureCodeProfileService); crushRuleService = TestBed.inject(CrushRuleService); router = TestBed.inject(Router); navigationSpy = spyOn(router, 'navigate').and.stub(); authStorageService = TestBed.inject(AuthStorageService); spyOn(authStorageService, 'getPermissions').and.callFake(() => ({ pool: poolPermissions })); poolPermissions = new Permission(['update', 'delete', 'read', 'create']); setUpPoolComponent(); component.loadingReady(); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('throws error for not allowed users', () => { const expectError = (redirected: boolean) => { navigationSpy.calls.reset(); if (redirected) { expect(() => component.authenticate()).toThrowError(DashboardNotFoundError); } else { expect(() => component.authenticate()).not.toThrowError(); } }; beforeEach(() => { poolPermissions = new Permission(['delete']); }); it('navigates to Dashboard if not allowed', () => { expect(() => component.authenticate()).toThrowError(DashboardNotFoundError); }); it('throws error if user is not allowed', () => { expectError(true); poolPermissions.read = true; expectError(true); poolPermissions.delete = true; expectError(true); poolPermissions.update = true; expectError(true); component.editing = true; poolPermissions.update = false; poolPermissions.create = true; expectError(true); }); it('does not throw error for users with right permissions', () => { poolPermissions.read = true; poolPermissions.create = true; expectError(false); component.editing = true; poolPermissions.update = true; expectError(false); poolPermissions.create = false; expectError(false); }); }); describe('pool form validation', () => { beforeEach(() => { fixture.detectChanges(); }); it('is invalid at the beginning all sub forms are valid', () => { expect(form.valid).toBeFalsy(); ['name', 'poolType', 'pgNum'].forEach((name) => formHelper.expectError(name, 'required')); ['size', 'crushRule', 'erasureProfile', 'ecOverwrites'].forEach((name) => formHelper.expectValid(name) ); expect(component.form.get('compression').valid).toBeTruthy(); }); it('validates name', () => { expect(component.editing).toBeFalsy(); formHelper.expectError('name', 'required'); formHelper.expectValidChange('name', 'some-name'); formHelper.expectValidChange('name', 'name/with/slash'); formHelper.expectErrorChange('name', 'someExistingPoolName', 'uniqueName'); formHelper.expectErrorChange('name', 'wrong format with spaces', 'pattern'); }); it('should validate with dots in pool name', () => { formHelper.expectValidChange('name', 'pool.default.bar', true); }); it('validates poolType', () => { formHelper.expectError('poolType', 'required'); formHelper.expectValidChange('poolType', 'erasure'); formHelper.expectValidChange('poolType', 'replicated'); }); it('validates that pgNum is required creation mode', () => { formHelper.expectError(form.get('pgNum'), 'required'); }); it('validates pgNum in edit mode', () => { component.data.pool = new Pool('test'); component.data.pool.pg_num = 16; component.editing = true; component.ngOnInit(); // Switches form into edit mode formHelper.setValue('poolType', 'erasure'); fixture.detectChanges(); formHelper.expectValid(setPgNum(8)); }); it('is valid if pgNum, poolType and name are valid', () => { formHelper.setValue('name', 'some-name'); formHelper.setValue('poolType', 'erasure'); fixture.detectChanges(); setPgNum(1); expect(form.valid).toBeTruthy(); }); it('validates crushRule with multiple crush rules', () => { formHelper.expectValidChange('poolType', 'replicated'); form.get('crushRule').updateValueAndValidity(); formHelper.expectError('crushRule', 'required'); // As multiple rules exist }); it('validates crushRule with no crush rules', () => { infoReturn.crush_rules_replicated = []; setUpPoolComponent(); formHelper.expectValidChange('poolType', 'replicated'); formHelper.expectValid('crushRule'); }); it('validates size', () => { component.info.nodes = Mocks.getCrushMap(); formHelper.setValue('poolType', 'replicated'); formHelper.expectValid('size'); }); it('validates if warning is displayed when size is 1', () => { formHelper.setValue('poolType', 'replicated'); formHelper.expectValid('size'); formHelper.setValue('size', 1, true); expect(fixtureHelper.getElementByCss('#size ~ .text-warning-dark')).toBeTruthy(); formHelper.setValue('size', 2, true); expect(fixtureHelper.getElementByCss('#size ~ .text-warning-dark')).toBeFalsy(); }); it('validates compression mode default value', () => { expect(form.getValue('mode')).toBe('none'); }); it('validate quotas', () => { formHelper.expectValid('max_bytes'); formHelper.expectValid('max_objects'); formHelper.expectValidChange('max_bytes', '10 Gib'); formHelper.expectValidChange('max_bytes', ''); formHelper.expectValidChange('max_objects', ''); formHelper.expectErrorChange('max_objects', -1, 'min'); }); describe('compression form', () => { beforeEach(() => { formHelper.setValue('poolType', 'replicated'); formHelper.setValue('mode', 'passive'); }); it('is valid', () => { expect(component.form.get('compression').valid).toBeTruthy(); }); it('validates minBlobSize to be only valid between 0 and maxBlobSize', () => { formHelper.expectErrorChange('minBlobSize', -1, 'min'); formHelper.expectValidChange('minBlobSize', 0); formHelper.setValue('maxBlobSize', '2 KiB'); formHelper.expectErrorChange('minBlobSize', '3 KiB', 'maximum'); formHelper.expectValidChange('minBlobSize', '1.9 KiB'); }); it('validates minBlobSize converts numbers', () => { const control = formHelper.setValue('minBlobSize', '1'); fixture.detectChanges(); formHelper.expectValid(control); expect(control.value).toBe('1 KiB'); }); it('validates maxBlobSize to be only valid bigger than minBlobSize', () => { formHelper.expectErrorChange('maxBlobSize', -1, 'min'); formHelper.setValue('minBlobSize', '1 KiB'); formHelper.expectErrorChange('maxBlobSize', '0.5 KiB', 'minimum'); formHelper.expectValidChange('maxBlobSize', '1.5 KiB'); }); it('s valid to only use one blob size', () => { formHelper.expectValid(formHelper.setValue('minBlobSize', '1 KiB')); formHelper.expectValid(formHelper.setValue('maxBlobSize', '')); formHelper.expectValid(formHelper.setValue('minBlobSize', '')); formHelper.expectValid(formHelper.setValue('maxBlobSize', '1 KiB')); }); it('dismisses any size error if one of the blob sizes is changed into a valid state', () => { const min = formHelper.setValue('minBlobSize', '10 KiB'); const max = formHelper.setValue('maxBlobSize', '1 KiB'); fixture.detectChanges(); max.setValue(''); formHelper.expectValid(min); formHelper.expectValid(max); max.setValue('1 KiB'); fixture.detectChanges(); min.setValue('0.5 KiB'); formHelper.expectValid(min); formHelper.expectValid(max); }); it('validates maxBlobSize converts numbers', () => { const control = formHelper.setValue('maxBlobSize', '2'); fixture.detectChanges(); expect(control.value).toBe('2 KiB'); }); it('validates that odd size validator works as expected', () => { const odd = (min: string, max: string) => component['oddBlobSize'](min, max); expect(odd('10', '8')).toBe(true); expect(odd('8', '-')).toBe(false); expect(odd('8', '10')).toBe(false); expect(odd(null, '8')).toBe(false); expect(odd('10', '')).toBe(false); expect(odd('10', null)).toBe(false); expect(odd(null, null)).toBe(false); }); it('validates ratio to be only valid between 0 and 1', () => { formHelper.expectValid('ratio'); formHelper.expectErrorChange('ratio', -0.1, 'min'); formHelper.expectValidChange('ratio', 0); formHelper.expectValidChange('ratio', 1); formHelper.expectErrorChange('ratio', 1.1, 'max'); }); }); it('validates application metadata name', () => { formHelper.setValue('poolType', 'replicated'); fixture.detectChanges(); const selectBadges = fixture.debugElement.query(By.directive(SelectBadgesComponent)) .componentInstance; const control = selectBadges.cdSelect.filter; formHelper.expectValid(control); control.setValue('?'); formHelper.expectError(control, 'pattern'); control.setValue('Ab3_'); formHelper.expectValid(control); control.setValue('a'.repeat(129)); formHelper.expectError(control, 'maxlength'); }); }); describe('pool type changes', () => { beforeEach(() => { component.ngOnInit(); }); it('should have a default replicated size of 3', () => { formHelper.setValue('poolType', 'replicated'); expect(form.getValue('size')).toBe(3); }); describe('replicatedRuleChange', () => { beforeEach(() => { formHelper.setValue('poolType', 'replicated'); formHelper.setValue('size', 99); }); it('should not set size if a replicated pool is not set', () => { formHelper.setValue('poolType', 'erasure'); expect(form.getValue('size')).toBe(99); formHelper.setValue('crushRule', component.info.crush_rules_replicated[1]); expect(form.getValue('size')).toBe(99); }); it('should set size to maximum if size exceeds maximum', () => { formHelper.setValue('crushRule', component.info.crush_rules_replicated[0]); expect(form.getValue('size')).toBe(10); }); it('should set size to minimum if size is lower than minimum', () => { formHelper.setValue('size', -1); formHelper.setValue('crushRule', component.info.crush_rules_replicated[0]); expect(form.getValue('size')).toBe(1); }); }); describe('rulesChange', () => { it('has no effect if info is not there', () => { delete component.info; formHelper.setValue('poolType', 'replicated'); expect(component.current.rules).toEqual([]); }); it('has no effect if pool type is not set', () => { component['poolTypeChange'](''); expect(component.current.rules).toEqual([]); }); it('shows all replicated rules when pool type is "replicated"', () => { formHelper.setValue('poolType', 'replicated'); expect(component.current.rules).toEqual(component.info.crush_rules_replicated); expect(component.current.rules.length).toBe(3); }); it('shows all erasure code rules when pool type is "erasure"', () => { formHelper.setValue('poolType', 'erasure'); expect(component.current.rules).toEqual(component.info.crush_rules_erasure); expect(component.current.rules.length).toBe(1); }); it('disables rule field if only one rule exists which is used in the disabled field', () => { infoReturn.crush_rules_replicated = [ Mocks.getCrushRule({ id: 0, name: 'rep1', type: 'replicated' }) ]; setUpPoolComponent(); formHelper.setValue('poolType', 'replicated'); const control = form.get('crushRule'); expect(control.value).toEqual(component.info.crush_rules_replicated[0]); expect(control.disabled).toBe(true); }); it('does not select the first rule if more than one exist', () => { formHelper.setValue('poolType', 'replicated'); const control = form.get('crushRule'); expect(control.value).toEqual(null); expect(control.disabled).toBe(false); }); it('changing between both pool types will not forget the crush rule selection', () => { formHelper.setValue('poolType', 'replicated'); const control = form.get('crushRule'); const currentRule = component.info.crush_rules_replicated[0]; control.setValue(currentRule); formHelper.setValue('poolType', 'erasure'); formHelper.setValue('poolType', 'replicated'); expect(control.value).toEqual(currentRule); }); }); }); describe('getMaxSize and getMinSize', () => { it('returns 0 if osd count is 0', () => { component.info.osd_count = 0; expect(component.getMinSize()).toBe(0); expect(component.getMaxSize()).toBe(0); }); it('returns 0 if info is not there', () => { delete component.info; expect(component.getMinSize()).toBe(0); expect(component.getMaxSize()).toBe(0); }); it('returns 1 as minimum and 3 as maximum if no crush rule is available', () => { expect(component.getMinSize()).toBe(1); expect(component.getMaxSize()).toBe(3); }); it('should return the osd count as minimum if its lower the the rule minimum', () => { component.info.osd_count = 0; formHelper.setValue('crushRule', component.info.crush_rules_replicated[0]); const control = form.get('crushRule'); expect(control.invalid).toBe(true); formHelper.expectError(control, 'tooFewOsds'); }); it('should get the right maximum if the device type is defined', () => { formHelper.setValue('crushRule', Mocks.getCrushRule({ itemName: 'default~ssd' })); expect(form.getValue('crushRule').usable_size).toBe(10); }); }); describe('application metadata', () => { let selectBadges: SelectBadgesComponent; const testAddApp = (app?: string, result?: string[]) => { selectBadges.cdSelect.filter.setValue(app); selectBadges.cdSelect.updateFilter(); selectBadges.cdSelect.selectOption(); expect(component.data.applications.selected).toEqual(result); }; const testRemoveApp = (app: string, result: string[]) => { selectBadges.cdSelect.removeItem(app); expect(component.data.applications.selected).toEqual(result); }; const setCurrentApps = (apps: string[]) => { component.data.applications.selected = apps; fixture.detectChanges(); selectBadges.cdSelect.ngOnInit(); return apps; }; beforeEach(() => { formHelper.setValue('poolType', 'replicated'); fixture.detectChanges(); selectBadges = fixture.debugElement.query(By.directive(SelectBadgesComponent)) .componentInstance; }); it('adds all predefined and a custom applications to the application metadata array', () => { testAddApp('g', ['rgw']); testAddApp('b', ['rbd', 'rgw']); testAddApp('c', ['cephfs', 'rbd', 'rgw']); testAddApp('ownApp', ['cephfs', 'ownApp', 'rbd', 'rgw']); }); it('only allows 4 apps to be added to the array', () => { const apps = setCurrentApps(['d', 'c', 'b', 'a']); testAddApp('e', apps); }); it('can remove apps', () => { setCurrentApps(['a', 'b', 'c', 'd']); testRemoveApp('c', ['a', 'b', 'd']); testRemoveApp('a', ['b', 'd']); testRemoveApp('d', ['b']); testRemoveApp('b', []); }); it('does not remove any app that is not in the array', () => { const apps = ['a', 'b', 'c', 'd']; setCurrentApps(apps); testRemoveApp('e', apps); testRemoveApp('0', apps); }); }); describe('pg number changes', () => { beforeEach(() => { formHelper.setValue('crushRule', { min_size: 1, max_size: 20 }); formHelper.setValue('poolType', 'erasure'); fixture.detectChanges(); setPgNum(256); }); it('updates by value', () => { testPgUpdate(10, undefined, 8); testPgUpdate(22, undefined, 16); testPgUpdate(26, undefined, 32); testPgUpdate(200, undefined, 256); testPgUpdate(300, undefined, 256); testPgUpdate(350, undefined, 256); }); it('updates by jump -> a magnitude of the power of 2', () => { testPgUpdate(undefined, 1, 512); testPgUpdate(undefined, -1, 256); }); it('returns 1 as minimum for false numbers', () => { testPgUpdate(-26, undefined, 1); testPgUpdate(0, undefined, 1); testPgUpdate(0, -1, 1); testPgUpdate(undefined, -20, 1); }); it('changes the value and than jumps', () => { testPgUpdate(230, 1, 512); testPgUpdate(3500, -1, 2048); }); describe('pg power jump', () => { it('should jump correctly at the beginning', () => { testPgUpdate(1, -1, 1); testPgUpdate(1, 1, 2); testPgUpdate(2, -1, 1); testPgUpdate(2, 1, 4); testPgUpdate(4, -1, 2); testPgUpdate(4, 1, 8); testPgUpdate(4, 1, 8); }); it('increments pg power if difference to the current number is 1', () => { testPgUpdate(undefined, 1, 512); testPgUpdate(undefined, 1, 1024); testPgUpdate(undefined, 1, 2048); testPgUpdate(undefined, 1, 4096); }); it('decrements pg power if difference to the current number is -1', () => { testPgUpdate(undefined, -1, 128); testPgUpdate(undefined, -1, 64); testPgUpdate(undefined, -1, 32); testPgUpdate(undefined, -1, 16); testPgUpdate(undefined, -1, 8); }); }); describe('pgCalc', () => { const PGS = 1; OSDS = 8; const getValidCase = () => ({ type: 'replicated', osds: OSDS, size: 4, ecp: { k: 2, m: 2 }, expected: 256 }); const testPgCalc = ({ type, osds, size, ecp, expected }: Record<string, any>) => { component.info.osd_count = osds; formHelper.setValue('poolType', type); if (type === 'replicated') { formHelper.setValue('size', size); } else { formHelper.setValue('erasureProfile', ecp); } expect(form.getValue('pgNum')).toBe(expected); expect(component.externalPgChange).toBe(PGS !== expected); }; beforeEach(() => { setPgNum(PGS); }); it('does not change anything if type is not valid', () => { const test = getValidCase(); test.type = ''; test.expected = PGS; testPgCalc(test); }); it('does not change anything if ecp is not valid', () => { const test = getValidCase(); test.expected = PGS; test.type = 'erasure'; test.ecp = null; testPgCalc(test); }); it('calculates some replicated values', () => { const test = getValidCase(); testPgCalc(test); test.osds = 16; test.expected = 512; testPgCalc(test); test.osds = 8; test.size = 8; test.expected = 128; testPgCalc(test); }); it('calculates erasure code values even if selection is disabled', () => { component['initEcp']([{ k: 2, m: 2, name: 'bla', plugin: '', technique: '' }]); const test = getValidCase(); test.type = 'erasure'; testPgCalc(test); expect(form.get('erasureProfile').disabled).toBeTruthy(); }); it('calculates some erasure code values', () => { const test = getValidCase(); test.type = 'erasure'; testPgCalc(test); test.osds = 16; test.ecp.m = 5; test.expected = 256; testPgCalc(test); test.ecp.k = 5; test.expected = 128; testPgCalc(test); }); it('should not change a manual set pg number', () => { form.get('pgNum').markAsDirty(); const test = getValidCase(); test.expected = PGS; testPgCalc(test); }); }); }); describe('crushRule', () => { const selectRuleByIndex = (n: number) => { formHelper.setValue('crushRule', component.info.crush_rules_replicated[n]); }; beforeEach(() => { formHelper.setValue('poolType', 'replicated'); selectRuleByIndex(0); fixture.detectChanges(); }); it('should select the newly created rule', () => { expect(form.getValue('crushRule').rule_name).toBe('rep1'); const name = 'awesomeRule'; spyOn(TestBed.inject(ModalService), 'show').and.callFake(() => { return { componentInstance: { submitAction: of({ name }) } }; }); infoReturn.crush_rules_replicated.push(Mocks.getCrushRule({ id: 8, name })); component.addCrushRule(); expect(form.getValue('crushRule').rule_name).toBe(name); }); it('should not show info per default', () => { fixtureHelper.expectElementVisible('#crushRule', true); fixtureHelper.expectElementVisible('#crush-info-block', false); }); it('should show info if the info button is clicked', () => { const infoButton = fixture.debugElement.query(By.css('#crush-info-button')); infoButton.triggerEventHandler('click', null); expect(component.data.crushInfo).toBeTruthy(); fixture.detectChanges(); expect(infoButton.classes['active']).toBeTruthy(); fixtureHelper.expectIdElementsVisible(['crushRule', 'crush-info-block'], true); }); it('should know which rules are in use', () => { selectRuleByIndex(2); expect(component.crushUsage).toEqual(['some.pool.uses.it']); }); describe('crush rule deletion', () => { let taskWrapper: TaskWrapperService; let deletion: CriticalConfirmationModalComponent; let deleteSpy: jasmine.Spy; let modalSpy: jasmine.Spy; const callDeletion = () => { component.deleteCrushRule(); deletion.submitActionObservable(); }; const callDeletionWithRuleByIndex = (index: number) => { deleteSpy.calls.reset(); selectRuleByIndex(index); callDeletion(); }; const expectSuccessfulDeletion = (name: string) => { expect(crushRuleService.delete).toHaveBeenCalledWith(name); expect(taskWrapper.wrapTaskAroundCall).toHaveBeenCalledWith( expect.objectContaining({ task: { name: 'crushRule/delete', metadata: { name: name } } }) ); }; beforeEach(() => { modalSpy = spyOn(TestBed.inject(ModalService), 'show').and.callFake( (deletionClass: any, initialState: any) => { deletion = Object.assign(new deletionClass(), initialState); return { componentInstance: deletion }; } ); deleteSpy = spyOn(crushRuleService, 'delete').and.callFake((name: string) => { const rules = infoReturn.crush_rules_replicated; const index = _.findIndex(rules, (rule) => rule.rule_name === name); rules.splice(index, 1); return of(undefined); }); taskWrapper = TestBed.inject(TaskWrapperService); spyOn(taskWrapper, 'wrapTaskAroundCall').and.callThrough(); }); describe('with unused rule', () => { beforeEach(() => { callDeletionWithRuleByIndex(0); }); it('should have called delete', () => { expectSuccessfulDeletion('rep1'); }); it('should not open the tooltip nor the crush info', () => { expect(component.crushDeletionBtn.isOpen()).toBe(false); expect(component.data.crushInfo).toBe(false); }); it('should reload the rules after deletion', () => { const expected = infoReturn.crush_rules_replicated; const currentRules = component.current.rules; expect(currentRules.length).toBe(expected.length); expect(currentRules).toEqual(expected); }); }); describe('rule in use', () => { beforeEach(() => { spyOn(global, 'setTimeout').and.callFake((fn: Function) => fn()); deleteSpy.calls.reset(); selectRuleByIndex(2); component.deleteCrushRule(); }); it('should not have called delete and opened the tooltip', () => { expect(crushRuleService.delete).not.toHaveBeenCalled(); expect(component.crushDeletionBtn.isOpen()).toBe(true); expect(component.data.crushInfo).toBe(true); }); it('should hide the tooltip when clicking on delete again', () => { component.deleteCrushRule(); expect(component.crushDeletionBtn.isOpen()).toBe(false); }); it('should hide the tooltip when clicking on add', () => { modalSpy.and.callFake((): any => ({ componentInstance: { submitAction: of('someRule') } })); component.addCrushRule(); expect(component.crushDeletionBtn.isOpen()).toBe(false); }); it('should hide the tooltip when changing the crush rule', () => { selectRuleByIndex(0); expect(component.crushDeletionBtn.isOpen()).toBe(false); }); }); }); }); describe('erasure code profile', () => { const setSelectedEcp = (name: string) => { formHelper.setValue('erasureProfile', { name: name }); }; beforeEach(() => { formHelper.setValue('poolType', 'erasure'); fixture.detectChanges(); }); it('should not show info per default', () => { fixtureHelper.expectElementVisible('#erasureProfile', true); fixtureHelper.expectElementVisible('#ecp-info-block', false); }); it('should show info if the info button is clicked', () => { const infoButton = fixture.debugElement.query(By.css('#ecp-info-button')); infoButton.triggerEventHandler('click', null); expect(component.data.erasureInfo).toBeTruthy(); fixture.detectChanges(); expect(infoButton.classes['active']).toBeTruthy(); fixtureHelper.expectIdElementsVisible(['erasureProfile', 'ecp-info-block'], true); }); it('should select the newly created profile', () => { spyOn(ecpService, 'list').and.callFake(() => of(infoReturn.erasure_code_profiles)); expect(form.getValue('erasureProfile').name).toBe('ecp1'); const name = 'awesomeProfile'; spyOn(TestBed.inject(ModalService), 'show').and.callFake(() => { return { componentInstance: { submitAction: of({ name }) } }; }); const ecp2 = new ErasureCodeProfile(); ecp2.name = name; infoReturn.erasure_code_profiles.push(ecp2); component.addErasureCodeProfile(); expect(form.getValue('erasureProfile').name).toBe(name); }); describe('ecp deletion', () => { let taskWrapper: TaskWrapperService; let deletion: CriticalConfirmationModalComponent; let deleteSpy: jasmine.Spy; let modalSpy: jasmine.Spy; let modal: NgbModalRef; const callEcpDeletion = () => { component.deleteErasureCodeProfile(); modal.componentInstance.callSubmitAction(); }; const expectSuccessfulEcpDeletion = (name: string) => { setSelectedEcp(name); callEcpDeletion(); expect(ecpService.delete).toHaveBeenCalledWith(name); expect(taskWrapper.wrapTaskAroundCall).toHaveBeenCalledWith( expect.objectContaining({ task: { name: 'ecp/delete', metadata: { name: name } } }) ); }; beforeEach(() => { deletion = undefined; modalSpy = spyOn(TestBed.inject(ModalService), 'show').and.callFake( (comp: any, init: any) => { modal = modalServiceShow(comp, init); return modal; } ); deleteSpy = spyOn(ecpService, 'delete').and.callFake((name: string) => { const profiles = infoReturn.erasure_code_profiles; const index = _.findIndex(profiles, (profile) => profile.name === name); profiles.splice(index, 1); return of({ status: 202 }); }); taskWrapper = TestBed.inject(TaskWrapperService); spyOn(taskWrapper, 'wrapTaskAroundCall').and.callThrough(); const ecp2 = new ErasureCodeProfile(); ecp2.name = 'someEcpName'; infoReturn.erasure_code_profiles.push(ecp2); const ecp3 = new ErasureCodeProfile(); ecp3.name = 'aDifferentEcpName'; infoReturn.erasure_code_profiles.push(ecp3); }); it('should delete two different erasure code profiles', () => { expectSuccessfulEcpDeletion('someEcpName'); expectSuccessfulEcpDeletion('aDifferentEcpName'); }); describe('with unused profile', () => { beforeEach(() => { expectSuccessfulEcpDeletion('someEcpName'); }); it('should not open the tooltip nor the crush info', () => { expect(component.ecpDeletionBtn.isOpen()).toBe(false); expect(component.data.erasureInfo).toBe(false); }); it('should reload the rules after deletion', () => { const expected = infoReturn.erasure_code_profiles; const currentProfiles = component.info.erasure_code_profiles; expect(currentProfiles.length).toBe(expected.length); expect(currentProfiles).toEqual(expected); }); }); describe('rule in use', () => { beforeEach(() => { spyOn(global, 'setTimeout').and.callFake((fn: Function) => fn()); deleteSpy.calls.reset(); setSelectedEcp('ecp1'); component.deleteErasureCodeProfile(); }); it('should not open the modal', () => { expect(deletion).toBe(undefined); }); it('should not have called delete and opened the tooltip', () => { expect(ecpService.delete).not.toHaveBeenCalled(); expect(component.ecpDeletionBtn.isOpen()).toBe(true); expect(component.data.erasureInfo).toBe(true); }); it('should hide the tooltip when clicking on delete again', () => { component.deleteErasureCodeProfile(); expect(component.ecpDeletionBtn.isOpen()).toBe(false); }); it('should hide the tooltip when clicking on add', () => { modalSpy.and.callFake((): any => ({ componentInstance: { submitAction: of('someProfile') } })); component.addErasureCodeProfile(); expect(component.ecpDeletionBtn.isOpen()).toBe(false); }); it('should hide the tooltip when changing the crush rule', () => { setSelectedEcp('someEcpName'); expect(component.ecpDeletionBtn.isOpen()).toBe(false); }); }); }); }); describe('submit - create', () => { const setMultipleValues = (settings: object) => { Object.keys(settings).forEach((name) => { formHelper.setValue(name, settings[name]); }); }; describe('erasure coded pool', () => { const expectEcSubmit = (o: any) => expectValidSubmit( Object.assign( { pool: 'ecPool', pool_type: 'erasure', pg_autoscale_mode: 'off', erasure_code_profile: 'ecp1', pg_num: 4 }, o ) ); beforeEach(() => { setMultipleValues({ name: 'ecPool', poolType: 'erasure', pgNum: 4 }); }); it('minimum requirements without ECP to create ec pool', () => { // Mock that no ec profiles exist infoReturn.erasure_code_profiles = []; setUpPoolComponent(); setMultipleValues({ name: 'minECPool', poolType: 'erasure', pgNum: 4 }); expectValidSubmit({ pool: 'minECPool', pool_type: 'erasure', pg_autoscale_mode: 'off', pg_num: 4 }); }); it('creates ec pool with erasure coded profile', () => { const ecp = { name: 'ecpMinimalMock' }; setMultipleValues({ erasureProfile: ecp }); expectEcSubmit({ erasure_code_profile: ecp.name }); }); it('creates ec pool with ec_overwrite flag', () => { setMultipleValues({ ecOverwrites: true }); expectEcSubmit({ flags: ['ec_overwrites'] }); }); it('should ignore replicated set settings for ec pools', () => { setMultipleValues({ size: 2 // will be ignored }); expectEcSubmit({}); }); it('creates a pool with compression', () => { setMultipleValues({ mode: 'passive', algorithm: 'lz4', minBlobSize: '4 K', maxBlobSize: '4 M', ratio: 0.7 }); expectEcSubmit({ compression_mode: 'passive', compression_algorithm: 'lz4', compression_min_blob_size: 4096, compression_max_blob_size: 4194304, compression_required_ratio: 0.7 }); }); it('creates a pool with application metadata', () => { component.data.applications.selected = ['cephfs', 'rgw']; expectEcSubmit({ application_metadata: ['cephfs', 'rgw'] }); }); }); describe('with replicated pool', () => { const expectReplicatedSubmit = (o: any) => expectValidSubmit( Object.assign( { pool: 'repPool', pool_type: 'replicated', pg_autoscale_mode: 'off', pg_num: 16, rule_name: 'rep1', size: 3 }, o ) ); beforeEach(() => { setMultipleValues({ name: 'repPool', poolType: 'replicated', crushRule: infoReturn.crush_rules_replicated[0], size: 3, pgNum: 16 }); }); it('uses the minimum requirements for replicated pools', () => { // Mock that no replicated rules exist infoReturn.crush_rules_replicated = []; setUpPoolComponent(); setMultipleValues({ name: 'minRepPool', poolType: 'replicated', size: 2, pgNum: 32 }); expectValidSubmit({ pool: 'minRepPool', pool_type: 'replicated', pg_num: 32, pg_autoscale_mode: 'off', size: 2 }); }); it('ignores erasure only set settings for replicated pools', () => { setMultipleValues({ erasureProfile: { name: 'ecpMinimalMock' }, // Will be ignored ecOverwrites: true // Will be ignored }); /** * As pgCalc is triggered through profile changes, which is normally not possible, * if type `replicated` is set, pgNum will be set to 256 with the current rule for * a replicated pool. */ expectReplicatedSubmit({ pg_num: 256 }); }); it('creates a pool with quotas', () => { setMultipleValues({ max_bytes: 1024 * 1024, max_objects: 3000 }); expectReplicatedSubmit({ quota_max_bytes: 1024 * 1024, quota_max_objects: 3000 }); }); it('creates a pool with rbd qos settings', () => { component.currentConfigurationValues = { rbd_qos_bps_limit: 55 }; expectReplicatedSubmit({ configuration: { rbd_qos_bps_limit: 55 } }); }); }); }); describe('edit mode', () => { const setUrl = (url: string) => { Object.defineProperty(router, 'url', { value: url }); setUpPoolComponent(); // Renew of component needed because the constructor has to be called }; let pool: Pool; beforeEach(() => { pool = new Pool('somePoolName'); pool.type = 'replicated'; pool.size = 3; pool.crush_rule = 'rep1'; pool.pg_num = 32; pool.options = {}; pool.options.compression_mode = 'passive'; pool.options.compression_algorithm = 'lz4'; pool.options.compression_min_blob_size = 1024 * 512; pool.options.compression_max_blob_size = 1024 * 1024; pool.options.compression_required_ratio = 0.8; pool.flags_names = 'someFlag1,someFlag2'; pool.application_metadata = ['rbd', 'ownApp']; pool.quota_max_bytes = 1024 * 1024 * 1024; pool.quota_max_objects = 3000; Mocks.getCrushRule({ name: 'someRule' }); spyOn(poolService, 'get').and.callFake(() => of(pool)); }); it('is not in edit mode if edit is not included in url', () => { setUrl('/pool/add'); expect(component.editing).toBeFalsy(); }); it('is in edit mode if edit is included in url', () => { setUrl('/pool/edit/somePoolName'); expect(component.editing).toBeTruthy(); }); describe('after ngOnInit', () => { beforeEach(() => { setUrl('/pool/edit/somePoolName'); fixture.detectChanges(); }); it('disabled inputs', () => { fixture.detectChanges(); const disabled = ['poolType', 'crushRule', 'size', 'erasureProfile', 'ecOverwrites']; disabled.forEach((controlName) => { return expect(form.get(controlName).disabled).toBeTruthy(); }); const enabled = [ 'name', 'pgNum', 'mode', 'algorithm', 'minBlobSize', 'maxBlobSize', 'ratio', 'max_bytes', 'max_objects' ]; enabled.forEach((controlName) => { return expect(form.get(controlName).enabled).toBeTruthy(); }); }); it('should include the custom app as valid option', () => { expect( component.data.applications.available.map((app: Record<string, any>) => app.name) ).toEqual(['cephfs', 'ownApp', 'rbd', 'rgw']); }); it('set all control values to the given pool', () => { expect(form.getValue('name')).toBe(pool.pool_name); expect(form.getValue('poolType')).toBe(pool.type); expect(form.getValue('crushRule')).toEqual(component.info.crush_rules_replicated[0]); expect(form.getValue('size')).toBe(pool.size); expect(form.getValue('pgNum')).toBe(pool.pg_num); expect(form.getValue('mode')).toBe(pool.options.compression_mode); expect(form.getValue('algorithm')).toBe(pool.options.compression_algorithm); expect(form.getValue('minBlobSize')).toBe('512 KiB'); expect(form.getValue('maxBlobSize')).toBe('1 MiB'); expect(form.getValue('ratio')).toBe(pool.options.compression_required_ratio); expect(form.getValue('max_bytes')).toBe('1 GiB'); expect(form.getValue('max_objects')).toBe(pool.quota_max_objects); }); it('updates pgs on every change', () => { testPgUpdate(undefined, -1, 16); testPgUpdate(undefined, -1, 8); }); it('is possible to use less or more pgs than before', () => { formHelper.expectValid(setPgNum(64)); formHelper.expectValid(setPgNum(4)); }); describe('submit', () => { const markControlAsPreviouslySet = (controlName: string) => form.get(controlName).markAsPristine(); beforeEach(() => { [ 'algorithm', 'maxBlobSize', 'minBlobSize', 'mode', 'pgNum', 'ratio', 'name' ].forEach((name) => markControlAsPreviouslySet(name)); fixture.detectChanges(); }); it(`always provides the application metadata array with submit even if it's empty`, () => { expect(form.get('mode').dirty).toBe(false); component.data.applications.selected = []; expectValidSubmit( { application_metadata: [], pool: 'somePoolName' }, 'pool/edit', 'update' ); }); it(`will always provide reset value for compression options`, () => { formHelper.setValue('minBlobSize', '').markAsDirty(); formHelper.setValue('maxBlobSize', '').markAsDirty(); formHelper.setValue('ratio', '').markAsDirty(); expectValidSubmit( { application_metadata: ['ownApp', 'rbd'], compression_max_blob_size: 0, compression_min_blob_size: 0, compression_required_ratio: 0, pool: 'somePoolName' }, 'pool/edit', 'update' ); }); it(`will unset mode not used anymore`, () => { formHelper.setValue('mode', 'none').markAsDirty(); expectValidSubmit( { application_metadata: ['ownApp', 'rbd'], compression_mode: 'unset', pool: 'somePoolName' }, 'pool/edit', 'update' ); }); }); }); }); describe('test pool configuration component', () => { it('is visible for replicated pools with rbd application', () => { const poolType = component.form.get('poolType'); poolType.markAsDirty(); poolType.setValue('replicated'); component.data.applications.selected = ['rbd']; fixture.detectChanges(); expect( fixture.debugElement.query(By.css('cd-rbd-configuration-form')).nativeElement.parentElement .hidden ).toBe(false); }); it('is invisible for erasure coded pools', () => { const poolType = component.form.get('poolType'); poolType.markAsDirty(); poolType.setValue('erasure'); fixture.detectChanges(); expect( fixture.debugElement.query(By.css('cd-rbd-configuration-form')).nativeElement.parentElement .hidden ).toBe(true); }); }); });
48,478
32.783275
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool-form/pool-form.component.ts
import { Component, OnInit, Type, ViewChild } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { NgbNav, NgbTooltip } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { Observable, ReplaySubject, Subscription } from 'rxjs'; import { DashboardNotFoundError } from '~/app/core/error/error'; import { CrushRuleService } from '~/app/shared/api/crush-rule.service'; import { ErasureCodeProfileService } from '~/app/shared/api/erasure-code-profile.service'; import { PoolService } from '~/app/shared/api/pool.service'; import { CrushNodeSelectionClass } from '~/app/shared/classes/crush.node.selection.class'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { SelectOption } from '~/app/shared/components/select/select-option.model'; import { ActionLabelsI18n, URLVerbs } 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 { CdValidators } from '~/app/shared/forms/cd-validators'; import { RbdConfigurationEntry, RbdConfigurationSourceField } from '~/app/shared/models/configuration'; import { CrushRule } from '~/app/shared/models/crush-rule'; import { CrushStep } from '~/app/shared/models/crush-step'; import { ErasureCodeProfile } from '~/app/shared/models/erasure-code-profile'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { Permission } from '~/app/shared/models/permissions'; import { PoolFormInfo } from '~/app/shared/models/pool-form-info'; 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 { ModalService } from '~/app/shared/services/modal.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { CrushRuleFormModalComponent } from '../crush-rule-form-modal/crush-rule-form-modal.component'; import { ErasureCodeProfileFormModalComponent } from '../erasure-code-profile-form/erasure-code-profile-form-modal.component'; import { Pool } from '../pool'; import { PoolFormData } from './pool-form-data'; interface FormFieldDescription { externalFieldName: string; formControlName: string; attr?: string; replaceFn?: Function; editable?: boolean; resetValue?: any; } @Component({ selector: 'cd-pool-form', templateUrl: './pool-form.component.html', styleUrls: ['./pool-form.component.scss'] }) export class PoolFormComponent extends CdForm implements OnInit { @ViewChild('crushInfoTabs') crushInfoTabs: NgbNav; @ViewChild('crushDeletionBtn') crushDeletionBtn: NgbTooltip; @ViewChild('ecpInfoTabs') ecpInfoTabs: NgbNav; @ViewChild('ecpDeletionBtn') ecpDeletionBtn: NgbTooltip; permission: Permission; form: CdFormGroup; ecProfiles: ErasureCodeProfile[]; info: PoolFormInfo; routeParamsSubscribe: any; editing = false; isReplicated = false; isErasure = false; data = new PoolFormData(); externalPgChange = false; current: Record<string, any> = { rules: [] }; initializeConfigData = new ReplaySubject<{ initialData: RbdConfigurationEntry[]; sourceType: RbdConfigurationSourceField; }>(1); currentConfigurationValues: { [configKey: string]: any } = {}; action: string; resource: string; icons = Icons; pgAutoscaleModes: string[]; crushUsage: string[] = undefined; // Will only be set if a rule is used by some pool ecpUsage: string[] = undefined; // Will only be set if a rule is used by some pool crushRuleMaxSize = 10; private modalSubscription: Subscription; constructor( private dimlessBinaryPipe: DimlessBinaryPipe, private route: ActivatedRoute, private router: Router, private modalService: ModalService, private poolService: PoolService, private authStorageService: AuthStorageService, private formatter: FormatterService, private taskWrapper: TaskWrapperService, private ecpService: ErasureCodeProfileService, private crushRuleService: CrushRuleService, public actionLabels: ActionLabelsI18n ) { super(); this.editing = this.router.url.startsWith(`/pool/${URLVerbs.EDIT}`); this.action = this.editing ? this.actionLabels.EDIT : this.actionLabels.CREATE; this.resource = $localize`pool`; this.authenticate(); this.createForm(); } authenticate() { this.permission = this.authStorageService.getPermissions().pool; if ( !this.permission.read || (!this.permission.update && this.editing) || (!this.permission.create && !this.editing) ) { throw new DashboardNotFoundError(); } } private createForm() { const compressionForm = new CdFormGroup({ mode: new FormControl('none'), algorithm: new FormControl(''), minBlobSize: new FormControl('', { updateOn: 'blur' }), maxBlobSize: new FormControl('', { updateOn: 'blur' }), ratio: new FormControl('', { updateOn: 'blur' }) }); this.form = new CdFormGroup( { name: new FormControl('', { validators: [ Validators.pattern(/^[.A-Za-z0-9_/-]+$/), Validators.required, CdValidators.custom('rbdPool', () => { return ( this.form && this.form.getValue('name').includes('/') && this.data && this.data.applications.selected.indexOf('rbd') !== -1 ); }) ] }), poolType: new FormControl('', { validators: [Validators.required] }), crushRule: new FormControl(null, { validators: [ CdValidators.custom( 'tooFewOsds', (rule: any) => this.info && rule && this.info.osd_count < 1 ), CdValidators.custom( 'required', (rule: CrushRule) => this.isReplicated && this.info.crush_rules_replicated.length > 0 && !rule ) ] }), size: new FormControl('', { updateOn: 'blur' }), erasureProfile: new FormControl(null), pgNum: new FormControl('', { validators: [Validators.required] }), pgAutoscaleMode: new FormControl(null), ecOverwrites: new FormControl(false), compression: compressionForm, max_bytes: new FormControl(''), max_objects: new FormControl(0) }, [CdValidators.custom('form', (): null => null)] ); } ngOnInit() { this.poolService.getInfo().subscribe((info: PoolFormInfo) => { this.initInfo(info); if (this.editing) { this.initEditMode(); } else { this.setAvailableApps(); this.loadingReady(); } this.listenToChanges(); this.setComplexValidators(); }); } private initInfo(info: PoolFormInfo) { this.pgAutoscaleModes = info.pg_autoscale_modes; this.form.silentSet('pgAutoscaleMode', info.pg_autoscale_default_mode); this.form.silentSet('algorithm', info.bluestore_compression_algorithm); this.info = info; this.initEcp(info.erasure_code_profiles); } private initEcp(ecProfiles: ErasureCodeProfile[]) { this.setListControlStatus('erasureProfile', ecProfiles); this.ecProfiles = ecProfiles; } /** * Used to update the crush rule or erasure code profile listings. * * If only one rule or profile exists it will be selected. * If nothing exists null will be selected. * If more than one rule or profile exists the listing will be enabled, * otherwise disabled. */ private setListControlStatus(controlName: string, arr: any[]) { const control = this.form.get(controlName); const value = control.value; if (arr.length === 1 && (!value || !_.isEqual(value, arr[0]))) { control.setValue(arr[0]); } else if (arr.length === 0 && value) { control.setValue(null); } if (arr.length <= 1) { if (control.enabled) { control.disable(); } } else if (control.disabled) { control.enable(); } } private initEditMode() { this.disableForEdit(); this.routeParamsSubscribe = this.route.params.subscribe((param: { name: string }) => this.poolService.get(param.name).subscribe((pool: Pool) => { this.data.pool = pool; this.initEditFormData(pool); this.loadingReady(); }) ); } private disableForEdit() { ['poolType', 'crushRule', 'size', 'erasureProfile', 'ecOverwrites'].forEach((controlName) => this.form.get(controlName).disable() ); } private initEditFormData(pool: Pool) { this.initializeConfigData.next({ initialData: pool.configuration, sourceType: RbdConfigurationSourceField.pool }); this.poolTypeChange(pool.type); const rules = this.info.crush_rules_replicated.concat(this.info.crush_rules_erasure); const dataMap = { name: pool.pool_name, poolType: pool.type, crushRule: rules.find((rule: CrushRule) => rule.rule_name === pool.crush_rule), size: pool.size, erasureProfile: this.ecProfiles.find((ecp) => ecp.name === pool.erasure_code_profile), pgAutoscaleMode: pool.pg_autoscale_mode, pgNum: pool.pg_num, ecOverwrites: pool.flags_names.includes('ec_overwrites'), mode: pool.options.compression_mode, algorithm: pool.options.compression_algorithm, minBlobSize: this.dimlessBinaryPipe.transform(pool.options.compression_min_blob_size), maxBlobSize: this.dimlessBinaryPipe.transform(pool.options.compression_max_blob_size), ratio: pool.options.compression_required_ratio, max_bytes: this.dimlessBinaryPipe.transform(pool.quota_max_bytes), max_objects: pool.quota_max_objects }; Object.keys(dataMap).forEach((controlName: string) => { const value = dataMap[controlName]; if (!_.isUndefined(value) && value !== '') { this.form.silentSet(controlName, value); } }); this.data.pgs = this.form.getValue('pgNum'); this.setAvailableApps(this.data.applications.default.concat(pool.application_metadata)); this.data.applications.selected = pool.application_metadata; } private setAvailableApps(apps: string[] = this.data.applications.default) { this.data.applications.available = _.uniq(apps.sort()).map( (x: string) => new SelectOption(false, x, '') ); } private listenToChanges() { this.listenToChangesDuringAddEdit(); if (!this.editing) { this.listenToChangesDuringAdd(); } } private listenToChangesDuringAddEdit() { this.form.get('pgNum').valueChanges.subscribe((pgs) => { const change = pgs - this.data.pgs; if (Math.abs(change) !== 1 || pgs === 2) { this.data.pgs = pgs; return; } this.doPgPowerJump(change as 1 | -1); }); } private doPgPowerJump(jump: 1 | -1) { const power = this.calculatePgPower() + jump; this.setPgs(jump === -1 ? Math.round(power) : Math.floor(power)); } private calculatePgPower(pgs = this.form.getValue('pgNum')): number { return Math.log(pgs) / Math.log(2); } private setPgs(power: number) { const pgs = Math.pow(2, power < 0 ? 0 : power); // Set size the nearest accurate size. this.data.pgs = pgs; this.form.silentSet('pgNum', pgs); } private listenToChangesDuringAdd() { this.form.get('poolType').valueChanges.subscribe((poolType) => { this.poolTypeChange(poolType); }); this.form.get('crushRule').valueChanges.subscribe((rule) => { // The crush rule can only be changed if type 'replicated' is set. if (this.crushDeletionBtn && this.crushDeletionBtn.isOpen()) { this.crushDeletionBtn.close(); } if (!rule) { return; } this.setCorrectMaxSize(rule); this.crushRuleIsUsedBy(rule.rule_name); this.replicatedRuleChange(); this.pgCalc(); }); this.form.get('size').valueChanges.subscribe(() => { // The size can only be changed if type 'replicated' is set. this.pgCalc(); }); this.form.get('erasureProfile').valueChanges.subscribe((profile) => { // The ec profile can only be changed if type 'erasure' is set. if (this.ecpDeletionBtn && this.ecpDeletionBtn.isOpen()) { this.ecpDeletionBtn.close(); } if (!profile) { return; } this.ecpIsUsedBy(profile.name); this.pgCalc(); }); this.form.get('mode').valueChanges.subscribe(() => { ['minBlobSize', 'maxBlobSize', 'ratio'].forEach((name) => { this.form.get(name).updateValueAndValidity({ emitEvent: false }); }); }); this.form.get('minBlobSize').valueChanges.subscribe(() => { this.form.get('maxBlobSize').updateValueAndValidity({ emitEvent: false }); }); this.form.get('maxBlobSize').valueChanges.subscribe(() => { this.form.get('minBlobSize').updateValueAndValidity({ emitEvent: false }); }); } private poolTypeChange(poolType: string) { if (poolType === 'replicated') { this.setTypeBooleans(true, false); } else if (poolType === 'erasure') { this.setTypeBooleans(false, true); } else { this.setTypeBooleans(false, false); } if (!poolType || !this.info) { this.current.rules = []; return; } const rules = this.info['crush_rules_' + poolType] || []; this.current.rules = rules; if (this.editing) { return; } if (this.isReplicated) { this.setListControlStatus('crushRule', rules); } this.replicatedRuleChange(); this.pgCalc(); } private setTypeBooleans(replicated: boolean, erasure: boolean) { this.isReplicated = replicated; this.isErasure = erasure; } private replicatedRuleChange() { if (!this.isReplicated) { return; } const control = this.form.get('size'); let size = this.form.getValue('size') || 3; const min = this.getMinSize(); const max = this.getMaxSize(); if (size < min) { size = min; } else if (size > max) { size = max; } if (size !== control.value) { this.form.silentSet('size', size); } } getMinSize(): number { if (!this.info || this.info.osd_count < 1) { return 0; } return 1; } getMaxSize(): number { const rule = this.form.getValue('crushRule'); if (!this.info) { return 0; } if (!rule) { const osds = this.info.osd_count; const defaultSize = 3; return Math.min(osds, defaultSize); } return rule.usable_size; } private pgCalc() { const poolType = this.form.getValue('poolType'); if (!this.info || this.form.get('pgNum').dirty || !poolType) { return; } const pgMax = this.info.osd_count * 100; const pgs = this.isReplicated ? this.replicatedPgCalc(pgMax) : this.erasurePgCalc(pgMax); if (!pgs) { return; } const oldValue = this.data.pgs; this.alignPgs(pgs); const newValue = this.data.pgs; if (!this.externalPgChange) { this.externalPgChange = oldValue !== newValue; } } private setCorrectMaxSize(rule: CrushRule = this.form.getValue('crushRule')) { if (!rule) { return; } const domains = CrushNodeSelectionClass.searchFailureDomains( this.info.nodes, rule.steps[0].item_name ); const currentDomain = domains[rule.steps[1].type]; const usable = currentDomain ? currentDomain.length : this.crushRuleMaxSize; rule.usable_size = Math.min(usable, this.crushRuleMaxSize); } private replicatedPgCalc(pgs: number): number { const sizeControl = this.form.get('size'); const size = sizeControl.value; return sizeControl.valid && size > 0 ? pgs / size : 0; } private erasurePgCalc(pgs: number): number { const ecpControl = this.form.get('erasureProfile'); const ecp = ecpControl.value; return (ecpControl.valid || ecpControl.disabled) && ecp ? pgs / (ecp.k + ecp.m) : 0; } alignPgs(pgs = this.form.getValue('pgNum')) { this.setPgs(Math.round(this.calculatePgPower(pgs < 1 ? 1 : pgs))); } private setComplexValidators() { if (this.editing) { this.form .get('name') .setValidators([ this.form.get('name').validator, CdValidators.custom( 'uniqueName', (name: string) => this.data.pool && this.info && this.info.pool_names.indexOf(name) !== -1 && this.info.pool_names.indexOf(name) !== this.info.pool_names.indexOf(this.data.pool.pool_name) ) ]); } else { CdValidators.validateIf(this.form.get('size'), () => this.isReplicated, [ CdValidators.custom( 'min', (value: number) => this.form.getValue('size') && value < this.getMinSize() ), CdValidators.custom( 'max', (value: number) => this.form.getValue('size') && this.getMaxSize() < value ) ]); this.form .get('name') .setValidators([ this.form.get('name').validator, CdValidators.custom( 'uniqueName', (name: string) => this.info && this.info.pool_names.indexOf(name) !== -1 ) ]); } this.setCompressionValidators(); } private setCompressionValidators() { CdValidators.validateIf(this.form.get('minBlobSize'), () => this.hasCompressionEnabled(), [ Validators.min(0), CdValidators.custom('maximum', (size: string) => this.oddBlobSize(size, this.form.getValue('maxBlobSize')) ) ]); CdValidators.validateIf(this.form.get('maxBlobSize'), () => this.hasCompressionEnabled(), [ Validators.min(0), CdValidators.custom('minimum', (size: string) => this.oddBlobSize(this.form.getValue('minBlobSize'), size) ) ]); CdValidators.validateIf(this.form.get('ratio'), () => this.hasCompressionEnabled(), [ Validators.min(0), Validators.max(1) ]); } private oddBlobSize(minimum: string, maximum: string) { const min = this.formatter.toBytes(minimum); const max = this.formatter.toBytes(maximum); return Boolean(min && max && min >= max); } hasCompressionEnabled() { return this.form.getValue('mode') && this.form.get('mode').value.toLowerCase() !== 'none'; } describeCrushStep(step: CrushStep) { return [ step.op.replace('_', ' '), step.item_name || '', step.type ? step.num + ' type ' + step.type : '' ].join(' '); } addErasureCodeProfile() { this.addModal(ErasureCodeProfileFormModalComponent, (name) => this.reloadECPs(name)); } private addModal(modalComponent: Type<any>, reload: (name: string) => void) { this.hideOpenTooltips(); const modalRef = this.modalService.show(modalComponent); modalRef.componentInstance.submitAction.subscribe((item: any) => { reload(item.name); }); } private hideOpenTooltips() { const hideTooltip = (btn: NgbTooltip) => btn && btn.isOpen() && btn.close(); hideTooltip(this.ecpDeletionBtn); hideTooltip(this.crushDeletionBtn); } private reloadECPs(profileName?: string) { this.reloadList({ newItemName: profileName, getInfo: () => this.ecpService.list(), initInfo: (profiles) => this.initEcp(profiles), findNewItem: () => this.ecProfiles.find((p) => p.name === profileName), controlName: 'erasureProfile' }); } private reloadList({ newItemName, getInfo, initInfo, findNewItem, controlName }: { newItemName: string; getInfo: () => Observable<any>; initInfo: (items: any) => void; findNewItem: () => any; controlName: string; }) { if (this.modalSubscription) { this.modalSubscription.unsubscribe(); } getInfo().subscribe((items: any) => { initInfo(items); if (!newItemName) { return; } const item = findNewItem(); if (item) { this.form.get(controlName).setValue(item); } }); } deleteErasureCodeProfile() { this.deletionModal({ value: this.form.getValue('erasureProfile'), usage: this.ecpUsage, deletionBtn: this.ecpDeletionBtn, dataName: 'erasureInfo', getTabs: () => this.ecpInfoTabs, tabPosition: 'used-by-pools', nameAttribute: 'name', itemDescription: $localize`erasure code profile`, reloadFn: () => this.reloadECPs(), deleteFn: (name) => this.ecpService.delete(name), taskName: 'ecp/delete' }); } private deletionModal({ value, usage, deletionBtn, dataName, getTabs, tabPosition, nameAttribute, itemDescription, reloadFn, deleteFn, taskName }: { value: any; usage: string[]; deletionBtn: NgbTooltip; dataName: string; getTabs: () => NgbNav; tabPosition: string; nameAttribute: string; itemDescription: string; reloadFn: Function; deleteFn: (name: string) => Observable<any>; taskName: string; }) { if (!value) { return; } if (usage) { deletionBtn.animation = false; deletionBtn.toggle(); this.data[dataName] = true; setTimeout(() => { const tabs = getTabs(); if (tabs) { tabs.select(tabPosition); } }, 50); return; } const name = value[nameAttribute]; this.modalService.show(CriticalConfirmationModalComponent, { itemDescription, itemNames: [name], submitActionObservable: () => { const deletion = deleteFn(name); deletion.subscribe(() => reloadFn()); return this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask(taskName, { name: name }), call: deletion }); } }); } addCrushRule() { this.addModal(CrushRuleFormModalComponent, (name) => this.reloadCrushRules(name)); } private reloadCrushRules(ruleName?: string) { this.reloadList({ newItemName: ruleName, getInfo: () => this.poolService.getInfo(), initInfo: (info) => { this.initInfo(info); this.poolTypeChange('replicated'); }, findNewItem: () => this.info.crush_rules_replicated.find((rule) => rule.rule_name === ruleName), controlName: 'crushRule' }); } deleteCrushRule() { this.deletionModal({ value: this.form.getValue('crushRule'), usage: this.crushUsage, deletionBtn: this.crushDeletionBtn, dataName: 'crushInfo', getTabs: () => this.crushInfoTabs, tabPosition: 'used-by-pools', nameAttribute: 'rule_name', itemDescription: $localize`crush rule`, reloadFn: () => this.reloadCrushRules(), deleteFn: (name) => this.crushRuleService.delete(name), taskName: 'crushRule/delete' }); } crushRuleIsUsedBy(ruleName: string) { this.crushUsage = ruleName ? this.info.used_rules[ruleName] : undefined; } ecpIsUsedBy(profileName: string) { this.ecpUsage = profileName ? this.info.used_profiles[profileName] : undefined; } submit() { if (this.form.invalid) { this.form.setErrors({ cdSubmitButton: true }); return; } const pool = { pool: this.form.getValue('name') }; this.assignFormFields(pool, [ { externalFieldName: 'pool_type', formControlName: 'poolType' }, { externalFieldName: 'pg_autoscale_mode', formControlName: 'pgAutoscaleMode', editable: true }, { externalFieldName: 'pg_num', formControlName: 'pgNum', replaceFn: (value: number) => (this.form.getValue('pgAutoscaleMode') === 'on' ? 1 : value), editable: true }, this.isReplicated ? { externalFieldName: 'size', formControlName: 'size' } : { externalFieldName: 'erasure_code_profile', formControlName: 'erasureProfile', attr: 'name' }, { externalFieldName: 'rule_name', formControlName: 'crushRule', replaceFn: (value: CrushRule) => (this.isReplicated ? value && value.rule_name : undefined) }, { externalFieldName: 'quota_max_bytes', formControlName: 'max_bytes', replaceFn: this.formatter.toBytes, editable: true, resetValue: this.editing ? 0 : undefined }, { externalFieldName: 'quota_max_objects', formControlName: 'max_objects', editable: true, resetValue: this.editing ? 0 : undefined } ]); if (this.info.is_all_bluestore) { this.assignFormField(pool, { externalFieldName: 'flags', formControlName: 'ecOverwrites', replaceFn: () => (this.isErasure ? ['ec_overwrites'] : undefined) }); if (this.form.getValue('mode') !== 'none') { this.assignFormFields(pool, [ { externalFieldName: 'compression_mode', formControlName: 'mode', editable: true, replaceFn: (value: boolean) => this.hasCompressionEnabled() && value }, { externalFieldName: 'compression_algorithm', formControlName: 'algorithm', editable: true }, { externalFieldName: 'compression_min_blob_size', formControlName: 'minBlobSize', replaceFn: this.formatter.toBytes, editable: true, resetValue: 0 }, { externalFieldName: 'compression_max_blob_size', formControlName: 'maxBlobSize', replaceFn: this.formatter.toBytes, editable: true, resetValue: 0 }, { externalFieldName: 'compression_required_ratio', formControlName: 'ratio', editable: true, resetValue: 0 } ]); } else if (this.editing) { this.assignFormFields(pool, [ { externalFieldName: 'compression_mode', formControlName: 'mode', editable: true, replaceFn: () => 'unset' // Is used if no compression is set }, { externalFieldName: 'srcpool', formControlName: 'name', editable: true, replaceFn: () => this.data.pool.pool_name } ]); } } const apps = this.data.applications.selected; if (apps.length > 0 || this.editing) { pool['application_metadata'] = apps; } // Only collect configuration data for replicated pools, as QoS cannot be configured on EC // pools. EC data pools inherit their settings from the corresponding replicated metadata pool. if (this.isReplicated && !_.isEmpty(this.currentConfigurationValues)) { pool['configuration'] = this.currentConfigurationValues; } this.triggerApiTask(pool); } /** * Retrieves the values for the given form field descriptions and assigns the values to the given * object. This method differentiates between `add` and `edit` mode and acts differently on one or * the other. */ private assignFormFields(pool: object, formFieldDescription: FormFieldDescription[]): void { formFieldDescription.forEach((item) => this.assignFormField(pool, item)); } /** * Retrieves the value for the given form field description and assigns the values to the given * object. This method differentiates between `add` and `edit` mode and acts differently on one or * the other. */ private assignFormField( pool: object, { externalFieldName, formControlName, attr, replaceFn, editable, resetValue }: FormFieldDescription ): void { if (this.editing && (!editable || this.form.get(formControlName).pristine)) { return; } const value = this.form.getValue(formControlName); let apiValue = replaceFn ? replaceFn(value) : attr ? _.get(value, attr) : value; if (!value || !apiValue) { if (editable && !_.isUndefined(resetValue)) { apiValue = resetValue; } else { return; } } pool[externalFieldName] = apiValue; } private triggerApiTask(pool: Record<string, any>) { this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('pool/' + (this.editing ? URLVerbs.EDIT : URLVerbs.CREATE), { pool_name: pool.hasOwnProperty('srcpool') ? pool.srcpool : pool.pool }), call: this.poolService[this.editing ? URLVerbs.UPDATE : URLVerbs.CREATE](pool) }) .subscribe({ error: (resp) => { if (_.isObject(resp.error) && resp.error.code === '34') { this.form.get('pgNum').setErrors({ '34': true }); } this.form.setErrors({ cdSubmitButton: true }); }, complete: () => this.router.navigate(['/pool']) }); } appSelection() { this.form.get('name').updateValueAndValidity({ emitEvent: false, onlySelf: true }); } }
29,391
31.052345
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool-list/pool-list.component.html
<nav ngbNav #nav="ngbNav" class="nav-tabs"> <ng-container ngbNavItem> <a ngbNavLink i18n>Pools List</a> <ng-template ngbNavContent> <cd-table #table id="pool-list" [data]="pools" [columns]="columns" selectionType="single" [hasDetails]="true" [status]="tableStatus" [autoReload]="-1" (fetchData)="taskListService.fetch()" (setExpandedRow)="setExpandedRow($event)" (updateSelection)="updateSelection($event)"> <cd-table-actions id="pool-list-actions" class="table-actions" [permission]="permissions.pool" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> <cd-pool-details cdTableDetail id="pool-list-details" [selection]="expandedRow" [permissions]="permissions" [cacheTiers]="cacheTiers"> </cd-pool-details> </cd-table> </ng-template> </ng-container> <ng-container ngbNavItem *cdScope="'grafana'"> <a ngbNavLink i18n>Overall Performance</a> <ng-template ngbNavContent> <cd-grafana i18n-title title="Ceph pools overview" [grafanaPath]="'ceph-pools-overview?'" [type]="'metrics'" uid="z99hzWtmk" grafanaStyle="two"> </cd-grafana> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="nav"></div> <ng-template #poolUsageTpl let-row="row"> <cd-usage-bar *ngIf="row.stats?.avail_raw?.latest" [total]="row.stats.bytes_used.latest + row.stats.avail_raw.latest" [used]="row.stats.bytes_used.latest" [title]="row.pool_name" decimals="2"> </cd-usage-bar> </ng-template>
2,055
32.16129
82
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool-list/pool-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 _ from 'lodash'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { RbdConfigurationListComponent } from '~/app/ceph/block/rbd-configuration-list/rbd-configuration-list.component'; import { PgCategoryService } from '~/app/ceph/shared/pg-category.service'; import { ConfigurationService } from '~/app/shared/api/configuration.service'; import { ErasureCodeProfileService } from '~/app/shared/api/erasure-code-profile.service'; import { PoolService } from '~/app/shared/api/pool.service'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { ErasureCodeProfile } from '~/app/shared/models/erasure-code-profile'; import { ExecutingTask } from '~/app/shared/models/executing-task'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { SummaryService } from '~/app/shared/services/summary.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, expectItemTasks, Mocks } from '~/testing/unit-test-helper'; import { Pool } from '../pool'; import { PoolDetailsComponent } from '../pool-details/pool-details.component'; import { PoolListComponent } from './pool-list.component'; describe('PoolListComponent', () => { let component: PoolListComponent; let fixture: ComponentFixture<PoolListComponent>; let poolService: PoolService; let getECPList: jasmine.Spy; const getPoolList = (): Pool[] => { return [Mocks.getPool('a', 0), Mocks.getPool('b', 1), Mocks.getPool('c', 2)]; }; const getECPProfiles = (): ErasureCodeProfile[] => { const ecpProfile = new ErasureCodeProfile(); ecpProfile.name = 'default'; ecpProfile.k = 2; ecpProfile.m = 1; return [ecpProfile]; }; configureTestBed({ declarations: [PoolListComponent, PoolDetailsComponent, RbdConfigurationListComponent], imports: [ BrowserAnimationsModule, SharedModule, ToastrModule.forRoot(), RouterTestingModule, NgbNavModule, HttpClientTestingModule ], providers: [PgCategoryService] }); beforeEach(() => { fixture = TestBed.createComponent(PoolListComponent); component = fixture.componentInstance; component.permissions.pool.read = true; poolService = TestBed.inject(PoolService); spyOn(poolService, 'getList').and.callFake(() => of(getPoolList())); getECPList = spyOn(TestBed.inject(ErasureCodeProfileService), 'list'); getECPList.and.returnValue(of(getECPProfiles())); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should have columns that are sortable', () => { expect( component.columns .filter((column) => !(column.prop === undefined)) .every((column) => Boolean(column.prop)) ).toBeTruthy(); }); describe('monAllowPoolDelete', () => { let configOptRead: boolean; let configurationService: ConfigurationService; beforeEach(() => { configOptRead = true; spyOn(TestBed.inject(AuthStorageService), 'getPermissions').and.callFake(() => ({ configOpt: { read: configOptRead } })); configurationService = TestBed.inject(ConfigurationService); }); it('should set value correctly if mon_allow_pool_delete flag is set to true', () => { const configOption = { name: 'mon_allow_pool_delete', value: [ { section: 'mon', value: 'true' } ] }; spyOn(configurationService, 'get').and.returnValue(of(configOption)); fixture = TestBed.createComponent(PoolListComponent); component = fixture.componentInstance; expect(component.monAllowPoolDelete).toBe(true); }); it('should set value correctly if mon_allow_pool_delete flag is set to false', () => { const configOption = { name: 'mon_allow_pool_delete', value: [ { section: 'mon', value: 'false' } ] }; spyOn(configurationService, 'get').and.returnValue(of(configOption)); fixture = TestBed.createComponent(PoolListComponent); component = fixture.componentInstance; expect(component.monAllowPoolDelete).toBe(false); }); it('should set value correctly if mon_allow_pool_delete flag is not set', () => { const configOption = { name: 'mon_allow_pool_delete' }; spyOn(configurationService, 'get').and.returnValue(of(configOption)); fixture = TestBed.createComponent(PoolListComponent); component = fixture.componentInstance; expect(component.monAllowPoolDelete).toBe(false); }); it('should set value correctly w/o config-opt read privileges', () => { configOptRead = false; fixture = TestBed.createComponent(PoolListComponent); component = fixture.componentInstance; expect(component.monAllowPoolDelete).toBe(false); }); }); describe('pool deletion', () => { let taskWrapper: TaskWrapperService; let modalRef: any; const setSelectedPool = (poolName: string) => (component.selection.selected = [{ pool_name: poolName }]); const callDeletion = () => { component.deletePoolModal(); expect(modalRef).toBeTruthy(); const deletion: CriticalConfirmationModalComponent = modalRef && modalRef.componentInstance; deletion.submitActionObservable(); }; const testPoolDeletion = (poolName: string) => { setSelectedPool(poolName); callDeletion(); expect(poolService.delete).toHaveBeenCalledWith(poolName); expect(taskWrapper.wrapTaskAroundCall).toHaveBeenCalledWith({ task: { name: 'pool/delete', metadata: { pool_name: poolName } }, call: undefined // because of stub }); }; beforeEach(() => { spyOn(TestBed.inject(ModalService), 'show').and.callFake((deletionClass, initialState) => { modalRef = { componentInstance: Object.assign(new deletionClass(), initialState) }; return modalRef; }); spyOn(poolService, 'delete').and.stub(); taskWrapper = TestBed.inject(TaskWrapperService); spyOn(taskWrapper, 'wrapTaskAroundCall').and.callThrough(); }); it('should pool deletion with two different pools', () => { testPoolDeletion('somePoolName'); testPoolDeletion('aDifferentPoolName'); }); }); describe('handling of executing tasks', () => { let summaryService: SummaryService; const addTask = (name: string, pool: string) => { const task = new ExecutingTask(); task.name = name; task.metadata = { pool_name: pool }; summaryService.addRunningTask(task); }; beforeEach(() => { summaryService = TestBed.inject(SummaryService); summaryService['summaryDataSource'].next({ executing_tasks: [], finished_tasks: [] }); }); it('gets all pools without executing pools', () => { expect(component.pools.length).toBe(3); expect(component.pools.every((pool) => !pool.executingTasks)).toBeTruthy(); }); it('gets a pool from a task during creation', () => { addTask('pool/create', 'd'); expect(component.pools.length).toBe(4); expectItemTasks(component.pools[3], 'Creating'); }); it('gets all pools with one executing pools', () => { addTask('pool/create', 'a'); expect(component.pools.length).toBe(3); expectItemTasks(component.pools[0], 'Creating'); expect(component.pools[1].cdExecuting).toBeFalsy(); expect(component.pools[2].cdExecuting).toBeFalsy(); }); it('gets all pools with multiple executing pools', () => { addTask('pool/create', 'a'); addTask('pool/edit', 'a'); addTask('pool/delete', 'a'); addTask('pool/edit', 'b'); addTask('pool/delete', 'b'); addTask('pool/delete', 'c'); expect(component.pools.length).toBe(3); expectItemTasks(component.pools[0], 'Creating..., Updating..., Deleting'); expectItemTasks(component.pools[1], 'Updating..., Deleting'); expectItemTasks(component.pools[2], 'Deleting'); }); it('gets all pools with multiple executing tasks (not only pool tasks)', () => { addTask('rbd/create', 'a'); addTask('rbd/edit', 'a'); addTask('pool/delete', 'a'); addTask('pool/edit', 'b'); addTask('rbd/delete', 'b'); addTask('rbd/delete', 'c'); expect(component.pools.length).toBe(3); expectItemTasks(component.pools[0], 'Deleting'); expectItemTasks(component.pools[1], 'Updating'); expect(component.pools[2].cdExecuting).toBeFalsy(); }); }); describe('getPgStatusCellClass', () => { const testMethod = (value: string, expected: string) => expect(component.getPgStatusCellClass('', '', value)).toEqual({ 'text-right': true, [expected]: true }); it('pg-clean', () => { testMethod('8 active+clean', 'pg-clean'); }); it('pg-working', () => { testMethod(' 8 active+clean+scrubbing+deep, 255 active+clean ', 'pg-working'); }); it('pg-warning', () => { testMethod('8 active+clean+scrubbing+down', 'pg-warning'); testMethod('8 active+clean+scrubbing+down+nonMappedState', 'pg-warning'); }); it('pg-unknown', () => { testMethod('8 active+clean+scrubbing+nonMappedState', 'pg-unknown'); testMethod('8 ', 'pg-unknown'); testMethod('', 'pg-unknown'); }); }); describe('custom row comparators', () => { const expectCorrectComparator = (statsAttribute: string) => { const mockPool = (v: number) => ({ stats: { [statsAttribute]: { latest: v } } }); const columnDefinition = _.find( component.columns, (column) => column.prop === `stats.${statsAttribute}.rates` ); expect(columnDefinition.comparator(undefined, undefined, mockPool(2), mockPool(1))).toBe(1); expect(columnDefinition.comparator(undefined, undefined, mockPool(1), mockPool(2))).toBe(-1); }; it('compares read bytes correctly', () => { expectCorrectComparator('rd_bytes'); }); it('compares write bytes correctly', () => { expectCorrectComparator('wr_bytes'); }); }); describe('transformPoolsData', () => { let pool: Pool; const getPoolData = (o: object) => [ _.merge( _.merge(Mocks.getPool('a', 0), { cdIsBinary: true, pg_status: '', stats: { bytes_used: { latest: 0, rate: 0, rates: [] }, max_avail: { latest: 0, rate: 0, rates: [] }, avail_raw: { latest: 0, rate: 0, rates: [] }, percent_used: { latest: 0, rate: 0, rates: [] }, rd: { latest: 0, rate: 0, rates: [] }, rd_bytes: { latest: 0, rate: 0, rates: [] }, wr: { latest: 0, rate: 0, rates: [] }, wr_bytes: { latest: 0, rate: 0, rates: [] } }, usage: 0, data_protection: 'replica: ×3' }), o ) ]; beforeEach(() => { pool = Mocks.getPool('a', 0); }); it('transforms replicated pools data correctly', () => { pool = _.merge(pool, { stats: { bytes_used: { latest: 5, rate: 0, rates: [] }, avail_raw: { latest: 15, rate: 0, rates: [] }, percent_used: { latest: 0.25, rate: 0, rates: [] }, rd_bytes: { latest: 6, rate: 4, rates: [ [0, 2], [1, 6] ] } }, pg_status: { 'active+clean': 8, down: 2 } }); expect(component.transformPoolsData([pool])).toEqual( getPoolData({ pg_status: '8 active+clean, 2 down', stats: { bytes_used: { latest: 5, rate: 0, rates: [] }, avail_raw: { latest: 15, rate: 0, rates: [] }, percent_used: { latest: 0.25, rate: 0, rates: [] }, rd_bytes: { latest: 6, rate: 4, rates: [2, 6] } }, usage: 0.25, data_protection: 'replica: ×3' }) ); }); it('transforms erasure pools data correctly', () => { pool.type = 'erasure'; pool.erasure_code_profile = 'default'; component.ecProfileList = getECPProfiles(); expect(component.transformPoolsData([pool])).toEqual( getPoolData({ type: 'erasure', erasure_code_profile: 'default', data_protection: 'EC: 2+1' }) ); }); it('transforms pools data correctly if stats are missing', () => { expect(component.transformPoolsData([pool])).toEqual(getPoolData({})); }); it('transforms empty pools data correctly', () => { expect(component.transformPoolsData(undefined)).toEqual(undefined); expect(component.transformPoolsData([])).toEqual([]); }); it('shows not marked pools in progress if pg_num does not match pg_num_target', () => { const pools = [ _.merge(pool, { pg_num: 32, pg_num_target: 16, pg_placement_num: 32, pg_placement_num_target: 16 }) ]; expect(component.transformPoolsData(pools)).toEqual( getPoolData({ cdExecuting: 'Updating', pg_num: 32, pg_num_target: 16, pg_placement_num: 32, pg_placement_num_target: 16, data_protection: 'replica: ×3' }) ); }); it('shows marked pools in progress as defined by task', () => { const pools = [ _.merge(pool, { pg_num: 32, pg_num_target: 16, pg_placement_num: 32, pg_placement_num_target: 16, cdExecuting: 'Updating... 50%' }) ]; expect(component.transformPoolsData(pools)).toEqual( getPoolData({ cdExecuting: 'Updating... 50%', pg_num: 32, pg_num_target: 16, pg_placement_num: 32, pg_placement_num_target: 16, data_protection: 'replica: ×3' }) ); }); }); describe('transformPgStatus', () => { it('returns status groups correctly', () => { const pgStatus = { 'active+clean': 8 }; const expected = '8 active+clean'; expect(component.transformPgStatus(pgStatus)).toEqual(expected); }); it('returns separated status groups', () => { const pgStatus = { 'active+clean': 8, down: 2 }; const expected = '8 active+clean, 2 down'; expect(component.transformPgStatus(pgStatus)).toEqual(expected); }); it('returns separated statuses correctly', () => { const pgStatus = { active: 8, down: 2 }; const expected = '8 active, 2 down'; expect(component.transformPgStatus(pgStatus)).toEqual(expected); }); it('returns empty string', () => { const pgStatus: any = undefined; const expected = ''; expect(component.transformPgStatus(pgStatus)).toEqual(expected); }); }); describe('getSelectionTiers', () => { const setSelectionTiers = (tiers: number[]) => { component.expandedRow = { tiers }; component.getSelectionTiers(); }; beforeEach(() => { component.pools = getPoolList(); }); it('should select multiple existing cache tiers', () => { setSelectionTiers([0, 1, 2]); expect(component.cacheTiers).toEqual(getPoolList()); }); it('should select correct existing cache tier', () => { setSelectionTiers([0]); expect(component.cacheTiers).toEqual([Mocks.getPool('a', 0)]); }); it('should not select cache tier if id is invalid', () => { setSelectionTiers([-1]); expect(component.cacheTiers).toEqual([]); }); it('should not select cache tier if empty', () => { setSelectionTiers([]); expect(component.cacheTiers).toEqual([]); }); it('should be able to selected one pool with multiple tiers, than with a single tier, than with no tiers', () => { setSelectionTiers([0, 1, 2]); expect(component.cacheTiers).toEqual(getPoolList()); setSelectionTiers([0]); expect(component.cacheTiers).toEqual([Mocks.getPool('a', 0)]); setSelectionTiers([]); expect(component.cacheTiers).toEqual([]); }); }); describe('getDisableDesc', () => { beforeEach(() => { component.selection.selected = [{ pool_name: 'foo' }]; }); it('should return message if mon_allow_pool_delete flag is set to false', () => { component.monAllowPoolDelete = false; expect(component.getDisableDesc()).toBe( 'Pool deletion is disabled by the mon_allow_pool_delete configuration setting.' ); }); it('should return false if mon_allow_pool_delete flag is set to true', () => { component.monAllowPoolDelete = true; expect(component.getDisableDesc()).toBeFalsy(); }); }); });
17,491
32.703276
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/pool/pool-list/pool-list.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import _ from 'lodash'; import { mergeMap } from 'rxjs/operators'; import { PgCategoryService } from '~/app/ceph/shared/pg-category.service'; import { ConfigurationService } from '~/app/shared/api/configuration.service'; import { ErasureCodeProfileService } from '~/app/shared/api/erasure-code-profile.service'; import { PoolService } from '~/app/shared/api/pool.service'; import { ListWithDetails } from '~/app/shared/classes/list-with-details.class'; 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, 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 { 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 { ErasureCodeProfile } from '~/app/shared/models/erasure-code-profile'; import { ExecutingTask } from '~/app/shared/models/executing-task'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { Permissions } from '~/app/shared/models/permissions'; import { DimlessPipe } from '~/app/shared/pipes/dimless.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 { URLBuilderService } from '~/app/shared/services/url-builder.service'; import { Pool } from '../pool'; import { PoolStat, PoolStats } from '../pool-stat'; const BASE_URL = 'pool'; @Component({ selector: 'cd-pool-list', templateUrl: './pool-list.component.html', providers: [ TaskListService, { provide: URLBuilderService, useValue: new URLBuilderService(BASE_URL) } ], styleUrls: ['./pool-list.component.scss'] }) export class PoolListComponent extends ListWithDetails implements OnInit { @ViewChild(TableComponent) table: TableComponent; @ViewChild('poolUsageTpl', { static: true }) poolUsageTpl: TemplateRef<any>; @ViewChild('poolConfigurationSourceTpl') poolConfigurationSourceTpl: TemplateRef<any>; pools: Pool[]; columns: CdTableColumn[]; selection = new CdTableSelection(); executingTasks: ExecutingTask[] = []; permissions: Permissions; tableActions: CdTableAction[]; tableStatus = new TableStatusViewCache(); cacheTiers: any[] = []; monAllowPoolDelete = false; ecProfileList: ErasureCodeProfile[]; constructor( private poolService: PoolService, private taskWrapper: TaskWrapperService, private ecpService: ErasureCodeProfileService, private authStorageService: AuthStorageService, public taskListService: TaskListService, private modalService: ModalService, private pgCategoryService: PgCategoryService, private dimlessPipe: DimlessPipe, private urlBuilder: URLBuilderService, private configurationService: ConfigurationService, public actionLabels: ActionLabelsI18n ) { super(); this.permissions = this.authStorageService.getPermissions(); this.tableActions = [ { permission: 'create', icon: Icons.add, routerLink: () => this.urlBuilder.getCreate(), name: this.actionLabels.CREATE }, { permission: 'update', icon: Icons.edit, routerLink: () => this.urlBuilder.getEdit(encodeURIComponent(this.selection.first().pool_name)), name: this.actionLabels.EDIT }, { permission: 'delete', icon: Icons.destroy, click: () => this.deletePoolModal(), name: this.actionLabels.DELETE, disable: this.getDisableDesc.bind(this) } ]; // Note, we need read permissions to get the 'mon_allow_pool_delete' // configuration option. if (this.permissions.configOpt.read) { this.configurationService.get('mon_allow_pool_delete').subscribe((data: any) => { if (_.has(data, 'value')) { const monSection = _.find(data.value, (v) => { return v.section === 'mon'; }) || { value: false }; this.monAllowPoolDelete = monSection.value === 'true' ? true : false; } }); } } ngOnInit() { const compare = (prop: string, pool1: Pool, pool2: Pool) => _.get(pool1, prop) > _.get(pool2, prop) ? 1 : -1; this.columns = [ { prop: 'pool_name', name: $localize`Name`, flexGrow: 4, cellTransformation: CellTemplate.executing }, { prop: 'data_protection', name: $localize`Data Protection`, cellTransformation: CellTemplate.badge, customTemplateConfig: { class: 'badge-background-gray' }, flexGrow: 1.3 }, { prop: 'application_metadata', name: $localize`Applications`, cellTransformation: CellTemplate.badge, customTemplateConfig: { class: 'badge-background-primary' }, flexGrow: 1.5 }, { prop: 'pg_status', name: $localize`PG Status`, flexGrow: 1.2, cellClass: ({ row, column, value }): any => { return this.getPgStatusCellClass(row, column, value); } }, { prop: 'crush_rule', name: $localize`Crush Ruleset`, isHidden: true, flexGrow: 2 }, { name: $localize`Usage`, prop: 'usage', cellTemplate: this.poolUsageTpl, flexGrow: 1.2 }, { prop: 'stats.rd_bytes.rates', name: $localize`Read bytes`, comparator: (_valueA: any, _valueB: any, rowA: Pool, rowB: Pool) => compare('stats.rd_bytes.latest', rowA, rowB), cellTransformation: CellTemplate.sparkline, flexGrow: 1.5 }, { prop: 'stats.wr_bytes.rates', name: $localize`Write bytes`, comparator: (_valueA: any, _valueB: any, rowA: Pool, rowB: Pool) => compare('stats.wr_bytes.latest', rowA, rowB), cellTransformation: CellTemplate.sparkline, flexGrow: 1.5 }, { prop: 'stats.rd.rate', name: $localize`Read ops`, flexGrow: 1, pipe: this.dimlessPipe, cellTransformation: CellTemplate.perSecond }, { prop: 'stats.wr.rate', name: $localize`Write ops`, flexGrow: 1, pipe: this.dimlessPipe, cellTransformation: CellTemplate.perSecond } ]; this.taskListService.init( () => this.ecpService.list().pipe( mergeMap((ecProfileList: ErasureCodeProfile[]) => { this.ecProfileList = ecProfileList; return this.poolService.getList(); }) ), undefined, (pools) => { this.pools = this.transformPoolsData(pools); this.tableStatus = new TableStatusViewCache(); }, () => { this.table.reset(); // Disable loading indicator. this.tableStatus = new TableStatusViewCache(ViewCacheStatus.ValueException); }, (task) => task.name.startsWith(`${BASE_URL}/`), (pool, task) => task.metadata['pool_name'] === pool.pool_name, { default: (metadata: any) => new Pool(metadata['pool_name']) } ); } updateSelection(selection: CdTableSelection) { this.selection = selection; } deletePoolModal() { const name = this.selection.first().pool_name; this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: 'Pool', itemNames: [name], submitActionObservable: () => this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask(`${BASE_URL}/${URLVerbs.DELETE}`, { pool_name: name }), call: this.poolService.delete(name) }) }); } getPgStatusCellClass(_row: any, _column: any, value: string): object { return { 'text-right': true, [`pg-${this.pgCategoryService.getTypeByStates(value)}`]: true }; } getErasureCodeProfile(erasureCodeProfile: string) { let ecpInfo = ''; _.forEach(this.ecProfileList, (ecpKey) => { if (ecpKey['name'] === erasureCodeProfile) { ecpInfo = `EC: ${ecpKey['k']}+${ecpKey['m']}`; } }); return ecpInfo; } transformPoolsData(pools: any) { const requiredStats = [ 'bytes_used', 'max_avail', 'avail_raw', 'percent_used', 'rd_bytes', 'wr_bytes', 'rd', 'wr' ]; const emptyStat: PoolStat = { latest: 0, rate: 0, rates: [] }; _.forEach(pools, (pool: Pool) => { pool['pg_status'] = this.transformPgStatus(pool['pg_status']); const stats: PoolStats = {}; _.forEach(requiredStats, (stat) => { stats[stat] = pool.stats && pool.stats[stat] ? pool.stats[stat] : emptyStat; }); pool['stats'] = stats; pool['usage'] = stats.percent_used.latest; if ( !pool.cdExecuting && pool.pg_num + pool.pg_placement_num !== pool.pg_num_target + pool.pg_placement_num_target ) { pool['cdExecuting'] = 'Updating'; } ['rd_bytes', 'wr_bytes'].forEach((stat) => { pool.stats[stat].rates = pool.stats[stat].rates.map((point: any) => point[1]); }); pool.cdIsBinary = true; if (pool['type'] === 'erasure') { const erasureCodeProfile = pool['erasure_code_profile']; pool['data_protection'] = this.getErasureCodeProfile(erasureCodeProfile); } if (pool['type'] === 'replicated') { pool['data_protection'] = `replica: ×${pool['size']}`; } }); return pools; } transformPgStatus(pgStatus: any): string { const strings: string[] = []; _.forEach(pgStatus, (count, state) => { strings.push(`${count} ${state}`); }); return strings.join(', '); } getSelectionTiers() { if (typeof this.expandedRow !== 'undefined') { const cacheTierIds = this.expandedRow['tiers']; this.cacheTiers = this.pools.filter((pool) => cacheTierIds.includes(pool.pool)); } } getDisableDesc(): boolean | string { if (this.selection?.hasSelection) { if (!this.monAllowPoolDelete) { return $localize`Pool deletion is disabled by the mon_allow_pool_delete configuration setting.`; } return false; } return true; } setExpandedRow(expandedRow: any) { super.setExpandedRow(expandedRow); this.getSelectionTiers(); } }
11,016
32.084084
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule, Routes } from '@angular/router'; import { NgbNavModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'; import { NgxPipeFunctionModule } from 'ngx-pipe-function'; import { ActionLabels, URLVerbs } from '~/app/shared/constants/app.constants'; import { CRUDTableComponent } from '~/app/shared/datatable/crud-table/crud-table.component'; import { SharedModule } from '~/app/shared/shared.module'; import { PerformanceCounterModule } from '../performance-counter/performance-counter.module'; import { RgwBucketDetailsComponent } from './rgw-bucket-details/rgw-bucket-details.component'; import { RgwBucketFormComponent } from './rgw-bucket-form/rgw-bucket-form.component'; import { RgwBucketListComponent } from './rgw-bucket-list/rgw-bucket-list.component'; import { RgwConfigModalComponent } from './rgw-config-modal/rgw-config-modal.component'; import { RgwDaemonDetailsComponent } from './rgw-daemon-details/rgw-daemon-details.component'; import { RgwDaemonListComponent } from './rgw-daemon-list/rgw-daemon-list.component'; import { RgwUserCapabilityModalComponent } from './rgw-user-capability-modal/rgw-user-capability-modal.component'; import { RgwUserDetailsComponent } from './rgw-user-details/rgw-user-details.component'; import { RgwUserFormComponent } from './rgw-user-form/rgw-user-form.component'; import { RgwUserListComponent } from './rgw-user-list/rgw-user-list.component'; import { RgwUserS3KeyModalComponent } from './rgw-user-s3-key-modal/rgw-user-s3-key-modal.component'; import { RgwUserSubuserModalComponent } from './rgw-user-subuser-modal/rgw-user-subuser-modal.component'; import { RgwUserSwiftKeyModalComponent } from './rgw-user-swift-key-modal/rgw-user-swift-key-modal.component'; import { RgwUserTabsComponent } from './rgw-user-tabs/rgw-user-tabs.component'; import { RgwMultisiteDetailsComponent } from './rgw-multisite-details/rgw-multisite-details.component'; import { TreeModule } from '@circlon/angular-tree-component'; import { DataTableModule } from '~/app/shared/datatable/datatable.module'; import { FeatureTogglesGuardService } from '~/app/shared/services/feature-toggles-guard.service'; import { ModuleStatusGuardService } from '~/app/shared/services/module-status-guard.service'; import { RgwMultisiteRealmFormComponent } from './rgw-multisite-realm-form/rgw-multisite-realm-form.component'; import { RgwMultisiteZonegroupFormComponent } from './rgw-multisite-zonegroup-form/rgw-multisite-zonegroup-form.component'; import { RgwMultisiteZoneFormComponent } from './rgw-multisite-zone-form/rgw-multisite-zone-form.component'; import { CrudFormComponent } from '~/app/shared/forms/crud-form/crud-form.component'; import { RgwMultisiteZoneDeletionFormComponent } from './models/rgw-multisite-zone-deletion-form/rgw-multisite-zone-deletion-form.component'; import { RgwMultisiteZonegroupDeletionFormComponent } from './models/rgw-multisite-zonegroup-deletion-form/rgw-multisite-zonegroup-deletion-form.component'; import { RgwSystemUserComponent } from './rgw-system-user/rgw-system-user.component'; import { RgwMultisiteMigrateComponent } from './rgw-multisite-migrate/rgw-multisite-migrate.component'; import { RgwMultisiteImportComponent } from './rgw-multisite-import/rgw-multisite-import.component'; import { RgwMultisiteExportComponent } from './rgw-multisite-export/rgw-multisite-export.component'; import { CreateRgwServiceEntitiesComponent } from './create-rgw-service-entities/create-rgw-service-entities.component'; @NgModule({ imports: [ CommonModule, SharedModule, FormsModule, ReactiveFormsModule, PerformanceCounterModule, NgbNavModule, RouterModule, NgbTooltipModule, NgxPipeFunctionModule, TreeModule, DataTableModule ], exports: [ RgwDaemonListComponent, RgwDaemonDetailsComponent, RgwBucketFormComponent, RgwBucketListComponent, RgwBucketDetailsComponent, RgwUserListComponent, RgwUserDetailsComponent ], declarations: [ RgwDaemonListComponent, RgwDaemonDetailsComponent, RgwBucketFormComponent, RgwBucketListComponent, RgwBucketDetailsComponent, RgwUserListComponent, RgwUserDetailsComponent, RgwBucketFormComponent, RgwUserFormComponent, RgwUserSwiftKeyModalComponent, RgwUserS3KeyModalComponent, RgwUserCapabilityModalComponent, RgwUserSubuserModalComponent, RgwConfigModalComponent, RgwUserTabsComponent, RgwMultisiteDetailsComponent, RgwMultisiteRealmFormComponent, RgwMultisiteZonegroupFormComponent, RgwMultisiteZoneFormComponent, RgwMultisiteZoneDeletionFormComponent, RgwMultisiteZonegroupDeletionFormComponent, RgwSystemUserComponent, RgwMultisiteMigrateComponent, RgwMultisiteImportComponent, RgwMultisiteExportComponent, CreateRgwServiceEntitiesComponent ] }) export class RgwModule {} const routes: Routes = [ { path: '' // Required for a clean reload on daemon selection. }, { path: 'daemon', component: RgwDaemonListComponent, data: { breadcrumbs: 'Gateways' } }, { path: 'user', data: { breadcrumbs: 'Users' }, children: [ { path: '', component: RgwUserListComponent }, { path: URLVerbs.CREATE, component: RgwUserFormComponent, data: { breadcrumbs: ActionLabels.CREATE } }, { path: `${URLVerbs.EDIT}/:uid`, component: RgwUserFormComponent, data: { breadcrumbs: ActionLabels.EDIT } } ] }, { path: 'roles', data: { breadcrumbs: 'Roles', resource: '[email protected]', tabs: [ { name: 'Users', url: '/rgw/user' }, { name: 'Roles', url: '/rgw/roles' } ] }, children: [ { path: '', component: CRUDTableComponent }, { path: URLVerbs.CREATE, component: CrudFormComponent, data: { breadcrumbs: ActionLabels.CREATE } } ] }, { path: 'bucket', data: { breadcrumbs: 'Buckets' }, children: [ { path: '', component: RgwBucketListComponent }, { path: URLVerbs.CREATE, component: RgwBucketFormComponent, data: { breadcrumbs: ActionLabels.CREATE } }, { path: `${URLVerbs.EDIT}/:bid`, component: RgwBucketFormComponent, data: { breadcrumbs: ActionLabels.EDIT } } ] }, { path: 'multisite', canActivate: [FeatureTogglesGuardService, ModuleStatusGuardService], data: { moduleStatusGuardConfig: { uiApiPath: 'rgw/multisite', redirectTo: 'error', header: 'Multi-site not configured', button_name: 'Add Multi-site Configuration', button_route: '/rgw/multisite/create', button_title: 'Add multi-site configuration (realms/zonegroups/zones)', secondary_button_name: 'Import Multi-site Configuration', secondary_button_route: 'rgw/multisite/import', secondary_button_title: 'Import multi-site configuration (import realm token from a secondary cluster)' }, breadcrumbs: 'Multisite' }, children: [{ path: '', component: RgwMultisiteDetailsComponent }] } ]; @NgModule({ imports: [RgwModule, RouterModule.forChild(routes)] }) export class RoutedRgwModule {}
7,514
37.737113
156
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/create-rgw-service-entities/create-rgw-service-entities.component.html
<cd-modal [modalRef]="activeModal"> <ng-container i18n="form title" class="modal-title">Create Realm/Zonegroup/Zone </ng-container> <ng-container class="modal-content"> <form name="createMultisiteEntitiesForm" #formDir="ngForm" [formGroup]="createMultisiteEntitiesForm" novalidate> <div class="modal-body"> <cd-alert-panel type="info" spacingClass="mb-3">The realm/zonegroup/zone created will be set as default and master. </cd-alert-panel> <div class="form-group row"> <label class="cd-col-form-label required" for="realmName" i18n>Realm Name</label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="Realm name..." id="realmName" name="realmName" formControlName="realmName"> <span class="invalid-feedback" *ngIf="createMultisiteEntitiesForm.showError('realmName', formDir, 'required')" i18n>This field is required.</span> </div> </div> <div class="form-group row"> <label class="cd-col-form-label required" for="zonegroupName" i18n>Zonegroup Name</label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="Zonegroup name..." id="zonegroupName" name="zonegroupName" formControlName="zonegroupName"> <span class="invalid-feedback" *ngIf="createMultisiteEntitiesForm.showError('zonegroupName', formDir, 'required')" i18n>This field is required.</span> </div> </div> <div class="form-group row"> <label class="cd-col-form-label required" for="zoneName" i18n>Zone Name</label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="Zone name..." id="zoneName" name="zoneName" formControlName="zoneName"> <span class="invalid-feedback" *ngIf="createMultisiteEntitiesForm.showError('zoneName', formDir, 'required')" i18n>This field is required.</span> </div> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="submit()" [form]="createMultisiteEntitiesForm"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
2,708
37.15493
109
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/create-rgw-service-entities/create-rgw-service-entities.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 { SharedModule } from '~/app/shared/shared.module'; import { CreateRgwServiceEntitiesComponent } from './create-rgw-service-entities.component'; describe('CreateRgwServiceEntitiesComponent', () => { let component: CreateRgwServiceEntitiesComponent; let fixture: ComponentFixture<CreateRgwServiceEntitiesComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ SharedModule, ReactiveFormsModule, RouterTestingModule, HttpClientTestingModule, ToastrModule.forRoot() ], providers: [NgbActiveModal], declarations: [CreateRgwServiceEntitiesComponent] }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(CreateRgwServiceEntitiesComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,305
32.487179
92
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/create-rgw-service-entities/create-rgw-service-entities.component.ts
import { Component, EventEmitter, Output } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { RgwMultisiteService } from '~/app/shared/api/rgw-multisite.service'; import { RgwRealmService } from '~/app/shared/api/rgw-realm.service'; import { RgwZoneService } from '~/app/shared/api/rgw-zone.service'; import { RgwZonegroupService } from '~/app/shared/api/rgw-zonegroup.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { RgwRealm, RgwZonegroup, RgwZone, SystemKey } from '../models/rgw-multisite'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { Subscription } from 'rxjs'; @Component({ selector: 'cd-create-rgw-service-entities', templateUrl: './create-rgw-service-entities.component.html', styleUrls: ['./create-rgw-service-entities.component.scss'] }) export class CreateRgwServiceEntitiesComponent { public sub = new Subscription(); createMultisiteEntitiesForm: CdFormGroup; realm: RgwRealm; zonegroup: RgwZonegroup; zone: RgwZone; @Output() submitAction = new EventEmitter(); constructor( public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, public rgwMultisiteService: RgwMultisiteService, public rgwZoneService: RgwZoneService, public notificationService: NotificationService, public rgwZonegroupService: RgwZonegroupService, public rgwRealmService: RgwRealmService, public modalService: ModalService ) { this.createForm(); } createForm() { this.createMultisiteEntitiesForm = new CdFormGroup({ realmName: new FormControl(null, { validators: [Validators.required] }), zonegroupName: new FormControl(null, { validators: [Validators.required] }), zoneName: new FormControl(null, { validators: [Validators.required] }) }); } submit() { const values = this.createMultisiteEntitiesForm.value; this.realm = new RgwRealm(); this.realm.name = values['realmName']; this.zonegroup = new RgwZonegroup(); this.zonegroup.name = values['zonegroupName']; this.zonegroup.endpoints = ''; this.zone = new RgwZone(); this.zone.name = values['zoneName']; this.zone.endpoints = ''; this.zone.system_key = new SystemKey(); this.zone.system_key.access_key = ''; this.zone.system_key.secret_key = ''; this.rgwRealmService .create(this.realm, true) .toPromise() .then(() => { this.rgwZonegroupService .create(this.realm, this.zonegroup, true, true) .toPromise() .then(() => { this.rgwZoneService .create(this.zone, this.zonegroup, true, true, this.zone.endpoints) .toPromise() .then(() => { this.notificationService.show( NotificationType.success, $localize`Realm/Zonegroup/Zone created successfully` ); this.submitAction.emit(); this.activeModal.close(); }) .catch(() => { this.notificationService.show( NotificationType.error, $localize`Realm/Zonegroup/Zone creation failed` ); }); }); }); } }
3,621
35.22
85
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-bucket-encryption.ts
export class RgwBucketEncryptionModel { kmsProviders = ['vault']; authMethods = ['token', 'agent']; secretEngines = ['kv', 'transit']; sse_s3 = 'AES256'; sse_kms = 'aws:kms'; }
187
22.5
39
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-bucket-mfa-delete.ts
export enum RgwBucketMfaDelete { ENABLED = 'Enabled', DISABLED = 'Disabled' }
82
15.6
32
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-bucket-versioning.ts
export enum RgwBucketVersioning { ENABLED = 'Enabled', SUSPENDED = 'Suspended' }
85
16.2
33
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-daemon.ts
export class RgwDaemon { id: string; service_map_id: string; version: string; server_hostname: string; realm_name: string; zonegroup_name: string; zone_name: string; default: boolean; port: number; }
218
17.25
26
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-multisite.ts
export class RgwRealm { id: string; name: string; current_period: string; epoch: number; } export class RgwZonegroup { id: string; name: string; api_name: string; is_master: boolean; endpoints: string; hostnames: string[]; hostnames_s3website: string[]; master_zone: string; zones: RgwZone[]; placement_targets: any[]; default_placement: string; realm_id: string; sync_policy: object; enabled_features: string[]; } export class RgwZone { id: string; name: string; domain_root: string; control_pool: string; gc_pool: string; lc_pool: string; log_pool: string; intent_log_pool: string; usage_log_pool: string; roles_pool: string; reshard_pool: string; user_keys_pool: string; user_email_pool: string; user_swift_pool: string; user_uid_pool: string; otp_pool: string; system_key: SystemKey; placement_pools: any[]; realm_id: string; notif_pool: string; endpoints: string; } export class SystemKey { access_key: string; secret_key: string; }
1,023
18.320755
32
ts