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/hosts/host-form/host-form.component.html
<cd-modal [pageURL]="pageURL" [modalRef]="activeModal"> <span class="modal-title" i18n>{{ action | titlecase }} {{ resource | upperFirst }}</span> <ng-container class="modal-content"> <div *cdFormLoading="loading"> <form name="hostForm" #formDir="ngForm" [formGroup]="hostForm" novalidate> <div class="modal-body"> <!-- Hostname --> <div class="form-group row"> <label class="cd-col-form-label required" for="hostname"> <ng-container i18n>Hostname</ng-container> <cd-helper> <p i18n>To add multiple hosts at once, you can enter:</p> <ul> <li i18n>a comma-separated list of hostnames <samp>(e.g.: example-01,example-02,example-03)</samp>,</li> <li i18n>a range expression <samp>(e.g.: example-[01-03].ceph)</samp>,</li> <li i18n>a comma separated range expression <samp>(e.g.: example-[01-05].lab.com,example2-[1-4].lab.com,example3-[001-006].lab.com)</samp></li> </ul> </cd-helper> </label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="mon-123" id="hostname" name="hostname" formControlName="hostname" autofocus (keyup)="checkHostNameValue()"> <span class="invalid-feedback" *ngIf="hostForm.showError('hostname', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="hostForm.showError('hostname', formDir, 'uniqueName')" i18n>The chosen hostname is already in use.</span> </div> </div> <!-- Address --> <div class="form-group row" *ngIf="!hostPattern"> <label class="cd-col-form-label" for="addr" i18n>Network address</label> <div class="cd-col-form-input"> <input class="form-control" type="text" placeholder="192.168.0.1" id="addr" name="addr" formControlName="addr"> <span class="invalid-feedback" *ngIf="hostForm.showError('addr', formDir, 'pattern')" i18n>The value is not a valid IP address.</span> </div> </div> <!-- Labels --> <div class="form-group row"> <label i18n for="labels" class="cd-col-form-label">Labels</label> <div class="cd-col-form-input"> <cd-select-badges id="labels" [data]="hostForm.controls.labels.value" [options]="labelsOption" [customBadges]="true" [messages]="messages"> </cd-select-badges> </div> </div> <!-- Maintenance Mode --> <div class="form-group row" *ngIf="!hideMaintenance"> <div class="cd-col-form-offset"> <div class="custom-control custom-checkbox"> <input class="custom-control-input" id="maintenance" type="checkbox" formControlName="maintenance"> <label class="custom-control-label" for="maintenance" i18n>Maintenance Mode</label> </div> </div> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="submit()" [form]="hostForm" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)" wrappingClass="text-right"></cd-form-button-panel> </div> </form> </div> </ng-container> </cd-modal>
4,270
38.183486
159
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/hosts/host-form/host-form.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { LoadingPanelComponent } from '~/app/shared/components/loading-panel/loading-panel.component'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FormHelper } from '~/testing/unit-test-helper'; import { HostFormComponent } from './host-form.component'; describe('HostFormComponent', () => { let component: HostFormComponent; let fixture: ComponentFixture<HostFormComponent>; let formHelper: FormHelper; configureTestBed( { imports: [ SharedModule, HttpClientTestingModule, RouterTestingModule, ReactiveFormsModule, ToastrModule.forRoot() ], declarations: [HostFormComponent], providers: [NgbActiveModal] }, [LoadingPanelComponent] ); beforeEach(() => { fixture = TestBed.createComponent(HostFormComponent); component = fixture.componentInstance; component.ngOnInit(); formHelper = new FormHelper(component.hostForm); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should open the form in a modal', () => { const nativeEl = fixture.debugElement.nativeElement; expect(nativeEl.querySelector('cd-modal')).not.toBe(null); }); it('should validate the network address is valid', fakeAsync(() => { formHelper.setValue('addr', '115.42.150.37', true); tick(); formHelper.expectValid('addr'); })); it('should show error if network address is invalid', fakeAsync(() => { formHelper.setValue('addr', '666.10.10.20', true); tick(); formHelper.expectError('addr', 'pattern'); })); it('should submit the network address', () => { component.hostForm.get('addr').setValue('127.0.0.1'); fixture.detectChanges(); component.submit(); expect(component.addr).toBe('127.0.0.1'); }); it('should validate the labels are added', () => { const labels = ['label1', 'label2']; component.hostForm.get('labels').patchValue(labels); fixture.detectChanges(); component.submit(); expect(component.allLabels).toBe(labels); }); it('should select maintenance mode', () => { component.hostForm.get('maintenance').setValue(true); fixture.detectChanges(); component.submit(); expect(component.status).toBe('maintenance'); }); it('should expand the hostname correctly', () => { component.hostForm.get('hostname').setValue('ceph-node-00.cephlab.com'); fixture.detectChanges(); component.submit(); expect(component.hostnameArray).toStrictEqual(['ceph-node-00.cephlab.com']); component.hostnameArray = []; component.hostForm.get('hostname').setValue('ceph-node-[00-10].cephlab.com'); fixture.detectChanges(); component.submit(); expect(component.hostnameArray).toStrictEqual([ 'ceph-node-00.cephlab.com', 'ceph-node-01.cephlab.com', 'ceph-node-02.cephlab.com', 'ceph-node-03.cephlab.com', 'ceph-node-04.cephlab.com', 'ceph-node-05.cephlab.com', 'ceph-node-06.cephlab.com', 'ceph-node-07.cephlab.com', 'ceph-node-08.cephlab.com', 'ceph-node-09.cephlab.com', 'ceph-node-10.cephlab.com' ]); component.hostnameArray = []; component.hostForm.get('hostname').setValue('ceph-node-00.cephlab.com,ceph-node-1.cephlab.com'); fixture.detectChanges(); component.submit(); expect(component.hostnameArray).toStrictEqual([ 'ceph-node-00.cephlab.com', 'ceph-node-1.cephlab.com' ]); component.hostnameArray = []; component.hostForm .get('hostname') .setValue('ceph-mon-[01-05].lab.com,ceph-osd-[1-4].lab.com,ceph-rgw-[001-006].lab.com'); fixture.detectChanges(); component.submit(); expect(component.hostnameArray).toStrictEqual([ 'ceph-mon-01.lab.com', 'ceph-mon-02.lab.com', 'ceph-mon-03.lab.com', 'ceph-mon-04.lab.com', 'ceph-mon-05.lab.com', 'ceph-osd-1.lab.com', 'ceph-osd-2.lab.com', 'ceph-osd-3.lab.com', 'ceph-osd-4.lab.com', 'ceph-rgw-001.lab.com', 'ceph-rgw-002.lab.com', 'ceph-rgw-003.lab.com', 'ceph-rgw-004.lab.com', 'ceph-rgw-005.lab.com', 'ceph-rgw-006.lab.com' ]); component.hostnameArray = []; component.hostForm .get('hostname') .setValue('ceph-(mon-[00-04],osd-[001-005],rgw-[1-3]).lab.com'); fixture.detectChanges(); component.submit(); expect(component.hostnameArray).toStrictEqual([ 'ceph-mon-00.lab.com', 'ceph-mon-01.lab.com', 'ceph-mon-02.lab.com', 'ceph-mon-03.lab.com', 'ceph-mon-04.lab.com', 'ceph-osd-001.lab.com', 'ceph-osd-002.lab.com', 'ceph-osd-003.lab.com', 'ceph-osd-004.lab.com', 'ceph-osd-005.lab.com', 'ceph-rgw-1.lab.com', 'ceph-rgw-2.lab.com', 'ceph-rgw-3.lab.com' ]); }); });
5,259
30.12426
102
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/hosts/host-form/host-form.component.ts
import { Component, OnInit } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { Router } from '@angular/router'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import expand from 'brace-expansion'; import { HostService } from '~/app/shared/api/host.service'; import { SelectMessages } from '~/app/shared/components/select/select-messages.model'; import { SelectOption } from '~/app/shared/components/select/select-option.model'; import { ActionLabelsI18n, URLVerbs } from '~/app/shared/constants/app.constants'; 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 { FinishedTask } from '~/app/shared/models/finished-task'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; @Component({ selector: 'cd-host-form', templateUrl: './host-form.component.html', styleUrls: ['./host-form.component.scss'] }) export class HostFormComponent extends CdForm implements OnInit { hostForm: CdFormGroup; action: string; resource: string; hostnames: string[]; hostnameArray: string[] = []; addr: string; status: string; allLabels: string[]; pageURL: string; hostPattern = false; labelsOption: Array<SelectOption> = []; hideMaintenance: boolean; messages = new SelectMessages({ empty: $localize`There are no labels.`, filter: $localize`Filter or add labels`, add: $localize`Add label` }); constructor( private router: Router, private actionLabels: ActionLabelsI18n, private hostService: HostService, private taskWrapper: TaskWrapperService, public activeModal: NgbActiveModal ) { super(); this.resource = $localize`host`; this.action = this.actionLabels.ADD; } ngOnInit() { if (this.router.url.includes('hosts')) { this.pageURL = 'hosts'; } this.createForm(); this.hostService.list('false').subscribe((resp: any[]) => { this.hostnames = resp.map((host) => { return host['hostname']; }); this.loadingReady(); }); this.hostService.getLabels().subscribe((resp: string[]) => { const uniqueLabels = new Set(resp.concat(this.hostService.predefinedLabels)); this.labelsOption = Array.from(uniqueLabels).map((label) => { return { enabled: true, name: label, selected: false, description: null }; }); }); } // check if hostname is a single value or pattern to hide network address field checkHostNameValue() { const hostNames = this.hostForm.get('hostname').value; hostNames.match(/[()\[\]{},]/g) ? (this.hostPattern = true) : (this.hostPattern = false); } private createForm() { this.hostForm = new CdFormGroup({ hostname: new FormControl('', { validators: [ Validators.required, CdValidators.custom('uniqueName', (hostname: string) => { return this.hostnames && this.hostnames.indexOf(hostname) !== -1; }) ] }), addr: new FormControl('', { validators: [CdValidators.ip()] }), labels: new FormControl([]), maintenance: new FormControl(false) }); } private isCommaSeparatedPattern(hostname: string) { // eg. ceph-node-01.cephlab.com,ceph-node-02.cephlab.com return hostname.includes(','); } private isRangeTypePattern(hostname: string) { // check if it is a range expression or comma separated range expression // eg. ceph-mon-[01-05].lab.com,ceph-osd-[02-08].lab.com,ceph-rgw-[01-09] return hostname.includes('[') && hostname.includes(']') && !hostname.match(/(?![^(]*\)),/g); } private replaceBraces(hostname: string) { // pattern to replace range [0-5] to [0..5](valid expression for brace expansion) // replace any kind of brackets with curly braces return hostname .replace(/(\d)\s*-\s*(\d)/g, '$1..$2') .replace(/\(/g, '{') .replace(/\)/g, '}') .replace(/\[/g, '{') .replace(/]/g, '}'); } // expand hostnames in case hostname is a pattern private checkHostNamePattern(hostname: string) { if (this.isRangeTypePattern(hostname)) { const hostnameRange = this.replaceBraces(hostname); this.hostnameArray = expand(hostnameRange); } else if (this.isCommaSeparatedPattern(hostname)) { let hostArray = []; hostArray = hostname.split(','); hostArray.forEach((host: string) => { if (this.isRangeTypePattern(host)) { const hostnameRange = this.replaceBraces(host); this.hostnameArray = this.hostnameArray.concat(expand(hostnameRange)); } else { this.hostnameArray.push(host); } }); } else { // single hostname this.hostnameArray.push(hostname); } } submit() { const hostname = this.hostForm.get('hostname').value; this.checkHostNamePattern(hostname); this.addr = this.hostForm.get('addr').value; this.status = this.hostForm.get('maintenance').value ? 'maintenance' : ''; this.allLabels = this.hostForm.get('labels').value; if (this.pageURL !== 'hosts' && !this.allLabels.includes('_no_schedule')) { this.allLabels.push('_no_schedule'); } this.hostnameArray.forEach((hostName: string) => { this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('host/' + URLVerbs.ADD, { hostname: hostName }), call: this.hostService.create(hostName, this.addr, this.allLabels, this.status) }) .subscribe({ error: () => { this.hostForm.setErrors({ cdSubmitButton: true }); }, complete: () => { this.pageURL === 'hosts' ? this.router.navigate([this.pageURL, { outlets: { modal: null } }]) : this.activeModal.close(); } }); }); } }
5,940
33.34104
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/inventory/inventory-host.model.ts
import { InventoryDevice } from './inventory-devices/inventory-device.model'; export class InventoryHost { name: string; devices: InventoryDevice[]; }
156
21.428571
77
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/inventory/inventory.component.html
<cd-orchestrator-doc-panel *ngIf="showDocPanel"></cd-orchestrator-doc-panel> <ng-container *ngIf="orchStatus?.available"> <legend i18n>Physical Disks</legend> <div class="row"> <div class="col-md-12"> <cd-inventory-devices [devices]="devices" [hiddenColumns]="hostname === undefined ? [] : ['hostname']" selectionType="single" (fetchInventory)="refresh()" [orchStatus]="orchStatus"> </cd-inventory-devices> </div> </div> </ng-container>
575
37.4
88
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/inventory/inventory.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { HostService } from '~/app/shared/api/host.service'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { InventoryDevicesComponent } from './inventory-devices/inventory-devices.component'; import { InventoryComponent } from './inventory.component'; describe('InventoryComponent', () => { let component: InventoryComponent; let fixture: ComponentFixture<InventoryComponent>; let orchService: OrchestratorService; let hostService: HostService; configureTestBed({ imports: [ BrowserAnimationsModule, FormsModule, SharedModule, HttpClientTestingModule, RouterTestingModule, ToastrModule.forRoot() ], declarations: [InventoryComponent, InventoryDevicesComponent] }); beforeEach(() => { fixture = TestBed.createComponent(InventoryComponent); component = fixture.componentInstance; orchService = TestBed.inject(OrchestratorService); hostService = TestBed.inject(HostService); spyOn(orchService, 'status').and.returnValue(of({ available: true })); spyOn(hostService, 'inventoryDeviceList').and.callThrough(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should not display doc panel if orchestrator is available', () => { expect(component.showDocPanel).toBeFalsy(); }); describe('after ngOnInit', () => { it('should load devices', () => { fixture.detectChanges(); component.refresh(); // click refresh button expect(hostService.inventoryDeviceList).toHaveBeenNthCalledWith(1, undefined, false); const newHost = 'host0'; component.hostname = newHost; fixture.detectChanges(); component.ngOnChanges(); expect(hostService.inventoryDeviceList).toHaveBeenNthCalledWith(2, newHost, false); component.refresh(); // click refresh button expect(hostService.inventoryDeviceList).toHaveBeenNthCalledWith(3, newHost, true); }); }); });
2,490
35.632353
92
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/inventory/inventory.component.ts
import { Component, Input, NgZone, OnChanges, OnDestroy, OnInit } from '@angular/core'; import { Subscription, timer as observableTimer } from 'rxjs'; import { HostService } from '~/app/shared/api/host.service'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; import { Icons } from '~/app/shared/enum/icons.enum'; import { OrchestratorStatus } from '~/app/shared/models/orchestrator.interface'; import { InventoryDevice } from './inventory-devices/inventory-device.model'; @Component({ selector: 'cd-inventory', templateUrl: './inventory.component.html', styleUrls: ['./inventory.component.scss'] }) export class InventoryComponent implements OnChanges, OnInit, OnDestroy { // Display inventory page only for this hostname, ignore to display all. @Input() hostname?: string; private reloadSubscriber: Subscription; private reloadInterval = 5000; private firstRefresh = true; icons = Icons; orchStatus: OrchestratorStatus; showDocPanel = false; devices: Array<InventoryDevice> = []; constructor( private orchService: OrchestratorService, private hostService: HostService, private ngZone: NgZone ) {} ngOnInit() { this.orchService.status().subscribe((status) => { this.orchStatus = status; this.showDocPanel = !status.available; if (status.available) { // Create a timer to get cached inventory from the orchestrator. // Do not ask the orchestrator frequently to refresh its cache data because it's expensive. this.ngZone.runOutsideAngular(() => { // start after first pass because the embedded table calls refresh at init. this.reloadSubscriber = observableTimer( this.reloadInterval, this.reloadInterval ).subscribe(() => { this.ngZone.run(() => { this.getInventory(false); }); }); }); } }); } ngOnDestroy() { this.reloadSubscriber?.unsubscribe(); } ngOnChanges() { if (this.orchStatus?.available) { this.devices = []; this.getInventory(false); } } getInventory(refresh: boolean) { if (this.hostname === '') { return; } this.hostService.inventoryDeviceList(this.hostname, refresh).subscribe( (devices: InventoryDevice[]) => { this.devices = devices; }, () => { this.devices = []; } ); } refresh() { // Make the first reload (triggered by table) use cached data, and // the remaining reloads (triggered by users) ask orchestrator to refresh inventory. this.getInventory(!this.firstRefresh); this.firstRefresh = false; } }
2,691
28.582418
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/inventory/inventory-devices/inventory-device.model.ts
export class SysAPI { vendor: string; model: string; size: number; rotational: string; human_readable_size: string; } export class InventoryDevice { hostname: string; uid: string; path: string; sys_api: SysAPI; available: boolean; rejected_reasons: string[]; device_id: string; human_readable_type: string; osd_ids: number[]; }
358
16.095238
30
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/inventory/inventory-devices/inventory-devices.component.html
<cd-table [data]="devices" [columns]="columns" identifier="uid" [forceIdentifier]="true" [selectionType]="selectionType" columnMode="flex" (fetchData)="getDevices()" [searchField]="false" (updateSelection)="updateSelection($event)" (columnFiltersChanged)="onColumnFiltersChanged($event)"> <cd-table-actions class="table-actions" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> </cd-table>
596
34.117647
66
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/inventory/inventory-devices/inventory-devices.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { HostService } from '~/app/shared/api/host.service'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { OrchestratorFeature } from '~/app/shared/models/orchestrator.enum'; import { OrchestratorStatus } from '~/app/shared/models/orchestrator.interface'; import { Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { InventoryDevicesComponent } from './inventory-devices.component'; describe('InventoryDevicesComponent', () => { let component: InventoryDevicesComponent; let fixture: ComponentFixture<InventoryDevicesComponent>; let orchService: OrchestratorService; let hostService: HostService; const fakeAuthStorageService = { getPermissions: () => { return new Permissions({ osd: ['read', 'update', 'create', 'delete'] }); } }; const mockOrchStatus = (available: boolean, features?: OrchestratorFeature[]) => { const orchStatus: OrchestratorStatus = { available: available, message: '', features: {} }; if (features) { features.forEach((feature: OrchestratorFeature) => { orchStatus.features[feature] = { available: true }; }); } component.orchStatus = orchStatus; }; configureTestBed({ imports: [ BrowserAnimationsModule, FormsModule, HttpClientTestingModule, SharedModule, RouterTestingModule, ToastrModule.forRoot() ], providers: [ { provide: AuthStorageService, useValue: fakeAuthStorageService }, TableActionsComponent ], declarations: [InventoryDevicesComponent] }); beforeEach(() => { fixture = TestBed.createComponent(InventoryDevicesComponent); component = fixture.componentInstance; hostService = TestBed.inject(HostService); orchService = TestBed.inject(OrchestratorService); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should have columns that are sortable', () => { expect(component.columns.every((column) => Boolean(column.prop))).toBeTruthy(); }); it('should call inventoryDataList only when showOnlyAvailableData is true', () => { const hostServiceSpy = spyOn(hostService, 'inventoryDeviceList').and.callThrough(); component.getDevices(); expect(hostServiceSpy).toBeCalledTimes(0); component.showAvailDeviceOnly = true; component.getDevices(); expect(hostServiceSpy).toBeCalledTimes(1); }); describe('table actions', () => { const fakeDevices = require('./fixtures/inventory_list_response.json'); beforeEach(() => { component.devices = fakeDevices; component.selectionType = 'single'; fixture.detectChanges(); }); const verifyTableActions = async ( tableActions: CdTableAction[], expectResult: { [action: string]: { disabled: boolean; disableDesc: string }; } ) => { fixture.detectChanges(); await fixture.whenStable(); const tableActionElement = fixture.debugElement.query(By.directive(TableActionsComponent)); // There is actually only one action for now const actions = {}; tableActions.forEach((action) => { const actionElement = tableActionElement.query(By.css('button')); actions[action.name] = { disabled: actionElement.classes.disabled ? true : false, disableDesc: actionElement.properties.title }; }); expect(actions).toEqual(expectResult); }; const testTableActions = async ( orch: boolean, features: OrchestratorFeature[], tests: { selectRow?: number; expectResults: any }[] ) => { mockOrchStatus(orch, features); fixture.detectChanges(); await fixture.whenStable(); for (const test of tests) { if (test.selectRow) { component.selection = new CdTableSelection(); component.selection.selected = [test.selectRow]; } await verifyTableActions(component.tableActions, test.expectResults); } }; it('should have correct states when Orchestrator is enabled', async () => { const tests = [ { expectResults: { Identify: { disabled: true, disableDesc: '' } } }, { selectRow: fakeDevices[0], expectResults: { Identify: { disabled: false, disableDesc: '' } } } ]; const features = [OrchestratorFeature.DEVICE_BLINK_LIGHT]; await testTableActions(true, features, tests); }); it('should have correct states when Orchestrator is disabled', async () => { const resultNoOrchestrator = { disabled: true, disableDesc: orchService.disableMessages.noOrchestrator }; const tests = [ { expectResults: { Identify: { disabled: true, disableDesc: '' } } }, { selectRow: fakeDevices[0], expectResults: { Identify: resultNoOrchestrator } } ]; await testTableActions(false, [], tests); }); it('should have correct states when Orchestrator features are missing', async () => { const resultMissingFeatures = { disabled: true, disableDesc: orchService.disableMessages.missingFeature }; const expectResults = [ { expectResults: { Identify: { disabled: true, disableDesc: '' } } }, { selectRow: fakeDevices[0], expectResults: { Identify: resultMissingFeatures } } ]; await testTableActions(true, [], expectResults); }); }); });
6,518
32.430769
101
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/inventory/inventory-devices/inventory-devices.component.ts
import { Component, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; import _ from 'lodash'; import { Subscription } from 'rxjs'; import { HostService } from '~/app/shared/api/host.service'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; import { FormModalComponent } from '~/app/shared/components/form-modal/form-modal.component'; import { TableComponent } from '~/app/shared/datatable/table/table.component'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableColumnFiltersChange } from '~/app/shared/models/cd-table-column-filters-change'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { OrchestratorFeature } from '~/app/shared/models/orchestrator.enum'; import { OrchestratorStatus } from '~/app/shared/models/orchestrator.interface'; import { Permission } from '~/app/shared/models/permissions'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { InventoryDevice } from './inventory-device.model'; @Component({ selector: 'cd-inventory-devices', templateUrl: './inventory-devices.component.html', styleUrls: ['./inventory-devices.component.scss'] }) export class InventoryDevicesComponent implements OnInit, OnDestroy { @ViewChild(TableComponent, { static: true }) table: TableComponent; // Devices @Input() devices: InventoryDevice[] = []; @Input() showAvailDeviceOnly = false; // Do not display these columns @Input() hiddenColumns: string[] = []; @Input() hostname = ''; @Input() diskType = ''; // Show filters for these columns, specify empty array to disable @Input() filterColumns = [ 'hostname', 'human_readable_type', 'available', 'sys_api.vendor', 'sys_api.model', 'sys_api.size' ]; // Device table row selection type @Input() selectionType: string = undefined; @Output() filterChange = new EventEmitter<CdTableColumnFiltersChange>(); @Output() fetchInventory = new EventEmitter(); icons = Icons; columns: Array<CdTableColumn> = []; selection: CdTableSelection = new CdTableSelection(); permission: Permission; tableActions: CdTableAction[]; fetchInventorySub: Subscription; @Input() orchStatus: OrchestratorStatus = undefined; actionOrchFeatures = { identify: [OrchestratorFeature.DEVICE_BLINK_LIGHT] }; constructor( private authStorageService: AuthStorageService, private dimlessBinary: DimlessBinaryPipe, private modalService: ModalService, private notificationService: NotificationService, private orchService: OrchestratorService, private hostService: HostService ) {} ngOnInit() { this.permission = this.authStorageService.getPermissions().osd; this.tableActions = [ { permission: 'update', icon: Icons.show, click: () => this.identifyDevice(), name: $localize`Identify`, disable: (selection: CdTableSelection) => this.getDisable('identify', selection), canBePrimary: (selection: CdTableSelection) => !selection.hasSingleSelection, visible: () => _.isString(this.selectionType) } ]; const columns = [ { name: $localize`Hostname`, prop: 'hostname', flexGrow: 1 }, { name: $localize`Device path`, prop: 'path', flexGrow: 1 }, { name: $localize`Type`, prop: 'human_readable_type', flexGrow: 1, cellTransformation: CellTemplate.badge, customTemplateConfig: { map: { hdd: { value: 'HDD', class: 'badge-hdd' }, ssd: { value: 'SSD', class: 'badge-ssd' } } } }, { name: $localize`Available`, prop: 'available', flexGrow: 1, cellClass: 'text-center', cellTransformation: CellTemplate.checkIcon }, { name: $localize`Vendor`, prop: 'sys_api.vendor', flexGrow: 1 }, { name: $localize`Model`, prop: 'sys_api.model', flexGrow: 1 }, { name: $localize`Size`, prop: 'sys_api.size', flexGrow: 1, pipe: this.dimlessBinary }, { name: $localize`OSDs`, prop: 'osd_ids', flexGrow: 1, cellTransformation: CellTemplate.badge, customTemplateConfig: { class: 'badge-dark', prefix: 'osd.' } } ]; this.columns = columns.filter((col: any) => { return !this.hiddenColumns.includes(col.prop); }); // init column filters _.forEach(this.filterColumns, (prop) => { const col = _.find(this.columns, { prop: prop }); if (col) { col.filterable = true; } if (col?.prop === 'human_readable_type' && this.diskType === 'ssd') { col.filterInitValue = this.diskType; } if (col?.prop === 'hostname' && this.hostname) { col.filterInitValue = this.hostname; } }); if (this.fetchInventory.observers.length > 0) { this.fetchInventorySub = this.table.fetchData.subscribe(() => { this.fetchInventory.emit(); }); } } getDevices() { if (this.showAvailDeviceOnly) { this.hostService.inventoryDeviceList().subscribe( (devices: InventoryDevice[]) => { this.devices = _.filter(devices, 'available'); this.devices = [...this.devices]; }, () => { this.devices = []; } ); } else { this.devices = [...this.devices]; } } ngOnDestroy() { if (this.fetchInventorySub) { this.fetchInventorySub.unsubscribe(); } } onColumnFiltersChanged(event: CdTableColumnFiltersChange) { this.filterChange.emit(event); } getDisable(action: 'identify', selection: CdTableSelection): boolean | string { if (!selection.hasSingleSelection) { return true; } return this.orchService.getTableActionDisableDesc( this.orchStatus, this.actionOrchFeatures[action] ); } updateSelection(selection: CdTableSelection) { this.selection = selection; } identifyDevice() { const selected = this.selection.first(); const hostname = selected.hostname; const device = selected.path || selected.device_id; this.modalService.show(FormModalComponent, { titleText: $localize`Identify device ${device}`, message: $localize`Please enter the duration how long to blink the LED.`, fields: [ { type: 'select', name: 'duration', value: 300, required: true, typeConfig: { options: [ { text: $localize`1 minute`, value: 60 }, { text: $localize`2 minutes`, value: 120 }, { text: $localize`5 minutes`, value: 300 }, { text: $localize`10 minutes`, value: 600 }, { text: $localize`15 minutes`, value: 900 } ] } } ], submitButtonText: $localize`Execute`, onSubmit: (values: any) => { this.hostService.identifyDevice(hostname, device, values.duration).subscribe(() => { this.notificationService.show( NotificationType.success, $localize`Identifying '${device}' started on host '${hostname}'` ); }); } }); } }
7,928
28.696629
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/logs/logs.component.html
<div *ngIf="contentData"> <ng-container *ngTemplateOutlet="logFiltersTpl"></ng-container> <nav ngbNav #nav="ngbNav" class="nav-tabs" cdStatefulTab="logs"> <ng-container ngbNavItem="cluster-logs"> <a ngbNavLink i18n>Cluster Logs</a> <ng-template ngbNavContent> <div class="card bg-light mb-3" *ngIf="clog"> <div class="btn-group" role="group" *ngIf="clog.length"> <cd-download-button [objectItem]="clog" [textItem]="clogText" fileName="cluster_log"> </cd-download-button> <cd-copy-2-clipboard-button [source]="clogText" [byId]="false"> </cd-copy-2-clipboard-button> </div> <div class="card-body"> <p *ngFor="let line of clog"> <span class="timestamp">{{ line.stamp | cdDate }}</span> <span class="priority {{ line.priority | logPriority }}">{{ line.priority }}</span> <span class="message" [innerHTML]="line.message | searchHighlight: search"></span> </p> <ng-container *ngIf="clog.length !== 0 else noEntriesTpl"></ng-container> </div> </div> </ng-template> </ng-container> <ng-container ngbNavItem="audit-logs"> <a ngbNavLink i18n>Audit Logs</a> <ng-template ngbNavContent> <div class="card bg-light mb-3" *ngIf="audit_log"> <div class="btn-group" role="group" *ngIf="audit_log.length"> <cd-download-button [objectItem]="audit_log" [textItem]="auditLogText" fileName="audit_log"> </cd-download-button> <cd-copy-2-clipboard-button [source]="auditLogText" [byId]="false"> </cd-copy-2-clipboard-button> </div> <div class="card-body"> <p *ngFor="let line of audit_log"> <span class="timestamp">{{ line.stamp | cdDate }}</span> <span class="priority {{ line.priority | logPriority }}">{{ line.priority }}</span> <span class="message" [innerHTML]="line.message | searchHighlight: search"></span> </p> <ng-container *ngIf="audit_log.length !== 0 else noEntriesTpl"></ng-container> </div> </div> </ng-template> </ng-container> <ng-container ngbNavItem="daemon-logs"> <a ngbNavLink i18n>Daemon Logs</a> <ng-template ngbNavContent> <ng-container *ngIf="lokiServiceStatus$ | async as lokiServiceStatus; else daemonLogsTpl"> <div *ngIf="promtailServiceStatus$ | async as promtailServiceStatus; else daemonLogsTpl"> <cd-grafana i18n-title title="Daemon logs" [grafanaPath]="'explore?'" [type]="'logs'" uid="CrAHE0iZz" grafanaStyle="three"> </cd-grafana> </div> </ng-container> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="nav"></div> </div> <ng-template #logFiltersTpl> <div class="row mb-3"> <div class="col-lg-10 d-flex"> <div class="col-sm-1 me-3"> <label for="logs-priority" class="fw-bold" i18n>Priority:</label> <select id="logs-priority" class="form-select" [(ngModel)]="priority" (ngModelChange)="filterLogs()"> <option *ngFor="let prio of priorities" [value]="prio.value">{{ prio.name }}</option> </select> </div> <div class="col-md-3 me-3"> <label for="logs-keyword" class="fw-bold" i18n>Keyword:</label> <div class="input-group"> <span class="input-group-text"> <i [ngClass]="[icons.search]"></i> </span> <input class="form-control" id="logs-keyword" type="text" [(ngModel)]="search" (keyup)="filterLogs()"> <button type="button" class="btn btn-light" (click)="clearSearchKey()" title="Clear"> <i class="icon-prepend {{ icons.destroy }}"></i> </button> </div> </div> <div class="col-md-3 me-3"> <label for="logs-date" class="fw-bold" i18n>Date:</label> <div class="input-group"> <input class="form-control" id="logs-date" placeholder="YYYY-MM-DD" ngbDatepicker [maxDate]="maxDate" #d="ngbDatepicker" (click)="d.open()" [(ngModel)]="selectedDate" (ngModelChange)="filterLogs()"> <button type="button" class="btn btn-light" (click)="clearDate()" title="Clear"> <i class="icon-prepend {{ icons.destroy }}"></i> </button> </div> </div> <div class="col-md-5"> <label i18n class="fw-bold">Time range:</label> <div class="d-flex"> <ngb-timepicker [spinners]="false" [(ngModel)]="startTime" (ngModelChange)="filterLogs()"></ngb-timepicker> <span class="mt-2">&nbsp;&mdash;&nbsp;</span> <ngb-timepicker [spinners]="false" [(ngModel)]="endTime" (ngModelChange)="filterLogs()"></ngb-timepicker> </div></div> </div></div> </ng-template> <ng-template #noEntriesTpl> <span i18n>No log entries found. Please try to select different filter options.</span> <span>&nbsp;</span> <a href="#" (click)="resetFilter()" i18n>Reset filter.</a> </ng-template> <ng-template #daemonLogsTpl> <cd-alert-panel type="info" title="Loki/Promtail service not running" i18n-title> <ng-container i18n>Please start the loki and promtail service to see these logs.</ng-container> </cd-alert-panel> </ng-template>
6,308
32.737968
99
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/logs/logs.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { NgbDatepickerModule, NgbNavModule, NgbTimepickerModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { LogsService } from '~/app/shared/api/logs.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { LogsComponent } from './logs.component'; describe('LogsComponent', () => { let component: LogsComponent; let fixture: ComponentFixture<LogsComponent>; let logsService: LogsService; let logsServiceSpy: jasmine.Spy; configureTestBed({ imports: [ HttpClientTestingModule, NgbNavModule, SharedModule, FormsModule, NgbDatepickerModule, NgbTimepickerModule, ToastrModule.forRoot() ], declarations: [LogsComponent] }); beforeEach(() => { logsService = TestBed.inject(LogsService); logsServiceSpy = spyOn(logsService, 'getLogs'); logsServiceSpy.and.returnValue(of(null)); fixture = TestBed.createComponent(LogsComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); describe('abstractFilters', () => { it('after initialized', () => { const filters = component.abstractFilters(); expect(filters.priority).toBe('All'); expect(filters.key).toBe(''); expect(filters.yearMonthDay).toBe(''); expect(filters.sTime).toBe(0); expect(filters.eTime).toBe(1439); }); it('change date', () => { component.selectedDate = { year: 2019, month: 1, day: 1 }; component.startTime = { hour: 1, minute: 10 }; component.endTime = { hour: 12, minute: 10 }; const filters = component.abstractFilters(); expect(filters.yearMonthDay).toBe('2019-01-01'); expect(filters.sTime).toBe(70); expect(filters.eTime).toBe(730); }); }); describe('filterLogs', () => { const contentData: Record<string, any> = { clog: [ { name: 'priority', stamp: '2019-02-21 09:39:49.572801', message: 'Manager daemon localhost is now available', priority: '[ERR]' }, { name: 'search', stamp: '2019-02-21 09:39:49.572801', message: 'Activating manager daemon localhost', priority: '[INF]' }, { name: 'date', stamp: '2019-01-21 09:39:49.572801', message: 'Manager daemon localhost is now available', priority: '[INF]' }, { name: 'time', stamp: '2019-02-21 01:39:49.572801', message: 'Manager daemon localhost is now available', priority: '[INF]' } ], audit_log: [] }; const resetFilter = () => { component.selectedDate = null; component.priority = 'All'; component.search = ''; component.startTime = { hour: 0, minute: 0 }; component.endTime = { hour: 23, minute: 59 }; }; beforeEach(() => { component.contentData = contentData; }); it('show all log', () => { component.filterLogs(); expect(component.clog.length).toBe(4); }); it('filter by search key', () => { resetFilter(); component.search = 'Activating'; component.filterLogs(); expect(component.clog.length).toBe(1); expect(component.clog[0].name).toBe('search'); }); it('filter by date', () => { resetFilter(); component.selectedDate = { year: 2019, month: 1, day: 21 }; component.filterLogs(); expect(component.clog.length).toBe(1); expect(component.clog[0].name).toBe('date'); }); it('filter by priority', () => { resetFilter(); component.priority = '[ERR]'; component.filterLogs(); expect(component.clog.length).toBe(1); expect(component.clog[0].name).toBe('priority'); }); it('filter by time range', () => { resetFilter(); component.startTime = { hour: 1, minute: 0 }; component.endTime = { hour: 2, minute: 0 }; component.filterLogs(); expect(component.clog.length).toBe(1); expect(component.clog[0].name).toBe('time'); }); }); describe('convert logs to text', () => { it('convert cluster & audit logs to text', () => { const logsPayload = { clog: [ { name: 'priority', stamp: '2019-02-21 09:39:49.572801', message: 'Manager daemon localhost is now available', priority: '[ERR]' } ], audit_log: [ { stamp: '2020-12-22T11:18:13.896920+0000', priority: '[INF]' } ] }; logsServiceSpy.and.returnValue(of(logsPayload)); fixture.detectChanges(); expect(component.clogText).toContain(logsPayload.clog[0].message); expect(component.auditLogText).toContain(logsPayload.audit_log[0].priority); }); }); });
5,192
29.547059
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/logs/logs.component.ts
import { DatePipe } from '@angular/common'; import { Component, NgZone, OnDestroy, OnInit } from '@angular/core'; import { NgbDateStruct } from '@ng-bootstrap/ng-bootstrap'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { CephServiceService } from '~/app/shared/api/ceph-service.service'; import { LogsService } from '~/app/shared/api/logs.service'; import { Icons } from '~/app/shared/enum/icons.enum'; @Component({ selector: 'cd-logs', templateUrl: './logs.component.html', styleUrls: ['./logs.component.scss'] }) export class LogsComponent implements OnInit, OnDestroy { contentData: any; clog: Array<any>; audit_log: Array<any>; icons = Icons; clogText: string; auditLogText: string; lokiServiceStatus$: Observable<boolean>; promtailServiceStatus$: Observable<boolean>; interval: number; priorities: Array<{ name: string; value: string }> = [ { name: 'Debug', value: '[DBG]' }, { name: 'Info', value: '[INF]' }, { name: 'Warning', value: '[WRN]' }, { name: 'Error', value: '[ERR]' }, { name: 'All', value: 'All' } ]; priority = 'All'; search = ''; selectedDate: NgbDateStruct; startTime = { hour: 0, minute: 0 }; endTime = { hour: 23, minute: 59 }; maxDate = { year: new Date().getFullYear(), month: new Date().getMonth() + 1, day: new Date().getDate() }; constructor( private logsService: LogsService, private cephService: CephServiceService, private datePipe: DatePipe, private ngZone: NgZone ) {} ngOnInit() { this.getInfo(); this.ngZone.runOutsideAngular(() => { this.getDaemonDetails(); this.interval = window.setInterval(() => { this.ngZone.run(() => { this.getInfo(); }); }, 5000); }); } ngOnDestroy() { clearInterval(this.interval); } getDaemonDetails() { this.lokiServiceStatus$ = this.cephService.getDaemons('loki').pipe( map((data: any) => { return data.length > 0 && data[0].status === 1; }) ); this.promtailServiceStatus$ = this.cephService.getDaemons('promtail').pipe( map((data: any) => { return data.length > 0 && data[0].status === 1; }) ); } getInfo() { this.logsService.getLogs().subscribe((data: any) => { this.contentData = data; this.clogText = this.logToText(this.contentData.clog); this.auditLogText = this.logToText(this.contentData.audit_log); this.filterLogs(); }); } abstractFilters(): any { const priority = this.priority; const key = this.search.toLowerCase(); let yearMonthDay: string; if (this.selectedDate) { const m = this.selectedDate.month; const d = this.selectedDate.day; const year = this.selectedDate.year; const month = m <= 9 ? `0${m}` : `${m}`; const day = d <= 9 ? `0${d}` : `${d}`; yearMonthDay = `${year}-${month}-${day}`; } else { yearMonthDay = ''; } const sHour = this.startTime?.hour ?? 0; const sMinutes = this.startTime?.minute ?? 0; const sTime = sHour * 60 + sMinutes; const eHour = this.endTime?.hour ?? 23; const eMinutes = this.endTime?.minute ?? 59; const eTime = eHour * 60 + eMinutes; return { priority, key, yearMonthDay, sTime, eTime }; } filterExecutor(logs: Array<any>, filters: any): Array<any> { return logs.filter((line) => { const localDate = this.datePipe.transform(line.stamp, 'mediumTime'); const hour = parseInt(localDate.split(':')[0], 10); const minutes = parseInt(localDate.split(':')[1], 10); let prio: string, y_m_d: string, timeSpan: number; prio = filters.priority === 'All' ? line.priority : filters.priority; y_m_d = filters.yearMonthDay ? filters.yearMonthDay : line.stamp; timeSpan = hour * 60 + minutes; return ( line.priority === prio && line.message.toLowerCase().indexOf(filters.key) !== -1 && line.stamp.indexOf(y_m_d) !== -1 && timeSpan >= filters.sTime && timeSpan <= filters.eTime ); }); } filterLogs() { const filters = this.abstractFilters(); this.clog = this.filterExecutor(this.contentData.clog, filters); this.audit_log = this.filterExecutor(this.contentData.audit_log, filters); } clearSearchKey() { this.search = ''; this.filterLogs(); } clearDate() { this.selectedDate = null; this.filterLogs(); } resetFilter() { this.priority = 'All'; this.search = ''; this.selectedDate = null; this.startTime = { hour: 0, minute: 0 }; this.endTime = { hour: 23, minute: 59 }; this.filterLogs(); return false; } logToText(log: object) { let logText = ''; for (const line of Object.keys(log)) { logText = logText + this.datePipe.transform(log[line].stamp, 'medium') + '\t' + log[line].priority + '\t' + log[line].message + '\n'; } return logText; } }
5,009
27.146067
79
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/mgr-modules/mgr-modules.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { AppRoutingModule } from '~/app/app-routing.module'; import { SharedModule } from '~/app/shared/shared.module'; import { MgrModuleDetailsComponent } from './mgr-module-details/mgr-module-details.component'; import { MgrModuleFormComponent } from './mgr-module-form/mgr-module-form.component'; import { MgrModuleListComponent } from './mgr-module-list/mgr-module-list.component'; @NgModule({ imports: [AppRoutingModule, CommonModule, ReactiveFormsModule, SharedModule, NgbNavModule], declarations: [MgrModuleListComponent, MgrModuleFormComponent, MgrModuleDetailsComponent] }) export class MgrModulesModule {}
827
45
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/mgr-modules/mgr-module-details/mgr-module-details.component.html
<ng-container *ngIf="selection"> <cd-table-key-value [data]="module_config"> </cd-table-key-value> </ng-container>
119
23
45
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/mgr-modules/mgr-module-details/mgr-module-details.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { MgrModuleDetailsComponent } from './mgr-module-details.component'; describe('MgrModuleDetailsComponent', () => { let component: MgrModuleDetailsComponent; let fixture: ComponentFixture<MgrModuleDetailsComponent>; configureTestBed({ declarations: [MgrModuleDetailsComponent], imports: [HttpClientTestingModule, SharedModule] }); beforeEach(() => { fixture = TestBed.createComponent(MgrModuleDetailsComponent); component = fixture.componentInstance; component.selection = undefined; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
897
31.071429
75
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/mgr-modules/mgr-module-details/mgr-module-details.component.ts
import { Component, Input, OnChanges } from '@angular/core'; import { MgrModuleService } from '~/app/shared/api/mgr-module.service'; @Component({ selector: 'cd-mgr-module-details', templateUrl: './mgr-module-details.component.html', styleUrls: ['./mgr-module-details.component.scss'] }) export class MgrModuleDetailsComponent implements OnChanges { module_config: any; @Input() selection: any; constructor(private mgrModuleService: MgrModuleService) {} ngOnChanges() { if (this.selection) { this.mgrModuleService.getConfig(this.selection.name).subscribe((resp: any) => { this.module_config = resp; }); } } }
659
24.384615
85
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/mgr-modules/mgr-module-form/mgr-module-form.component.html
<div class="cd-col-form" *cdFormLoading="loading"> <form name="mgrModuleForm" #frm="ngForm" [formGroup]="mgrModuleForm" novalidate> <div class="card"> <div class="card-header" i18n>Edit Manager module</div> <div class="card-body"> <div class="form-group row" *ngFor="let moduleOption of moduleOptions | keyvalue"> <!-- Field label --> <label class="cd-col-form-label" for="{{ moduleOption.value.name }}"> {{ moduleOption.value.name }} <cd-helper *ngIf="moduleOption.value.long_desc || moduleOption.value.desc"> {{ moduleOption.value.long_desc || moduleOption.value.desc | upperFirst }} </cd-helper> </label> <!-- Field control --> <!-- bool --> <div class="cd-col-form-input" *ngIf="moduleOption.value.type === 'bool'"> <div class="custom-control custom-checkbox"> <input id="{{ moduleOption.value.name }}" type="checkbox" class="custom-control-input" formControlName="{{ moduleOption.value.name }}"> <label class="custom-control-label" for="{{ moduleOption.value.name }}"></label> </div> </div> <!-- addr|str|uuid --> <div class="cd-col-form-input" *ngIf="['addr', 'str', 'uuid'].includes(moduleOption.value.type)"> <input id="{{ moduleOption.value.name }}" class="form-control" type="text" formControlName="{{ moduleOption.value.name }}" *ngIf="moduleOption.value.enum_allowed.length === 0"> <select id="{{ moduleOption.value.name }}" class="form-select" formControlName="{{ moduleOption.value.name }}" *ngIf="moduleOption.value.enum_allowed.length > 0"> <option *ngFor="let value of moduleOption.value.enum_allowed" [ngValue]="value"> {{ value }} </option> </select> <span class="invalid-feedback" *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'invalidUuid')" i18n>The entered value is not a valid UUID, e.g.: 67dcac9f-2c03-4d6c-b7bd-1210b3a259a8</span> <span class="invalid-feedback" *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'pattern')" i18n>The entered value needs to be a valid IP address.</span> </div> <!-- uint|int|size|secs --> <div class="cd-col-form-input" *ngIf="['uint', 'int', 'size', 'secs'].includes(moduleOption.value.type)"> <input id="{{ moduleOption.value.name }}" class="form-control" type="number" formControlName="{{ moduleOption.value.name }}" min="{{ moduleOption.value.min }}" max="{{ moduleOption.value.max }}"> <span class="invalid-feedback" *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'max')" i18n>The entered value is too high! It must be lower or equal to {{ moduleOption.value.max }}.</span> <span class="invalid-feedback" *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'min')" i18n>The entered value is too low! It must be greater or equal to {{ moduleOption.value.min }}.</span> <span class="invalid-feedback" *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'pattern')" i18n>The entered value needs to be a number.</span> </div> <!-- float --> <div class="cd-col-form-input" *ngIf="moduleOption.value.type === 'float'"> <input id="{{ moduleOption.value.name }}" class="form-control" type="number" formControlName="{{ moduleOption.value.name }}"> <span class="invalid-feedback" *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="mgrModuleForm.showError(moduleOption.value.name, frm, 'pattern')" i18n>The entered value needs to be a number or decimal.</span> </div> </div> </div> <div class="card-footer"> <cd-form-button-panel (submitActionEvent)="onSubmit()" [form]="mgrModuleForm" [submitText]="actionLabels.UPDATE" wrappingClass="text-right"></cd-form-button-panel> </div> </div> </form> </div>
5,185
45.720721
120
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/mgr-modules/mgr-module-form/mgr-module-form.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { 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 { MgrModuleFormComponent } from './mgr-module-form.component'; describe('MgrModuleFormComponent', () => { let component: MgrModuleFormComponent; let fixture: ComponentFixture<MgrModuleFormComponent>; configureTestBed( { declarations: [MgrModuleFormComponent], imports: [ HttpClientTestingModule, ReactiveFormsModule, RouterTestingModule, SharedModule, ToastrModule.forRoot() ] }, [LoadingPanelComponent] ); beforeEach(() => { fixture = TestBed.createComponent(MgrModuleFormComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('getValidators', () => { it('should return ip validator for type addr', () => { const result = component.getValidators({ type: 'addr' }); expect(result.length).toBe(1); }); it('should return required validator for types uint, int, size, secs', () => { const types = ['uint', 'int', 'size', 'secs']; types.forEach((type) => { const result = component.getValidators({ type: type }); expect(result.length).toBe(1); }); }); it('should return required, decimalNumber validators for type float', () => { const result = component.getValidators({ type: 'float' }); expect(result.length).toBe(2); }); it('should return uuid validator for type uuid', () => { const result = component.getValidators({ type: 'uuid' }); expect(result.length).toBe(1); }); it('should return no validator for type str', () => { const result = component.getValidators({ type: 'str' }); expect(result.length).toBe(0); }); it('should return min validator for type str', () => { const result = component.getValidators({ type: 'str', min: 1 }); expect(result.length).toBe(1); }); it('should return min, max validators for type str', () => { const result = component.getValidators({ type: 'str', min: 1, max: 127 }); expect(result.length).toBe(2); }); }); });
2,660
31.851852
102
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/mgr-modules/mgr-module-form/mgr-module-form.component.ts
import { Component, OnInit } from '@angular/core'; import { ValidatorFn, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import _ from 'lodash'; import { forkJoin as observableForkJoin } from 'rxjs'; import { MgrModuleService } from '~/app/shared/api/mgr-module.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 { CdValidators } from '~/app/shared/forms/cd-validators'; import { NotificationService } from '~/app/shared/services/notification.service'; @Component({ selector: 'cd-mgr-module-form', templateUrl: './mgr-module-form.component.html', styleUrls: ['./mgr-module-form.component.scss'] }) export class MgrModuleFormComponent extends CdForm implements OnInit { mgrModuleForm: CdFormGroup; moduleName = ''; moduleOptions: any[] = []; constructor( public actionLabels: ActionLabelsI18n, private route: ActivatedRoute, private router: Router, private formBuilder: CdFormBuilder, private mgrModuleService: MgrModuleService, private notificationService: NotificationService ) { super(); } ngOnInit() { this.route.params.subscribe((params: { name: string }) => { this.moduleName = decodeURIComponent(params.name); const observables = [ this.mgrModuleService.getOptions(this.moduleName), this.mgrModuleService.getConfig(this.moduleName) ]; observableForkJoin(observables).subscribe( (resp: object) => { this.moduleOptions = resp[0]; // Create the form dynamically. this.createForm(); // Set the form field values. this.mgrModuleForm.setValue(resp[1]); this.loadingReady(); }, (_error) => { this.loadingError(); } ); }); } getValidators(moduleOption: any): ValidatorFn[] { const result = []; switch (moduleOption.type) { case 'addr': result.push(CdValidators.ip()); break; case 'uint': case 'int': case 'size': case 'secs': result.push(Validators.required); break; case 'str': if (_.isNumber(moduleOption.min)) { result.push(Validators.minLength(moduleOption.min)); } if (_.isNumber(moduleOption.max)) { result.push(Validators.maxLength(moduleOption.max)); } break; case 'float': result.push(Validators.required); result.push(CdValidators.decimalNumber()); break; case 'uuid': result.push(CdValidators.uuid()); break; } return result; } createForm() { const controlsConfig = {}; _.forEach(this.moduleOptions, (moduleOption) => { controlsConfig[moduleOption.name] = [ moduleOption.default_value, this.getValidators(moduleOption) ]; }); this.mgrModuleForm = this.formBuilder.group(controlsConfig); } goToListView() { this.router.navigate(['/mgr-modules']); } onSubmit() { // Exit immediately if the form isn't dirty. if (this.mgrModuleForm.pristine) { this.goToListView(); return; } const config = {}; _.forEach(this.moduleOptions, (moduleOption) => { const control = this.mgrModuleForm.get(moduleOption.name); // Append the option only if the value has been modified. if (control.dirty && control.valid) { config[moduleOption.name] = control.value; } }); this.mgrModuleService.updateConfig(this.moduleName, config).subscribe( () => { this.notificationService.show( NotificationType.success, $localize`Updated options for module '${this.moduleName}'.` ); this.goToListView(); }, () => { // Reset the 'Submit' button. this.mgrModuleForm.setErrors({ cdSubmitButton: true }); } ); } }
4,162
29.610294
81
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/mgr-modules/mgr-module-list/mgr-module-list.component.html
<cd-table #table [autoReload]="false" [data]="modules" [columns]="columns" columnMode="flex" selectionType="single" [hasDetails]="true" (setExpandedRow)="setExpandedRow($event)" (updateSelection)="updateSelection($event)" identifier="module" (fetchData)="getModuleList($event)"> <cd-table-actions class="table-actions" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> <cd-mgr-module-details cdTableDetail [selection]="expandedRow"> </cd-mgr-module-details> </cd-table>
714
33.047619
53
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/mgr-modules/mgr-module-list/mgr-module-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of as observableOf, throwError as observableThrowError } from 'rxjs'; import { MgrModuleService } from '~/app/shared/api/mgr-module.service'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, PermissionHelper } from '~/testing/unit-test-helper'; import { MgrModuleDetailsComponent } from '../mgr-module-details/mgr-module-details.component'; import { MgrModuleListComponent } from './mgr-module-list.component'; describe('MgrModuleListComponent', () => { let component: MgrModuleListComponent; let fixture: ComponentFixture<MgrModuleListComponent>; let mgrModuleService: MgrModuleService; let notificationService: NotificationService; configureTestBed({ declarations: [MgrModuleListComponent, MgrModuleDetailsComponent], imports: [ BrowserAnimationsModule, RouterTestingModule, SharedModule, HttpClientTestingModule, NgbNavModule, ToastrModule.forRoot() ], providers: [MgrModuleService, NotificationService] }); beforeEach(() => { fixture = TestBed.createComponent(MgrModuleListComponent); component = fixture.componentInstance; mgrModuleService = TestBed.inject(MgrModuleService); notificationService = TestBed.inject(NotificationService); }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should test all TableActions combinations', () => { const permissionHelper: PermissionHelper = new PermissionHelper(component.permission); const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions( component.tableActions ); expect(tableActions).toEqual({ 'create,update,delete': { actions: ['Edit', 'Enable', 'Disable'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, 'create,update': { actions: ['Edit', 'Enable', 'Disable'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, 'create,delete': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, create: { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, 'update,delete': { actions: ['Edit', 'Enable', 'Disable'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, update: { actions: ['Edit', 'Enable', 'Disable'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, delete: { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); describe('should update module state', () => { beforeEach(() => { component.selection = new CdTableSelection(); spyOn(notificationService, 'suspendToasties'); spyOn(component.blockUI, 'start'); spyOn(component.blockUI, 'stop'); spyOn(component.table, 'refreshBtn'); }); it('should enable module', fakeAsync(() => { spyOn(mgrModuleService, 'enable').and.returnValue(observableThrowError('y')); spyOn(mgrModuleService, 'list').and.returnValues(observableThrowError('z'), observableOf([])); component.selection.add({ name: 'foo', enabled: false, always_on: false }); component.updateModuleState(); tick(2000); tick(2000); expect(mgrModuleService.enable).toHaveBeenCalledWith('foo'); expect(mgrModuleService.list).toHaveBeenCalledTimes(2); expect(notificationService.suspendToasties).toHaveBeenCalledTimes(2); expect(component.blockUI.start).toHaveBeenCalled(); expect(component.blockUI.stop).toHaveBeenCalled(); expect(component.table.refreshBtn).toHaveBeenCalled(); })); it('should disable module', fakeAsync(() => { spyOn(mgrModuleService, 'disable').and.returnValue(observableThrowError('x')); spyOn(mgrModuleService, 'list').and.returnValue(observableOf([])); component.selection.add({ name: 'bar', enabled: true, always_on: false }); component.updateModuleState(); tick(2000); expect(mgrModuleService.disable).toHaveBeenCalledWith('bar'); expect(mgrModuleService.list).toHaveBeenCalledTimes(1); expect(notificationService.suspendToasties).toHaveBeenCalledTimes(2); expect(component.blockUI.start).toHaveBeenCalled(); expect(component.blockUI.stop).toHaveBeenCalled(); expect(component.table.refreshBtn).toHaveBeenCalled(); })); it.only('should not disable module without selecting one', () => { expect(component.getTableActionDisabledDesc()).toBeTruthy(); }); it('should not disable dashboard module', () => { component.selection.selected = [ { name: 'dashboard' } ]; expect(component.getTableActionDisabledDesc()).toBeTruthy(); }); it('should not disable an always-on module', () => { component.selection.selected = [ { name: 'bar', always_on: true } ]; expect(component.getTableActionDisabledDesc()).toBe('This Manager module is always on.'); }); }); });
6,020
37.596154
101
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/mgr-modules/mgr-module-list/mgr-module-list.component.ts
import { Component, ViewChild } from '@angular/core'; import { BlockUI, NgBlockUI } from 'ng-block-ui'; import { timer as observableTimer } from 'rxjs'; import { MgrModuleService } from '~/app/shared/api/mgr-module.service'; import { ListWithDetails } from '~/app/shared/classes/list-with-details.class'; 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 { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { NotificationService } from '~/app/shared/services/notification.service'; @Component({ selector: 'cd-mgr-module-list', templateUrl: './mgr-module-list.component.html', styleUrls: ['./mgr-module-list.component.scss'] }) export class MgrModuleListComponent extends ListWithDetails { @ViewChild(TableComponent, { static: true }) table: TableComponent; @BlockUI() blockUI: NgBlockUI; permission: Permission; tableActions: CdTableAction[]; columns: CdTableColumn[] = []; modules: object[] = []; selection: CdTableSelection = new CdTableSelection(); constructor( private authStorageService: AuthStorageService, private mgrModuleService: MgrModuleService, private notificationService: NotificationService ) { super(); this.permission = this.authStorageService.getPermissions().configOpt; this.columns = [ { name: $localize`Name`, prop: 'name', flexGrow: 1 }, { name: $localize`Enabled`, prop: 'enabled', flexGrow: 1, cellClass: 'text-center', cellTransformation: CellTemplate.checkIcon }, { name: $localize`Always-On`, prop: 'always_on', flexGrow: 1, cellClass: 'text-center', cellTransformation: CellTemplate.checkIcon } ]; const getModuleUri = () => this.selection.first() && encodeURIComponent(this.selection.first().name); this.tableActions = [ { name: $localize`Edit`, permission: 'update', disable: () => { if (!this.selection.hasSelection) { return true; } // Disable the 'edit' button when the module has no options. return Object.values(this.selection.first().options).length === 0; }, routerLink: () => `/mgr-modules/edit/${getModuleUri()}`, icon: Icons.edit }, { name: $localize`Enable`, permission: 'update', click: () => this.updateModuleState(), disable: () => this.isTableActionDisabled('enabled'), icon: Icons.start }, { name: $localize`Disable`, permission: 'update', click: () => this.updateModuleState(), disable: () => this.getTableActionDisabledDesc(), icon: Icons.stop } ]; } getModuleList(context: CdTableFetchDataContext) { this.mgrModuleService.list().subscribe( (resp: object[]) => { this.modules = resp; }, () => { context.error(); } ); } updateSelection(selection: CdTableSelection) { this.selection = selection; } /** * Check if the table action is disabled. * @param state The expected module state, e.g. ``enabled`` or ``disabled``. * @returns If the specified state is validated to true or no selection is * done, then ``true`` is returned, otherwise ``false``. */ isTableActionDisabled(state: 'enabled' | 'disabled') { if (!this.selection.hasSelection) { return true; } const selected = this.selection.first(); // Make sure the user can't modify the run state of the 'Dashboard' module. // This check is only done in the UI because the REST API should still be // able to do so. if (selected.name === 'dashboard') { return true; } // Always-on modules can't be disabled. if (selected.always_on) { return true; } switch (state) { case 'enabled': return selected.enabled; case 'disabled': return !selected.enabled; } } getTableActionDisabledDesc(): string | boolean { if (this.selection.first()?.always_on) { return $localize`This Manager module is always on.`; } return this.isTableActionDisabled('disabled'); } /** * Update the Ceph Mgr module state to enabled or disabled. */ updateModuleState() { if (!this.selection.hasSelection) { return; } let $obs; const fnWaitUntilReconnected = () => { observableTimer(2000).subscribe(() => { // Trigger an API request to check if the connection is // re-established. this.mgrModuleService.list().subscribe( () => { // Resume showing the notification toasties. this.notificationService.suspendToasties(false); // Unblock the whole UI. this.blockUI.stop(); // Reload the data table content. this.table.refreshBtn(); }, () => { fnWaitUntilReconnected(); } ); }); }; // Note, the Ceph Mgr is always restarted when a module // is enabled/disabled. const module = this.selection.first(); if (module.enabled) { $obs = this.mgrModuleService.disable(module.name); } else { $obs = this.mgrModuleService.enable(module.name); } $obs.subscribe( () => undefined, () => { // Suspend showing the notification toasties. this.notificationService.suspendToasties(true); // Block the whole UI to prevent user interactions until // the connection to the backend is reestablished this.blockUI.start($localize`Reconnecting, please wait ...`); fnWaitUntilReconnected(); } ); } }
6,249
30.407035
90
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/monitor/monitor.component.html
<div class="row"> <div class="col-lg-4"> <fieldset> <legend class="cd-header" i18n>Status</legend> <table class="table table-striped" *ngIf="mon_status"> <tbody> <tr> <td i18n class="bold">Cluster ID</td> <td>{{ mon_status.monmap.fsid }}</td> </tr> <tr> <td i18n class="bold">monmap modified</td> <td>{{ mon_status.monmap.modified | relativeDate }}</td> </tr> <tr> <td i18n class="bold">monmap epoch</td> <td>{{ mon_status.monmap.epoch }}</td> </tr> <tr> <td i18n class="bold">quorum con</td> <td>{{ mon_status.features.quorum_con }}</td> </tr> <tr> <td i18n class="bold">quorum mon</td> <td>{{ mon_status.features.quorum_mon }}</td> </tr> <tr> <td i18n class="bold">required con</td> <td>{{ mon_status.features.required_con }}</td> </tr> <tr> <td i18n class="bold">required mon</td> <td>{{ mon_status.features.required_mon }}</td> </tr> </tbody> </table> </fieldset> </div> <div class="col-lg-8"> <legend i18n class="in-quorum cd-header">In Quorum</legend> <div> <cd-table [data]="inQuorum.data" [columns]="inQuorum.columns"> </cd-table></div> <legend i18n class="in-quorum cd-header">Not In Quorum</legend> <div> <cd-table [data]="notInQuorum.data" (fetchData)="refresh()" [columns]="notInQuorum.columns"> </cd-table></div> </div> </div>
1,837
26.848485
68
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/monitor/monitor.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 { of } from 'rxjs'; import { MonitorService } from '~/app/shared/api/monitor.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { MonitorComponent } from './monitor.component'; describe('MonitorComponent', () => { let component: MonitorComponent; let fixture: ComponentFixture<MonitorComponent>; let getMonitorSpy: jasmine.Spy; configureTestBed({ imports: [HttpClientTestingModule, SharedModule], declarations: [MonitorComponent], schemas: [NO_ERRORS_SCHEMA], providers: [MonitorService] }); beforeEach(() => { fixture = TestBed.createComponent(MonitorComponent); component = fixture.componentInstance; const getMonitorPayload: Record<string, any> = { in_quorum: [ { stats: { num_sessions: [[1, 5]] } }, { stats: { num_sessions: [ [1, 1], [2, 10], [3, 1] ] } }, { stats: { num_sessions: [ [1, 0], [2, 3] ] } }, { stats: { num_sessions: [ [1, 2], [2, 1], [3, 7], [4, 5] ] } } ], mon_status: null, out_quorum: [] }; getMonitorSpy = spyOn(TestBed.inject(MonitorService), 'getMonitor').and.returnValue( of(getMonitorPayload) ); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should sort by open sessions column correctly', () => { component.refresh(); expect(getMonitorSpy).toHaveBeenCalled(); expect(component.inQuorum.columns[3].comparator(undefined, undefined)).toBe(0); expect(component.inQuorum.columns[3].comparator(null, null)).toBe(0); expect(component.inQuorum.columns[3].comparator([], [])).toBe(0); expect( component.inQuorum.columns[3].comparator( component.inQuorum.data[0].cdOpenSessions, component.inQuorum.data[3].cdOpenSessions ) ).toBe(0); expect( component.inQuorum.columns[3].comparator( component.inQuorum.data[0].cdOpenSessions, component.inQuorum.data[1].cdOpenSessions ) ).toBe(1); expect( component.inQuorum.columns[3].comparator( component.inQuorum.data[1].cdOpenSessions, component.inQuorum.data[0].cdOpenSessions ) ).toBe(-1); expect( component.inQuorum.columns[3].comparator( component.inQuorum.data[2].cdOpenSessions, component.inQuorum.data[1].cdOpenSessions ) ).toBe(1); }); });
2,917
26.528302
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/monitor/monitor.component.ts
import { Component } from '@angular/core'; import _ from 'lodash'; import { MonitorService } from '~/app/shared/api/monitor.service'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; @Component({ selector: 'cd-monitor', templateUrl: './monitor.component.html', styleUrls: ['./monitor.component.scss'] }) export class MonitorComponent { mon_status: any; inQuorum: any; notInQuorum: any; interval: any; constructor(private monitorService: MonitorService) { this.inQuorum = { columns: [ { prop: 'name', name: $localize`Name`, cellTransformation: CellTemplate.routerLink }, { prop: 'rank', name: $localize`Rank` }, { prop: 'public_addr', name: $localize`Public Address` }, { prop: 'cdOpenSessions', name: $localize`Open Sessions`, cellTransformation: CellTemplate.sparkline, comparator: (dataA: any, dataB: any) => { // We get the last value of time series to compare: const lastValueA = _.last(dataA); const lastValueB = _.last(dataB); if (!lastValueA || !lastValueB || lastValueA === lastValueB) { return 0; } return lastValueA > lastValueB ? 1 : -1; } } ] }; this.notInQuorum = { columns: [ { prop: 'name', name: $localize`Name`, cellTransformation: CellTemplate.routerLink }, { prop: 'rank', name: $localize`Rank` }, { prop: 'public_addr', name: $localize`Public Address` } ] }; } refresh() { this.monitorService.getMonitor().subscribe((data: any) => { data.in_quorum.map((row: any) => { row.cdOpenSessions = row.stats.num_sessions.map((i: string) => i[1]); row.cdLink = '/perf_counters/mon/' + row.name; row.cdParams = { fromLink: '/monitor' }; return row; }); data.out_quorum.map((row: any) => { row.cdLink = '/perf_counters/mon/' + row.name; row.cdParams = { fromLink: '/monitor' }; return row; }); this.inQuorum.data = [...data.in_quorum]; this.notInQuorum.data = [...data.out_quorum]; this.mon_status = data.mon_status; }); } }
2,232
28.773333
93
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-creation-preview-modal/osd-creation-preview-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container class="modal-title" i18n>OSD creation preview</ng-container> <ng-container class="modal-content"> <form #frm="ngForm" [formGroup]="formGroup" novalidate> <div class="modal-body"> <h4 i18n>DriveGroups</h4> <pre>{{ driveGroups | json}}</pre> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="onSubmit()" [form]="formGroup" [submitText]="action | titlecase"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
658
30.380952
87
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-creation-preview-modal/osd-creation-preview-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { OsdCreationPreviewModalComponent } from './osd-creation-preview-modal.component'; describe('OsdCreationPreviewModalComponent', () => { let component: OsdCreationPreviewModalComponent; let fixture: ComponentFixture<OsdCreationPreviewModalComponent>; configureTestBed({ imports: [ HttpClientTestingModule, ReactiveFormsModule, SharedModule, RouterTestingModule, ToastrModule.forRoot() ], providers: [NgbActiveModal], declarations: [OsdCreationPreviewModalComponent] }); beforeEach(() => { fixture = TestBed.createComponent(OsdCreationPreviewModalComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,267
31.512821
90
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-creation-preview-modal/osd-creation-preview-modal.component.ts
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { OsdService } from '~/app/shared/api/osd.service'; import { ActionLabelsI18n, URLVerbs } from '~/app/shared/constants/app.constants'; import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; @Component({ selector: 'cd-osd-creation-preview-modal', templateUrl: './osd-creation-preview-modal.component.html', styleUrls: ['./osd-creation-preview-modal.component.scss'] }) export class OsdCreationPreviewModalComponent { @Input() driveGroups: Object[] = []; @Output() submitAction = new EventEmitter(); action: string; formGroup: CdFormGroup; constructor( public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private formBuilder: CdFormBuilder, private osdService: OsdService, private taskWrapper: TaskWrapperService ) { this.action = actionLabels.CREATE; this.createForm(); } createForm() { this.formGroup = this.formBuilder.group({}); } onSubmit() { const trackingId = _.join(_.map(this.driveGroups, 'service_id'), ', '); this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('osd/' + URLVerbs.CREATE, { tracking_id: trackingId }), call: this.osdService.create(this.driveGroups, trackingId) }) .subscribe({ error: () => { this.formGroup.setErrors({ cdSubmitButton: true }); }, complete: () => { this.submitAction.emit(); this.activeModal.close(); } }); } }
1,872
28.730159
82
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-details/osd-details.component.html
<ng-container *ngIf="selection"> <nav ngbNav #nav="ngbNav" id="tabset-osd-details" class="nav-tabs" cdStatefulTab="osd-details"> <ng-container ngbNavItem="devices"> <a ngbNavLink i18n>Devices</a> <ng-template ngbNavContent> <cd-device-list [osdId]="osd?.id" [hostname]="selection?.host.name" [osdList]="true"></cd-device-list> </ng-template> </ng-container> <ng-container ngbNavItem="attributes"> <a ngbNavLink i18n>Attributes (OSD map)</a> <ng-template ngbNavContent> <cd-table-key-value [data]="osd?.details?.osd_map"> </cd-table-key-value> </ng-template> </ng-container> <ng-container ngbNavItem="metadata"> <a ngbNavLink i18n>Metadata</a> <ng-template ngbNavContent> <cd-table-key-value *ngIf="osd?.details?.osd_metadata; else noMetaData" (fetchData)="refresh()" [data]="osd?.details?.osd_metadata"> </cd-table-key-value> <ng-template #noMetaData> <cd-alert-panel type="warning" i18n>Metadata not available</cd-alert-panel> </ng-template> </ng-template> </ng-container> <ng-container ngbNavItem="device-health"> <a ngbNavLink i18n>Device health</a> <ng-template ngbNavContent> <cd-smart-list [osdId]="osd?.id"></cd-smart-list> </ng-template> </ng-container> <ng-container ngbNavItem="performance-counter"> <a ngbNavLink i18n>Performance counter</a> <ng-template ngbNavContent> <cd-table-performance-counter *ngIf="osd?.details" serviceType="osd" [serviceId]="osd?.id"> </cd-table-performance-counter> </ng-template> </ng-container> <ng-container ngbNavItem="performance-details" *ngIf="grafanaPermission.read"> <a ngbNavLink i18n>Performance Details</a> <ng-template ngbNavContent> <cd-grafana i18n-title title="OSD details" [grafanaPath]="'osd-device-details?var-osd=osd.' + osd['id']" [type]="'metrics'" uid="CrAHE0iZz" grafanaStyle="three"> </cd-grafana> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="nav"></div> </ng-container>
2,524
33.589041
81
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-details/osd-details.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { TablePerformanceCounterComponent } from '~/app/ceph/performance-counter/table-performance-counter/table-performance-counter.component'; import { CephSharedModule } from '~/app/ceph/shared/ceph-shared.module'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { OsdDetailsComponent } from './osd-details.component'; describe('OsdDetailsComponent', () => { let component: OsdDetailsComponent; let fixture: ComponentFixture<OsdDetailsComponent>; configureTestBed({ imports: [HttpClientTestingModule, NgbNavModule, SharedModule, CephSharedModule], declarations: [OsdDetailsComponent, TablePerformanceCounterComponent] }); beforeEach(() => { fixture = TestBed.createComponent(OsdDetailsComponent); component = fixture.componentInstance; component.selection = undefined; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,198
36.46875
144
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-details/osd-details.component.ts
import { Component, Input, OnChanges } from '@angular/core'; import _ from 'lodash'; import { OsdService } from '~/app/shared/api/osd.service'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; @Component({ selector: 'cd-osd-details', templateUrl: './osd-details.component.html', styleUrls: ['./osd-details.component.scss'] }) export class OsdDetailsComponent implements OnChanges { @Input() selection: any; osd: { id?: number; details?: any; tree?: any; }; grafanaPermission: Permission; constructor(private osdService: OsdService, private authStorageService: AuthStorageService) { this.grafanaPermission = this.authStorageService.getPermissions().grafana; } ngOnChanges() { if (this.osd?.id !== this.selection?.id) { this.osd = this.selection; } if (_.isNumber(this.osd?.id)) { this.refresh(); } } refresh() { this.osdService.getDetails(this.osd.id).subscribe((data) => { this.osd.details = data; }); } }
1,094
23.333333
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-devices-selection-groups/devices-selection-change-event.interface.ts
import { CdTableColumnFiltersChange } from '~/app/shared/models/cd-table-column-filters-change'; export interface DevicesSelectionChangeEvent extends CdTableColumnFiltersChange { type: string; }
198
32.166667
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-devices-selection-groups/devices-selection-clear-event.interface.ts
import { InventoryDevice } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-device.model'; export interface DevicesSelectionClearEvent { type: string; clearedDevices: InventoryDevice[]; }
207
28.714286
104
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-devices-selection-groups/osd-devices-selection-groups.component.html
<!-- button --> <div class="form-group row"> <label class="cd-col-form-label" for="createDeleteButton"> <ng-container i18n>{{ name }} devices</ng-container> <cd-helper> <span i18n *ngIf="type === 'data'">The primary storage devices. These devices contain all OSD data.</span> <span i18n *ngIf="type === 'wal'">Write-Ahead-Log devices. These devices are used for BlueStore’s internal journal. It is only useful to use a WAL device if the device is faster than the primary device (e.g. NVME devices or SSDs). If there is only a small amount of fast storage available (e.g., less than a gigabyte), we recommend using it as a WAL device.</span> <span i18n *ngIf="type === 'db'">DB devices can be used for storing BlueStore’s internal metadata. It is only helpful to provision a DB device if it is faster than the primary device (e.g. NVME devices or SSD).</span> </cd-helper> </label> <div class="cd-col-form-input"> <ng-container *ngIf="devices.length === 0; else blockClearDevices"> <button type="button" class="btn btn-light" (click)="showSelectionModal()" data-toggle="tooltip" [title]="addButtonTooltip" [disabled]="availDevices.length === 0 || !canSelect || expansionCanSelect"> <i [ngClass]="[icons.add]"></i> <ng-container i18n>Add</ng-container> </button> </ng-container> <ng-template #blockClearDevices> <div class="pb-2 my-2 border-bottom"> <span *ngFor="let filter of appliedFilters"> <span class="badge badge-dark me-2">{{ filter.name }}: {{ filter.value.formatted }}</span> </span> <a class="tc_clearSelections" href="" (click)="clearDevices(); false"> <i [ngClass]="[icons.clearFilters]"></i> <ng-container i18n>Clear</ng-container> </a> </div> <div> <cd-inventory-devices [devices]="devices" [hiddenColumns]="['available', 'osd_ids']" [filterColumns]="[]"> </cd-inventory-devices> </div> <div *ngIf="type === 'data'" class="float-end"> <span i18n>Raw capacity: {{ capacity | dimlessBinary }}</span> </div> </ng-template> </div> </div>
2,360
44.403846
365
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-devices-selection-groups/osd-devices-selection-groups.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { InventoryDevice } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-device.model'; import { InventoryDevicesComponent } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-devices.component'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FixtureHelper, Mocks } from '~/testing/unit-test-helper'; import { OsdDevicesSelectionGroupsComponent } from './osd-devices-selection-groups.component'; describe('OsdDevicesSelectionGroupsComponent', () => { let component: OsdDevicesSelectionGroupsComponent; let fixture: ComponentFixture<OsdDevicesSelectionGroupsComponent>; let fixtureHelper: FixtureHelper; const devices: InventoryDevice[] = [Mocks.getInventoryDevice('node0', '1')]; const buttonSelector = '.cd-col-form-input button'; const getButton = () => { const debugElement = fixtureHelper.getElementByCss(buttonSelector); return debugElement.nativeElement; }; const clearTextSelector = '.tc_clearSelections'; const getClearText = () => { const debugElement = fixtureHelper.getElementByCss(clearTextSelector); return debugElement.nativeElement; }; configureTestBed({ imports: [ BrowserAnimationsModule, FormsModule, HttpClientTestingModule, SharedModule, ToastrModule.forRoot(), RouterTestingModule ], declarations: [OsdDevicesSelectionGroupsComponent, InventoryDevicesComponent] }); beforeEach(() => { fixture = TestBed.createComponent(OsdDevicesSelectionGroupsComponent); fixtureHelper = new FixtureHelper(fixture); component = fixture.componentInstance; component.canSelect = true; }); describe('without available devices', () => { beforeEach(() => { component.availDevices = []; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should display Add button in disabled state', () => { const button = getButton(); expect(button).toBeTruthy(); expect(button.disabled).toBe(true); expect(button.textContent).toBe('Add'); }); it('should not display devices table', () => { fixtureHelper.expectElementVisible('cd-inventory-devices', false); }); }); describe('without devices selected', () => { beforeEach(() => { component.availDevices = devices; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should display Add button in enabled state', () => { const button = getButton(); expect(button).toBeTruthy(); expect(button.disabled).toBe(false); expect(button.textContent).toBe('Add'); }); it('should not display devices table', () => { fixtureHelper.expectElementVisible('cd-inventory-devices', false); }); }); describe('with devices selected', () => { beforeEach(() => { component.isOsdPage = true; component.availDevices = []; component.devices = devices; component.ngOnInit(); fixture.detectChanges(); }); it('should display clear link', () => { const text = getClearText(); expect(text).toBeTruthy(); expect(text.textContent).toBe('Clear'); }); it('should display devices table', () => { fixtureHelper.expectElementVisible('cd-inventory-devices', true); }); it('should clear devices by clicking Clear link', () => { spyOn(component.cleared, 'emit'); fixtureHelper.clickElement(clearTextSelector); fixtureHelper.expectElementVisible('cd-inventory-devices', false); const event: Record<string, any> = { type: undefined, clearedDevices: devices }; expect(component.cleared.emit).toHaveBeenCalledWith(event); }); }); });
4,189
32.253968
119
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-devices-selection-groups/osd-devices-selection-groups.component.ts
import { Component, EventEmitter, Input, OnChanges, OnInit, Output } from '@angular/core'; import { Router } from '@angular/router'; import _ from 'lodash'; import { InventoryDevice } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-device.model'; import { OsdService } from '~/app/shared/api/osd.service'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdTableColumnFiltersChange } from '~/app/shared/models/cd-table-column-filters-change'; import { ModalService } from '~/app/shared/services/modal.service'; import { OsdDevicesSelectionModalComponent } from '../osd-devices-selection-modal/osd-devices-selection-modal.component'; import { DevicesSelectionChangeEvent } from './devices-selection-change-event.interface'; import { DevicesSelectionClearEvent } from './devices-selection-clear-event.interface'; @Component({ selector: 'cd-osd-devices-selection-groups', templateUrl: './osd-devices-selection-groups.component.html', styleUrls: ['./osd-devices-selection-groups.component.scss'] }) export class OsdDevicesSelectionGroupsComponent implements OnInit, OnChanges { // data, wal, db @Input() type: string; // Data, WAL, DB @Input() name: string; @Input() hostname: string; @Input() availDevices: InventoryDevice[]; @Input() canSelect: boolean; @Output() selected = new EventEmitter<DevicesSelectionChangeEvent>(); @Output() cleared = new EventEmitter<DevicesSelectionClearEvent>(); icons = Icons; devices: InventoryDevice[] = []; capacity = 0; appliedFilters = new Array(); expansionCanSelect = false; isOsdPage: boolean; addButtonTooltip: String; tooltips = { noAvailDevices: $localize`No available devices`, addPrimaryFirst: $localize`Please add primary devices first`, addByFilters: $localize`Add devices by using filters` }; constructor( private modalService: ModalService, public osdService: OsdService, private router: Router ) { this.isOsdPage = this.router.url.includes('/osd'); } ngOnInit() { if (!this.isOsdPage) { this.osdService?.osdDevices[this.type] ? (this.devices = this.osdService.osdDevices[this.type]) : (this.devices = []); this.capacity = _.sumBy(this.devices, 'sys_api.size'); this.osdService?.osdDevices ? (this.expansionCanSelect = this.osdService?.osdDevices['disableSelect']) : (this.expansionCanSelect = false); } this.updateAddButtonTooltip(); } ngOnChanges() { this.updateAddButtonTooltip(); } showSelectionModal() { const filterColumns = [ 'hostname', 'human_readable_type', 'sys_api.vendor', 'sys_api.model', 'sys_api.size' ]; const diskType = this.name === 'Primary' ? 'hdd' : 'ssd'; const initialState = { hostname: this.hostname, deviceType: this.name, diskType: diskType, devices: this.availDevices, filterColumns: filterColumns }; const modalRef = this.modalService.show(OsdDevicesSelectionModalComponent, initialState, { size: 'xl' }); modalRef.componentInstance.submitAction.subscribe((result: CdTableColumnFiltersChange) => { this.devices = result.data; this.capacity = _.sumBy(this.devices, 'sys_api.size'); this.appliedFilters = result.filters; const event = _.assign({ type: this.type }, result); if (!this.isOsdPage) { this.osdService.osdDevices[this.type] = this.devices; this.osdService.osdDevices['disableSelect'] = this.canSelect || this.devices.length === this.availDevices.length; this.osdService.osdDevices[this.type]['capacity'] = this.capacity; } this.selected.emit(event); }); } private updateAddButtonTooltip() { if (this.type === 'data' && this.availDevices.length === 0) { this.addButtonTooltip = this.tooltips.noAvailDevices; } else { if (!this.canSelect) { // No primary devices added yet. this.addButtonTooltip = this.tooltips.addPrimaryFirst; } else if (this.availDevices.length === 0) { this.addButtonTooltip = this.tooltips.noAvailDevices; } else { this.addButtonTooltip = this.tooltips.addByFilters; } } } clearDevices() { if (!this.isOsdPage) { this.expansionCanSelect = false; this.osdService.osdDevices['disableSelect'] = false; this.osdService.osdDevices = []; } const event = { type: this.type, clearedDevices: [...this.devices] }; this.devices = []; this.cleared.emit(event); } }
4,575
31.453901
121
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-devices-selection-modal/osd-devices-selection-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container class="modal-title" i18n>{{ deviceType }} devices</ng-container> <ng-container class="modal-content"> <form #frm="ngForm" [formGroup]="formGroup" novalidate> <div class="modal-body"> <cd-alert-panel *ngIf="!canSubmit" type="warning" size="slim" [showTitle]="false"> <ng-container i18n>At least one of these filters must be applied in order to proceed:</ng-container> <span *ngFor="let filter of requiredFilters" class="badge badge-dark ms-2"> {{ filter }} </span> </cd-alert-panel> <cd-inventory-devices #inventoryDevices [devices]="devices" [filterColumns]="filterColumns" [hostname]="hostname" [diskType]="diskType" [hiddenColumns]="['available', 'osd_ids']" (filterChange)="onFilterChange($event)"> </cd-inventory-devices> <div *ngIf="canSubmit"> <p class="text-center"> <span i18n>Number of devices: {{ filteredDevices.length }}. Raw capacity: {{ capacity | dimlessBinary }}.</span> </p> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="onSubmit()" [form]="formGroup" [disabled]="!canSubmit || filteredDevices.length === 0" [submitText]="action | titlecase"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
1,791
39.727273
110
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-devices-selection-modal/osd-devices-selection-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { InventoryDevice } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-device.model'; import { InventoryDevicesComponent } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-devices.component'; import { CdTableColumnFiltersChange } from '~/app/shared/models/cd-table-column-filters-change'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, Mocks } from '~/testing/unit-test-helper'; import { OsdDevicesSelectionModalComponent } from './osd-devices-selection-modal.component'; describe('OsdDevicesSelectionModalComponent', () => { let component: OsdDevicesSelectionModalComponent; let fixture: ComponentFixture<OsdDevicesSelectionModalComponent>; let timeoutFn: Function; const devices: InventoryDevice[] = [Mocks.getInventoryDevice('node0', '1')]; const expectSubmitButton = (enabled: boolean) => { const nativeElement = fixture.debugElement.nativeElement; const button = nativeElement.querySelector('.modal-footer .tc_submitButton'); expect(button.disabled).toBe(!enabled); }; configureTestBed({ imports: [ BrowserAnimationsModule, FormsModule, HttpClientTestingModule, SharedModule, ReactiveFormsModule, RouterTestingModule, ToastrModule.forRoot() ], providers: [NgbActiveModal], declarations: [OsdDevicesSelectionModalComponent, InventoryDevicesComponent] }); beforeEach(() => { spyOn(window, 'setTimeout').and.callFake((fn) => (timeoutFn = fn)); fixture = TestBed.createComponent(OsdDevicesSelectionModalComponent); component = fixture.componentInstance; component.devices = devices; // Mocks InventoryDeviceComponent component.inventoryDevices = { columns: [ { name: 'Device path', prop: 'path' }, { name: 'Type', prop: 'human_readable_type' }, { name: 'Available', prop: 'available' } ] } as InventoryDevicesComponent; // Mocks the update from the above component component.filterColumns = ['path', 'human_readable_type']; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should disable submit button initially', () => { expectSubmitButton(false); }); it( 'should update requiredFilters after ngAfterViewInit is called to prevent ' + 'ExpressionChangedAfterItHasBeenCheckedError', () => { expect(component.requiredFilters).toEqual([]); timeoutFn(); expect(component.requiredFilters).toEqual(['Device path', 'Type']); } ); it('should enable submit button after filtering some devices', () => { const event: CdTableColumnFiltersChange = { filters: [ { name: 'hostname', prop: 'hostname', value: { raw: 'node0', formatted: 'node0' } }, { name: 'size', prop: 'size', value: { raw: '1024', formatted: '1KiB' } } ], data: devices, dataOut: [] }; component.onFilterChange(event); fixture.detectChanges(); expectSubmitButton(true); }); });
3,638
32.081818
119
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-devices-selection-modal/osd-devices-selection-modal.component.ts
import { AfterViewInit, ChangeDetectorRef, Component, EventEmitter, Output, ViewChild } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { TableColumnProp } from '@swimlane/ngx-datatable'; import _ from 'lodash'; import { InventoryDevice } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-device.model'; import { InventoryDevicesComponent } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-devices.component'; 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 { CdTableColumnFiltersChange } from '~/app/shared/models/cd-table-column-filters-change'; import { WizardStepsService } from '~/app/shared/services/wizard-steps.service'; @Component({ selector: 'cd-osd-devices-selection-modal', templateUrl: './osd-devices-selection-modal.component.html', styleUrls: ['./osd-devices-selection-modal.component.scss'] }) export class OsdDevicesSelectionModalComponent implements AfterViewInit { @ViewChild('inventoryDevices') inventoryDevices: InventoryDevicesComponent; @Output() submitAction = new EventEmitter<CdTableColumnFiltersChange>(); icons = Icons; filterColumns: TableColumnProp[] = []; hostname: string; deviceType: string; diskType: string; formGroup: CdFormGroup; action: string; devices: InventoryDevice[] = []; filteredDevices: InventoryDevice[] = []; capacity = 0; event: CdTableColumnFiltersChange; canSubmit = false; requiredFilters: string[] = []; constructor( private formBuilder: CdFormBuilder, private cdRef: ChangeDetectorRef, public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, public wizardStepService: WizardStepsService ) { this.action = actionLabels.ADD; this.createForm(); } ngAfterViewInit() { // At least one filter other than hostname is required // Extract the name from table columns for i18n strings const cols = _.filter(this.inventoryDevices.columns, (col) => { return this.filterColumns.includes(col.prop) && col.prop !== 'hostname'; }); // Fixes 'ExpressionChangedAfterItHasBeenCheckedError' setTimeout(() => { this.requiredFilters = _.map(cols, 'name'); }, 0); } createForm() { this.formGroup = this.formBuilder.group({}); } onFilterChange(event: CdTableColumnFiltersChange) { this.capacity = 0; this.canSubmit = false; if (_.isEmpty(event.filters)) { // filters are cleared this.filteredDevices = []; this.event = undefined; } else { // at least one filter is required (except hostname) const filters = event.filters.filter((filter) => { return filter.prop !== 'hostname'; }); this.canSubmit = !_.isEmpty(filters); this.filteredDevices = event.data; this.capacity = _.sumBy(this.filteredDevices, 'sys_api.size'); this.event = event; } this.cdRef.detectChanges(); } onSubmit() { this.submitAction.emit(this.event); this.activeModal.close(); } }
3,243
30.495146
119
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-flags-indiv-modal/osd-flags-indiv-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container class="modal-title" i18n>Individual OSD Flags</ng-container> <ng-container class="modal-content"> <form name="osdFlagsForm" #formDir="ngForm" [formGroup]="osdFlagsForm" novalidate> <div class="modal-body osd-modal"> <div class="custom-control custom-checkbox" *ngFor="let flag of flags; let last = last"> <input class="custom-control-input" type="checkbox" [checked]="flag.value" [indeterminate]="flag.indeterminate" (change)="changeValue(flag)" [name]="flag.code" [id]="flag.code"> <label class="custom-control-label" [for]="flag.code" ng-class="['tc_' + key]"> <strong>{{ flag.name }}</strong> <span class="badge badge-hdd ms-2" [ngbTooltip]="clusterWideTooltip" *ngIf="flag.clusterWide" i18n>Cluster-wide</span> <br> <span class="form-text text-muted">{{ flag.description }}</span> </label> <hr class="m-1" *ngIf="!last"> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-light" (click)="resetSelection()" i18n>Restore previous selection</button> <cd-form-button-panel (submitActionEvent)="submitAction()" [form]="osdFlagsForm" [showSubmit]="permissions.osd.update" [submitText]="actionLabels.UPDATE"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
1,810
35.959184
88
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-flags-indiv-modal/osd-flags-indiv-modal.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of as observableOf } from 'rxjs'; import { OsdService } from '~/app/shared/api/osd.service'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { Flag } from '~/app/shared/models/flag'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { OsdFlagsIndivModalComponent } from './osd-flags-indiv-modal.component'; describe('OsdFlagsIndivModalComponent', () => { let component: OsdFlagsIndivModalComponent; let fixture: ComponentFixture<OsdFlagsIndivModalComponent>; let httpTesting: HttpTestingController; let osdService: OsdService; configureTestBed({ imports: [ HttpClientTestingModule, ReactiveFormsModule, SharedModule, ToastrModule.forRoot(), NgbTooltipModule, RouterTestingModule ], declarations: [OsdFlagsIndivModalComponent], providers: [NgbActiveModal] }); beforeEach(() => { httpTesting = TestBed.inject(HttpTestingController); fixture = TestBed.createComponent(OsdFlagsIndivModalComponent); component = fixture.componentInstance; osdService = TestBed.inject(OsdService); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('getActivatedIndivFlags', () => { function checkFlagsCount( counts: { [key: string]: number }, expected: { [key: string]: number } ) { Object.entries(expected).forEach(([expectedKey, expectedValue]) => { expect(counts[expectedKey]).toBe(expectedValue); }); } it('should count correctly if no flag has been set', () => { component.selected = generateSelected(); const countedFlags = component.getActivatedIndivFlags(); checkFlagsCount(countedFlags, { noup: 0, nodown: 0, noin: 0, noout: 0 }); }); it('should count correctly if some of the flags have been set', () => { component.selected = generateSelected([['noin'], ['noin', 'noout'], ['nodown']]); const countedFlags = component.getActivatedIndivFlags(); checkFlagsCount(countedFlags, { noup: 0, nodown: 1, noin: 2, noout: 1 }); }); }); describe('changeValue', () => { it('should change value correctly and set indeterminate to false', () => { const testFlag = component.flags[0]; const value = testFlag.value; component.changeValue(testFlag); expect(testFlag.value).toBe(!value); expect(testFlag.indeterminate).toBeFalsy(); }); }); describe('resetSelection', () => { it('should set a new flags object by deep cloning the initial selection', () => { component.resetSelection(); expect(component.flags === component.initialSelection).toBeFalsy(); }); }); describe('OSD single-select', () => { beforeEach(() => { component.selected = [{ osd: 0 }]; }); describe('ngOnInit', () => { it('should clone flags as initial selection', () => { expect(component.flags === component.initialSelection).toBeFalsy(); }); it('should initialize form correctly if no individual and global flags are set', () => { component.selected[0]['state'] = ['exists', 'up']; spyOn(osdService, 'getFlags').and.callFake(() => observableOf([])); fixture.detectChanges(); checkFlags(component.flags); }); it('should initialize form correctly if individual but no global flags are set', () => { component.selected[0]['state'] = ['exists', 'noout', 'up']; spyOn(osdService, 'getFlags').and.callFake(() => observableOf([])); fixture.detectChanges(); const expected = { noout: { value: true, clusterWide: false, indeterminate: false } }; checkFlags(component.flags, expected); }); it('should initialize form correctly if multiple individual but no global flags are set', () => { component.selected[0]['state'] = ['exists', 'noin', 'noout', 'up']; spyOn(osdService, 'getFlags').and.callFake(() => observableOf([])); fixture.detectChanges(); const expected = { noout: { value: true, clusterWide: false, indeterminate: false }, noin: { value: true, clusterWide: false, indeterminate: false } }; checkFlags(component.flags, expected); }); it('should initialize form correctly if no individual but global flags are set', () => { component.selected[0]['state'] = ['exists', 'up']; spyOn(osdService, 'getFlags').and.callFake(() => observableOf(['noout'])); fixture.detectChanges(); const expected = { noout: { value: false, clusterWide: true, indeterminate: false } }; checkFlags(component.flags, expected); }); }); describe('submitAction', () => { let notificationType: NotificationType; let notificationService: NotificationService; let bsModalRef: NgbActiveModal; let flags: object; beforeEach(() => { notificationService = TestBed.inject(NotificationService); spyOn(notificationService, 'show').and.callFake((type) => { notificationType = type; }); bsModalRef = TestBed.inject(NgbActiveModal); spyOn(bsModalRef, 'close').and.callThrough(); flags = { nodown: false, noin: false, noout: false, noup: false }; }); it('should submit an activated flag', () => { const code = component.flags[0].code; component.flags[0].value = true; component.submitAction(); flags[code] = true; const req = httpTesting.expectOne('api/osd/flags/individual'); req.flush({ flags, ids: [0] }); expect(req.request.body).toEqual({ flags, ids: [0] }); expect(notificationType).toBe(NotificationType.success); expect(component.activeModal.close).toHaveBeenCalledTimes(1); }); it('should submit multiple flags', () => { const codes = [component.flags[0].code, component.flags[1].code]; component.flags[0].value = true; component.flags[1].value = true; component.submitAction(); flags[codes[0]] = true; flags[codes[1]] = true; const req = httpTesting.expectOne('api/osd/flags/individual'); req.flush({ flags, ids: [0] }); expect(req.request.body).toEqual({ flags, ids: [0] }); expect(notificationType).toBe(NotificationType.success); expect(component.activeModal.close).toHaveBeenCalledTimes(1); }); it('should hide modal if request fails', () => { component.flags = []; component.submitAction(); const req = httpTesting.expectOne('api/osd/flags/individual'); req.flush([], { status: 500, statusText: 'failure' }); expect(notificationService.show).toHaveBeenCalledTimes(0); expect(component.activeModal.close).toHaveBeenCalledTimes(1); }); }); }); describe('OSD multi-select', () => { describe('ngOnInit', () => { it('should initialize form correctly if same individual and no global flags are set', () => { component.selected = generateSelected([['noin'], ['noin'], ['noin']]); spyOn(osdService, 'getFlags').and.callFake(() => observableOf([])); fixture.detectChanges(); const expected = { noin: { value: true, clusterWide: false, indeterminate: false } }; checkFlags(component.flags, expected); }); it('should initialize form correctly if different individual and no global flags are set', () => { component.selected = generateSelected([['noin'], ['noout'], ['noin']]); spyOn(osdService, 'getFlags').and.callFake(() => observableOf([])); fixture.detectChanges(); const expected = { noin: { value: false, clusterWide: false, indeterminate: true }, noout: { value: false, clusterWide: false, indeterminate: true } }; checkFlags(component.flags, expected); }); it('should initialize form correctly if different and same individual and no global flags are set', () => { component.selected = generateSelected([ ['noin', 'nodown'], ['noout', 'nodown'], ['noin', 'nodown'] ]); spyOn(osdService, 'getFlags').and.callFake(() => observableOf([])); fixture.detectChanges(); const expected = { noin: { value: false, clusterWide: false, indeterminate: true }, noout: { value: false, clusterWide: false, indeterminate: true }, nodown: { value: true, clusterWide: false, indeterminate: false } }; checkFlags(component.flags, expected); }); it('should initialize form correctly if a flag is set for all OSDs individually and globally', () => { component.selected = generateSelected([ ['noin', 'nodown'], ['noout', 'nodown'], ['noin', 'nodown'] ]); spyOn(osdService, 'getFlags').and.callFake(() => observableOf(['noout'])); fixture.detectChanges(); const expected = { noin: { value: false, clusterWide: false, indeterminate: true }, noout: { value: false, clusterWide: true, indeterminate: true }, nodown: { value: true, clusterWide: false, indeterminate: false } }; checkFlags(component.flags, expected); }); it('should initialize form correctly if different individual and global flags are set', () => { component.selected = generateSelected([ ['noin', 'nodown', 'noout'], ['noout', 'nodown'], ['noin', 'nodown', 'noout'] ]); spyOn(osdService, 'getFlags').and.callFake(() => observableOf(['noout'])); fixture.detectChanges(); const expected = { noin: { value: false, clusterWide: false, indeterminate: true }, noout: { value: true, clusterWide: true, indeterminate: false }, nodown: { value: true, clusterWide: false, indeterminate: false } }; checkFlags(component.flags, expected); }); }); describe('submitAction', () => { let notificationType: NotificationType; let notificationService: NotificationService; let bsModalRef: NgbActiveModal; let flags: object; beforeEach(() => { notificationService = TestBed.inject(NotificationService); spyOn(notificationService, 'show').and.callFake((type) => { notificationType = type; }); bsModalRef = TestBed.inject(NgbActiveModal); spyOn(bsModalRef, 'close').and.callThrough(); flags = { nodown: false, noin: false, noout: false, noup: false }; }); it('should submit an activated flag for multiple OSDs', () => { component.selected = generateSelected(); const code = component.flags[0].code; const submittedIds = [0, 1, 2]; component.flags[0].value = true; component.submitAction(); flags[code] = true; const req = httpTesting.expectOne('api/osd/flags/individual'); req.flush({ flags, ids: submittedIds }); expect(req.request.body).toEqual({ flags, ids: submittedIds }); expect(notificationType).toBe(NotificationType.success); expect(component.activeModal.close).toHaveBeenCalledTimes(1); }); it('should submit multiple flags for multiple OSDs', () => { component.selected = generateSelected(); const codes = [component.flags[0].code, component.flags[1].code]; const submittedIds = [0, 1, 2]; component.flags[0].value = true; component.flags[1].value = true; component.submitAction(); flags[codes[0]] = true; flags[codes[1]] = true; const req = httpTesting.expectOne('api/osd/flags/individual'); req.flush({ flags, ids: submittedIds }); expect(req.request.body).toEqual({ flags, ids: submittedIds }); expect(notificationType).toBe(NotificationType.success); expect(component.activeModal.close).toHaveBeenCalledTimes(1); }); }); }); function checkFlags(flags: Flag[], expected: object = {}) { flags.forEach((flag) => { let value = false; let clusterWide = false; let indeterminate = false; if (Object.keys(expected).includes(flag.code)) { value = expected[flag.code]['value']; clusterWide = expected[flag.code]['clusterWide']; indeterminate = expected[flag.code]['indeterminate']; } expect(flag.value).toBe(value); expect(flag.clusterWide).toBe(clusterWide); expect(flag.indeterminate).toBe(indeterminate); }); } function generateSelected(flags: string[][] = []) { const defaultFlags = ['exists', 'up']; const osds = []; const count = flags.length || 3; for (let i = 0; i < count; i++) { const osd = { osd: i, state: defaultFlags.concat(flags[i]) || defaultFlags }; osds.push(osd); } return osds; } });
13,627
37.497175
113
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-flags-indiv-modal/osd-flags-indiv-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { OsdService } from '~/app/shared/api/osd.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { Flag } from '~/app/shared/models/flag'; import { Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { NotificationService } from '~/app/shared/services/notification.service'; @Component({ selector: 'cd-osd-flags-indiv-modal', templateUrl: './osd-flags-indiv-modal.component.html', styleUrls: ['./osd-flags-indiv-modal.component.scss'] }) export class OsdFlagsIndivModalComponent implements OnInit { permissions: Permissions; selected: object[]; initialSelection: Flag[] = []; osdFlagsForm = new FormGroup({}); flags: Flag[] = [ { code: 'noup', name: $localize`No Up`, description: $localize`OSDs are not allowed to start`, value: false, clusterWide: false, indeterminate: false }, { code: 'nodown', name: $localize`No Down`, description: $localize`OSD failure reports are being ignored, such that the monitors will not mark OSDs down`, value: false, clusterWide: false, indeterminate: false }, { code: 'noin', name: $localize`No In`, description: $localize`OSDs that were previously marked out will not be marked back in when they start`, value: false, clusterWide: false, indeterminate: false }, { code: 'noout', name: $localize`No Out`, description: $localize`OSDs will not automatically be marked out after the configured interval`, value: false, clusterWide: false, indeterminate: false } ]; clusterWideTooltip: string = $localize`The flag has been enabled for the entire cluster.`; constructor( public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private authStorageService: AuthStorageService, private osdService: OsdService, private notificationService: NotificationService ) { this.permissions = this.authStorageService.getPermissions(); } ngOnInit() { const osdCount = this.selected.length; this.osdService.getFlags().subscribe((clusterWideFlags: string[]) => { const activatedIndivFlags = this.getActivatedIndivFlags(); this.flags.forEach((flag) => { const flagCount = activatedIndivFlags[flag.code]; if (clusterWideFlags.includes(flag.code)) { flag.clusterWide = true; } if (flagCount === osdCount) { flag.value = true; } else if (flagCount > 0) { flag.indeterminate = true; } }); this.initialSelection = _.cloneDeep(this.flags); }); } getActivatedIndivFlags(): { [flag: string]: number } { const flagsCount = {}; this.flags.forEach((flag) => { flagsCount[flag.code] = 0; }); [].concat(...this.selected.map((osd) => osd['state'])).map((activatedFlag) => { if (Object.keys(flagsCount).includes(activatedFlag)) { flagsCount[activatedFlag] = flagsCount[activatedFlag] + 1; } }); return flagsCount; } changeValue(flag: Flag) { flag.value = !flag.value; flag.indeterminate = false; } resetSelection() { this.flags = _.cloneDeep(this.initialSelection); } submitAction() { const activeFlags = {}; this.flags.forEach((flag) => { if (flag.indeterminate) { activeFlags[flag.code] = null; } else { activeFlags[flag.code] = flag.value; } }); const selectedIds = this.selected.map((selection) => selection['osd']); this.osdService.updateIndividualFlags(activeFlags, selectedIds).subscribe( () => { this.notificationService.show(NotificationType.success, $localize`Updated OSD Flags`); this.activeModal.close(); }, () => { this.activeModal.close(); } ); } }
4,206
30.162963
116
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-flags-modal/osd-flags-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container class="modal-title" i18n>Cluster-wide OSD Flags</ng-container> <ng-container class="modal-content"> <form name="osdFlagsForm" #formDir="ngForm" [formGroup]="osdFlagsForm" novalidate cdFormScope="osd"> <div class="modal-body osd-modal"> <div class="custom-control custom-checkbox" *ngFor="let flag of flags; let last = last"> <input class="custom-control-input" type="checkbox" [checked]="flag.value" (change)="flag.value = !flag.value" [name]="flag.code" [id]="flag.code" [disabled]="flag.disabled"> <label class="custom-control-label" [for]="flag.code" ng-class="['tc_' + key]"> <strong>{{ flag.name }}</strong> <br> <span class="form-text text-muted">{{ flag.description }}</span> </label> <hr class="m-1" *ngIf="!last"> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="submitAction()" [form]="osdFlagsForm" [showSubmit]="permissions.osd.update" [submitText]="actionLabels.UPDATE"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
1,484
34.357143
88
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-flags-modal/osd-flags-modal.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { ToastrModule } from 'ngx-toastr'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { OsdFlagsModalComponent } from './osd-flags-modal.component'; function getFlagsArray(component: OsdFlagsModalComponent) { const allFlags = _.cloneDeep(component.allFlags); allFlags['purged_snapdirs'].value = true; allFlags['pause'].value = true; return _.toArray(allFlags); } describe('OsdFlagsModalComponent', () => { let component: OsdFlagsModalComponent; let fixture: ComponentFixture<OsdFlagsModalComponent>; let httpTesting: HttpTestingController; configureTestBed({ imports: [ ReactiveFormsModule, SharedModule, HttpClientTestingModule, RouterTestingModule, ToastrModule.forRoot() ], declarations: [OsdFlagsModalComponent], providers: [NgbActiveModal] }); beforeEach(() => { httpTesting = TestBed.inject(HttpTestingController); fixture = TestBed.createComponent(OsdFlagsModalComponent); component = fixture.componentInstance; }); it('should create', () => { expect(component).toBeTruthy(); }); it('should finish running ngOnInit', () => { fixture.detectChanges(); const flags = getFlagsArray(component); const req = httpTesting.expectOne('api/osd/flags'); req.flush(['purged_snapdirs', 'pause', 'foo']); expect(component.flags).toEqual(flags); expect(component.unknownFlags).toEqual(['foo']); }); describe('test submitAction', function () { let notificationType: NotificationType; let notificationService: NotificationService; let bsModalRef: NgbActiveModal; beforeEach(() => { notificationService = TestBed.inject(NotificationService); spyOn(notificationService, 'show').and.callFake((type) => { notificationType = type; }); bsModalRef = TestBed.inject(NgbActiveModal); spyOn(bsModalRef, 'close').and.callThrough(); component.unknownFlags = ['foo']; }); it('should run submitAction', () => { component.flags = getFlagsArray(component); component.submitAction(); const req = httpTesting.expectOne('api/osd/flags'); req.flush(['purged_snapdirs', 'pause', 'foo']); expect(req.request.body).toEqual({ flags: ['pause', 'purged_snapdirs', 'foo'] }); expect(notificationType).toBe(NotificationType.success); expect(component.activeModal.close).toHaveBeenCalledTimes(1); }); it('should hide modal if request fails', () => { component.flags = []; component.submitAction(); const req = httpTesting.expectOne('api/osd/flags'); req.flush([], { status: 500, statusText: 'failure' }); expect(notificationService.show).toHaveBeenCalledTimes(0); expect(component.activeModal.close).toHaveBeenCalledTimes(1); }); }); });
3,403
33.04
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-flags-modal/osd-flags-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { OsdService } from '~/app/shared/api/osd.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { NotificationService } from '~/app/shared/services/notification.service'; @Component({ selector: 'cd-osd-flags-modal', templateUrl: './osd-flags-modal.component.html', styleUrls: ['./osd-flags-modal.component.scss'] }) export class OsdFlagsModalComponent implements OnInit { permissions: Permissions; osdFlagsForm = new FormGroup({}); allFlags = { noin: { code: 'noin', name: $localize`No In`, value: false, description: $localize`OSDs that were previously marked out will not be marked back in when they start` }, noout: { code: 'noout', name: $localize`No Out`, value: false, description: $localize`OSDs will not automatically be marked out after the configured interval` }, noup: { code: 'noup', name: $localize`No Up`, value: false, description: $localize`OSDs are not allowed to start` }, nodown: { code: 'nodown', name: $localize`No Down`, value: false, description: $localize`OSD failure reports are being ignored, such that the monitors will not mark OSDs down` }, pause: { code: 'pause', name: $localize`Pause`, value: false, description: $localize`Pauses reads and writes` }, noscrub: { code: 'noscrub', name: $localize`No Scrub`, value: false, description: $localize`Scrubbing is disabled` }, 'nodeep-scrub': { code: 'nodeep-scrub', name: $localize`No Deep Scrub`, value: false, description: $localize`Deep Scrubbing is disabled` }, nobackfill: { code: 'nobackfill', name: $localize`No Backfill`, value: false, description: $localize`Backfilling of PGs is suspended` }, norebalance: { code: 'norebalance', name: $localize`No Rebalance`, value: false, description: $localize`OSD will choose not to backfill unless PG is also degraded` }, norecover: { code: 'norecover', name: $localize`No Recover`, value: false, description: $localize`Recovery of PGs is suspended` }, sortbitwise: { code: 'sortbitwise', name: $localize`Bitwise Sort`, value: false, description: $localize`Use bitwise sort`, disabled: true }, purged_snapdirs: { code: 'purged_snapdirs', name: $localize`Purged Snapdirs`, value: false, description: $localize`OSDs have converted snapsets`, disabled: true }, recovery_deletes: { code: 'recovery_deletes', name: $localize`Recovery Deletes`, value: false, description: $localize`Deletes performed during recovery instead of peering`, disabled: true }, pglog_hardlimit: { code: 'pglog_hardlimit', name: $localize`PG Log Hard Limit`, value: false, description: $localize`Puts a hard limit on pg log length`, disabled: true } }; flags: any[]; unknownFlags: string[] = []; constructor( public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private authStorageService: AuthStorageService, private osdService: OsdService, private notificationService: NotificationService ) { this.permissions = this.authStorageService.getPermissions(); } ngOnInit() { this.osdService.getFlags().subscribe((res: string[]) => { res.forEach((value) => { if (this.allFlags[value]) { this.allFlags[value].value = true; } else { this.unknownFlags.push(value); } }); this.flags = _.toArray(this.allFlags); }); } submitAction() { const newFlags = this.flags .filter((flag) => flag.value) .map((flag) => flag.code) .concat(this.unknownFlags); this.osdService.updateFlags(newFlags).subscribe( () => { this.notificationService.show(NotificationType.success, $localize`Updated OSD Flags`); this.activeModal.close(); }, () => { this.activeModal.close(); } ); } }
4,597
28.286624
115
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-form/drive-group.model.ts
import _ from 'lodash'; import { CdTableColumnFiltersChange } from '~/app/shared/models/cd-table-column-filters-change'; import { FormatterService } from '~/app/shared/services/formatter.service'; export class DriveGroup { spec: Object; // Map from filter column prop to device selection attribute name private deviceSelectionAttrs: { [key: string]: { name: string; formatter?: Function; }; }; private formatterService: FormatterService; constructor() { this.reset(); this.formatterService = new FormatterService(); this.deviceSelectionAttrs = { 'sys_api.vendor': { name: 'vendor' }, 'sys_api.model': { name: 'model' }, device_id: { name: 'device_id' }, human_readable_type: { name: 'rotational', formatter: (value: string) => { return value.toLowerCase() === 'hdd'; } }, 'sys_api.size': { name: 'size', formatter: (value: string) => { return this.formatterService .format_number(value, 1024, ['B', 'KB', 'MB', 'GB', 'TB', 'PB']) .replace(' ', ''); } } }; } reset() { this.spec = { service_type: 'osd', service_id: `dashboard-${_.now()}` }; } setName(name: string) { this.spec['service_id'] = name; } setHostPattern(pattern: string) { this.spec['host_pattern'] = pattern; } setDeviceSelection(type: string, appliedFilters: CdTableColumnFiltersChange['filters']) { const key = `${type}_devices`; this.spec[key] = {}; appliedFilters.forEach((filter) => { const attr = this.deviceSelectionAttrs[filter.prop]; if (attr) { const name = attr.name; this.spec[key][name] = attr.formatter ? attr.formatter(filter.value.raw) : filter.value.raw; } }); } clearDeviceSelection(type: string) { const key = `${type}_devices`; delete this.spec[key]; } setSlots(type: string, slots: number) { const key = `${type}_slots`; if (slots === 0) { delete this.spec[key]; } else { this.spec[key] = slots; } } setFeature(feature: string, enabled: boolean) { if (enabled) { this.spec[feature] = true; } else { delete this.spec[feature]; } } }
2,320
22.683673
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-form/osd-feature.interface.ts
export interface OsdFeature { desc: string; key?: string; }
64
12
29
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-form/osd-form.component.html
<cd-orchestrator-doc-panel *ngIf="!hasOrchestrator"></cd-orchestrator-doc-panel> <div class="card" *cdFormLoading="loading"> <div i18n="form title|Example: Create Pool@@formTitle" class="card-header" *ngIf="!hideTitle">{{ action | titlecase }} {{ resource | upperFirst }}</div> <div class="card-body ms-2"> <form name="form" #formDir="ngForm" [formGroup]="form" novalidate> <cd-alert-panel *ngIf="!deploymentOptions?.recommended_option" type="warning" class="mx-3" i18n> No devices(HDD, SSD or NVME) were found. Creation of OSDs will remain disabled until devices are added. </cd-alert-panel> <div class="accordion"> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button" type="button" data-toggle="collapse" aria-label="toggle deployment options" [ngClass]="{collapsed: !simpleDeployment}" (click)="emitDeploymentMode()" i18n>Deployment Options</button> </h2> </div> <div class="accordion-collapse collapse" [ngClass]="{show: simpleDeployment}"> <div class="accordion-body"> <div class="pt-3 pb-3" *ngFor="let optionName of optionNames"> <div class="custom-control form-check custom-control-inline"> <input class="form-check-input" type="radio" name="deploymentOption" [id]="optionName" [value]="optionName" formControlName="deploymentOption" (change)="emitDeploymentSelection()" [attr.disabled]="!deploymentOptions?.options[optionName].available ? true : null"> <label class="form-check-label" [id]="'label_' + optionName" [for]="optionName" i18n>{{ deploymentOptions?.options[optionName].title }} {{ deploymentOptions?.recommended_option === optionName ? "(Recommended)" : "" }} <cd-helper> <span>{{ deploymentOptions?.options[optionName].desc }}</span> </cd-helper> </label> </div> </div> <!-- @TODO: Visualize the storage used on a chart --> <!-- <div class="pie-chart"> <h4 class="text-center">Selected Capacity</h4> <h5 class="margin text-center">10 Hosts | 30 NVMes </h5> <div class="char-i-contain"> <cd-health-pie [data]="data" [config]="rawCapacityChartConfig" [isBytesData]="true" (prepareFn)="prepareRawUsage($event[0], $event[1])"> </cd-health-pie> </div> </div> --> </div> </div> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button" type="button" aria-label="toggle advanced mode" [ngClass]="{collapsed: simpleDeployment}" (click)="emitDeploymentMode()" i18n>Advanced Mode</button> </h2> </div> <div class="accordion-collapse collapse" [ngClass]="{show: !simpleDeployment}"> <div class="accordion-body"> <div class="card-body"> <fieldset> <cd-osd-devices-selection-groups #dataDeviceSelectionGroups name="Primary" type="data" [availDevices]="availDevices" [canSelect]="availDevices.length !== 0" (selected)="onDevicesSelected($event)" (cleared)="onDevicesCleared($event)"> </cd-osd-devices-selection-groups> </fieldset> <!-- Shared devices --> <fieldset> <legend i18n>Shared devices</legend> <!-- WAL devices button and table --> <cd-osd-devices-selection-groups #walDeviceSelectionGroups name="WAL" type="wal" [availDevices]="availDevices" [canSelect]="dataDeviceSelectionGroups.devices.length !== 0" (selected)="onDevicesSelected($event)" (cleared)="onDevicesCleared($event)" [hostname]="hostname"> </cd-osd-devices-selection-groups> <!-- WAL slots --> <div class="form-group row" *ngIf="walDeviceSelectionGroups.devices.length !== 0"> <label class="cd-col-form-label" for="walSlots"> <ng-container i18n>WAL slots</ng-container> <cd-helper> <span i18n>How many OSDs per WAL device.</span> <br> <span i18n>Specify 0 to let Orchestrator backend decide it.</span> </cd-helper> </label> <div class="cd-col-form-input"> <input class="form-control" id="walSlots" name="walSlots" type="number" min="0" formControlName="walSlots"> <span class="invalid-feedback" *ngIf="form.showError('walSlots', formDir, 'min')" i18n>Value should be greater than or equal to 0</span> </div> </div> <!-- DB devices button and table --> <cd-osd-devices-selection-groups #dbDeviceSelectionGroups name="DB" type="db" [availDevices]="availDevices" [canSelect]="dataDeviceSelectionGroups.devices.length !== 0" (selected)="onDevicesSelected($event)" (cleared)="onDevicesCleared($event)" [hostname]="hostname"> </cd-osd-devices-selection-groups> <!-- DB slots --> <div class="form-group row" *ngIf="dbDeviceSelectionGroups.devices.length !== 0"> <label class="cd-col-form-label" for="dbSlots"> <ng-container i18n>DB slots</ng-container> <cd-helper> <span i18n>How many OSDs per DB device.</span> <br> <span i18n>Specify 0 to let Orchestrator backend decide it.</span> </cd-helper> </label> <div class="cd-col-form-input"> <input class="form-control" id="dbSlots" name="dbSlots" type="number" min="0" formControlName="dbSlots"> <span class="invalid-feedback" *ngIf="form.showError('dbSlots', formDir, 'min')" i18n>Value should be greater than or equal to 0</span> </div> </div> </fieldset> </div> </div> </div> <!-- Features --> <div class="accordion-item"> <h2 class="accordion-header"> <button class="accordion-button" type="button" data-toggle="collapse" aria-label="features" aria-expanded="true" i18n>Features</button> </h2> </div> <div class="accordion-collapse collapse show"> <div class="accordion-body"> <div class="pt-3 pb-3" formGroupName="features"> <div class="custom-control custom-checkbox" *ngFor="let feature of featureList"> <input type="checkbox" class="custom-control-input" id="{{ feature.key }}" name="{{ feature.key }}" formControlName="{{ feature.key }}" (change)="emitDeploymentSelection()"> <label class="custom-control-label" for="{{ feature.key }}">{{ feature.desc }}</label> </div> </div> </div> </div> </div> </form> </div> <div class="card-footer" *ngIf="!hideSubmitBtn"> <cd-form-button-panel #previewButtonPanel (submitActionEvent)="submit()" [form]="form" [disabled]="dataDeviceSelectionGroups.devices.length === 0 && !simpleDeployment" [submitText]="simpleDeployment ? 'Create OSDs' : actionLabels.PREVIEW" wrappingClass="text-right"></cd-form-button-panel> </div> </div>
10,052
44.90411
109
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-form/osd-form.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { BehaviorSubject, of } from 'rxjs'; import { InventoryDevice } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-device.model'; import { InventoryDevicesComponent } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-devices.component'; import { DashboardModule } from '~/app/ceph/dashboard/dashboard.module'; import { HostService } from '~/app/shared/api/host.service'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { DeploymentOptions, OsdDeploymentOptions } from '~/app/shared/models/osd-deployment-options'; import { SummaryService } from '~/app/shared/services/summary.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FixtureHelper, FormHelper } from '~/testing/unit-test-helper'; import { DevicesSelectionChangeEvent } from '../osd-devices-selection-groups/devices-selection-change-event.interface'; import { DevicesSelectionClearEvent } from '../osd-devices-selection-groups/devices-selection-clear-event.interface'; import { OsdDevicesSelectionGroupsComponent } from '../osd-devices-selection-groups/osd-devices-selection-groups.component'; import { OsdFormComponent } from './osd-form.component'; describe('OsdFormComponent', () => { let form: CdFormGroup; let component: OsdFormComponent; let formHelper: FormHelper; let fixture: ComponentFixture<OsdFormComponent>; let fixtureHelper: FixtureHelper; let orchService: OrchestratorService; let hostService: HostService; let summaryService: SummaryService; const devices: InventoryDevice[] = [ { hostname: 'node0', uid: '1', path: '/dev/sda', sys_api: { vendor: 'VENDOR', model: 'MODEL', size: 1024, rotational: 'false', human_readable_size: '1 KB' }, available: true, rejected_reasons: [''], device_id: 'VENDOR-MODEL-ID', human_readable_type: 'nvme/ssd', osd_ids: [] } ]; const deploymentOptions: DeploymentOptions = { options: { cost_capacity: { name: OsdDeploymentOptions.COST_CAPACITY, available: true, capacity: 0, used: 0, hdd_used: 0, ssd_used: 0, nvme_used: 0, title: 'Cost/Capacity-optimized', desc: 'All the available HDDs are selected' }, throughput_optimized: { name: OsdDeploymentOptions.THROUGHPUT, available: false, capacity: 0, used: 0, hdd_used: 0, ssd_used: 0, nvme_used: 0, title: 'Throughput-optimized', desc: 'HDDs/SSDs are selected for data devices and SSDs/NVMes for DB/WAL devices' }, iops_optimized: { name: OsdDeploymentOptions.IOPS, available: false, capacity: 0, used: 0, hdd_used: 0, ssd_used: 0, nvme_used: 0, title: 'IOPS-optimized', desc: 'All the available NVMes are selected' } }, recommended_option: OsdDeploymentOptions.COST_CAPACITY }; const expectPreviewButton = (enabled: boolean) => { const debugElement = fixtureHelper.getElementByCss('.tc_submitButton'); expect(debugElement.nativeElement.disabled).toBe(!enabled); }; const selectDevices = (type: string) => { const event: DevicesSelectionChangeEvent = { type: type, filters: [], data: devices, dataOut: [] }; component.onDevicesSelected(event); if (type === 'data') { component.dataDeviceSelectionGroups.devices = devices; } else if (type === 'wal') { component.walDeviceSelectionGroups.devices = devices; } else if (type === 'db') { component.dbDeviceSelectionGroups.devices = devices; } fixture.detectChanges(); }; const clearDevices = (type: string) => { const event: DevicesSelectionClearEvent = { type: type, clearedDevices: [] }; component.onDevicesCleared(event); fixture.detectChanges(); }; const features = ['encrypted']; const checkFeatures = (enabled: boolean) => { for (const feature of features) { const element = fixtureHelper.getElementByCss(`#${feature}`).nativeElement; expect(element.disabled).toBe(!enabled); expect(element.checked).toBe(false); } }; configureTestBed({ imports: [ BrowserAnimationsModule, HttpClientTestingModule, FormsModule, SharedModule, RouterTestingModule, ReactiveFormsModule, ToastrModule.forRoot(), DashboardModule ], declarations: [OsdFormComponent, OsdDevicesSelectionGroupsComponent, InventoryDevicesComponent] }); beforeEach(() => { fixture = TestBed.createComponent(OsdFormComponent); fixtureHelper = new FixtureHelper(fixture); component = fixture.componentInstance; form = component.form; formHelper = new FormHelper(form); orchService = TestBed.inject(OrchestratorService); hostService = TestBed.inject(HostService); summaryService = TestBed.inject(SummaryService); summaryService['summaryDataSource'] = new BehaviorSubject(null); summaryService['summaryData$'] = summaryService['summaryDataSource'].asObservable(); summaryService['summaryDataSource'].next({ version: 'master' }); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('without orchestrator', () => { beforeEach(() => { spyOn(orchService, 'status').and.returnValue(of({ available: false })); spyOn(hostService, 'inventoryDeviceList').and.callThrough(); fixture.detectChanges(); }); it('should display info panel to document', () => { fixtureHelper.expectElementVisible('cd-alert-panel', true); fixtureHelper.expectElementVisible('.col-sm-10 form', false); }); it('should not call inventoryDeviceList', () => { expect(hostService.inventoryDeviceList).not.toHaveBeenCalled(); }); }); describe('with orchestrator', () => { beforeEach(() => { component.simpleDeployment = false; spyOn(orchService, 'status').and.returnValue(of({ available: true })); spyOn(hostService, 'inventoryDeviceList').and.returnValue(of([])); component.deploymentOptions = deploymentOptions; fixture.detectChanges(); }); it('should display the accordion', () => { fixtureHelper.expectElementVisible('.card-body .accordion', true); }); it('should display the three deployment scenarios', () => { fixtureHelper.expectElementVisible('#cost_capacity', true); fixtureHelper.expectElementVisible('#throughput_optimized', true); fixtureHelper.expectElementVisible('#iops_optimized', true); }); it('should only disable the options that are not available', () => { let radioBtn = fixtureHelper.getElementByCss('#throughput_optimized').nativeElement; expect(radioBtn.disabled).toBeTruthy(); radioBtn = fixtureHelper.getElementByCss('#iops_optimized').nativeElement; expect(radioBtn.disabled).toBeTruthy(); // Make the throughput_optimized option available and verify the option is not disabled deploymentOptions.options['throughput_optimized'].available = true; fixture.detectChanges(); radioBtn = fixtureHelper.getElementByCss('#throughput_optimized').nativeElement; expect(radioBtn.disabled).toBeFalsy(); }); it('should be a Recommended option only when it is recommended by backend', () => { const label = fixtureHelper.getElementByCss('#label_cost_capacity').nativeElement; const throughputLabel = fixtureHelper.getElementByCss('#label_throughput_optimized') .nativeElement; expect(label.innerHTML).toContain('Recommended'); expect(throughputLabel.innerHTML).not.toContain('Recommended'); deploymentOptions.recommended_option = OsdDeploymentOptions.THROUGHPUT; fixture.detectChanges(); expect(throughputLabel.innerHTML).toContain('Recommended'); expect(label.innerHTML).not.toContain('Recommended'); }); it('should display form', () => { fixtureHelper.expectElementVisible('cd-alert-panel', false); fixtureHelper.expectElementVisible('.card-body form', true); }); describe('without data devices selected', () => { it('should disable preview button', () => { expectPreviewButton(false); }); it('should not display shared devices slots', () => { fixtureHelper.expectElementVisible('#walSlots', false); fixtureHelper.expectElementVisible('#dbSlots', false); }); it('should disable the checkboxes', () => { checkFeatures(false); }); }); describe('with data devices selected', () => { beforeEach(() => { selectDevices('data'); }); it('should enable preview button', () => { expectPreviewButton(true); }); it('should not display shared devices slots', () => { fixtureHelper.expectElementVisible('#walSlots', false); fixtureHelper.expectElementVisible('#dbSlots', false); }); it('should enable the checkboxes', () => { checkFeatures(true); }); it('should disable the checkboxes after clearing data devices', () => { clearDevices('data'); checkFeatures(false); }); describe('with shared devices selected', () => { beforeEach(() => { selectDevices('wal'); selectDevices('db'); }); it('should display slots', () => { fixtureHelper.expectElementVisible('#walSlots', true); fixtureHelper.expectElementVisible('#dbSlots', true); }); it('validate slots', () => { for (const control of ['walSlots', 'dbSlots']) { formHelper.expectValid(control); formHelper.expectValidChange(control, 1); formHelper.expectErrorChange(control, -1, 'min'); } }); describe('test clearing data devices', () => { beforeEach(() => { clearDevices('data'); }); it('should not display shared devices slots and should disable checkboxes', () => { fixtureHelper.expectElementVisible('#walSlots', false); fixtureHelper.expectElementVisible('#dbSlots', false); checkFeatures(false); }); }); }); }); }); });
10,853
34.012903
124
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-form/osd-form.component.ts
import { Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Router } from '@angular/router'; import _ from 'lodash'; import { InventoryDevice } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-device.model'; import { HostService } from '~/app/shared/api/host.service'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; import { OsdService } from '~/app/shared/api/osd.service'; import { FormButtonPanelComponent } from '~/app/shared/components/form-button-panel/form-button-panel.component'; 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 { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { DeploymentOptions, OsdDeploymentOptions } from '~/app/shared/models/osd-deployment-options'; 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 { OsdCreationPreviewModalComponent } from '../osd-creation-preview-modal/osd-creation-preview-modal.component'; import { DevicesSelectionChangeEvent } from '../osd-devices-selection-groups/devices-selection-change-event.interface'; import { DevicesSelectionClearEvent } from '../osd-devices-selection-groups/devices-selection-clear-event.interface'; import { OsdDevicesSelectionGroupsComponent } from '../osd-devices-selection-groups/osd-devices-selection-groups.component'; import { DriveGroup } from './drive-group.model'; import { OsdFeature } from './osd-feature.interface'; @Component({ selector: 'cd-osd-form', templateUrl: './osd-form.component.html', styleUrls: ['./osd-form.component.scss'] }) export class OsdFormComponent extends CdForm implements OnInit { @ViewChild('dataDeviceSelectionGroups') dataDeviceSelectionGroups: OsdDevicesSelectionGroupsComponent; @ViewChild('walDeviceSelectionGroups') walDeviceSelectionGroups: OsdDevicesSelectionGroupsComponent; @ViewChild('dbDeviceSelectionGroups') dbDeviceSelectionGroups: OsdDevicesSelectionGroupsComponent; @ViewChild('previewButtonPanel') previewButtonPanel: FormButtonPanelComponent; @Input() hideTitle = false; @Input() hideSubmitBtn = false; @Output() emitDriveGroup: EventEmitter<DriveGroup> = new EventEmitter(); @Output() emitDeploymentOption: EventEmitter<object> = new EventEmitter(); @Output() emitMode: EventEmitter<boolean> = new EventEmitter(); icons = Icons; form: CdFormGroup; columns: Array<CdTableColumn> = []; allDevices: InventoryDevice[] = []; availDevices: InventoryDevice[] = []; dataDeviceFilters: any[] = []; dbDeviceFilters: any[] = []; walDeviceFilters: any[] = []; hostname = ''; driveGroup = new DriveGroup(); action: string; resource: string; features: { [key: string]: OsdFeature }; featureList: OsdFeature[] = []; hasOrchestrator = true; simpleDeployment = true; deploymentOptions: DeploymentOptions; optionNames = Object.values(OsdDeploymentOptions); constructor( public actionLabels: ActionLabelsI18n, private authStorageService: AuthStorageService, private orchService: OrchestratorService, private hostService: HostService, private router: Router, private modalService: ModalService, private osdService: OsdService, private taskWrapper: TaskWrapperService ) { super(); this.resource = $localize`OSDs`; this.action = this.actionLabels.CREATE; this.features = { encrypted: { key: 'encrypted', desc: $localize`Encryption` } }; this.featureList = _.map(this.features, (o, key) => Object.assign(o, { key: key })); this.createForm(); } ngOnInit() { this.orchService.status().subscribe((status) => { this.hasOrchestrator = status.available; if (status.available) { this.getDataDevices(); } else { this.loadingNone(); } }); this.osdService.getDeploymentOptions().subscribe((options) => { this.deploymentOptions = options; this.form.get('deploymentOption').setValue(this.deploymentOptions?.recommended_option); if (this.deploymentOptions?.recommended_option) { this.enableFeatures(); } }); this.form.get('walSlots').valueChanges.subscribe((value) => this.setSlots('wal', value)); this.form.get('dbSlots').valueChanges.subscribe((value) => this.setSlots('db', value)); _.each(this.features, (feature) => { this.form .get('features') .get(feature.key) .valueChanges.subscribe((value) => this.featureFormUpdate(feature.key, value)); }); } createForm() { this.form = new CdFormGroup({ walSlots: new FormControl(0), dbSlots: new FormControl(0), features: new CdFormGroup( this.featureList.reduce((acc: object, e) => { // disable initially because no data devices are selected acc[e.key] = new FormControl({ value: false, disabled: true }); return acc; }, {}) ), deploymentOption: new FormControl(0) }); } getDataDevices() { this.hostService.inventoryDeviceList().subscribe( (devices: InventoryDevice[]) => { this.allDevices = _.filter(devices, 'available'); this.availDevices = [...this.allDevices]; this.loadingReady(); }, () => { this.allDevices = []; this.availDevices = []; this.loadingError(); } ); } setSlots(type: string, slots: number) { if (typeof slots !== 'number') { return; } if (slots >= 0) { this.driveGroup.setSlots(type, slots); } } featureFormUpdate(key: string, checked: boolean) { this.driveGroup.setFeature(key, checked); } enableFeatures() { this.featureList.forEach((feature) => { this.form.get(feature.key).enable({ emitEvent: false }); }); } disableFeatures() { this.featureList.forEach((feature) => { const control = this.form.get(feature.key); control.disable({ emitEvent: false }); control.setValue(false, { emitEvent: false }); }); } onDevicesSelected(event: DevicesSelectionChangeEvent) { this.availDevices = event.dataOut; if (event.type === 'data') { // If user selects data devices for a single host, make only remaining devices on // that host as available. const hostnameFilter = _.find(event.filters, { prop: 'hostname' }); if (hostnameFilter) { this.hostname = hostnameFilter.value.raw; this.availDevices = event.dataOut.filter((device: InventoryDevice) => { return device.hostname === this.hostname; }); this.driveGroup.setHostPattern(this.hostname); } else { this.driveGroup.setHostPattern('*'); } this.enableFeatures(); } this.driveGroup.setDeviceSelection(event.type, event.filters); this.emitDriveGroup.emit(this.driveGroup); } onDevicesCleared(event: DevicesSelectionClearEvent) { if (event.type === 'data') { this.hostname = ''; this.availDevices = [...this.allDevices]; this.walDeviceSelectionGroups.devices = []; this.dbDeviceSelectionGroups.devices = []; this.disableFeatures(); this.driveGroup.reset(); this.form.get('walSlots').setValue(0, { emitEvent: false }); this.form.get('dbSlots').setValue(0, { emitEvent: false }); } else { this.availDevices = [...this.availDevices, ...event.clearedDevices]; this.driveGroup.clearDeviceSelection(event.type); const slotControlName = `${event.type}Slots`; this.form.get(slotControlName).setValue(0, { emitEvent: false }); } } emitDeploymentSelection() { const option = this.form.get('deploymentOption').value; const encrypted = this.form.get('encrypted').value; this.emitDeploymentOption.emit({ option: option, encrypted: encrypted }); } emitDeploymentMode() { this.simpleDeployment = !this.simpleDeployment; if (!this.simpleDeployment && this.dataDeviceSelectionGroups.devices.length === 0) { this.disableFeatures(); } else { this.enableFeatures(); } this.emitMode.emit(this.simpleDeployment); } submit() { if (this.simpleDeployment) { const option = this.form.get('deploymentOption').value; const encrypted = this.form.get('encrypted').value; const deploymentSpec = { option: option, encrypted: encrypted }; const title = this.deploymentOptions.options[deploymentSpec.option].title; const trackingId = `${title} deployment`; this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('osd/' + URLVerbs.CREATE, { tracking_id: trackingId }), call: this.osdService.create([deploymentSpec], trackingId, 'predefined') }) .subscribe({ complete: () => { this.router.navigate(['/osd']); } }); } else { // use user name and timestamp for drive group name const user = this.authStorageService.getUsername(); this.driveGroup.setName(`dashboard-${user}-${_.now()}`); const modalRef = this.modalService.show(OsdCreationPreviewModalComponent, { driveGroups: [this.driveGroup.spec] }); modalRef.componentInstance.submitAction.subscribe(() => { this.router.navigate(['/osd']); }); this.previewButtonPanel.submitButton.loading = false; } } }
9,835
33.271777
124
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-list/osd-list.component.html
<nav ngbNav #nav="ngbNav" class="nav-tabs"> <ng-container ngbNavItem> <a ngbNavLink i18n>OSDs List</a> <ng-template ngbNavContent> <cd-table [data]="osds" (fetchData)="getOsdList()" [columns]="columns" selectionType="multiClick" [hasDetails]="true" (setExpandedRow)="setExpandedRow($event)" (updateSelection)="updateSelection($event)" [updateSelectionOnRefresh]="'never'"> <div class="table-actions btn-toolbar"> <cd-table-actions [permission]="permissions.osd" [selection]="selection" class="btn-group" id="osd-actions" [tableActions]="tableActions"> </cd-table-actions> <cd-table-actions [permission]="{read: true}" [selection]="selection" dropDownOnly="Cluster-wide configuration" btnColor="light" class="btn-group" id="cluster-wide-actions" [tableActions]="clusterWideActions"> </cd-table-actions> </div> <cd-osd-details cdTableDetail [selection]="expandedRow"> </cd-osd-details> </cd-table> </ng-template> </ng-container> <ng-container ngbNavItem *ngIf="permissions.grafana.read"> <a ngbNavLink i18n>Overall Performance</a> <ng-template ngbNavContent> <cd-grafana i18n-title title="OSD list" [grafanaPath]="'osd-overview?'" [type]="'metrics'" uid="lo02I1Aiz" grafanaStyle="four"> </cd-grafana> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="nav"></div> <ng-template #markOsdConfirmationTpl let-markActionDescription="markActionDescription" let-osdIds="osdIds"> <ng-container i18n><strong>OSD(s) {{ osdIds | join }}</strong> will be marked <strong>{{ markActionDescription }}</strong> if you proceed.</ng-container> </ng-template> <ng-template #criticalConfirmationTpl let-safeToPerform="safeToPerform" let-message="message" let-active="active" let-missingStats="missingStats" let-storedPgs="storedPgs" let-actionDescription="actionDescription" let-osdIds="osdIds"> <div *ngIf="!safeToPerform" class="danger mb-3"> <cd-alert-panel type="warning"> <span i18n> The {selection.hasSingleSelection, select, true {OSD is} other {OSDs are}} not safe to be {{ actionDescription }}! </span> <br> <ul class="mb-0 ps-4"> <li *ngIf="active.length > 0" i18n> {selection.hasSingleSelection, select, true {} other {{{ active | join }} : }} Some PGs are currently mapped to {active.length === 1, select, true {it} other {them}}. </li> <li *ngIf="missingStats.length > 0" i18n> {selection.hasSingleSelection, select, true {} other {{{ missingStats | join }} : }} There are no reported stats and not all PGs are active and clean. </li> <li *ngIf="storedPgs.length > 0" i18n> {selection.hasSingleSelection, select, true {OSD} other {{{ storedPgs | join }} : OSDs }} still store some PG data and not all PGs are active and clean. </li> <li *ngIf="message"> {{ message }} </li> </ul> </cd-alert-panel> </div> <div *ngIf="safeToPerform" class="danger mb-3"> <cd-alert-panel type="info"> <span i18n> The {selection.hasSingleSelection, select, true {OSD is} other {OSDs are}} safe to destroy without reducing data durability. </span> </cd-alert-panel> </div> <ng-container i18n><strong>OSD {{ osdIds | join }}</strong> will be <strong>{{ actionDescription }}</strong> if you proceed.</ng-container> </ng-template> <ng-template #flagsTpl let-row="row"> <span *ngFor="let flag of row.cdClusterFlags;" class="badge badge-hdd me-1">{{ flag }}</span> <span *ngFor="let flag of row.cdIndivFlags;" class="badge badge-info me-1">{{ flag }}</span> </ng-template> <ng-template #osdUsageTpl let-row="row"> <cd-usage-bar [title]="'osd ' + row.osd" [total]="row.stats.stat_bytes" [used]="row.stats.stat_bytes_used" [warningThreshold]="osdSettings.nearfull_ratio" [errorThreshold]="osdSettings.full_ratio"> </cd-usage-bar> </ng-template> <ng-template #deleteOsdExtraTpl let-form="form"> <ng-container [formGroup]="form"> <ng-container formGroupName="child"> <div class="form-group"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" name="preserve" id="preserve" formControlName="preserve"> <label class="custom-control-label" for="preserve" i18n>Preserve OSD ID(s) for replacement.</label> </div> </div> </ng-container> </ng-container> </ng-template>
5,469
34.290323
99
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-list/osd-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { ToastrModule } from 'ngx-toastr'; import { EMPTY, of } from 'rxjs'; import { CephModule } from '~/app/ceph/ceph.module'; import { PerformanceCounterModule } from '~/app/ceph/performance-counter/performance-counter.module'; import { CoreModule } from '~/app/core/core.module'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; import { OsdService } from '~/app/shared/api/osd.service'; import { ConfirmationModalComponent } from '~/app/shared/components/confirmation-modal/confirmation-modal.component'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { FormModalComponent } from '~/app/shared/components/form-modal/form-modal.component'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { OrchestratorFeature } from '~/app/shared/models/orchestrator.enum'; import { Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { configureTestBed, OrchestratorHelper, PermissionHelper, TableActionHelper } from '~/testing/unit-test-helper'; import { OsdReweightModalComponent } from '../osd-reweight-modal/osd-reweight-modal.component'; import { OsdListComponent } from './osd-list.component'; describe('OsdListComponent', () => { let component: OsdListComponent; let fixture: ComponentFixture<OsdListComponent>; let modalServiceShowSpy: jasmine.Spy; let osdService: OsdService; let orchService: OrchestratorService; const fakeAuthStorageService = { getPermissions: () => { return new Permissions({ 'config-opt': ['read', 'update', 'create', 'delete'], osd: ['read', 'update', 'create', 'delete'] }); } }; const getTableAction = (name: string) => component.tableActions.find((action) => action.name === name); const setFakeSelection = () => { // Default data and selection const selection = [{ id: 1, tree: { device_class: 'ssd' } }]; const data = [{ id: 1, tree: { device_class: 'ssd' } }]; // Table data and selection component.selection = new CdTableSelection(); component.selection.selected = selection; component.osds = data; component.permissions = fakeAuthStorageService.getPermissions(); }; const openActionModal = (actionName: string) => { setFakeSelection(); getTableAction(actionName).click(); }; /** * The following modals are called after the information about their * safety to destroy/remove/mark them lost has been retrieved, hence * we will have to fake its request to be able to open those modals. */ const mockSafeToDestroy = () => { spyOn(TestBed.inject(OsdService), 'safeToDestroy').and.callFake(() => of({ is_safe_to_destroy: true }) ); }; const mockSafeToDelete = () => { spyOn(TestBed.inject(OsdService), 'safeToDelete').and.callFake(() => of({ is_safe_to_delete: true }) ); }; const mockOrch = () => { const features = [OrchestratorFeature.OSD_CREATE, OrchestratorFeature.OSD_DELETE]; OrchestratorHelper.mockStatus(true, features); }; configureTestBed({ imports: [ BrowserAnimationsModule, HttpClientTestingModule, PerformanceCounterModule, ToastrModule.forRoot(), CephModule, ReactiveFormsModule, NgbDropdownModule, RouterTestingModule, CoreModule, RouterTestingModule ], providers: [ { provide: AuthStorageService, useValue: fakeAuthStorageService }, TableActionsComponent, ModalService ] }); beforeEach(() => { fixture = TestBed.createComponent(OsdListComponent); component = fixture.componentInstance; osdService = TestBed.inject(OsdService); modalServiceShowSpy = spyOn(TestBed.inject(ModalService), 'show').and.returnValue({ // mock the close function, it might be called if there are async tests. close: jest.fn() }); orchService = TestBed.inject(OrchestratorService); }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should have columns that are sortable', () => { fixture.detectChanges(); expect( component.columns .filter((column) => !(column.prop === undefined)) .every((column) => Boolean(column.prop)) ).toBeTruthy(); }); describe('getOsdList', () => { let osds: any[]; let flagsSpy: jasmine.Spy; const createOsd = (n: number) => <Record<string, any>>{ in: 'in', up: 'up', tree: { device_class: 'ssd' }, stats_history: { op_out_bytes: [ [n, n], [n * 2, n * 2] ], op_in_bytes: [ [n * 3, n * 3], [n * 4, n * 4] ] }, stats: { stat_bytes_used: n * n, stat_bytes: n * n * n }, state: [] }; const expectAttributeOnEveryOsd = (attr: string) => expect(component.osds.every((osd) => Boolean(_.get(osd, attr)))).toBeTruthy(); beforeEach(() => { spyOn(osdService, 'getList').and.callFake(() => of(osds)); flagsSpy = spyOn(osdService, 'getFlags').and.callFake(() => of([])); osds = [createOsd(1), createOsd(2), createOsd(3)]; component.getOsdList(); }); it('should replace "this.osds" with new data', () => { expect(component.osds.length).toBe(3); expect(osdService.getList).toHaveBeenCalledTimes(1); osds = [createOsd(4)]; component.getOsdList(); expect(component.osds.length).toBe(1); expect(osdService.getList).toHaveBeenCalledTimes(2); }); it('should have custom attribute "collectedStates"', () => { expectAttributeOnEveryOsd('collectedStates'); expect(component.osds[0].collectedStates).toEqual(['in', 'up']); }); it('should have "destroyed" state in "collectedStates"', () => { osds[0].state.push('destroyed'); osds[0].up = 0; component.getOsdList(); expectAttributeOnEveryOsd('collectedStates'); expect(component.osds[0].collectedStates).toEqual(['in', 'destroyed']); }); it('should have custom attribute "stats_history.out_bytes"', () => { expectAttributeOnEveryOsd('stats_history.out_bytes'); expect(component.osds[0].stats_history.out_bytes).toEqual([1, 2]); }); it('should have custom attribute "stats_history.in_bytes"', () => { expectAttributeOnEveryOsd('stats_history.in_bytes'); expect(component.osds[0].stats_history.in_bytes).toEqual([3, 4]); }); it('should have custom attribute "stats.usage"', () => { expectAttributeOnEveryOsd('stats.usage'); expect(component.osds[0].stats.usage).toBe(1); expect(component.osds[1].stats.usage).toBe(0.5); expect(component.osds[2].stats.usage).toBe(3 / 9); }); it('should have custom attribute "cdIsBinary" to be true', () => { expectAttributeOnEveryOsd('cdIsBinary'); expect(component.osds[0].cdIsBinary).toBe(true); }); it('should return valid individual flags only', () => { const osd1 = createOsd(1); const osd2 = createOsd(2); osd1.state = ['noup', 'exists', 'up']; osd2.state = ['noup', 'exists', 'up', 'noin']; osds = [osd1, osd2]; component.getOsdList(); expect(component.osds[0].cdIndivFlags).toStrictEqual(['noup']); expect(component.osds[1].cdIndivFlags).toStrictEqual(['noup', 'noin']); }); it('should not fail on empty individual flags list', () => { expect(component.osds[0].cdIndivFlags).toStrictEqual([]); }); it('should not return disabled cluster-wide flags', () => { flagsSpy.and.callFake(() => of(['noout', 'nodown', 'sortbitwise'])); component.getOsdList(); expect(component.osds[0].cdClusterFlags).toStrictEqual(['noout', 'nodown']); flagsSpy.and.callFake(() => of(['noout', 'purged_snapdirs', 'nodown'])); component.getOsdList(); expect(component.osds[0].cdClusterFlags).toStrictEqual(['noout', 'nodown']); flagsSpy.and.callFake(() => of(['recovery_deletes', 'noout', 'pglog_hardlimit', 'nodown'])); component.getOsdList(); expect(component.osds[0].cdClusterFlags).toStrictEqual(['noout', 'nodown']); }); it('should not fail on empty cluster-wide flags list', () => { flagsSpy.and.callFake(() => of([])); component.getOsdList(); expect(component.osds[0].cdClusterFlags).toStrictEqual([]); }); it('should have custom attribute "cdExecuting"', () => { osds[1].operational_status = 'unmanaged'; osds[2].operational_status = 'deleting'; component.getOsdList(); expect(component.osds[0].cdExecuting).toBeUndefined(); expect(component.osds[1].cdExecuting).toBeUndefined(); expect(component.osds[2].cdExecuting).toBe('deleting'); }); }); describe('show osd actions as defined', () => { const getOsdActions = () => { fixture.detectChanges(); return fixture.debugElement.query(By.css('#cluster-wide-actions')).componentInstance .dropDownActions; }; it('shows osd actions after osd-actions', () => { fixture.detectChanges(); expect(fixture.debugElement.query(By.css('#cluster-wide-actions'))).toBe( fixture.debugElement.queryAll(By.directive(TableActionsComponent))[1] ); }); it('shows both osd actions', () => { const osdActions = getOsdActions(); expect(osdActions).toEqual(component.clusterWideActions); expect(osdActions.length).toBe(3); }); it('shows only "Flags" action', () => { component.permissions.configOpt.read = false; const osdActions = getOsdActions(); expect(osdActions[0].name).toBe('Flags'); expect(osdActions.length).toBe(1); }); it('shows only "Recovery Priority" action', () => { component.permissions.osd.read = false; const osdActions = getOsdActions(); expect(osdActions[0].name).toBe('Recovery Priority'); expect(osdActions[1].name).toBe('PG scrub'); expect(osdActions.length).toBe(2); }); it('shows no osd actions', () => { component.permissions.configOpt.read = false; component.permissions.osd.read = false; const osdActions = getOsdActions(); expect(osdActions).toEqual([]); }); }); it('should test all TableActions combinations', () => { const permissionHelper: PermissionHelper = new PermissionHelper(component.permissions.osd); const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions( component.tableActions ); expect(tableActions).toEqual({ 'create,update,delete': { actions: [ 'Create', 'Edit', 'Flags', 'Scrub', 'Deep Scrub', 'Reweight', 'Mark Out', 'Mark In', 'Mark Down', 'Mark Lost', 'Purge', 'Destroy', 'Delete' ], primary: { multiple: 'Scrub', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,update': { actions: [ 'Create', 'Edit', 'Flags', 'Scrub', 'Deep Scrub', 'Reweight', 'Mark Out', 'Mark In', 'Mark Down' ], primary: { multiple: 'Scrub', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,delete': { actions: ['Create', 'Mark Lost', 'Purge', 'Destroy', 'Delete'], primary: { multiple: 'Create', executing: 'Mark Lost', single: 'Mark Lost', no: 'Create' } }, create: { actions: ['Create'], primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' } }, 'update,delete': { actions: [ 'Edit', 'Flags', 'Scrub', 'Deep Scrub', 'Reweight', 'Mark Out', 'Mark In', 'Mark Down', 'Mark Lost', 'Purge', 'Destroy', 'Delete' ], primary: { multiple: 'Scrub', executing: 'Edit', single: 'Edit', no: 'Edit' } }, update: { actions: [ 'Edit', 'Flags', 'Scrub', 'Deep Scrub', 'Reweight', 'Mark Out', 'Mark In', 'Mark Down' ], primary: { multiple: 'Scrub', executing: 'Edit', single: 'Edit', no: 'Edit' } }, delete: { actions: ['Mark Lost', 'Purge', 'Destroy', 'Delete'], primary: { multiple: 'Mark Lost', executing: 'Mark Lost', single: 'Mark Lost', no: 'Mark Lost' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); describe('test table actions in submenu', () => { beforeEach(() => { fixture.detectChanges(); }); beforeEach(fakeAsync(() => { // The menu needs a click to render the dropdown! const dropDownToggle = fixture.debugElement.query(By.css('.dropdown-toggle')); dropDownToggle.triggerEventHandler('click', null); tick(); fixture.detectChanges(); })); it('has all menu entries disabled except create', () => { const tableActionElement = fixture.debugElement.query(By.directive(TableActionsComponent)); const toClassName = TestBed.inject(TableActionsComponent).toClassName; const getActionClasses = (action: CdTableAction) => tableActionElement.query(By.css(`[ngbDropdownItem].${toClassName(action)}`)).classes; component.tableActions.forEach((action) => { if (action.name === 'Create') { return; } expect(getActionClasses(action).disabled).toBe(true); }); }); }); describe('tests if all modals are opened correctly', () => { /** * Helper function to check if a function opens a modal * * @param modalClass - The expected class of the modal */ const expectOpensModal = (actionName: string, modalClass: any): void => { openActionModal(actionName); // @TODO: check why tsc is complaining when passing 'expectationFailOutput' param. expect(modalServiceShowSpy.calls.any()).toBeTruthy(); expect(modalServiceShowSpy.calls.first().args[0]).toBe(modalClass); modalServiceShowSpy.calls.reset(); }; it('opens the reweight modal', () => { expectOpensModal('Reweight', OsdReweightModalComponent); }); it('opens the form modal', () => { expectOpensModal('Edit', FormModalComponent); }); it('opens all confirmation modals', () => { const modalClass = ConfirmationModalComponent; expectOpensModal('Mark Out', modalClass); expectOpensModal('Mark In', modalClass); expectOpensModal('Mark Down', modalClass); }); it('opens all critical confirmation modals', () => { const modalClass = CriticalConfirmationModalComponent; mockSafeToDestroy(); expectOpensModal('Mark Lost', modalClass); expectOpensModal('Purge', modalClass); expectOpensModal('Destroy', modalClass); mockOrch(); mockSafeToDelete(); expectOpensModal('Delete', modalClass); }); }); describe('tests if the correct methods are called on confirmation', () => { const expectOsdServiceMethodCalled = ( actionName: string, osdServiceMethodName: | 'markOut' | 'markIn' | 'markDown' | 'markLost' | 'purge' | 'destroy' | 'delete' ): void => { const osdServiceSpy = spyOn(osdService, osdServiceMethodName).and.callFake(() => EMPTY); openActionModal(actionName); const initialState = modalServiceShowSpy.calls.first().args[1]; const submit = initialState.onSubmit || initialState.submitAction; submit.call(component); expect(osdServiceSpy.calls.count()).toBe(1); expect(osdServiceSpy.calls.first().args[0]).toBe(1); // Reset spies to be able to recreate them osdServiceSpy.calls.reset(); modalServiceShowSpy.calls.reset(); }; it('calls the corresponding service methods in confirmation modals', () => { expectOsdServiceMethodCalled('Mark Out', 'markOut'); expectOsdServiceMethodCalled('Mark In', 'markIn'); expectOsdServiceMethodCalled('Mark Down', 'markDown'); }); it('calls the corresponding service methods in critical confirmation modals', () => { mockSafeToDestroy(); expectOsdServiceMethodCalled('Mark Lost', 'markLost'); expectOsdServiceMethodCalled('Purge', 'purge'); expectOsdServiceMethodCalled('Destroy', 'destroy'); mockOrch(); mockSafeToDelete(); expectOsdServiceMethodCalled('Delete', 'delete'); }); }); describe('table actions', () => { const fakeOsds = require('./fixtures/osd_list_response.json'); beforeEach(() => { component.permissions = fakeAuthStorageService.getPermissions(); spyOn(osdService, 'getList').and.callFake(() => of(fakeOsds)); spyOn(osdService, 'getFlags').and.callFake(() => of([])); }); const testTableActions = async ( orch: boolean, features: OrchestratorFeature[], tests: { selectRow?: number; expectResults: any }[] ) => { OrchestratorHelper.mockStatus(orch, features); fixture.detectChanges(); await fixture.whenStable(); for (const test of tests) { if (test.selectRow) { component.selection = new CdTableSelection(); component.selection.selected = [test.selectRow]; } await TableActionHelper.verifyTableActions( fixture, component.tableActions, test.expectResults ); } }; it('should have correct states when Orchestrator is enabled', async () => { const tests = [ { expectResults: { Create: { disabled: false, disableDesc: '' }, Delete: { disabled: true, disableDesc: '' } } }, { selectRow: fakeOsds[0], expectResults: { Create: { disabled: false, disableDesc: '' }, Delete: { disabled: false, disableDesc: '' } } }, { selectRow: fakeOsds[1], // Select a row that is not managed. expectResults: { Create: { disabled: false, disableDesc: '' }, Delete: { disabled: true, disableDesc: '' } } }, { selectRow: fakeOsds[2], // Select a row that is being deleted. expectResults: { Create: { disabled: false, disableDesc: '' }, Delete: { disabled: true, disableDesc: '' } } } ]; const features = [ OrchestratorFeature.OSD_CREATE, OrchestratorFeature.OSD_DELETE, OrchestratorFeature.OSD_GET_REMOVE_STATUS ]; await testTableActions(true, features, tests); }); it('should have correct states when Orchestrator is disabled', async () => { const resultNoOrchestrator = { disabled: true, disableDesc: orchService.disableMessages.noOrchestrator }; const tests = [ { expectResults: { Create: resultNoOrchestrator, Delete: { disabled: true, disableDesc: '' } } }, { selectRow: fakeOsds[0], expectResults: { Create: resultNoOrchestrator, Delete: resultNoOrchestrator } } ]; await testTableActions(false, [], tests); }); it('should have correct states when Orchestrator features are missing', async () => { const resultMissingFeatures = { disabled: true, disableDesc: orchService.disableMessages.missingFeature }; const tests = [ { expectResults: { Create: resultMissingFeatures, Delete: { disabled: true, disableDesc: '' } } }, { selectRow: fakeOsds[0], expectResults: { Create: resultMissingFeatures, Delete: resultMissingFeatures } } ]; await testTableActions(true, [], tests); }); }); });
21,244
32.0919
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-list/osd-list.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Router } from '@angular/router'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { forkJoin as observableForkJoin, Observable } from 'rxjs'; import { take } from 'rxjs/operators'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; import { OsdService } from '~/app/shared/api/osd.service'; import { ListWithDetails } from '~/app/shared/classes/list-with-details.class'; import { ConfirmationModalComponent } from '~/app/shared/components/confirmation-modal/confirmation-modal.component'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { FormModalComponent } from '~/app/shared/components/form-modal/form-modal.component'; import { ActionLabelsI18n, URLVerbs } from '~/app/shared/constants/app.constants'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; 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 { OrchestratorFeature } from '~/app/shared/models/orchestrator.enum'; import { OrchestratorStatus } from '~/app/shared/models/orchestrator.interface'; 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 { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { URLBuilderService } from '~/app/shared/services/url-builder.service'; import { OsdFlagsIndivModalComponent } from '../osd-flags-indiv-modal/osd-flags-indiv-modal.component'; import { OsdFlagsModalComponent } from '../osd-flags-modal/osd-flags-modal.component'; import { OsdPgScrubModalComponent } from '../osd-pg-scrub-modal/osd-pg-scrub-modal.component'; import { OsdRecvSpeedModalComponent } from '../osd-recv-speed-modal/osd-recv-speed-modal.component'; import { OsdReweightModalComponent } from '../osd-reweight-modal/osd-reweight-modal.component'; import { OsdScrubModalComponent } from '../osd-scrub-modal/osd-scrub-modal.component'; const BASE_URL = 'osd'; @Component({ selector: 'cd-osd-list', templateUrl: './osd-list.component.html', styleUrls: ['./osd-list.component.scss'], providers: [{ provide: URLBuilderService, useValue: new URLBuilderService(BASE_URL) }] }) export class OsdListComponent extends ListWithDetails implements OnInit { @ViewChild('osdUsageTpl', { static: true }) osdUsageTpl: TemplateRef<any>; @ViewChild('markOsdConfirmationTpl', { static: true }) markOsdConfirmationTpl: TemplateRef<any>; @ViewChild('criticalConfirmationTpl', { static: true }) criticalConfirmationTpl: TemplateRef<any>; @ViewChild('reweightBodyTpl') reweightBodyTpl: TemplateRef<any>; @ViewChild('safeToDestroyBodyTpl') safeToDestroyBodyTpl: TemplateRef<any>; @ViewChild('deleteOsdExtraTpl') deleteOsdExtraTpl: TemplateRef<any>; @ViewChild('flagsTpl', { static: true }) flagsTpl: TemplateRef<any>; permissions: Permissions; tableActions: CdTableAction[]; bsModalRef: NgbModalRef; columns: CdTableColumn[]; clusterWideActions: CdTableAction[]; icons = Icons; osdSettings = new OsdSettings(); selection = new CdTableSelection(); osds: any[] = []; disabledFlags: string[] = [ 'sortbitwise', 'purged_snapdirs', 'recovery_deletes', 'pglog_hardlimit' ]; indivFlagNames: string[] = ['noup', 'nodown', 'noin', 'noout']; orchStatus: OrchestratorStatus; actionOrchFeatures = { create: [OrchestratorFeature.OSD_CREATE], delete: [OrchestratorFeature.OSD_DELETE] }; protected static collectStates(osd: any) { const states = [osd['in'] ? 'in' : 'out']; if (osd['up']) { states.push('up'); } else if (osd.state.includes('destroyed')) { states.push('destroyed'); } else { states.push('down'); } return states; } constructor( private authStorageService: AuthStorageService, private osdService: OsdService, private dimlessBinaryPipe: DimlessBinaryPipe, private modalService: ModalService, private urlBuilder: URLBuilderService, private router: Router, private taskWrapper: TaskWrapperService, public actionLabels: ActionLabelsI18n, public notificationService: NotificationService, private orchService: OrchestratorService ) { super(); this.permissions = this.authStorageService.getPermissions(); this.tableActions = [ { name: this.actionLabels.CREATE, permission: 'create', icon: Icons.add, click: () => this.router.navigate([this.urlBuilder.getCreate()]), disable: (selection: CdTableSelection) => this.getDisable('create', selection), canBePrimary: (selection: CdTableSelection) => !selection.hasSelection }, { name: this.actionLabels.EDIT, permission: 'update', icon: Icons.edit, click: () => this.editAction() }, { name: this.actionLabels.FLAGS, permission: 'update', icon: Icons.flag, click: () => this.configureFlagsIndivAction(), disable: () => !this.hasOsdSelected }, { name: this.actionLabels.SCRUB, permission: 'update', icon: Icons.analyse, click: () => this.scrubAction(false), disable: () => !this.hasOsdSelected, canBePrimary: (selection: CdTableSelection) => selection.hasSelection }, { name: this.actionLabels.DEEP_SCRUB, permission: 'update', icon: Icons.deepCheck, click: () => this.scrubAction(true), disable: () => !this.hasOsdSelected }, { name: this.actionLabels.REWEIGHT, permission: 'update', click: () => this.reweight(), disable: () => !this.hasOsdSelected || !this.selection.hasSingleSelection, icon: Icons.reweight }, { name: this.actionLabels.MARK_OUT, permission: 'update', click: () => this.showConfirmationModal($localize`out`, this.osdService.markOut), disable: () => this.isNotSelectedOrInState('out'), icon: Icons.left }, { name: this.actionLabels.MARK_IN, permission: 'update', click: () => this.showConfirmationModal($localize`in`, this.osdService.markIn), disable: () => this.isNotSelectedOrInState('in'), icon: Icons.right }, { name: this.actionLabels.MARK_DOWN, permission: 'update', click: () => this.showConfirmationModal($localize`down`, this.osdService.markDown), disable: () => this.isNotSelectedOrInState('down'), icon: Icons.down }, { name: this.actionLabels.MARK_LOST, permission: 'delete', click: () => this.showCriticalConfirmationModal( $localize`Mark`, $localize`OSD lost`, $localize`marked lost`, (ids: number[]) => { return this.osdService.safeToDestroy(JSON.stringify(ids)); }, 'is_safe_to_destroy', this.osdService.markLost ), disable: () => this.isNotSelectedOrInState('up'), icon: Icons.flatten }, { name: this.actionLabels.PURGE, permission: 'delete', click: () => this.showCriticalConfirmationModal( $localize`Purge`, $localize`OSD`, $localize`purged`, (ids: number[]) => { return this.osdService.safeToDestroy(JSON.stringify(ids)); }, 'is_safe_to_destroy', (id: number) => { this.selection = new CdTableSelection(); return this.osdService.purge(id); } ), disable: () => this.isNotSelectedOrInState('up'), icon: Icons.erase }, { name: this.actionLabels.DESTROY, permission: 'delete', click: () => this.showCriticalConfirmationModal( $localize`destroy`, $localize`OSD`, $localize`destroyed`, (ids: number[]) => { return this.osdService.safeToDestroy(JSON.stringify(ids)); }, 'is_safe_to_destroy', (id: number) => { this.selection = new CdTableSelection(); return this.osdService.destroy(id); } ), disable: () => this.isNotSelectedOrInState('up'), icon: Icons.destroyCircle }, { name: this.actionLabels.DELETE, permission: 'delete', click: () => this.delete(), disable: (selection: CdTableSelection) => this.getDisable('delete', selection), icon: Icons.destroy } ]; } ngOnInit() { this.clusterWideActions = [ { name: $localize`Flags`, icon: Icons.flag, click: () => this.configureFlagsAction(), permission: 'read', visible: () => this.permissions.osd.read }, { name: $localize`Recovery Priority`, icon: Icons.deepCheck, click: () => this.configureQosParamsAction(), permission: 'read', visible: () => this.permissions.configOpt.read }, { name: $localize`PG scrub`, icon: Icons.analyse, click: () => this.configurePgScrubAction(), permission: 'read', visible: () => this.permissions.configOpt.read } ]; this.columns = [ { prop: 'id', name: $localize`ID`, flexGrow: 1, cellTransformation: CellTemplate.executing, customTemplateConfig: { valueClass: 'bold' } }, { prop: 'host.name', name: $localize`Host` }, { prop: 'collectedStates', name: $localize`Status`, flexGrow: 1, cellTransformation: CellTemplate.badge, customTemplateConfig: { map: { in: { class: 'badge-success' }, up: { class: 'badge-success' }, down: { class: 'badge-danger' }, out: { class: 'badge-danger' }, destroyed: { class: 'badge-danger' } } } }, { prop: 'tree.device_class', name: $localize`Device class`, flexGrow: 1.2, cellTransformation: CellTemplate.badge, customTemplateConfig: { map: { hdd: { class: 'badge-hdd' }, ssd: { class: 'badge-ssd' } } } }, { prop: 'stats.numpg', name: $localize`PGs`, flexGrow: 1 }, { prop: 'stats.stat_bytes', name: $localize`Size`, flexGrow: 1, pipe: this.dimlessBinaryPipe }, { prop: 'state', name: $localize`Flags`, cellTemplate: this.flagsTpl }, { prop: 'stats.usage', name: $localize`Usage`, cellTemplate: this.osdUsageTpl }, { prop: 'stats_history.out_bytes', name: $localize`Read bytes`, cellTransformation: CellTemplate.sparkline }, { prop: 'stats_history.in_bytes', name: $localize`Write bytes`, cellTransformation: CellTemplate.sparkline }, { prop: 'stats.op_r', name: $localize`Read ops`, cellTransformation: CellTemplate.perSecond }, { prop: 'stats.op_w', name: $localize`Write ops`, cellTransformation: CellTemplate.perSecond } ]; this.orchService.status().subscribe((status: OrchestratorStatus) => (this.orchStatus = status)); this.osdService .getOsdSettings() .pipe(take(1)) .subscribe((data: any) => { this.osdSettings = data; }); } getDisable(action: 'create' | 'delete', selection: CdTableSelection): boolean | string { if (action === 'delete') { if (!selection.hasSelection) { return true; } else { // Disable delete action if any selected OSDs are under deleting or unmanaged. const deletingOSDs = _.some(this.getSelectedOsds(), (osd) => { const status = _.get(osd, 'operational_status'); return status === 'deleting' || status === 'unmanaged'; }); if (deletingOSDs) { return true; } } } return this.orchService.getTableActionDisableDesc( this.orchStatus, this.actionOrchFeatures[action] ); } /** * Only returns valid IDs, e.g. if an OSD is falsely still selected after being deleted, it won't * get returned. */ getSelectedOsdIds(): number[] { const osdIds = this.osds.map((osd) => osd.id); return this.selection.selected .map((row) => row.id) .filter((id) => osdIds.includes(id)) .sort(); } getSelectedOsds(): any[] { return this.osds.filter( (osd) => !_.isUndefined(osd) && this.getSelectedOsdIds().includes(osd.id) ); } get hasOsdSelected(): boolean { return this.getSelectedOsdIds().length > 0; } updateSelection(selection: CdTableSelection) { this.selection = selection; } /** * Returns true if no rows are selected or if *any* of the selected rows are in the given * state. Useful for deactivating the corresponding menu entry. */ isNotSelectedOrInState(state: 'in' | 'up' | 'down' | 'out'): boolean { const selectedOsds = this.getSelectedOsds(); if (selectedOsds.length === 0) { return true; } switch (state) { case 'in': return selectedOsds.some((osd) => osd.in === 1); case 'out': return selectedOsds.some((osd) => osd.in !== 1); case 'down': return selectedOsds.some((osd) => osd.up !== 1); case 'up': return selectedOsds.some((osd) => osd.up === 1); } } getOsdList() { const observables = [this.osdService.getList(), this.osdService.getFlags()]; observableForkJoin(observables).subscribe((resp: [any[], string[]]) => { this.osds = resp[0].map((osd) => { osd.collectedStates = OsdListComponent.collectStates(osd); osd.stats_history.out_bytes = osd.stats_history.op_out_bytes.map((i: string) => i[1]); osd.stats_history.in_bytes = osd.stats_history.op_in_bytes.map((i: string) => i[1]); osd.stats.usage = osd.stats.stat_bytes_used / osd.stats.stat_bytes; osd.cdIsBinary = true; osd.cdIndivFlags = osd.state.filter((f: string) => this.indivFlagNames.includes(f)); osd.cdClusterFlags = resp[1].filter((f: string) => !this.disabledFlags.includes(f)); const deploy_state = _.get(osd, 'operational_status', 'unmanaged'); if (deploy_state !== 'unmanaged' && deploy_state !== 'working') { osd.cdExecuting = deploy_state; } return osd; }); }); } editAction() { const selectedOsd = _.filter(this.osds, ['id', this.selection.first().id]).pop(); this.modalService.show(FormModalComponent, { titleText: $localize`Edit OSD: ${selectedOsd.id}`, fields: [ { type: 'text', name: 'deviceClass', value: selectedOsd.tree.device_class, label: $localize`Device class`, required: true } ], submitButtonText: $localize`Edit OSD`, onSubmit: (values: any) => { this.osdService.update(selectedOsd.id, values.deviceClass).subscribe(() => { this.notificationService.show( NotificationType.success, $localize`Updated OSD '${selectedOsd.id}'` ); this.getOsdList(); }); } }); } scrubAction(deep: boolean) { if (!this.hasOsdSelected) { return; } const initialState = { selected: this.getSelectedOsdIds(), deep: deep }; this.bsModalRef = this.modalService.show(OsdScrubModalComponent, initialState); } configureFlagsAction() { this.bsModalRef = this.modalService.show(OsdFlagsModalComponent); } configureFlagsIndivAction() { const initialState = { selected: this.getSelectedOsds() }; this.bsModalRef = this.modalService.show(OsdFlagsIndivModalComponent, initialState); } showConfirmationModal(markAction: string, onSubmit: (id: number) => Observable<any>) { const osdIds = this.getSelectedOsdIds(); this.bsModalRef = this.modalService.show(ConfirmationModalComponent, { titleText: $localize`Mark OSD ${markAction}`, buttonText: $localize`Mark ${markAction}`, bodyTpl: this.markOsdConfirmationTpl, bodyContext: { markActionDescription: markAction, osdIds }, onSubmit: () => { observableForkJoin( this.getSelectedOsdIds().map((osd: any) => onSubmit.call(this.osdService, osd)) ).subscribe(() => this.bsModalRef.close()); } }); } reweight() { const selectedOsd = this.osds.filter((o) => o.id === this.selection.first().id).pop(); this.bsModalRef = this.modalService.show(OsdReweightModalComponent, { currentWeight: selectedOsd.weight, osdId: selectedOsd.id }); } delete() { const deleteFormGroup = new CdFormGroup({ preserve: new FormControl(false) }); this.showCriticalConfirmationModal( $localize`delete`, $localize`OSD`, $localize`deleted`, (ids: number[]) => { return this.osdService.safeToDelete(JSON.stringify(ids)); }, 'is_safe_to_delete', (id: number) => { this.selection = new CdTableSelection(); return this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('osd/' + URLVerbs.DELETE, { svc_id: id }), call: this.osdService.delete(id, deleteFormGroup.value.preserve, true) }); }, true, deleteFormGroup, this.deleteOsdExtraTpl ); } /** * Perform check first and display a critical confirmation modal. * @param {string} actionDescription name of the action. * @param {string} itemDescription the item's name that the action operates on. * @param {string} templateItemDescription the action name to be displayed in modal template. * @param {Function} check the function is called to check if the action is safe. * @param {string} checkKey the safe indicator's key in the check response. * @param {Function} action the action function. * @param {boolean} taskWrapped if true, hide confirmation modal after action * @param {CdFormGroup} childFormGroup additional child form group to be passed to confirmation modal * @param {TemplateRef<any>} childFormGroupTemplate template for additional child form group */ showCriticalConfirmationModal( actionDescription: string, itemDescription: string, templateItemDescription: string, check: (ids: number[]) => Observable<any>, checkKey: string, action: (id: number | number[]) => Observable<any>, taskWrapped: boolean = false, childFormGroup?: CdFormGroup, childFormGroupTemplate?: TemplateRef<any> ): void { check(this.getSelectedOsdIds()).subscribe((result) => { const modalRef = this.modalService.show(CriticalConfirmationModalComponent, { actionDescription: actionDescription, itemDescription: itemDescription, bodyTemplate: this.criticalConfirmationTpl, bodyContext: { safeToPerform: result[checkKey], message: result.message, active: result.active, missingStats: result.missing_stats, storedPgs: result.stored_pgs, actionDescription: templateItemDescription, osdIds: this.getSelectedOsdIds() }, childFormGroup: childFormGroup, childFormGroupTemplate: childFormGroupTemplate, submitAction: () => { const observable = observableForkJoin( this.getSelectedOsdIds().map((osd: any) => action.call(this.osdService, osd)) ); if (taskWrapped) { observable.subscribe({ error: () => { this.getOsdList(); modalRef.close(); }, complete: () => modalRef.close() }); } else { observable.subscribe( () => { this.getOsdList(); modalRef.close(); }, () => modalRef.close() ); } } }); }); } configureQosParamsAction() { this.bsModalRef = this.modalService.show(OsdRecvSpeedModalComponent); } configurePgScrubAction() { this.bsModalRef = this.modalService.show(OsdPgScrubModalComponent, undefined, { size: 'lg' }); } }
21,467
33.3488
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-pg-scrub-modal/osd-pg-scrub-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 #formDir="ngForm" [formGroup]="osdPgScrubForm" novalidate cdFormScope="osd"> <div class="modal-body osd-modal"> <!-- Basic --> <cd-config-option [optionNames]="basicOptions" [optionsForm]="osdPgScrubForm" [optionsFormDir]="formDir" [optionsFormGroupName]="'basicFormGroup'" #basicOptionsValues></cd-config-option> <!-- Advanced --> <div class="row"> <div class="col-sm-12"> <a class="pull-right margin-right-md" (click)="advancedEnabled = true" *ngIf="!advancedEnabled" i18n>Advanced...</a> </div> </div> <div *ngIf="advancedEnabled"> <h3 class="page-header" i18n>Advanced configuration options</h3> <cd-config-option [optionNames]="advancedOptions" [optionsForm]="osdPgScrubForm" [optionsFormDir]="formDir" [optionsFormGroupName]="'advancedFormGroup'" #advancedOptionsValues></cd-config-option> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="submitAction()" [form]="osdPgScrubForm" [showSubmit]="permissions.configOpt.update" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"> </cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
1,873
39.73913
103
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-pg-scrub-modal/osd-pg-scrub-modal.component.spec.ts
import { HttpClientTestingModule } 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 { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of as observableOf } from 'rxjs'; import { ConfigurationService } from '~/app/shared/api/configuration.service'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { OsdPgScrubModalComponent } from './osd-pg-scrub-modal.component'; describe('OsdPgScrubModalComponent', () => { let component: OsdPgScrubModalComponent; let fixture: ComponentFixture<OsdPgScrubModalComponent>; let configurationService: ConfigurationService; configureTestBed({ imports: [ HttpClientTestingModule, ReactiveFormsModule, RouterTestingModule, SharedModule, ToastrModule.forRoot() ], declarations: [OsdPgScrubModalComponent], providers: [NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(OsdPgScrubModalComponent); component = fixture.componentInstance; fixture.detectChanges(); configurationService = TestBed.inject(ConfigurationService); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('submitAction', () => { let notificationService: NotificationService; beforeEach(() => { spyOn(TestBed.inject(Router), 'navigate').and.stub(); notificationService = TestBed.inject(NotificationService); spyOn(notificationService, 'show'); }); it('test create success notification', () => { spyOn(configurationService, 'bulkCreate').and.returnValue(observableOf([])); component.submitAction(); expect(notificationService.show).toHaveBeenCalledWith( NotificationType.success, 'Updated PG scrub options' ); }); }); });
2,254
33.692308
82
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-pg-scrub-modal/osd-pg-scrub-modal.component.ts
import { Component, ViewChild } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { forkJoin as observableForkJoin } from 'rxjs'; import { ConfigOptionComponent } from '~/app/shared/components/config-option/config-option.component'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { OsdPgScrubModalOptions } from './osd-pg-scrub-modal.options'; @Component({ selector: 'cd-osd-pg-scrub-modal', templateUrl: './osd-pg-scrub-modal.component.html', styleUrls: ['./osd-pg-scrub-modal.component.scss'] }) export class OsdPgScrubModalComponent { osdPgScrubForm: CdFormGroup; action: string; resource: string; permissions: Permissions; @ViewChild('basicOptionsValues', { static: true }) basicOptionsValues: ConfigOptionComponent; basicOptions: Array<string> = OsdPgScrubModalOptions.basicOptions; @ViewChild('advancedOptionsValues') advancedOptionsValues: ConfigOptionComponent; advancedOptions: Array<string> = OsdPgScrubModalOptions.advancedOptions; advancedEnabled = false; constructor( public activeModal: NgbActiveModal, private authStorageService: AuthStorageService, private notificationService: NotificationService, public actionLabels: ActionLabelsI18n ) { this.osdPgScrubForm = new CdFormGroup({}); this.resource = $localize`PG scrub options`; this.action = this.actionLabels.EDIT; this.permissions = this.authStorageService.getPermissions(); } submitAction() { const observables = [this.basicOptionsValues.saveValues()]; if (this.advancedOptionsValues) { observables.push(this.advancedOptionsValues.saveValues()); } observableForkJoin(observables).subscribe( () => { this.notificationService.show( NotificationType.success, $localize`Updated PG scrub options` ); this.activeModal.close(); }, () => { this.activeModal.close(); } ); } }
2,359
33.202899
102
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-pg-scrub-modal/osd-pg-scrub-modal.options.ts
export class OsdPgScrubModalOptions { public static basicOptions: Array<string> = [ 'osd_scrub_during_recovery', 'osd_scrub_begin_hour', 'osd_scrub_end_hour', 'osd_scrub_begin_week_day', 'osd_scrub_end_week_day', 'osd_scrub_min_interval', 'osd_scrub_max_interval', 'osd_deep_scrub_interval', 'osd_scrub_auto_repair', 'osd_max_scrubs', 'osd_scrub_priority', 'osd_scrub_sleep' ]; public static advancedOptions: Array<string> = [ 'osd_scrub_auto_repair_num_errors', 'osd_debug_deep_scrub_sleep', 'osd_deep_scrub_keys', 'osd_deep_scrub_large_omap_object_key_threshold', 'osd_deep_scrub_large_omap_object_value_sum_threshold', 'osd_deep_scrub_randomize_ratio', 'osd_deep_scrub_stride', 'osd_deep_scrub_update_digest_min_age', 'osd_requested_scrub_priority', 'osd_scrub_backoff_ratio', 'osd_scrub_chunk_max', 'osd_scrub_chunk_min', 'osd_scrub_cost', 'osd_scrub_interval_randomize_ratio', 'osd_scrub_invalid_stats', 'osd_scrub_load_threshold', 'osd_scrub_max_preemptions', 'osd_shallow_scrub_chunk_max', 'osd_shallow_scrub_chunk_min' ]; }
1,165
28.897436
59
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-recv-speed-modal/osd-recv-speed-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container class="modal-title" i18n>OSD Recovery Priority</ng-container> <ng-container class="modal-content"> <form #formDir="ngForm" [formGroup]="osdRecvSpeedForm" novalidate cdFormScope="osd"> <div class="modal-body"> <!-- Priority --> <div class="form-group row"> <label class="cd-col-form-label required" for="priority" i18n>Priority</label> <div class="cd-col-form-input"> <select class="form-select" formControlName="priority" id="priority" (change)="onPriorityChange($event.target.value)"> <option *ngFor="let priority of priorities" [value]="priority.name"> {{ priority.text }} </option> </select> <span class="invalid-feedback" *ngIf="osdRecvSpeedForm.showError('priority', formDir, 'required')" i18n>This field is required.</span> </div> </div> <!-- Customize priority --> <div class="form-group row"> <div class="cd-col-form-offset"> <div class="custom-control custom-checkbox"> <input formControlName="customizePriority" class="custom-control-input" id="customizePriority" name="customizePriority" type="checkbox" (change)="onCustomizePriorityChange()"> <label class="custom-control-label" for="customizePriority" i18n>Customize priority values</label> </div> </div> </div> <!-- Priority values --> <div class="form-group row" *ngFor="let attr of priorityAttrs | keyvalue"> <label class="cd-col-form-label" [for]="attr.key"> <span [ngClass]="{'required': osdRecvSpeedForm.getValue('customizePriority')}"> {{ attr.value.text }} </span> <cd-helper *ngIf="attr.value.desc">{{ attr.value.desc }}</cd-helper> </label> <div class="cd-col-form-input"> <input class="form-control" type="number" [id]="attr.key" [formControlName]="attr.key" [readonly]="!osdRecvSpeedForm.getValue('customizePriority')"> <span class="invalid-feedback" *ngIf="osdRecvSpeedForm.getValue('customizePriority') && osdRecvSpeedForm.showError(attr.key, formDir, 'required')" i18n>This field is required!</span> <span class="invalid-feedback" *ngIf="osdRecvSpeedForm.getValue('customizePriority') && osdRecvSpeedForm.showError(attr.key, formDir, 'pattern')" i18n>{{ attr.value.patternHelpText }}</span> <span class="invalid-feedback" *ngIf="osdRecvSpeedForm.getValue('customizePriority') && osdRecvSpeedForm.showError(attr.key, formDir, 'max')" i18n>The entered value is too high! It must not be greater than {{ attr.value.maxValue }}.</span> <span class="invalid-feedback" *ngIf="osdRecvSpeedForm.getValue('customizePriority') && osdRecvSpeedForm.showError(attr.key, formDir, 'min')" i18n>The entered value is too low! It must not be lower than {{ attr.value.minValue }}.</span> </div> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="submitAction()" [form]="osdRecvSpeedForm" [submitText]="actionLabels.UPDATE" [showSubmit]="permissions.configOpt.update"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
4,085
42.935484
115
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-recv-speed-modal/osd-recv-speed-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { ToastrModule } from 'ngx-toastr'; import { of as observableOf } from 'rxjs'; import { ConfigurationService } from '~/app/shared/api/configuration.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { OsdRecvSpeedModalComponent } from './osd-recv-speed-modal.component'; describe('OsdRecvSpeedModalComponent', () => { let component: OsdRecvSpeedModalComponent; let fixture: ComponentFixture<OsdRecvSpeedModalComponent>; let configurationService: ConfigurationService; configureTestBed({ imports: [ HttpClientTestingModule, ReactiveFormsModule, RouterTestingModule, SharedModule, ToastrModule.forRoot() ], declarations: [OsdRecvSpeedModalComponent], providers: [NgbActiveModal] }); let configOptions: any[] = []; beforeEach(() => { fixture = TestBed.createComponent(OsdRecvSpeedModalComponent); component = fixture.componentInstance; fixture.detectChanges(); configurationService = TestBed.inject(ConfigurationService); configOptions = [ { name: 'osd_max_backfills', desc: '', type: 'uint', default: 1 }, { name: 'osd_recovery_max_active', desc: '', type: 'uint', default: 3 }, { name: 'osd_recovery_max_single_start', desc: '', type: 'uint', default: 1 }, { name: 'osd_recovery_sleep', desc: 'Time in seconds to sleep before next recovery or backfill op', type: 'float', default: 0 } ]; spyOn(configurationService, 'filter').and.returnValue(observableOf(configOptions)); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('ngOnInit', () => { let setPriority: jasmine.Spy; let setValidators: jasmine.Spy; beforeEach(() => { setPriority = spyOn(component, 'setPriority').and.callThrough(); setValidators = spyOn(component, 'setValidators').and.callThrough(); component.ngOnInit(); }); it('should call setValidators', () => { expect(setValidators).toHaveBeenCalled(); }); it('should get and set priority correctly', () => { const defaultPriority = _.find(component.priorities, (p) => { return _.isEqual(p.name, 'default'); }); expect(setPriority).toHaveBeenCalledWith(defaultPriority); }); it('should set descriptions correctly', () => { expect(component.priorityAttrs['osd_max_backfills'].desc).toBe(''); expect(component.priorityAttrs['osd_recovery_max_active'].desc).toBe(''); expect(component.priorityAttrs['osd_recovery_max_single_start'].desc).toBe(''); expect(component.priorityAttrs['osd_recovery_sleep'].desc).toBe( 'Time in seconds to sleep before next recovery or backfill op' ); }); }); describe('setPriority', () => { it('should prepare the form for a custom priority', () => { const customPriority = { name: 'custom', text: 'Custom', values: { osd_max_backfills: 1, osd_recovery_max_active: 4, osd_recovery_max_single_start: 1, osd_recovery_sleep: 1 } }; component.setPriority(customPriority); const customInPriorities = _.find(component.priorities, (p) => { return p.name === 'custom'; }); expect(customInPriorities).not.toBeNull(); expect(component.osdRecvSpeedForm.getValue('priority')).toBe('custom'); expect(component.osdRecvSpeedForm.getValue('osd_max_backfills')).toBe(1); expect(component.osdRecvSpeedForm.getValue('osd_recovery_max_active')).toBe(4); expect(component.osdRecvSpeedForm.getValue('osd_recovery_max_single_start')).toBe(1); expect(component.osdRecvSpeedForm.getValue('osd_recovery_sleep')).toBe(1); }); it('should prepare the form for a none custom priority', () => { const lowPriority = { name: 'low', text: 'Low', values: { osd_max_backfills: 1, osd_recovery_max_active: 1, osd_recovery_max_single_start: 1, osd_recovery_sleep: 0.5 } }; component.setPriority(lowPriority); const customInPriorities = _.find(component.priorities, (p) => { return p.name === 'custom'; }); expect(customInPriorities).toBeUndefined(); expect(component.osdRecvSpeedForm.getValue('priority')).toBe('low'); expect(component.osdRecvSpeedForm.getValue('osd_max_backfills')).toBe(1); expect(component.osdRecvSpeedForm.getValue('osd_recovery_max_active')).toBe(1); expect(component.osdRecvSpeedForm.getValue('osd_recovery_max_single_start')).toBe(1); expect(component.osdRecvSpeedForm.getValue('osd_recovery_sleep')).toBe(0.5); }); }); describe('detectPriority', () => { const configOptionsLow = { osd_max_backfills: 1, osd_recovery_max_active: 1, osd_recovery_max_single_start: 1, osd_recovery_sleep: 0.5 }; const configOptionsDefault = { osd_max_backfills: 1, osd_recovery_max_active: 3, osd_recovery_max_single_start: 1, osd_recovery_sleep: 0 }; const configOptionsHigh = { osd_max_backfills: 4, osd_recovery_max_active: 4, osd_recovery_max_single_start: 4, osd_recovery_sleep: 0 }; const configOptionsCustom = { osd_max_backfills: 1, osd_recovery_max_active: 2, osd_recovery_max_single_start: 1, osd_recovery_sleep: 0 }; const configOptionsIncomplete = { osd_max_backfills: 1, osd_recovery_max_single_start: 1, osd_recovery_sleep: 0 }; it('should return priority "low" if the config option values have been set accordingly', () => { component.detectPriority(configOptionsLow, (priority: Record<string, any>) => { expect(priority.name).toBe('low'); }); expect(component.osdRecvSpeedForm.getValue('customizePriority')).toBeFalsy(); }); it('should return priority "default" if the config option values have been set accordingly', () => { component.detectPriority(configOptionsDefault, (priority: Record<string, any>) => { expect(priority.name).toBe('default'); }); expect(component.osdRecvSpeedForm.getValue('customizePriority')).toBeFalsy(); }); it('should return priority "high" if the config option values have been set accordingly', () => { component.detectPriority(configOptionsHigh, (priority: Record<string, any>) => { expect(priority.name).toBe('high'); }); expect(component.osdRecvSpeedForm.getValue('customizePriority')).toBeFalsy(); }); it('should return priority "custom" if the config option values do not match any priority', () => { component.detectPriority(configOptionsCustom, (priority: Record<string, any>) => { expect(priority.name).toBe('custom'); }); expect(component.osdRecvSpeedForm.getValue('customizePriority')).toBeTruthy(); }); it('should return no priority if the config option values are incomplete', () => { component.detectPriority(configOptionsIncomplete, (priority: Record<string, any>) => { expect(priority.name).toBeNull(); }); expect(component.osdRecvSpeedForm.getValue('customizePriority')).toBeFalsy(); }); }); describe('getCurrentValues', () => { it('should return default values if no value has been set by the user', () => { const currentValues = component.getCurrentValues(configOptions); configOptions.forEach((configOption) => { const configOptionValue = currentValues.values[configOption.name]; expect(configOptionValue).toBe(configOption.default); }); }); it('should return the values set by the user if they exist', () => { configOptions.forEach((configOption) => { configOption['value'] = [{ section: 'osd', value: 7 }]; }); const currentValues = component.getCurrentValues(configOptions); Object.values(currentValues.values).forEach((configValue) => { expect(configValue).toBe(7); }); }); it('should return the default value if one is missing', () => { for (let i = 1; i < configOptions.length; i++) { configOptions[i]['value'] = [{ section: 'osd', value: 7 }]; } const currentValues = component.getCurrentValues(configOptions); Object.entries(currentValues.values).forEach(([configName, configValue]) => { if (configName === 'osd_max_backfills') { expect(configValue).toBe(1); } else { expect(configValue).toBe(7); } }); }); it('should return nothing if neither value nor default value is given', () => { configOptions[0].default = null; const currentValues = component.getCurrentValues(configOptions); expect(currentValues.values).not.toContain('osd_max_backfills'); }); }); describe('setDescription', () => { it('should set the description if one is given', () => { component.setDescription(configOptions); Object.keys(component.priorityAttrs).forEach((configOptionName) => { if (configOptionName === 'osd_recovery_sleep') { expect(component.priorityAttrs[configOptionName].desc).toBe( 'Time in seconds to sleep before next recovery or backfill op' ); } else { expect(component.priorityAttrs[configOptionName].desc).toBe(''); } }); }); }); describe('setValidators', () => { it('should set needed validators for config option', () => { component.setValidators(configOptions); configOptions.forEach((configOption) => { const control = component.osdRecvSpeedForm.controls[configOption.name]; if (configOption.type === 'float') { expect(component.priorityAttrs[configOption.name].patternHelpText).toBe( 'The entered value needs to be a number or decimal.' ); } else { expect(component.priorityAttrs[configOption.name].minValue).toBe(0); expect(component.priorityAttrs[configOption.name].patternHelpText).toBe( 'The entered value needs to be an unsigned number.' ); control.setValue(-1); expect(control.hasError('min')).toBeTruthy(); } control.setValue(null); expect(control.hasError('required')).toBeTruthy(); control.setValue('E'); expect(control.hasError('pattern')).toBeTruthy(); control.setValue(3); expect(control.hasError('required')).toBeFalsy(); expect(control.hasError('min')).toBeFalsy(); expect(control.hasError('pattern')).toBeFalsy(); }); }); }); });
11,202
34.22956
104
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-recv-speed-modal/osd-recv-speed-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { ConfigurationService } from '~/app/shared/api/configuration.service'; import { OsdService } from '~/app/shared/api/osd.service'; import { ConfigOptionTypes } from '~/app/shared/components/config-option/config-option.types'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { NotificationService } from '~/app/shared/services/notification.service'; @Component({ selector: 'cd-osd-recv-speed-modal', templateUrl: './osd-recv-speed-modal.component.html', styleUrls: ['./osd-recv-speed-modal.component.scss'] }) export class OsdRecvSpeedModalComponent implements OnInit { osdRecvSpeedForm: CdFormGroup; permissions: Permissions; priorities: any[] = []; priorityAttrs = {}; constructor( public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private authStorageService: AuthStorageService, private configService: ConfigurationService, private notificationService: NotificationService, private osdService: OsdService ) { this.permissions = this.authStorageService.getPermissions(); this.priorities = this.osdService.osdRecvSpeedModalPriorities.KNOWN_PRIORITIES; this.osdRecvSpeedForm = new CdFormGroup({ priority: new FormControl(null, { validators: [Validators.required] }), customizePriority: new FormControl(false) }); this.priorityAttrs = { osd_max_backfills: { text: $localize`Max Backfills`, desc: '', patternHelpText: '', maxValue: undefined, minValue: undefined }, osd_recovery_max_active: { text: $localize`Recovery Max Active`, desc: '', patternHelpText: '', maxValue: undefined, minValue: undefined }, osd_recovery_max_single_start: { text: $localize`Recovery Max Single Start`, desc: '', patternHelpText: '', maxValue: undefined, minValue: undefined }, osd_recovery_sleep: { text: $localize`Recovery Sleep`, desc: '', patternHelpText: '', maxValue: undefined, minValue: undefined } }; Object.keys(this.priorityAttrs).forEach((configOptionName) => { this.osdRecvSpeedForm.addControl( configOptionName, new FormControl(null, { validators: [Validators.required] }) ); }); } ngOnInit() { this.configService.filter(Object.keys(this.priorityAttrs)).subscribe((data: any) => { const config_option_values = this.getCurrentValues(data); this.detectPriority(config_option_values.values, (priority: any) => { this.setPriority(priority); }); this.setDescription(config_option_values.configOptions); this.setValidators(config_option_values.configOptions); }); } detectPriority(configOptionValues: any, callbackFn: Function) { const priority = _.find(this.priorities, (p) => { return _.isEqual(p.values, configOptionValues); }); this.osdRecvSpeedForm.controls.customizePriority.setValue(false); if (priority) { return callbackFn(priority); } if (Object.entries(configOptionValues).length === 4) { this.osdRecvSpeedForm.controls.customizePriority.setValue(true); return callbackFn( Object({ name: 'custom', text: $localize`Custom`, values: configOptionValues }) ); } return callbackFn(this.priorities[0]); } getCurrentValues(configOptions: any) { const currentValues: Record<string, any> = { values: {}, configOptions: [] }; configOptions.forEach((configOption: any) => { currentValues.configOptions.push(configOption); if ('value' in configOption) { configOption.value.forEach((value: any) => { if (value.section === 'osd') { currentValues.values[configOption.name] = Number(value.value); } }); } else if ('default' in configOption && configOption.default !== null) { currentValues.values[configOption.name] = Number(configOption.default); } }); return currentValues; } setDescription(configOptions: Array<any>) { configOptions.forEach((configOption) => { if (configOption.desc !== '') { this.priorityAttrs[configOption.name].desc = configOption.desc; } }); } setPriority(priority: any) { const customPriority = _.find(this.priorities, (p) => { return p.name === 'custom'; }); if (priority.name === 'custom') { if (!customPriority) { this.priorities.push(priority); } } else { if (customPriority) { this.priorities.splice(this.priorities.indexOf(customPriority), 1); } } this.osdRecvSpeedForm.controls.priority.setValue(priority.name); Object.entries(priority.values).forEach(([name, value]) => { this.osdRecvSpeedForm.controls[name].setValue(value); }); } setValidators(configOptions: Array<any>) { configOptions.forEach((configOption) => { const typeValidators = ConfigOptionTypes.getTypeValidators(configOption); if (typeValidators) { typeValidators.validators.push(Validators.required); if ('max' in typeValidators && typeValidators.max !== '') { this.priorityAttrs[configOption.name].maxValue = typeValidators.max; } if ('min' in typeValidators && typeValidators.min !== '') { this.priorityAttrs[configOption.name].minValue = typeValidators.min; } this.priorityAttrs[configOption.name].patternHelpText = typeValidators.patternHelpText; this.osdRecvSpeedForm.controls[configOption.name].setValidators(typeValidators.validators); } else { this.osdRecvSpeedForm.controls[configOption.name].setValidators(Validators.required); } }); } onCustomizePriorityChange() { const values = {}; Object.keys(this.priorityAttrs).forEach((configOptionName) => { values[configOptionName] = this.osdRecvSpeedForm.getValue(configOptionName); }); if (this.osdRecvSpeedForm.getValue('customizePriority')) { const customPriority = { name: 'custom', text: $localize`Custom`, values: values }; this.setPriority(customPriority); } else { this.detectPriority(values, (priority: any) => { this.setPriority(priority); }); } } onPriorityChange(selectedPriorityName: string) { const selectedPriority = _.find(this.priorities, (p) => { return p.name === selectedPriorityName; }) || this.priorities[0]; // Uncheck the 'Customize priority values' checkbox. this.osdRecvSpeedForm.get('customizePriority').setValue(false); // Set the priority profile values. this.setPriority(selectedPriority); } submitAction() { const options = {}; Object.keys(this.priorityAttrs).forEach((configOptionName) => { options[configOptionName] = { section: 'osd', value: this.osdRecvSpeedForm.getValue(configOptionName) }; }); this.configService.bulkCreate({ options: options }).subscribe( () => { this.notificationService.show( NotificationType.success, $localize`Updated OSD recovery speed priority '${this.osdRecvSpeedForm.getValue( 'priority' )}'` ); this.activeModal.close(); }, () => { this.activeModal.close(); } ); } }
7,911
32.104603
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-reweight-modal/osd-reweight-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container class="modal-title" i18n>Reweight OSD: {{ osdId }}</ng-container> <ng-container class="modal-content"> <form [formGroup]="reweightForm"> <div class="modal-body"> <div class="row"> <label for="weight" class="cd-col-form-label">Weight</label> <div class="cd-col-form-input"> <input id="weight" class="form-control" type="number" step="0.1" formControlName="weight" min="0" max="1" [value]="currentWeight"> <span class="invalid-feedback" *ngIf="weight.errors"> <span *ngIf="weight.errors?.required" i18n>This field is required.</span> <span *ngIf="weight.errors?.max || weight.errors?.min" i18n>The value needs to be between 0 and 1.</span> </span> </div> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="reweight()" [form]="reweightForm" [submitText]="actionLabels.REWEIGHT"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
1,367
34.076923
90
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-reweight-modal/osd-reweight-modal.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 { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { of } from 'rxjs'; import { OsdService } from '~/app/shared/api/osd.service'; import { BackButtonComponent } from '~/app/shared/components/back-button/back-button.component'; import { ModalComponent } from '~/app/shared/components/modal/modal.component'; import { SubmitButtonComponent } from '~/app/shared/components/submit-button/submit-button.component'; import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder'; import { configureTestBed } from '~/testing/unit-test-helper'; import { OsdReweightModalComponent } from './osd-reweight-modal.component'; describe('OsdReweightModalComponent', () => { let component: OsdReweightModalComponent; let fixture: ComponentFixture<OsdReweightModalComponent>; configureTestBed({ imports: [ReactiveFormsModule, HttpClientTestingModule, RouterTestingModule], declarations: [ OsdReweightModalComponent, ModalComponent, SubmitButtonComponent, BackButtonComponent ], schemas: [NO_ERRORS_SCHEMA], providers: [OsdService, NgbActiveModal, CdFormBuilder] }); beforeEach(() => { fixture = TestBed.createComponent(OsdReweightModalComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should call OsdService::reweight() on submit', () => { component.osdId = 1; component.reweightForm.get('weight').setValue(0.5); const osdServiceSpy = spyOn(TestBed.inject(OsdService), 'reweight').and.callFake(() => of(true) ); component.reweight(); expect(osdServiceSpy.calls.count()).toBe(1); expect(osdServiceSpy.calls.first().args).toEqual([1, 0.5]); }); });
2,078
35.473684
102
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-reweight-modal/osd-reweight-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { Validators } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { OsdService } from '~/app/shared/api/osd.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; @Component({ selector: 'cd-osd-reweight-modal', templateUrl: './osd-reweight-modal.component.html', styleUrls: ['./osd-reweight-modal.component.scss'] }) export class OsdReweightModalComponent implements OnInit { currentWeight = 1; osdId: number; reweightForm: CdFormGroup; constructor( public actionLabels: ActionLabelsI18n, public activeModal: NgbActiveModal, private osdService: OsdService, private fb: CdFormBuilder ) {} get weight() { return this.reweightForm.get('weight'); } ngOnInit() { this.reweightForm = this.fb.group({ weight: this.fb.control(this.currentWeight, [Validators.required]) }); } reweight() { this.osdService .reweight(this.osdId, this.reweightForm.value.weight) .subscribe(() => this.activeModal.close()); } }
1,241
27.227273
72
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-scrub-modal/osd-scrub-modal.component.html
<cd-modal [modalRef]="activeModal"> <span class="modal-title" i18n>OSDs {deep, select, true {Deep } other {}}Scrub</span> <ng-container class="modal-content"> <form name="scrubForm" #formDir="ngForm" [formGroup]="scrubForm" novalidate> <div class="modal-body"> <p i18n>You are about to apply a {deep, select, true {deep } other {}}scrub to the OSD(s): <strong>{{ selected | join }}</strong>.</p> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="scrub()" [form]="scrubForm" [submitText]="actionLabels.UPDATE"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
767
32.391304
88
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-scrub-modal/osd-scrub-modal.component.spec.ts
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { OsdService } from '~/app/shared/api/osd.service'; import { JoinPipe } from '~/app/shared/pipes/join.pipe'; import { NotificationService } from '~/app/shared/services/notification.service'; import { configureTestBed } from '~/testing/unit-test-helper'; import { OsdScrubModalComponent } from './osd-scrub-modal.component'; describe('OsdScrubModalComponent', () => { let component: OsdScrubModalComponent; let fixture: ComponentFixture<OsdScrubModalComponent>; const fakeService = { list: () => { return new Promise(() => undefined); }, scrub: () => { return new Promise(() => undefined); }, scrub_many: () => { return new Promise(() => undefined); } }; configureTestBed({ imports: [ReactiveFormsModule], declarations: [OsdScrubModalComponent, JoinPipe], schemas: [NO_ERRORS_SCHEMA], providers: [ NgbActiveModal, JoinPipe, { provide: OsdService, useValue: fakeService }, { provide: NotificationService, useValue: fakeService } ] }); beforeEach(() => { fixture = TestBed.createComponent(OsdScrubModalComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,515
28.72549
81
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/osd/osd-scrub-modal/osd-scrub-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { forkJoin } from 'rxjs'; import { OsdService } from '~/app/shared/api/osd.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { JoinPipe } from '~/app/shared/pipes/join.pipe'; import { NotificationService } from '~/app/shared/services/notification.service'; @Component({ selector: 'cd-osd-scrub-modal', templateUrl: './osd-scrub-modal.component.html', styleUrls: ['./osd-scrub-modal.component.scss'] }) export class OsdScrubModalComponent implements OnInit { deep: boolean; scrubForm: FormGroup; selected: any[] = []; constructor( public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private osdService: OsdService, private notificationService: NotificationService, private joinPipe: JoinPipe ) {} ngOnInit() { this.scrubForm = new FormGroup({}); } scrub() { forkJoin(this.selected.map((id: any) => this.osdService.scrub(id, this.deep))).subscribe( () => { const operation = this.deep ? 'Deep scrub' : 'Scrub'; this.notificationService.show( NotificationType.success, $localize`${operation} was initialized in the following OSD(s): ${this.joinPipe.transform( this.selected )}` ); this.activeModal.close(); }, () => this.activeModal.close() ); } }
1,604
29.283019
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/active-alert-list/active-alert-list.component.html
<cd-prometheus-tabs></cd-prometheus-tabs> <cd-alert-panel *ngIf="!isAlertmanagerConfigured" type="info" i18n>To see all active Prometheus alerts, please provide the URL to the API of Prometheus' Alertmanager as described in the <cd-doc section="prometheus"></cd-doc>.</cd-alert-panel> <cd-table *ngIf="isAlertmanagerConfigured" [data]="prometheusAlertService.alerts" [columns]="columns" identifier="fingerprint" [forceIdentifier]="true" [customCss]="customCss" selectionType="single" [hasDetails]="true" (setExpandedRow)="setExpandedRow($event)" (updateSelection)="updateSelection($event)"> <cd-table-actions class="table-actions" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> <cd-table-key-value cdTableDetail *ngIf="expandedRow" [renderObjects]="true" [hideEmpty]="true" [appendParentKey]="false" [data]="expandedRow" [customCss]="customCss" [autoReload]="false"> </cd-table-key-value> </cd-table> <ng-template #externalLinkTpl let-row="row" let-value="value"> <a [href]="value" target="_blank"><i [ngClass]="[icons.lineChart]"></i> Source</a> </ng-template>
1,501
34.761905
72
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/active-alert-list/active-alert-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { CephModule } from '~/app/ceph/ceph.module'; import { ClusterModule } from '~/app/ceph/cluster/cluster.module'; import { DashboardModule } from '~/app/ceph/dashboard/dashboard.module'; import { CoreModule } from '~/app/core/core.module'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, PermissionHelper } from '~/testing/unit-test-helper'; import { ActiveAlertListComponent } from './active-alert-list.component'; describe('ActiveAlertListComponent', () => { let component: ActiveAlertListComponent; let fixture: ComponentFixture<ActiveAlertListComponent>; configureTestBed({ imports: [ BrowserAnimationsModule, HttpClientTestingModule, NgbNavModule, RouterTestingModule, ToastrModule.forRoot(), SharedModule, ClusterModule, DashboardModule, CephModule, CoreModule ] }); beforeEach(() => { fixture = TestBed.createComponent(ActiveAlertListComponent); component = fixture.componentInstance; }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should test all TableActions combinations', () => { component.ngOnInit(); const permissionHelper: PermissionHelper = new PermissionHelper(component.permission); const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions( component.tableActions ); expect(tableActions).toEqual({ 'create,update,delete': { actions: ['Create Silence'], primary: { multiple: 'Create Silence', executing: 'Create Silence', single: 'Create Silence', no: 'Create Silence' } }, 'create,update': { actions: ['Create Silence'], primary: { multiple: 'Create Silence', executing: 'Create Silence', single: 'Create Silence', no: 'Create Silence' } }, 'create,delete': { actions: ['Create Silence'], primary: { multiple: 'Create Silence', executing: 'Create Silence', single: 'Create Silence', no: 'Create Silence' } }, create: { actions: ['Create Silence'], primary: { multiple: 'Create Silence', executing: 'Create Silence', single: 'Create Silence', no: 'Create Silence' } }, 'update,delete': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, update: { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, delete: { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); });
3,389
31.596154
101
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/active-alert-list/active-alert-list.component.ts
import { Component, Inject, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { PrometheusService } from '~/app/shared/api/prometheus.service'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { Icons } from '~/app/shared/enum/icons.enum'; import { PrometheusListHelper } from '~/app/shared/helpers/prometheus-list-helper'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { PrometheusAlertService } from '~/app/shared/services/prometheus-alert.service'; import { URLBuilderService } from '~/app/shared/services/url-builder.service'; const BASE_URL = 'silences'; // as only silence actions can be used @Component({ selector: 'cd-active-alert-list', providers: [{ provide: URLBuilderService, useValue: new URLBuilderService(BASE_URL) }], templateUrl: './active-alert-list.component.html', styleUrls: ['./active-alert-list.component.scss'] }) export class ActiveAlertListComponent extends PrometheusListHelper implements OnInit { @ViewChild('externalLinkTpl', { static: true }) externalLinkTpl: TemplateRef<any>; columns: CdTableColumn[]; tableActions: CdTableAction[]; permission: Permission; selection = new CdTableSelection(); icons = Icons; constructor( // NotificationsComponent will refresh all alerts every 5s (No need to do it here as well) private authStorageService: AuthStorageService, public prometheusAlertService: PrometheusAlertService, private urlBuilder: URLBuilderService, @Inject(PrometheusService) prometheusService: PrometheusService ) { super(prometheusService); this.permission = this.authStorageService.getPermissions().prometheus; this.tableActions = [ { permission: 'create', canBePrimary: (selection: CdTableSelection) => selection.hasSingleSelection, disable: (selection: CdTableSelection) => !selection.hasSingleSelection || selection.first().cdExecuting, icon: Icons.add, routerLink: () => '/monitoring' + this.urlBuilder.getCreateFrom(this.selection.first().fingerprint), name: $localize`Create Silence` } ]; } ngOnInit() { super.ngOnInit(); this.columns = [ { name: $localize`Name`, prop: 'labels.alertname', cellClass: 'fw-bold', flexGrow: 2 }, { name: $localize`Summary`, prop: 'annotations.summary', flexGrow: 3 }, { name: $localize`Severity`, prop: 'labels.severity', flexGrow: 1, cellTransformation: CellTemplate.badge, customTemplateConfig: { map: { critical: { class: 'badge-danger' }, warning: { class: 'badge-warning' } } } }, { name: $localize`State`, prop: 'status.state', flexGrow: 1, cellTransformation: CellTemplate.badge, customTemplateConfig: { map: { active: { class: 'badge-info' }, unprocessed: { class: 'badge-warning' }, suppressed: { class: 'badge-dark' } } } }, { name: $localize`Started`, prop: 'startsAt', cellTransformation: CellTemplate.timeAgo, flexGrow: 1 }, { name: $localize`URL`, prop: 'generatorURL', flexGrow: 1, sortable: false, cellTemplate: this.externalLinkTpl } ]; } updateSelection(selection: CdTableSelection) { this.selection = selection; } }
3,838
32.675439
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/prometheus-tabs/prometheus-tabs.component.html
<ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link" routerLink="/monitoring/active-alerts" routerLinkActive="active" ariaCurrentWhenActive="page" [routerLinkActiveOptions]="{exact: true}" i18n>Active Alerts <small *ngIf="prometheusAlertService.activeCriticalAlerts > 0" class="badge badge-danger ms-1">{{ prometheusAlertService.activeCriticalAlerts }}</small> <small *ngIf="prometheusAlertService.activeWarningAlerts > 0" class="badge badge-warning ms-1">{{ prometheusAlertService.activeWarningAlerts }}</small></a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/monitoring/alerts" routerLinkActive="active" ariaCurrentWhenActive="page" [routerLinkActiveOptions]="{exact: true}" i18n>Alerts</a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/monitoring/silences" routerLinkActive="active" ariaCurrentWhenActive="page" [routerLinkActiveOptions]="{exact: true}" i18n>Silences</a> </li> </ul>
1,087
34.096774
101
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/prometheus-tabs/prometheus-tabs.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { PrometheusAlertService } from '~/app/shared/services/prometheus-alert.service'; import { configureTestBed } from '~/testing/unit-test-helper'; import { PrometheusTabsComponent } from './prometheus-tabs.component'; describe('PrometheusTabsComponent', () => { let component: PrometheusTabsComponent; let fixture: ComponentFixture<PrometheusTabsComponent>; configureTestBed({ imports: [RouterTestingModule, NgbNavModule], declarations: [PrometheusTabsComponent], providers: [{ provide: PrometheusAlertService, useValue: { alerts: [] } }] }); beforeEach(() => { fixture = TestBed.createComponent(PrometheusTabsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,002
32.433333
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/prometheus-tabs/prometheus-tabs.component.ts
import { Component } from '@angular/core'; import { PrometheusAlertService } from '~/app/shared/services/prometheus-alert.service'; @Component({ selector: 'cd-prometheus-tabs', templateUrl: './prometheus-tabs.component.html', styleUrls: ['./prometheus-tabs.component.scss'] }) export class PrometheusTabsComponent { constructor(public prometheusAlertService: PrometheusAlertService) {} }
398
29.692308
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/rules-list/rules-list.component.html
<cd-prometheus-tabs></cd-prometheus-tabs> <cd-alert-panel *ngIf="!isPrometheusConfigured" type="info" i18n>To see all configured Prometheus alerts, please provide the URL to the API of Prometheus as described in the <cd-doc section="prometheus"></cd-doc>.</cd-alert-panel> <cd-table *ngIf="isPrometheusConfigured" [data]="prometheusAlertService.rules" [columns]="columns" [selectionType]="'single'" [hasDetails]="true" (setExpandedRow)="setExpandedRow($event)" (updateSelection)="updateSelection($event)"> <cd-table-key-value cdTableDetail *ngIf="expandedRow" [data]="expandedRow" [renderObjects]="true" [hideKeys]="hideKeys"> </cd-table-key-value> </cd-table>
851
36.043478
68
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/rules-list/rules-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { PrometheusService } from '~/app/shared/api/prometheus.service'; import { SettingsService } from '~/app/shared/api/settings.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { PrometheusTabsComponent } from '../prometheus-tabs/prometheus-tabs.component'; import { RulesListComponent } from './rules-list.component'; describe('RulesListComponent', () => { let component: RulesListComponent; let fixture: ComponentFixture<RulesListComponent>; configureTestBed({ declarations: [RulesListComponent, PrometheusTabsComponent], imports: [ HttpClientTestingModule, SharedModule, NgbNavModule, RouterTestingModule, ToastrModule.forRoot() ], providers: [PrometheusService, SettingsService] }); beforeEach(() => { fixture = TestBed.createComponent(RulesListComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,379
32.658537
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/rules-list/rules-list.component.ts
import { Component, Inject, OnInit } from '@angular/core'; import _ from 'lodash'; import { PrometheusService } from '~/app/shared/api/prometheus.service'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { PrometheusListHelper } from '~/app/shared/helpers/prometheus-list-helper'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { PrometheusRule } from '~/app/shared/models/prometheus-alerts'; import { DurationPipe } from '~/app/shared/pipes/duration.pipe'; import { PrometheusAlertService } from '~/app/shared/services/prometheus-alert.service'; @Component({ selector: 'cd-rules-list', templateUrl: './rules-list.component.html', styleUrls: ['./rules-list.component.scss'] }) export class RulesListComponent extends PrometheusListHelper implements OnInit { columns: CdTableColumn[]; expandedRow: PrometheusRule; selection = new CdTableSelection(); /** * Hide active alerts in details of alerting rules as they are already shown * in the 'active alerts' table. Also hide the 'type' column as the type is * always supposed to be 'alerting'. */ hideKeys = ['alerts', 'type']; constructor( public prometheusAlertService: PrometheusAlertService, @Inject(PrometheusService) prometheusService: PrometheusService ) { super(prometheusService); } ngOnInit() { super.ngOnInit(); this.columns = [ { prop: 'name', name: $localize`Name`, cellClass: 'fw-bold', flexGrow: 2 }, { prop: 'labels.severity', name: $localize`Severity`, flexGrow: 1, cellTransformation: CellTemplate.badge, customTemplateConfig: { map: { critical: { class: 'badge-danger' }, warning: { class: 'badge-warning' } } } }, { prop: 'group', name: $localize`Group`, flexGrow: 1, cellTransformation: CellTemplate.badge }, { prop: 'duration', name: $localize`Duration`, pipe: new DurationPipe(), flexGrow: 1 }, { prop: 'query', name: $localize`Query`, isHidden: true, flexGrow: 1 }, { prop: 'annotations.summary', name: $localize`Summary`, flexGrow: 3 } ]; } updateSelection(selection: CdTableSelection) { this.selection = selection; } }
2,372
32.9
93
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/silence-form/silence-form.component.html
<ng-template #matcherTpl let-matcher="matcher" let-index="index"> <div class="input-group my-2"> <ng-container *ngFor="let config of matcherConfig"> <span class="input-group-text" *ngIf="config.attribute === 'isRegex'"> <i *ngIf="matcher[config.attribute]" [ngbTooltip]="config.tooltip">~</i> <i *ngIf="!matcher[config.attribute]" ngbTooltip="Equals">=</i> </span> <ng-container *ngIf="config.attribute !== 'isRegex'"> <input type="text" id="matcher-{{config.attribute}}-{{index}}" class="form-control" [value]="matcher[config.attribute]" disabled readonly> </ng-container> </ng-container> <!-- Matcher actions --> <button type="button" class="btn btn-light" id="matcher-edit-{{index}}" i18n-ngbTooltip ngbTooltip="Edit" (click)="showMatcherModal(index)"> <i [ngClass]="[icons.edit]"></i> </button> <button type="button" class="btn btn-light" id="matcher-delete-{{index}}" i18n-ngbTooltip ngbTooltip="Delete" (click)="deleteMatcher(index)"> <i [ngClass]="[icons.trash]"></i> </button> </div> <span class="help-block"></span> </ng-template> <div class="cd-col-form"> <form #formDir="ngForm" [formGroup]="form" class="form" name="form" novalidate> <div class="card"> <div class="card-header"> <span i18n>{{ action | titlecase }} {{ resource | upperFirst }}</span> <cd-helper *ngIf="edit" i18n>Editing a silence will expire the old silence and recreate it as a new silence</cd-helper> </div> <!-- Creator --> <div class="card-body"> <div class="form-group row"> <label class="cd-col-form-label required" for="created-by" i18n>Creator</label> <div class="cd-col-form-input"> <input class="form-control" formControlName="createdBy" id="created-by" name="created-by" type="text"> <span *ngIf="form.showError('createdBy', formDir, 'required')" class="invalid-feedback" i18n>This field is required!</span> </div> </div> <!-- Comment --> <div class="form-group row"> <label class="cd-col-form-label required" for="comment" i18n>Comment</label> <div class="cd-col-form-input"> <textarea class="form-control" formControlName="comment" id="comment" name="comment" type="text"> </textarea> <span *ngIf="form.showError('comment', formDir, 'required')" class="invalid-feedback" i18n>This field is required!</span> </div> </div> <!-- Start time --> <div class="form-group row"> <label class="cd-col-form-label" for="starts-at"> <span class="required" i18n>Start time</span> <cd-helper i18n>If the start time lies in the past the creation time will be used</cd-helper> </label> <div class="cd-col-form-input"> <input class="form-control" formControlName="startsAt" [ngbPopover]="popStart" triggers="manual" #ps="ngbPopover" (click)="ps.open()" (keypress)="ps.close()"> <span *ngIf="form.showError('startsAt', formDir, 'required')" class="invalid-feedback" i18n>This field is required!</span> </div> </div> <!-- Duration --> <div class="form-group row"> <label class="cd-col-form-label required" for="duration" i18n>Duration</label> <div class="cd-col-form-input"> <input class="form-control" formControlName="duration" id="duration" name="duration" type="text"> <span *ngIf="form.showError('duration', formDir, 'required')" class="invalid-feedback" i18n>This field is required!</span> </div> </div> <!-- End time --> <div class="form-group row"> <label class="cd-col-form-label required" for="ends-at" i18n>End time</label> <div class="cd-col-form-input"> <input class="form-control" formControlName="endsAt" [ngbPopover]="popEnd" triggers="manual" #pe="ngbPopover" (click)="pe.open()" (keypress)="pe.close()"> <span *ngIf="form.showError('endsAt', formDir, 'required')" class="invalid-feedback" i18n>This field is required!</span> </div> </div> <!-- Matchers --> <fieldset> <legend class="required" i18n>Matchers</legend> <div class="cd-col-form-offset"> <h5 *ngIf="matchers.length === 0" [ngClass]="{'text-warning': !formDir.submitted, 'text-danger': formDir.submitted}"> <strong i18n>A silence requires at least one matcher</strong> </h5> <span *ngFor="let matcher of matchers; let i=index;"> <ng-container *ngTemplateOutlet="matcherTpl; context:{index: i, matcher: matcher}"></ng-container> </span> <div class="row"> <div class="col-12"> <button type="button" id="add-matcher" class="btn btn-light float-end my-3" [ngClass]="{'btn-warning': formDir.submitted && matchers.length === 0 }" (click)="showMatcherModal()"> <i [ngClass]="[icons.add]"></i> <ng-container i18n>Add matcher</ng-container> </button> </div> </div> </div> <div *ngIf="matchers.length && matcherMatch" class="cd-col-form-offset {{matcherMatch.cssClass}}" id="match-state"> <span class="text-muted {{matcherMatch.cssClass}}"> {{ matcherMatch.status }} </span> </div> </fieldset> </div> <div class="card-footer"> <div class="text-right"> <cd-form-button-panel (submitActionEvent)="submit()" [form]="form" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"></cd-form-button-panel> </div> </div> </div> </form> </div> <ng-template #popStart> <cd-date-time-picker [control]="form.get('startsAt')" [hasSeconds]="false"></cd-date-time-picker> </ng-template> <ng-template #popEnd> <cd-date-time-picker [control]="form.get('endsAt')" [hasSeconds]="false"></cd-date-time-picker> </ng-template>
7,499
34.377358
123
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/silence-form/silence-form.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { ActivatedRoute, Router, Routes } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbPopoverModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import moment from 'moment'; import { ToastrModule } from 'ngx-toastr'; import { of, throwError } from 'rxjs'; import { DashboardNotFoundError } from '~/app/core/error/error'; import { ErrorComponent } from '~/app/core/error/error.component'; import { PrometheusService } from '~/app/shared/api/prometheus.service'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { AlertmanagerSilence, AlertmanagerSilenceMatcher } from '~/app/shared/models/alertmanager-silence'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FixtureHelper, FormHelper, PrometheusHelper } from '~/testing/unit-test-helper'; import { SilenceFormComponent } from './silence-form.component'; describe('SilenceFormComponent', () => { // SilenceFormComponent specific let component: SilenceFormComponent; let fixture: ComponentFixture<SilenceFormComponent>; let form: CdFormGroup; // Spied on let prometheusService: PrometheusService; let authStorageService: AuthStorageService; let notificationService: NotificationService; let router: Router; // Spies let rulesSpy: jasmine.Spy; let ifPrometheusSpy: jasmine.Spy; // Helper let prometheus: PrometheusHelper; let formHelper: FormHelper; let fixtureH: FixtureHelper; let params: Record<string, any>; // Date mocking related const baseTime = '2022-02-22 00:00'; const beginningDate = '2022-02-22T00:00:12.35'; let prometheusPermissions: Permission; const routes: Routes = [{ path: '404', component: ErrorComponent }]; configureTestBed({ declarations: [ErrorComponent, SilenceFormComponent], imports: [ HttpClientTestingModule, RouterTestingModule.withRoutes(routes), SharedModule, ToastrModule.forRoot(), NgbTooltipModule, NgbPopoverModule, ReactiveFormsModule ], providers: [ { provide: ActivatedRoute, useValue: { params: { subscribe: (fn: Function) => fn(params) } } } ] }); const createMatcher = (name: string, value: any, isRegex: boolean) => ({ name, value, isRegex }); const addMatcher = (name: string, value: any, isRegex: boolean) => component['setMatcher'](createMatcher(name, value, isRegex)); const callInit = () => fixture.ngZone.run(() => { component['init'](); }); const changeAction = (action: string) => { const modes = { add: '/monitoring/silences/add', alertAdd: '/monitoring/silences/add/alert0', recreate: '/monitoring/silences/recreate/someExpiredId', edit: '/monitoring/silences/edit/someNotExpiredId' }; Object.defineProperty(router, 'url', { value: modes[action] }); callInit(); }; beforeEach(() => { params = {}; spyOn(Date, 'now').and.returnValue(new Date(beginningDate)); prometheus = new PrometheusHelper(); prometheusService = TestBed.inject(PrometheusService); spyOn(prometheusService, 'getAlerts').and.callFake(() => { const name = _.split(router.url, '/').pop(); return of([prometheus.createAlert(name)]); }); ifPrometheusSpy = spyOn(prometheusService, 'ifPrometheusConfigured').and.callFake((fn) => fn()); rulesSpy = spyOn(prometheusService, 'getRules').and.callFake(() => of({ groups: [ { file: '', interval: 0, name: '', rules: [ prometheus.createRule('alert0', 'someSeverity', [prometheus.createAlert('alert0')]), prometheus.createRule('alert1', 'someSeverity', []), prometheus.createRule('alert2', 'someOtherSeverity', [ prometheus.createAlert('alert2') ]) ] } ] }) ); router = TestBed.inject(Router); notificationService = TestBed.inject(NotificationService); spyOn(notificationService, 'show').and.stub(); authStorageService = TestBed.inject(AuthStorageService); spyOn(authStorageService, 'getUsername').and.returnValue('someUser'); spyOn(authStorageService, 'getPermissions').and.callFake(() => ({ prometheus: prometheusPermissions })); prometheusPermissions = new Permission(['update', 'delete', 'read', 'create']); fixture = TestBed.createComponent(SilenceFormComponent); fixtureH = new FixtureHelper(fixture); component = fixture.componentInstance; form = component.form; formHelper = new FormHelper(form); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); expect(_.isArray(component.rules)).toBeTruthy(); }); it('should have set the logged in user name as creator', () => { expect(component.form.getValue('createdBy')).toBe('someUser'); }); it('should call disablePrometheusConfig on error calling getRules', () => { spyOn(prometheusService, 'disablePrometheusConfig'); rulesSpy.and.callFake(() => throwError({})); callInit(); expect(component.rules).toEqual([]); expect(prometheusService.disablePrometheusConfig).toHaveBeenCalled(); }); it('should remind user if prometheus is not set when it is not configured', () => { ifPrometheusSpy.and.callFake((_x: any, fn: Function) => fn()); callInit(); expect(component.rules).toEqual([]); expect(notificationService.show).toHaveBeenCalledWith( NotificationType.info, 'Please add your Prometheus host to the dashboard configuration and refresh the page', undefined, undefined, 'Prometheus' ); }); describe('throw error for not allowed users', () => { let navigateSpy: jasmine.Spy; const expectError = (action: string, redirected: boolean) => { Object.defineProperty(router, 'url', { value: action }); if (redirected) { expect(() => callInit()).toThrowError(DashboardNotFoundError); } else { expect(() => callInit()).not.toThrowError(); } navigateSpy.calls.reset(); }; beforeEach(() => { navigateSpy = spyOn(router, 'navigate').and.stub(); }); it('should throw error if not allowed', () => { prometheusPermissions = new Permission(['delete', 'read']); expectError('add', true); expectError('alertAdd', true); }); it('should throw error if user does not have minimum permissions to create silences', () => { prometheusPermissions = new Permission(['update', 'delete', 'read']); expectError('add', true); prometheusPermissions = new Permission(['update', 'delete', 'create']); expectError('recreate', true); }); it('should throw error if user does not have minimum permissions to update silences', () => { prometheusPermissions = new Permission(['delete', 'read']); expectError('edit', true); prometheusPermissions = new Permission(['create', 'delete', 'update']); expectError('edit', true); }); it('does not throw error if user has minimum permissions to create silences', () => { prometheusPermissions = new Permission(['create', 'read']); expectError('add', false); expectError('alertAdd', false); expectError('recreate', false); }); it('does not throw error if user has minimum permissions to update silences', () => { prometheusPermissions = new Permission(['read', 'create']); expectError('edit', false); }); }); describe('choose the right action', () => { const expectMode = (routerMode: string, edit: boolean, recreate: boolean, action: string) => { changeAction(routerMode); expect(component.recreate).toBe(recreate); expect(component.edit).toBe(edit); expect(component.action).toBe(action); }; beforeEach(() => { spyOn(prometheusService, 'getSilences').and.callFake(() => { const id = _.split(router.url, '/').pop(); return of([prometheus.createSilence(id)]); }); }); it('should have no special action activate by default', () => { expectMode('add', false, false, 'Create'); expect(prometheusService.getSilences).not.toHaveBeenCalled(); expect(component.form.value).toEqual({ comment: null, createdBy: 'someUser', duration: '2h', startsAt: baseTime, endsAt: '2022-02-22 02:00' }); }); it('should be in edit action if route includes edit', () => { params = { id: 'someNotExpiredId' }; expectMode('edit', true, false, 'Edit'); expect(prometheusService.getSilences).toHaveBeenCalled(); expect(component.form.value).toEqual({ comment: `A comment for ${params.id}`, createdBy: `Creator of ${params.id}`, duration: '1d', startsAt: '2022-02-22 22:22', endsAt: '2022-02-23 22:22' }); expect(component.matchers).toEqual([createMatcher('job', 'someJob', true)]); }); it('should be in recreation action if route includes recreate', () => { params = { id: 'someExpiredId' }; expectMode('recreate', false, true, 'Recreate'); expect(prometheusService.getSilences).toHaveBeenCalled(); expect(component.form.value).toEqual({ comment: `A comment for ${params.id}`, createdBy: `Creator of ${params.id}`, duration: '2h', startsAt: baseTime, endsAt: '2022-02-22 02:00' }); expect(component.matchers).toEqual([createMatcher('job', 'someJob', true)]); }); it('adds matchers based on the label object of the alert with the given id', () => { params = { id: 'alert0' }; expectMode('alertAdd', false, false, 'Create'); expect(prometheusService.getSilences).not.toHaveBeenCalled(); expect(prometheusService.getAlerts).toHaveBeenCalled(); expect(component.matchers).toEqual([createMatcher('alertname', 'alert0', false)]); expect(component.matcherMatch).toEqual({ cssClass: 'has-success', status: 'Matches 1 rule with 1 active alert.' }); }); }); describe('time', () => { const changeEndDate = (text: string) => component.form.patchValue({ endsAt: text }); const changeStartDate = (text: string) => component.form.patchValue({ startsAt: text }); it('have all dates set at beginning', () => { expect(form.getValue('startsAt')).toEqual(baseTime); expect(form.getValue('duration')).toBe('2h'); expect(form.getValue('endsAt')).toEqual('2022-02-22 02:00'); }); describe('on start date change', () => { it('changes end date on start date change if it exceeds it', fakeAsync(() => { changeStartDate('2022-02-28 04:05'); expect(form.getValue('duration')).toEqual('2h'); expect(form.getValue('endsAt')).toEqual('2022-02-28 06:05'); changeStartDate('2022-12-31 22:00'); expect(form.getValue('duration')).toEqual('2h'); expect(form.getValue('endsAt')).toEqual('2023-01-01 00:00'); })); it('changes duration if start date does not exceed end date ', fakeAsync(() => { changeStartDate('2022-02-22 00:45'); expect(form.getValue('duration')).toEqual('1h 15m'); expect(form.getValue('endsAt')).toEqual('2022-02-22 02:00'); })); it('should raise invalid start date error', fakeAsync(() => { changeStartDate('No valid date'); formHelper.expectError('startsAt', 'format'); expect(form.getValue('startsAt').toString()).toBe('No valid date'); expect(form.getValue('endsAt')).toEqual('2022-02-22 02:00'); })); }); describe('on duration change', () => { it('changes end date if duration is changed', () => { formHelper.setValue('duration', '15m'); expect(form.getValue('endsAt')).toEqual('2022-02-22 00:15'); formHelper.setValue('duration', '5d 23h'); expect(form.getValue('endsAt')).toEqual('2022-02-27 23:00'); }); }); describe('on end date change', () => { it('changes duration on end date change if it exceeds start date', fakeAsync(() => { changeEndDate('2022-02-28 04:05'); expect(form.getValue('duration')).toEqual('6d 4h 5m'); expect(form.getValue('startsAt')).toEqual(baseTime); })); it('changes start date if end date happens before it', fakeAsync(() => { changeEndDate('2022-02-21 02:00'); expect(form.getValue('duration')).toEqual('2h'); expect(form.getValue('startsAt')).toEqual('2022-02-21 00:00'); })); it('should raise invalid end date error', fakeAsync(() => { changeEndDate('No valid date'); formHelper.expectError('endsAt', 'format'); expect(form.getValue('endsAt').toString()).toBe('No valid date'); expect(form.getValue('startsAt')).toEqual(baseTime); })); }); }); it('should have a creator field', () => { formHelper.expectValid('createdBy'); formHelper.expectErrorChange('createdBy', '', 'required'); formHelper.expectValidChange('createdBy', 'Mighty FSM'); }); it('should have a comment field', () => { formHelper.expectError('comment', 'required'); formHelper.expectValidChange('comment', 'A pretty long comment'); }); it('should be a valid form if all inputs are filled and at least one matcher was added', () => { expect(form.valid).toBeFalsy(); formHelper.expectValidChange('createdBy', 'Mighty FSM'); formHelper.expectValidChange('comment', 'A pretty long comment'); addMatcher('job', 'someJob', false); expect(form.valid).toBeTruthy(); }); describe('matchers', () => { const expectMatch = (helpText: string) => { expect(fixtureH.getText('#match-state')).toBe(helpText); }; it('should show the add matcher button', () => { fixtureH.expectElementVisible('#add-matcher', true); fixtureH.expectIdElementsVisible( [ 'matcher-name-0', 'matcher-value-0', 'matcher-isRegex-0', 'matcher-edit-0', 'matcher-delete-0' ], false ); expectMatch(null); }); it('should show added matcher', () => { addMatcher('job', 'someJob', true); fixtureH.expectIdElementsVisible( ['matcher-name-0', 'matcher-value-0', 'matcher-edit-0', 'matcher-delete-0'], true ); expectMatch(null); }); it('should show multiple matchers', () => { addMatcher('severity', 'someSeverity', false); addMatcher('alertname', 'alert0', false); fixtureH.expectIdElementsVisible( [ 'matcher-name-0', 'matcher-value-0', 'matcher-edit-0', 'matcher-delete-0', 'matcher-name-1', 'matcher-value-1', 'matcher-edit-1', 'matcher-delete-1' ], true ); expectMatch('Matches 1 rule with 1 active alert.'); }); it('should show the right matcher values', () => { addMatcher('alertname', 'alert.*', true); addMatcher('job', 'someJob', false); fixture.detectChanges(); fixtureH.expectFormFieldToBe('#matcher-name-0', 'alertname'); fixtureH.expectFormFieldToBe('#matcher-value-0', 'alert.*'); expectMatch(null); }); it('should be able to edit a matcher', () => { addMatcher('alertname', 'alert.*', true); expectMatch(null); const modalService = TestBed.inject(ModalService); spyOn(modalService, 'show').and.callFake(() => { return { componentInstance: { preFillControls: (matcher: any) => { expect(matcher).toBe(component.matchers[0]); }, submitAction: of({ name: 'alertname', value: 'alert0', isRegex: false }) } }; }); fixtureH.clickElement('#matcher-edit-0'); fixtureH.expectFormFieldToBe('#matcher-name-0', 'alertname'); fixtureH.expectFormFieldToBe('#matcher-value-0', 'alert0'); expectMatch('Matches 1 rule with 1 active alert.'); }); it('should be able to remove a matcher', () => { addMatcher('alertname', 'alert0', false); expectMatch('Matches 1 rule with 1 active alert.'); fixtureH.clickElement('#matcher-delete-0'); expect(component.matchers).toEqual([]); fixtureH.expectIdElementsVisible( ['matcher-name-0', 'matcher-value-0', 'matcher-isRegex-0'], false ); expectMatch(null); }); it('should be able to remove a matcher and update the matcher text', () => { addMatcher('alertname', 'alert0', false); addMatcher('alertname', 'alert1', false); expectMatch('Your matcher seems to match no currently defined rule or active alert.'); fixtureH.clickElement('#matcher-delete-1'); expectMatch('Matches 1 rule with 1 active alert.'); }); it('should show form as invalid if no matcher is set', () => { expect(form.errors).toEqual({ matcherRequired: true }); }); it('should show form as valid if matcher was added', () => { addMatcher('some name', 'some value', true); expect(form.errors).toEqual(null); }); }); describe('submit tests', () => { const endsAt = '2022-02-22 02:00'; let silence: AlertmanagerSilence; const silenceId = '50M3-10N6-1D'; const expectSuccessNotification = ( titleStartsWith: string, matchers: AlertmanagerSilenceMatcher[] ) => { let msg = ''; for (const matcher of matchers) { msg = msg.concat(` ${matcher.name} - ${matcher.value},`); } expect(notificationService.show).toHaveBeenCalledWith( NotificationType.success, `${titleStartsWith} silence for ${msg.slice(0, -1)}`, undefined, undefined, 'Prometheus' ); }; const fillAndSubmit = () => { ['createdBy', 'comment'].forEach((attr) => { formHelper.setValue(attr, silence[attr]); }); silence.matchers.forEach((matcher) => addMatcher(matcher.name, matcher.value, matcher.isRegex) ); component.submit(); }; beforeEach(() => { spyOn(prometheusService, 'setSilence').and.callFake(() => of({ body: { silenceId } })); spyOn(router, 'navigate').and.stub(); silence = { createdBy: 'some creator', comment: 'some comment', startsAt: moment(baseTime).toISOString(), endsAt: moment(endsAt).toISOString(), matchers: [ { name: 'some attribute name', value: 'some value', isRegex: false }, { name: 'job', value: 'node-exporter', isRegex: false }, { name: 'instance', value: 'localhost:9100', isRegex: false }, { name: 'alertname', value: 'load_0', isRegex: false } ] }; }); // it('should not create a silence if the form is invalid', () => { // component.submit(); // expect(notificationService.show).not.toHaveBeenCalled(); // expect(form.valid).toBeFalsy(); // expect(prometheusService.setSilence).not.toHaveBeenCalledWith(silence); // expect(router.navigate).not.toHaveBeenCalled(); // }); // it('should route back to previous tab on success', () => { // fillAndSubmit(); // expect(form.valid).toBeTruthy(); // expect(router.navigate).toHaveBeenCalledWith(['/monitoring'], { fragment: 'silences' }); // }); it('should create a silence', () => { fillAndSubmit(); expect(prometheusService.setSilence).toHaveBeenCalledWith(silence); expectSuccessNotification('Created', silence.matchers); }); it('should recreate a silence', () => { component.recreate = true; component.id = 'recreateId'; fillAndSubmit(); expect(prometheusService.setSilence).toHaveBeenCalledWith(silence); expectSuccessNotification('Recreated', silence.matchers); }); it('should edit a silence', () => { component.edit = true; component.id = 'editId'; silence.id = component.id; fillAndSubmit(); expect(prometheusService.setSilence).toHaveBeenCalledWith(silence); expectSuccessNotification('Edited', silence.matchers); }); }); });
21,066
34.46633
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/silence-form/silence-form.component.ts
import { Component } from '@angular/core'; import { Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import _ from 'lodash'; import moment from 'moment'; import { DashboardNotFoundError } from '~/app/core/error/error'; import { PrometheusService } from '~/app/shared/api/prometheus.service'; import { ActionLabelsI18n, SucceededActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.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 { AlertmanagerSilence, AlertmanagerSilenceMatcher, AlertmanagerSilenceMatcherMatch } from '~/app/shared/models/alertmanager-silence'; import { Permission } from '~/app/shared/models/permissions'; import { AlertmanagerAlert, PrometheusRule } from '~/app/shared/models/prometheus-alerts'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { PrometheusSilenceMatcherService } from '~/app/shared/services/prometheus-silence-matcher.service'; import { TimeDiffService } from '~/app/shared/services/time-diff.service'; import { SilenceMatcherModalComponent } from '../silence-matcher-modal/silence-matcher-modal.component'; @Component({ selector: 'cd-prometheus-form', templateUrl: './silence-form.component.html', styleUrls: ['./silence-form.component.scss'] }) export class SilenceFormComponent { icons = Icons; permission: Permission; form: CdFormGroup; rules: PrometheusRule[]; matchName = ''; matchValue = ''; recreate = false; edit = false; id: string; action: string; resource = $localize`silence`; matchers: AlertmanagerSilenceMatcher[] = []; matcherMatch: AlertmanagerSilenceMatcherMatch = undefined; matcherConfig = [ { tooltip: $localize`Attribute name`, attribute: 'name' }, { tooltip: $localize`Regular expression`, attribute: 'isRegex' }, { tooltip: $localize`Value`, attribute: 'value' } ]; datetimeFormat = 'YYYY-MM-DD HH:mm'; isNavigate = true; constructor( private router: Router, private authStorageService: AuthStorageService, private formBuilder: CdFormBuilder, private prometheusService: PrometheusService, private notificationService: NotificationService, private route: ActivatedRoute, private timeDiff: TimeDiffService, private modalService: ModalService, private silenceMatcher: PrometheusSilenceMatcherService, private actionLabels: ActionLabelsI18n, private succeededLabels: SucceededActionLabelsI18n ) { this.init(); } private init() { this.chooseMode(); this.authenticate(); this.createForm(); this.setupDates(); this.getData(); } private chooseMode() { this.edit = this.router.url.startsWith('/monitoring/silences/edit'); this.recreate = this.router.url.startsWith('/monitoring/silences/recreate'); if (this.edit) { this.action = this.actionLabels.EDIT; } else if (this.recreate) { this.action = this.actionLabels.RECREATE; } else { this.action = this.actionLabels.CREATE; } } private authenticate() { this.permission = this.authStorageService.getPermissions().prometheus; const allowed = this.permission.read && (this.edit ? this.permission.update : this.permission.create); if (!allowed) { throw new DashboardNotFoundError(); } } private createForm() { const formatValidator = CdValidators.custom('format', (expiresAt: string) => { const result = expiresAt === '' || moment(expiresAt, this.datetimeFormat).isValid(); return !result; }); this.form = this.formBuilder.group( { startsAt: ['', [Validators.required, formatValidator]], duration: ['2h', [Validators.min(1)]], endsAt: ['', [Validators.required, formatValidator]], createdBy: [this.authStorageService.getUsername(), [Validators.required]], comment: [null, [Validators.required]] }, { validators: CdValidators.custom('matcherRequired', () => this.matchers.length === 0) } ); } private setupDates() { const now = moment().format(this.datetimeFormat); this.form.silentSet('startsAt', now); this.updateDate(); this.subscribeDateChanges(); } private updateDate(updateStartDate?: boolean) { const date = moment( this.form.getValue(updateStartDate ? 'endsAt' : 'startsAt'), this.datetimeFormat ).toDate(); const next = this.timeDiff.calculateDate(date, this.form.getValue('duration'), updateStartDate); if (next) { const nextDate = moment(next).format(this.datetimeFormat); this.form.silentSet(updateStartDate ? 'startsAt' : 'endsAt', nextDate); } } private subscribeDateChanges() { this.form.get('startsAt').valueChanges.subscribe(() => { this.onDateChange(); }); this.form.get('duration').valueChanges.subscribe(() => { this.updateDate(); }); this.form.get('endsAt').valueChanges.subscribe(() => { this.onDateChange(true); }); } private onDateChange(updateStartDate?: boolean) { const startsAt = moment(this.form.getValue('startsAt'), this.datetimeFormat); const endsAt = moment(this.form.getValue('endsAt'), this.datetimeFormat); if (startsAt.isBefore(endsAt)) { this.updateDuration(); } else { this.updateDate(updateStartDate); } } private updateDuration() { const startsAt = moment(this.form.getValue('startsAt'), this.datetimeFormat).toDate(); const endsAt = moment(this.form.getValue('endsAt'), this.datetimeFormat).toDate(); this.form.silentSet('duration', this.timeDiff.calculateDuration(startsAt, endsAt)); } private getData() { this.getRules(); this.getModeSpecificData(); } getRules() { this.prometheusService.ifPrometheusConfigured( () => this.prometheusService.getRules().subscribe( (groups) => { this.rules = groups['groups'].reduce( (acc, group) => _.concat<PrometheusRule>(acc, group.rules), [] ); }, () => { this.prometheusService.disablePrometheusConfig(); this.rules = []; } ), () => { this.rules = []; this.notificationService.show( NotificationType.info, $localize`Please add your Prometheus host to the dashboard configuration and refresh the page`, undefined, undefined, 'Prometheus' ); } ); return this.rules; } private getModeSpecificData() { this.route.params.subscribe((params: { id: string }) => { if (!params.id) { return; } if (this.edit || this.recreate) { this.prometheusService.getSilences().subscribe((silences) => { const silence = _.find(silences, ['id', params.id]); if (!_.isUndefined(silence)) { this.fillFormWithSilence(silence); } }); } else { this.prometheusService.getAlerts().subscribe((alerts) => { const alert = _.find(alerts, ['fingerprint', params.id]); if (!_.isUndefined(alert)) { this.fillFormByAlert(alert); } }); } }); } private fillFormWithSilence(silence: AlertmanagerSilence) { this.id = silence.id; if (this.edit) { ['startsAt', 'endsAt'].forEach((attr) => this.form.silentSet(attr, moment(silence[attr]).format(this.datetimeFormat)) ); this.updateDuration(); } ['createdBy', 'comment'].forEach((attr) => this.form.silentSet(attr, silence[attr])); this.matchers = silence.matchers; this.validateMatchers(); } private validateMatchers() { if (!this.rules) { window.setTimeout(() => this.validateMatchers(), 100); return; } this.matcherMatch = this.silenceMatcher.multiMatch(this.matchers, this.rules); this.form.markAsDirty(); this.form.updateValueAndValidity(); } private fillFormByAlert(alert: AlertmanagerAlert) { const labels = alert.labels; this.setMatcher({ name: 'alertname', value: labels.alertname, isRegex: false }); } private setMatcher(matcher: AlertmanagerSilenceMatcher, index?: number) { if (_.isNumber(index)) { this.matchers[index] = matcher; } else { this.matchers.push(matcher); } this.validateMatchers(); } showMatcherModal(index?: number) { const modalRef = this.modalService.show(SilenceMatcherModalComponent); const modalComponent = modalRef.componentInstance as SilenceMatcherModalComponent; modalComponent.rules = this.rules; if (_.isNumber(index)) { modalComponent.editMode = true; modalComponent.preFillControls(this.matchers[index]); } modalComponent.submitAction.subscribe((matcher: AlertmanagerSilenceMatcher) => { this.setMatcher(matcher, index); }); } deleteMatcher(index: number) { this.matchers.splice(index, 1); this.validateMatchers(); } submit(data?: any) { if (this.form.invalid) { return; } this.prometheusService.setSilence(this.getSubmitData()).subscribe( (resp) => { if (data) { data.silenceId = resp.body['silenceId']; } if (this.isNavigate) { this.router.navigate(['/monitoring/silences']); } this.notificationService.show( NotificationType.success, this.getNotificationTile(this.matchers), undefined, undefined, 'Prometheus' ); this.matchers = []; }, () => this.form.setErrors({ cdSubmitButton: true }) ); } private getSubmitData(): AlertmanagerSilence { const payload = this.form.value; delete payload.duration; payload.startsAt = moment(payload.startsAt, this.datetimeFormat).toISOString(); payload.endsAt = moment(payload.endsAt, this.datetimeFormat).toISOString(); payload.matchers = this.matchers; if (this.edit) { payload.id = this.id; } return payload; } private getNotificationTile(matchers: AlertmanagerSilenceMatcher[]) { let action; if (this.edit) { action = this.succeededLabels.EDITED; } else if (this.recreate) { action = this.succeededLabels.RECREATED; } else { action = this.succeededLabels.CREATED; } let msg = ''; for (const matcher of matchers) { msg = msg.concat(` ${matcher.name} - ${matcher.value},`); } return `${action} ${this.resource} for ${msg.slice(0, -1)}`; } }
11,005
30.445714
107
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/silence-list/silence-list.component.html
<cd-prometheus-tabs></cd-prometheus-tabs> <cd-alert-panel *ngIf="!isAlertmanagerConfigured" type="info" i18n>To enable Silences, please provide the URL to the API of the Prometheus' Alertmanager as described in the <cd-doc section="prometheus"></cd-doc>.</cd-alert-panel> <cd-table *ngIf="isAlertmanagerConfigured" [data]="silences" [columns]="columns" [forceIdentifier]="true" [customCss]="customCss" [sorts]="sorts" selectionType="single" [hasDetails]="true" (setExpandedRow)="setExpandedRow($event)" (fetchData)="refresh()" (updateSelection)="updateSelection($event)"> <cd-table-actions class="table-actions" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> <cd-table-key-value cdTableDetail *ngIf="expandedRow" [renderObjects]="true" [hideEmpty]="true" [appendParentKey]="false" [data]="expandedRow" [customCss]="customCss" [autoReload]="false"> </cd-table-key-value> </cd-table>
1,296
36.057143
66
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/silence-list/silence-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { PrometheusService } from '~/app/shared/api/prometheus.service'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, PermissionHelper } from '~/testing/unit-test-helper'; import { PrometheusTabsComponent } from '../prometheus-tabs/prometheus-tabs.component'; import { SilenceListComponent } from './silence-list.component'; describe('SilenceListComponent', () => { let component: SilenceListComponent; let fixture: ComponentFixture<SilenceListComponent>; let prometheusService: PrometheusService; let authStorageService: AuthStorageService; let prometheusPermissions: Permission; configureTestBed({ imports: [ BrowserAnimationsModule, SharedModule, ToastrModule.forRoot(), RouterTestingModule, HttpClientTestingModule, NgbNavModule ], declarations: [SilenceListComponent, PrometheusTabsComponent] }); beforeEach(() => { authStorageService = TestBed.inject(AuthStorageService); prometheusPermissions = new Permission(['update', 'delete', 'read', 'create']); spyOn(authStorageService, 'getPermissions').and.callFake(() => ({ prometheus: prometheusPermissions })); fixture = TestBed.createComponent(SilenceListComponent); component = fixture.componentInstance; prometheusService = TestBed.inject(PrometheusService); }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should test all TableActions combinations', () => { const permissionHelper: PermissionHelper = new PermissionHelper(component.permission); const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions( component.tableActions ); expect(tableActions).toEqual({ 'create,update,delete': { actions: ['Create', 'Recreate', 'Edit', 'Expire'], primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,update': { actions: ['Create', 'Recreate', 'Edit'], primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,delete': { actions: ['Create', 'Recreate', 'Expire'], primary: { multiple: 'Create', executing: 'Expire', single: 'Expire', no: 'Create' } }, create: { actions: ['Create', 'Recreate'], primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' } }, 'update,delete': { actions: ['Edit', 'Expire'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, update: { actions: ['Edit'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, delete: { actions: ['Expire'], primary: { multiple: 'Expire', executing: 'Expire', single: 'Expire', no: 'Expire' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); describe('expire silence', () => { const setSelectedSilence = (silenceName: string) => (component.selection.selected = [{ id: silenceName }]); const expireSilence = () => { component.expireSilence(); const deletion: CriticalConfirmationModalComponent = component.modalRef.componentInstance; // deletion.modalRef = new BsModalRef(); deletion.ngOnInit(); deletion.callSubmitAction(); }; const expectSilenceToExpire = (silenceId: string) => { setSelectedSilence(silenceId); expireSilence(); expect(prometheusService.expireSilence).toHaveBeenCalledWith(silenceId); }; beforeEach(() => { const mockObservable = () => of([]); spyOn(component, 'refresh').and.callFake(mockObservable); spyOn(prometheusService, 'expireSilence').and.callFake(mockObservable); spyOn(TestBed.inject(ModalService), 'show').and.callFake((deletionClass, config) => { return { componentInstance: Object.assign(new deletionClass(), config) }; }); }); it('should expire a silence', () => { const notificationService = TestBed.inject(NotificationService); spyOn(notificationService, 'show').and.stub(); expectSilenceToExpire('someSilenceId'); expect(notificationService.show).toHaveBeenCalledWith( NotificationType.success, 'Expired Silence someSilenceId', undefined, undefined, 'Prometheus' ); }); it('should refresh after expiring a silence', () => { expectSilenceToExpire('someId'); expect(component.refresh).toHaveBeenCalledTimes(1); expectSilenceToExpire('someOtherId'); expect(component.refresh).toHaveBeenCalledTimes(2); }); }); });
5,848
37.993333
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/silence-list/silence-list.component.ts
import { Component, Inject } from '@angular/core'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { SortDirection, SortPropDir } from '@swimlane/ngx-datatable'; import { Observable, Subscriber } from 'rxjs'; import { PrometheusListHelper } from '~/app/shared/helpers/prometheus-list-helper'; import { SilenceFormComponent } from '~/app/ceph/cluster/prometheus/silence-form/silence-form.component'; import { PrometheusService } from '~/app/shared/api/prometheus.service'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { ActionLabelsI18n, SucceededActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { AlertmanagerSilence } from '~/app/shared/models/alertmanager-silence'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { Permission } from '~/app/shared/models/permissions'; import { PrometheusRule } from '~/app/shared/models/prometheus-alerts'; import { CdDatePipe } from '~/app/shared/pipes/cd-date.pipe'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { PrometheusSilenceMatcherService } from '~/app/shared/services/prometheus-silence-matcher.service'; import { URLBuilderService } from '~/app/shared/services/url-builder.service'; const BASE_URL = 'monitoring/silences'; @Component({ providers: [ { provide: URLBuilderService, useValue: new URLBuilderService(BASE_URL) }, SilenceFormComponent ], selector: 'cd-silences-list', templateUrl: './silence-list.component.html', styleUrls: ['./silence-list.component.scss'] }) export class SilenceListComponent extends PrometheusListHelper { silences: AlertmanagerSilence[] = []; columns: CdTableColumn[]; tableActions: CdTableAction[]; permission: Permission; selection = new CdTableSelection(); modalRef: NgbModalRef; customCss = { 'badge badge-danger': 'active', 'badge badge-warning': 'pending', 'badge badge-default': 'expired' }; sorts: SortPropDir[] = [{ prop: 'endsAt', dir: SortDirection.desc }]; rules: PrometheusRule[]; visited: boolean; constructor( private authStorageService: AuthStorageService, private cdDatePipe: CdDatePipe, private modalService: ModalService, private notificationService: NotificationService, private urlBuilder: URLBuilderService, private actionLabels: ActionLabelsI18n, private succeededLabels: SucceededActionLabelsI18n, private silenceFormComponent: SilenceFormComponent, private silenceMatcher: PrometheusSilenceMatcherService, @Inject(PrometheusService) prometheusService: PrometheusService ) { super(prometheusService); this.permission = this.authStorageService.getPermissions().prometheus; const selectionExpired = (selection: CdTableSelection) => selection.first() && selection.first().status && selection.first().status.state === 'expired'; this.tableActions = [ { permission: 'create', icon: Icons.add, routerLink: () => this.urlBuilder.getCreate(), canBePrimary: (selection: CdTableSelection) => !selection.hasSingleSelection, name: this.actionLabels.CREATE }, { permission: 'create', canBePrimary: (selection: CdTableSelection) => selection.hasSingleSelection && selectionExpired(selection), disable: (selection: CdTableSelection) => !selection.hasSingleSelection || selection.first().cdExecuting || (selection.first().cdExecuting && selectionExpired(selection)) || !selectionExpired(selection), icon: Icons.copy, routerLink: () => this.urlBuilder.getRecreate(this.selection.first().id), name: this.actionLabels.RECREATE }, { permission: 'update', icon: Icons.edit, canBePrimary: (selection: CdTableSelection) => selection.hasSingleSelection && !selectionExpired(selection), disable: (selection: CdTableSelection) => !selection.hasSingleSelection || selection.first().cdExecuting || (selection.first().cdExecuting && !selectionExpired(selection)) || selectionExpired(selection), routerLink: () => this.urlBuilder.getEdit(this.selection.first().id), name: this.actionLabels.EDIT }, { permission: 'delete', icon: Icons.trash, canBePrimary: (selection: CdTableSelection) => selection.hasSingleSelection && !selectionExpired(selection), disable: (selection: CdTableSelection) => !selection.hasSingleSelection || selection.first().cdExecuting || selectionExpired(selection), click: () => this.expireSilence(), name: this.actionLabels.EXPIRE } ]; this.columns = [ { name: $localize`ID`, prop: 'id', flexGrow: 3 }, { name: $localize`Alerts Silenced`, prop: 'silencedAlerts', flexGrow: 3, cellTransformation: CellTemplate.badge }, { name: $localize`Created by`, prop: 'createdBy', flexGrow: 2 }, { name: $localize`Started`, prop: 'startsAt', pipe: this.cdDatePipe }, { name: $localize`Updated`, prop: 'updatedAt', pipe: this.cdDatePipe }, { name: $localize`Ends`, prop: 'endsAt', pipe: this.cdDatePipe }, { name: $localize`Status`, prop: 'status.state', cellTransformation: CellTemplate.classAdding } ]; } refresh() { this.prometheusService.ifAlertmanagerConfigured(() => { this.prometheusService.getSilences().subscribe( (silences) => { this.silences = silences; const activeSilences = silences.filter( (silence: AlertmanagerSilence) => silence.status.state !== 'expired' ); this.getAlerts(activeSilences); }, () => { this.prometheusService.disableAlertmanagerConfig(); } ); }); } updateSelection(selection: CdTableSelection) { this.selection = selection; } getAlerts(silences: any) { const rules = this.silenceFormComponent.getRules(); silences.forEach((silence: any) => { silence.matchers.forEach((matcher: any) => { this.rules = this.silenceMatcher.getMatchedRules(matcher, rules); const alertNames: string[] = []; for (const rule of this.rules) { alertNames.push(rule.name); } silence.silencedAlerts = alertNames; }); }); } expireSilence() { const id = this.selection.first().id; const i18nSilence = $localize`Silence`; const applicationName = 'Prometheus'; this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: i18nSilence, itemNames: [id], actionDescription: this.actionLabels.EXPIRE, submitActionObservable: () => new Observable((observer: Subscriber<any>) => { this.prometheusService.expireSilence(id).subscribe( () => { this.notificationService.show( NotificationType.success, `${this.succeededLabels.EXPIRED} ${i18nSilence} ${id}`, undefined, undefined, applicationName ); }, (resp) => { resp['application'] = applicationName; observer.error(resp); }, () => { observer.complete(); this.refresh(); } ); }) }); } }
8,253
35.522124
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/silence-matcher-modal/silence-matcher-modal.component.html
<cd-modal [modalRef]="activeModal"> <span class="modal-title" i18n>{editMode, select, true {Edit} other {Add}} Matcher</span> <ng-container class="modal-content"> <form class="form" #formDir="ngForm" [formGroup]="form" novalidate> <div class="modal-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"> <select class="form-select" id="name" formControlName="name" name="name"> <option [ngValue]="null" i18n>-- Select an attribute to match against --</option> <option *ngFor="let attribute of nameAttributes" [value]="attribute"> {{ attribute }} </option> </select> <span class="help-block" *ngIf="form.showError('name', formDir, 'required')" i18n>This field is required!</span> </div> </div> <!-- Value --> <div class="form-group row"> <label class="cd-col-form-label required" for="value" i18n>Value</label> <div class="cd-col-form-input"> <input id="value" (focus)="valueFocus.next($any($event).target.value)" (click)="valueClick.next($any($event).target.value)" class="form-control" type="text" [ngbTypeahead]="search" formControlName="value" #instance="ngbTypeahead"> <span *ngIf="form.showError('value', formDir, 'required')" class="help-block" i18n>This field is required!</span> </div> <div *ngIf="form.getValue('value') && !form.getValue('isRegex') && matcherMatch" class="cd-col-form-offset {{matcherMatch.cssClass}}" id="match-state"> <span class="text-muted {{matcherMatch.cssClass}}"> {{matcherMatch.status}} </span> </div> </div> <!-- isRegex --> <div class="form-group row"> <div class="cd-col-form-offset"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" formControlName="isRegex" name="is-regex" id="is-regex"> <label for="is-regex" class="custom-control-label" i18n>Use regular expression</label> </div> </div> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="onSubmit()" [form]="form" [submitText]="getMode()"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
3,139
35.511628
90
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/silence-matcher-modal/silence-matcher-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal, NgbTypeaheadModule } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { of } from 'rxjs'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FixtureHelper, FormHelper, PrometheusHelper } from '~/testing/unit-test-helper'; import { SilenceMatcherModalComponent } from './silence-matcher-modal.component'; describe('SilenceMatcherModalComponent', () => { let component: SilenceMatcherModalComponent; let fixture: ComponentFixture<SilenceMatcherModalComponent>; let formH: FormHelper; let fixtureH: FixtureHelper; let prometheus: PrometheusHelper; configureTestBed({ declarations: [SilenceMatcherModalComponent], imports: [ HttpClientTestingModule, SharedModule, NgbTypeaheadModule, RouterTestingModule, ReactiveFormsModule ], providers: [NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(SilenceMatcherModalComponent); component = fixture.componentInstance; fixtureH = new FixtureHelper(fixture); formH = new FormHelper(component.form); prometheus = new PrometheusHelper(); component.rules = [ prometheus.createRule('alert0', 'someSeverity', [prometheus.createAlert('alert0')]), prometheus.createRule('alert1', 'someSeverity', []) ]; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should have a name field', () => { formH.expectError('name', 'required'); formH.expectValidChange('name', 'alertname'); }); it('should only allow a specific set of name attributes', () => { expect(component.nameAttributes).toEqual(['alertname', 'instance', 'job', 'severity']); }); it('should autocomplete a list based on the set name', () => { const expectations = { alertname: ['alert0', 'alert1'], instance: ['someInstance'], job: ['someJob'], severity: ['someSeverity'] }; Object.keys(expectations).forEach((key) => { formH.setValue('name', key); expect(component.possibleValues).toEqual(expectations[key]); }); }); describe('test rule matching', () => { const expectMatch = (name: string, value: string, helpText: string) => { component.preFillControls({ name: name, value: value, isRegex: false }); expect(fixtureH.getText('#match-state')).toBe(helpText); }; it('should match no rule and no alert', () => { expectMatch( 'alertname', 'alert', 'Your matcher seems to match no currently defined rule or active alert.' ); }); it('should match a rule with no alert', () => { expectMatch('alertname', 'alert1', 'Matches 1 rule with no active alerts.'); }); it('should match a rule and an alert', () => { expectMatch('alertname', 'alert0', 'Matches 1 rule with 1 active alert.'); }); it('should match multiple rules and an alert', () => { expectMatch('severity', 'someSeverity', 'Matches 2 rules with 1 active alert.'); }); it('should match multiple rules and multiple alerts', () => { component.rules[1].alerts.push(null); expectMatch('severity', 'someSeverity', 'Matches 2 rules with 2 active alerts.'); }); it('should not show match-state if regex is checked', () => { fixtureH.expectElementVisible('#match-state', false); formH.setValue('name', 'severity'); formH.setValue('value', 'someSeverity'); fixtureH.expectElementVisible('#match-state', true); formH.setValue('isRegex', true); fixtureH.expectElementVisible('#match-state', false); }); }); it('should only enable value field if name was set', () => { const value = component.form.get('value'); expect(value.disabled).toBeTruthy(); formH.setValue('name', component.nameAttributes[0]); expect(value.enabled).toBeTruthy(); formH.setValue('name', null); expect(value.disabled).toBeTruthy(); }); it('should have a value field', () => { formH.setValue('name', component.nameAttributes[0]); formH.expectError('value', 'required'); formH.expectValidChange('value', 'alert0'); }); it('should test preFillControls', () => { const controlValues = { name: 'alertname', value: 'alert0', isRegex: false }; component.preFillControls(controlValues); expect(component.form.value).toEqual(controlValues); }); it('should test submit', (done) => { const controlValues = { name: 'alertname', value: 'alert0', isRegex: false }; component.preFillControls(controlValues); component.submitAction.subscribe((resp: object) => { expect(resp).toEqual(controlValues); done(); }); component.onSubmit(); }); describe('typeahead', () => { let equality: { [key: string]: boolean }; let expectations: { [key: string]: string[] }; const search = (s: string) => { Object.keys(expectations).forEach((key) => { formH.setValue('name', key); component.search(of(s)).subscribe((result) => { // Expect won't fail the test inside subscribe equality[key] = _.isEqual(result, expectations[key]); }); expect(equality[key]).toBeTruthy(); }); }; beforeEach(() => { equality = { alertname: false, instance: false, job: false, severity: false }; expectations = { alertname: ['alert0', 'alert1'], instance: ['someInstance'], job: ['someJob'], severity: ['someSeverity'] }; }); it('should show all values on name switch', () => { search(''); }); it('should search for "some"', () => { expectations['alertname'] = []; search('some'); }); it('should search for "er"', () => { expectations['instance'] = []; expectations['job'] = []; search('er'); }); }); });
6,262
28.82381
91
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/prometheus/silence-matcher-modal/silence-matcher-modal.component.ts
import { Component, EventEmitter, Output, ViewChild } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { NgbActiveModal, NgbTypeahead } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { merge, Observable, Subject } from 'rxjs'; import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators'; 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 { AlertmanagerSilenceMatcher, AlertmanagerSilenceMatcherMatch } from '~/app/shared/models/alertmanager-silence'; import { PrometheusRule } from '~/app/shared/models/prometheus-alerts'; import { PrometheusSilenceMatcherService } from '~/app/shared/services/prometheus-silence-matcher.service'; @Component({ selector: 'cd-silence-matcher-modal', templateUrl: './silence-matcher-modal.component.html', styleUrls: ['./silence-matcher-modal.component.scss'] }) export class SilenceMatcherModalComponent { @ViewChild(NgbTypeahead, { static: true }) typeahead: NgbTypeahead; @Output() submitAction = new EventEmitter(); form: CdFormGroup; editMode = false; rules: PrometheusRule[]; nameAttributes = ['alertname', 'instance', 'job', 'severity']; possibleValues: string[] = []; matcherMatch: AlertmanagerSilenceMatcherMatch = undefined; // For typeahead usage valueClick = new Subject<string>(); valueFocus = new Subject<string>(); search = (text$: Observable<string>) => { return merge( text$.pipe(debounceTime(200), distinctUntilChanged()), this.valueFocus, this.valueClick.pipe(filter(() => !this.typeahead.isPopupOpen())) ).pipe( map((term) => (term === '' ? this.possibleValues : this.possibleValues.filter((v) => v.toLowerCase().indexOf(term.toLowerCase()) > -1) ).slice(0, 10) ) ); }; constructor( private formBuilder: CdFormBuilder, private silenceMatcher: PrometheusSilenceMatcherService, public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n ) { this.createForm(); this.subscribeToChanges(); } private createForm() { this.form = this.formBuilder.group({ name: [null, [Validators.required]], value: [{ value: '', disabled: true }, [Validators.required]], isRegex: new FormControl(false) }); } private subscribeToChanges() { this.form.get('name').valueChanges.subscribe((name) => { if (name === null) { this.form.get('value').disable(); return; } this.setPossibleValues(name); this.form.get('value').enable(); }); this.form.get('value').valueChanges.subscribe((value) => { const values = this.form.value; values.value = value; // Isn't the current value at this stage this.matcherMatch = this.silenceMatcher.singleMatch(values, this.rules); }); } private setPossibleValues(name: string) { this.possibleValues = _.sortedUniq( this.rules.map((r) => _.get(r, this.silenceMatcher.getAttributePath(name))).filter((x) => x) ); } getMode() { return this.editMode ? this.actionLabels.EDIT : this.actionLabels.ADD; } preFillControls(matcher: AlertmanagerSilenceMatcher) { this.form.setValue(matcher); } onSubmit() { this.submitAction.emit(this.form.value); this.activeModal.close(); } }
3,489
31.314815
107
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/placement.pipe.spec.ts
import { PlacementPipe } from './placement.pipe'; describe('PlacementPipe', () => { const pipe = new PlacementPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms to no spec', () => { expect(pipe.transform(undefined)).toBe('no spec'); }); it('transforms to unmanaged', () => { expect(pipe.transform({ unmanaged: true })).toBe('unmanaged'); }); it('transforms placement (1)', () => { expect( pipe.transform({ placement: { hosts: ['mon0'] } }) ).toBe('mon0'); }); it('transforms placement (2)', () => { expect( pipe.transform({ placement: { hosts: ['mon0', 'mgr0'] } }) ).toBe('mon0;mgr0'); }); it('transforms placement (3)', () => { expect( pipe.transform({ placement: { count: 1 } }) ).toBe('count:1'); }); it('transforms placement (4)', () => { expect( pipe.transform({ placement: { label: 'foo' } }) ).toBe('label:foo'); }); it('transforms placement (5)', () => { expect( pipe.transform({ placement: { host_pattern: 'abc.ceph.xyz.com' } }) ).toBe('abc.ceph.xyz.com'); }); it('transforms placement (6)', () => { expect( pipe.transform({ placement: { count: 2, hosts: ['mon0', 'mgr0'] } }) ).toBe('mon0;mgr0;count:2'); }); });
1,507
18.088608
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/placement.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; import _ from 'lodash'; @Pipe({ name: 'placement' }) export class PlacementPipe implements PipeTransform { /** * Convert the placement configuration into human readable form. * The output is equal to the column 'PLACEMENT' in 'ceph orch ls'. * @param serviceSpec The service specification to process. * @return The placement configuration as human readable string. */ transform(serviceSpec: object | undefined): string { if (_.isUndefined(serviceSpec)) { return $localize`no spec`; } if (_.get(serviceSpec, 'unmanaged', false)) { return $localize`unmanaged`; } const kv: Array<any> = []; const hosts: Array<string> = _.get(serviceSpec, 'placement.hosts'); const count: number = _.get(serviceSpec, 'placement.count'); const label: string = _.get(serviceSpec, 'placement.label'); const hostPattern: string = _.get(serviceSpec, 'placement.host_pattern'); if (_.isArray(hosts)) { kv.push(...hosts); } if (_.isNumber(count)) { kv.push($localize`count:${count}`); } if (_.isString(label)) { kv.push($localize`label:${label}`); } if (_.isString(hostPattern)) { kv.push(hostPattern); } return kv.join(';'); } }
1,289
29.714286
77
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/services.component.html
<cd-orchestrator-doc-panel *ngIf="showDocPanel"></cd-orchestrator-doc-panel> <ng-container *ngIf="orchStatus?.available"> <cd-table [data]="services" [columns]="columns" identifier="service_name" forceIdentifier="true" columnMode="flex" selectionType="single" [autoReload]="5000" (fetchData)="getServices($event)" [hasDetails]="hasDetails" [serverSide]="true" [count]="count" (setExpandedRow)="setExpandedRow($event)" (updateSelection)="updateSelection($event)"> <cd-table-actions class="table-actions" [permission]="permissions.hosts" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> <cd-service-details cdTableDetail [permissions]="permissions" [selection]="expandedRow"> </cd-service-details> </cd-table> </ng-container> <router-outlet name="modal"></router-outlet> <ng-template #runningTpl let-value="value"> <span ngbTooltip="Service instances running out of the total number of services requested."> {{ value.running }} / {{ value.size }} </span> <i *ngIf="value.running == 0 || value.size == 0" class="icon-warning-color" [ngClass]="[icons.warning]"> </i> </ng-template>
1,419
34.5
94
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/services.component.spec.ts
import { HttpHeaders } from '@angular/common/http'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { CephModule } from '~/app/ceph/ceph.module'; import { CoreModule } from '~/app/core/core.module'; import { CephServiceService } from '~/app/shared/api/ceph-service.service'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; import { PaginateObservable } from '~/app/shared/api/paginate.model'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { Permissions } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { ServicesComponent } from './services.component'; describe('ServicesComponent', () => { let component: ServicesComponent; let fixture: ComponentFixture<ServicesComponent>; let headers: HttpHeaders; const fakeAuthStorageService = { getPermissions: () => { return new Permissions({ hosts: ['read'] }); } }; const services = [ { service_type: 'osd', service_name: 'osd', status: { size: 3, running: 3, last_refresh: '2020-02-25T04:33:26.465699' } }, { service_type: 'crash', service_name: 'crash', status: { size: 1, running: 1, last_refresh: '2020-02-25T04:33:26.465766' } } ]; configureTestBed({ imports: [ BrowserAnimationsModule, CephModule, CoreModule, SharedModule, HttpClientTestingModule, RouterTestingModule, ToastrModule.forRoot() ], providers: [{ provide: AuthStorageService, useValue: fakeAuthStorageService }] }); beforeEach(() => { fixture = TestBed.createComponent(ServicesComponent); component = fixture.componentInstance; const orchService = TestBed.inject(OrchestratorService); const cephServiceService = TestBed.inject(CephServiceService); spyOn(orchService, 'status').and.returnValue(of({ available: true })); headers = new HttpHeaders().set('X-Total-Count', '2'); const paginate_obs = new PaginateObservable<any>(of({ body: services, headers: headers })); spyOn(cephServiceService, 'list').and.returnValue(paginate_obs); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should have columns that are sortable', () => { expect( component.columns // Filter the 'Expand/Collapse Row' column. .filter((column) => !(column.cellClass === 'cd-datatable-expand-collapse')) // Filter the 'Placement' column. .filter((column) => !(column.prop === '')) .every((column) => Boolean(column.prop)) ).toBeTruthy(); }); it('should return all services', () => { const context = new CdTableFetchDataContext(() => undefined); context.pageInfo.offset = 0; context.pageInfo.limit = -1; component.getServices(context); expect(component.services.length).toBe(2); }); it('should not display doc panel if orchestrator is available', () => { expect(component.showDocPanel).toBeFalsy(); }); });
3,549
32.490566
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/services.component.ts
import { Component, Input, OnChanges, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { delay } from 'rxjs/operators'; import { CephServiceService } from '~/app/shared/api/ceph-service.service'; import { OrchestratorService } from '~/app/shared/api/orchestrator.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, URLVerbs } from '~/app/shared/constants/app.constants'; import { TableComponent } from '~/app/shared/datatable/table/table.component'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { OrchestratorFeature } from '~/app/shared/models/orchestrator.enum'; import { OrchestratorStatus } from '~/app/shared/models/orchestrator.interface'; import { Permissions } from '~/app/shared/models/permissions'; import { CephServiceSpec } from '~/app/shared/models/service.interface'; import { RelativeDatePipe } from '~/app/shared/pipes/relative-date.pipe'; 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 { URLBuilderService } from '~/app/shared/services/url-builder.service'; import { PlacementPipe } from './placement.pipe'; import { ServiceFormComponent } from './service-form/service-form.component'; const BASE_URL = 'services'; @Component({ selector: 'cd-services', templateUrl: './services.component.html', styleUrls: ['./services.component.scss'], providers: [{ provide: URLBuilderService, useValue: new URLBuilderService(BASE_URL) }] }) export class ServicesComponent extends ListWithDetails implements OnChanges, OnInit { @ViewChild(TableComponent, { static: true }) table: TableComponent; @ViewChild('runningTpl', { static: true }) public runningTpl: TemplateRef<any>; @Input() hostname: string; // Do not display these columns @Input() hiddenColumns: string[] = []; @Input() hiddenServices: string[] = []; @Input() hasDetails = true; @Input() routedModal = true; permissions: Permissions; tableActions: CdTableAction[]; showDocPanel = false; count = 0; bsModalRef: NgbModalRef; orchStatus: OrchestratorStatus; actionOrchFeatures = { create: [OrchestratorFeature.SERVICE_CREATE], update: [OrchestratorFeature.SERVICE_EDIT], delete: [OrchestratorFeature.SERVICE_DELETE] }; columns: Array<CdTableColumn> = []; services: Array<CephServiceSpec> = []; isLoadingServices = false; selection: CdTableSelection = new CdTableSelection(); icons = Icons; constructor( private actionLabels: ActionLabelsI18n, private authStorageService: AuthStorageService, private modalService: ModalService, private orchService: OrchestratorService, private cephServiceService: CephServiceService, private relativeDatePipe: RelativeDatePipe, private taskWrapperService: TaskWrapperService, private router: Router ) { super(); this.permissions = this.authStorageService.getPermissions(); this.tableActions = [ { permission: 'create', icon: Icons.add, click: () => this.openModal(), name: this.actionLabels.CREATE, canBePrimary: (selection: CdTableSelection) => !selection.hasSelection // disable: (selection: CdTableSelection) => this.getDisable('create', selection) }, { permission: 'update', icon: Icons.edit, click: () => this.openModal(true), name: this.actionLabels.EDIT, disable: (selection: CdTableSelection) => this.getDisable('update', selection) }, { permission: 'delete', icon: Icons.destroy, click: () => this.deleteAction(), name: this.actionLabels.DELETE, disable: (selection: CdTableSelection) => this.getDisable('delete', selection) } ]; } openModal(edit = false) { if (this.routedModal) { edit ? this.router.navigate([ BASE_URL, { outlets: { modal: [ URLVerbs.EDIT, this.selection.first().service_type, this.selection.first().service_name ] } } ]) : this.router.navigate([BASE_URL, { outlets: { modal: [URLVerbs.CREATE] } }]); } else { let initialState = {}; edit ? (initialState = { serviceName: this.selection.first()?.service_name, serviceType: this.selection?.first()?.service_type, hiddenServices: this.hiddenServices, editing: edit }) : (initialState = { hiddenServices: this.hiddenServices, editing: edit }); this.bsModalRef = this.modalService.show(ServiceFormComponent, initialState, { size: 'lg' }); } } ngOnInit() { const columns = [ { name: $localize`Service`, prop: 'service_name', flexGrow: 1 }, { name: $localize`Placement`, prop: '', pipe: new PlacementPipe(), flexGrow: 2 }, { name: $localize`Running`, prop: 'status', flexGrow: 1, cellTemplate: this.runningTpl }, { name: $localize`Last Refreshed`, prop: 'status.last_refresh', pipe: this.relativeDatePipe, flexGrow: 1 } ]; this.columns = columns.filter((col: any) => { return !this.hiddenColumns.includes(col.prop); }); this.orchService.status().subscribe((status: OrchestratorStatus) => { this.orchStatus = status; this.showDocPanel = !status.available; }); } ngOnChanges() { if (this.orchStatus?.available) { this.services = []; this.table.reloadData(); } } getDisable( action: 'create' | 'update' | 'delete', selection: CdTableSelection ): boolean | string { if (action === 'delete') { if (!selection?.hasSingleSelection) { return true; } } if (action === 'update') { const disableEditServices = ['osd', 'container']; if (disableEditServices.indexOf(this.selection.first()?.service_type) >= 0) { return true; } } return this.orchService.getTableActionDisableDesc( this.orchStatus, this.actionOrchFeatures[action] ); } getServices(context: CdTableFetchDataContext) { if (this.isLoadingServices) { return; } this.isLoadingServices = true; const pagination_obs = this.cephServiceService.list(context.toParams()); pagination_obs.observable.subscribe( (services: CephServiceSpec[]) => { this.services = services; this.count = pagination_obs.count; this.services = this.services.filter((col: any) => { return !this.hiddenServices.includes(col.service_name); }); this.isLoadingServices = false; }, () => { this.isLoadingServices = false; this.services = []; context.error(); } ); } updateSelection(selection: CdTableSelection) { this.selection = selection; } deleteAction() { const service = this.selection.first(); this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: $localize`Service`, itemNames: [service.service_name], actionDescription: 'delete', submitActionObservable: () => this.taskWrapperService .wrapTaskAroundCall({ task: new FinishedTask(`service/${URLVerbs.DELETE}`, { service_name: service.service_name }), call: this.cephServiceService.delete(service.service_name) }) .pipe( // Delay closing the dialog, otherwise the datatable still // shows the deleted service after an auto-reload. // Showing the dialog while delaying is done to increase // the user experience. delay(5000) ) }); } }
8,692
32.179389
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/service-daemon-list/service-daemon-list.component.html
<cd-orchestrator-doc-panel *ngIf="showDocPanel"></cd-orchestrator-doc-panel> <div *ngIf="flag === 'hostDetails'; else serviceDetailsTpl"> <ng-container *ngTemplateOutlet="serviceDaemonDetailsTpl"></ng-container> </div> <ng-template #serviceDetailsTpl> <ng-container> <nav ngbNav #nav="ngbNav" class="nav-tabs" cdStatefulTab="service-details"> <ng-container ngbNavItem="details"> <a ngbNavLink i18n>Daemons</a> <ng-template ngbNavContent> <ng-container *ngTemplateOutlet="serviceDaemonDetailsTpl"></ng-container> </ng-template> </ng-container> <ng-container ngbNavItem="service_events"> <a ngbNavLink i18n>Service Events</a> <ng-template ngbNavContent> <cd-table *ngIf="hasOrchestrator" #serviceTable [data]="services" [columns]="serviceColumns" columnMode="flex" (fetchData)="getServices($event)"> </cd-table> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="nav"></div> </ng-container> </ng-template> <ng-template #statusTpl let-row="row"> <span class="badge" [ngClass]="row | pipeFunction:getStatusClass"> {{ row.status_desc }} </span> </ng-template> <ng-template #listTpl let-events="value"> <ul class="list-group list-group-flush" *ngIf="events?.length else noEventsAvailable"> <li class="list-group-item" *ngFor="let event of events; trackBy:trackByFn"> <b>{{ event.created | relativeDate }} - </b> <span class="badge badge-info">{{ event.subject }}</span><br> <span *ngIf="event.level === 'INFO'"> <i [ngClass]="[icons.infoCircle]" aria-hidden="true"></i> </span> <span *ngIf="event.level === 'ERROR'"> <i [ngClass]="[icons.warning]" aria-hidden="true"></i> </span> {{ event.message }} </li> </ul> <ng-template #noEventsAvailable> <div *ngIf="events?.length === 0" class="list-group-item"> <span>No data available</span> </div> </ng-template> </ng-template> <ng-template #serviceDaemonDetailsTpl> <cd-table *ngIf="hasOrchestrator" #daemonsTable [data]="daemons" selectionType="single" [columns]="columns" columnMode="flex" identifier="daemon_name" (fetchData)="getDaemons($event)" (updateSelection)="updateSelection($event)"> <cd-table-actions id="service-daemon-list-actions" class="table-actions" [selection]="selection" [permission]="permissions.hosts" [tableActions]="tableActions"> </cd-table-actions> </cd-table> </ng-template> <ng-template #cpuTpl let-row="row"> <cd-usage-bar [total]="total" [calculatePerc]="false" [used]="row.cpu_percentage" [isBinary]="false" [warningThreshold]="warningThreshold" [errorThreshold]="errorThreshold"> </cd-usage-bar> </ng-template>
3,227
30.339806
83
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/service-daemon-list/service-daemon-list.component.spec.ts
import { HttpHeaders } from '@angular/common/http'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import _ from 'lodash'; import { NgxPipeFunctionModule } from 'ngx-pipe-function'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { CephModule } from '~/app/ceph/ceph.module'; import { CoreModule } from '~/app/core/core.module'; import { CephServiceService } from '~/app/shared/api/ceph-service.service'; import { HostService } from '~/app/shared/api/host.service'; import { PaginateObservable } from '~/app/shared/api/paginate.model'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { ServiceDaemonListComponent } from './service-daemon-list.component'; describe('ServiceDaemonListComponent', () => { let component: ServiceDaemonListComponent; let fixture: ComponentFixture<ServiceDaemonListComponent>; let headers: HttpHeaders; const daemons = [ { hostname: 'osd0', container_id: '003c10beafc8c27b635bcdfed1ed832e4c1005be89bb1bb05ad4cc6c2b98e41b', container_image_id: 'e70344c77bcbf3ee389b9bf5128f635cf95f3d59e005c5d8e67fc19bcc74ed23', container_image_name: 'docker.io/ceph/daemon-base:latest-master-devel', daemon_id: '3', daemon_type: 'osd', daemon_name: 'osd.3', version: '15.1.0-1174-g16a11f7', memory_usage: '17.7', cpu_percentage: '3.54%', status: 1, status_desc: 'running', last_refresh: '2020-02-25T04:33:26.465699', events: [ { created: '2020-02-24T04:33:26.465699' }, { created: '2020-02-25T04:33:26.465699' }, { created: '2020-02-26T04:33:26.465699' } ] }, { hostname: 'osd0', container_id: 'baeec41a01374b3ed41016d542d19aef4a70d69c27274f271e26381a0cc58e7a', container_image_id: 'e70344c77bcbf3ee389b9bf5128f635cf95f3d59e005c5d8e67fc19bcc74ed23', container_image_name: 'docker.io/ceph/daemon-base:latest-master-devel', daemon_id: '4', daemon_type: 'osd', daemon_name: 'osd.4', version: '15.1.0-1174-g16a11f7', memory_usage: '17.7', cpu_percentage: '3.54%', status: 1, status_desc: 'running', last_refresh: '2020-02-25T04:33:26.465822', events: [] }, { hostname: 'osd0', container_id: '8483de277e365bea4365cee9e1f26606be85c471e4da5d51f57e4b85a42c616e', container_image_id: 'e70344c77bcbf3ee389b9bf5128f635cf95f3d59e005c5d8e67fc19bcc74ed23', container_image_name: 'docker.io/ceph/daemon-base:latest-master-devel', daemon_id: '5', daemon_type: 'osd', daemon_name: 'osd.5', version: '15.1.0-1174-g16a11f7', memory_usage: '17.7', cpu_percentage: '3.54%', status: 1, status_desc: 'running', last_refresh: '2020-02-25T04:33:26.465886', events: [] }, { hostname: 'mon0', container_id: '6ca0574f47e300a6979eaf4e7c283a8c4325c2235ae60358482fc4cd58844a21', container_image_id: 'e70344c77bcbf3ee389b9bf5128f635cf95f3d59e005c5d8e67fc19bcc74ed23', container_image_name: 'docker.io/ceph/daemon-base:latest-master-devel', daemon_id: 'a', daemon_name: 'mon.a', daemon_type: 'mon', version: '15.1.0-1174-g16a11f7', memory_usage: '17.7', cpu_percentage: '3.54%', status: 1, status_desc: 'running', last_refresh: '2020-02-25T04:33:26.465886', events: [] } ]; const services = [ { service_type: 'osd', service_name: 'osd', status: { container_image_id: 'e70344c77bcbf3ee389b9bf5128f635cf95f3d59e005c5d8e67fc19bcc74ed23', container_image_name: 'docker.io/ceph/daemon-base:latest-master-devel', size: 3, running: 3, last_refresh: '2020-02-25T04:33:26.465699' }, events: '2021-03-22T07:34:48.582163Z service:osd [INFO] "service was created"' }, { service_type: 'crash', service_name: 'crash', status: { container_image_id: 'e70344c77bcbf3ee389b9bf5128f635cf95f3d59e005c5d8e67fc19bcc74ed23', container_image_name: 'docker.io/ceph/daemon-base:latest-master-devel', size: 1, running: 1, last_refresh: '2020-02-25T04:33:26.465766' }, events: '2021-03-22T07:34:48.582163Z service:osd [INFO] "service was created"' } ]; const context = new CdTableFetchDataContext(() => undefined); const getDaemonsByHostname = (hostname?: string) => { return hostname ? _.filter(daemons, { hostname: hostname }) : daemons; }; const getDaemonsByServiceName = (serviceName?: string) => { return serviceName ? _.filter(daemons, { daemon_type: serviceName }) : daemons; }; configureTestBed({ imports: [ HttpClientTestingModule, CephModule, CoreModule, NgxPipeFunctionModule, SharedModule, ToastrModule.forRoot() ] }); beforeEach(() => { fixture = TestBed.createComponent(ServiceDaemonListComponent); component = fixture.componentInstance; const hostService = TestBed.inject(HostService); const cephServiceService = TestBed.inject(CephServiceService); spyOn(hostService, 'getDaemons').and.callFake(() => of(getDaemonsByHostname(component.hostname)) ); spyOn(cephServiceService, 'getDaemons').and.callFake(() => of(getDaemonsByServiceName(component.serviceName)) ); headers = new HttpHeaders().set('X-Total-Count', '2'); const paginate_obs = new PaginateObservable<any>(of({ body: services, headers: headers })); spyOn(cephServiceService, 'list').and.returnValue(paginate_obs); context.pageInfo.offset = 0; context.pageInfo.limit = -1; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should list daemons by host', () => { component.hostname = 'mon0'; component.getDaemons(context); expect(component.daemons.length).toBe(1); }); it('should list daemons by service', () => { component.serviceName = 'osd'; component.getDaemons(context); expect(component.daemons.length).toBe(3); }); it('should list services', () => { component.getServices(context); expect(component.services.length).toBe(2); }); it('should not display doc panel if orchestrator is available', () => { expect(component.showDocPanel).toBeFalsy(); }); it('should call daemon action', () => { const daemon = daemons[0]; component.selection.selected = [daemon]; component['daemonService'].action = jest.fn(() => of()); for (const action of ['start', 'stop', 'restart', 'redeploy']) { component.daemonAction(action); expect(component['daemonService'].action).toHaveBeenCalledWith(daemon.daemon_name, action); } }); it('should disable daemon actions', () => { const daemon = { daemon_type: 'osd', status_desc: 'running' }; const states = { start: true, stop: false, restart: false, redeploy: false }; const expectBool = (toExpect: boolean, arg: boolean) => { if (toExpect === true) { expect(arg).toBeTruthy(); } else { expect(arg).toBeFalsy(); } }; component.selection.selected = [daemon]; for (const action of ['start', 'stop', 'restart', 'redeploy']) { expectBool(states[action], component.actionDisabled(action)); } daemon.status_desc = 'stopped'; states.start = false; states.stop = true; component.selection.selected = [daemon]; for (const action of ['start', 'stop', 'restart', 'redeploy']) { expectBool(states[action], component.actionDisabled(action)); } }); it('should disable daemon actions in mgr and mon daemon', () => { const daemon = { daemon_type: 'mgr', status_desc: 'running' }; for (const action of ['start', 'stop', 'restart', 'redeploy']) { expect(component.actionDisabled(action)).toBeTruthy(); } daemon.daemon_type = 'mon'; for (const action of ['start', 'stop', 'restart', 'redeploy']) { expect(component.actionDisabled(action)).toBeTruthy(); } }); it('should disable daemon actions if no selection', () => { component.selection.selected = []; for (const action of ['start', 'stop', 'restart', 'redeploy']) { expect(component.actionDisabled(action)).toBeTruthy(); } }); it('should sort daemons events', () => { component.sortDaemonEvents(); const daemon = daemons[0]; for (let i = 1; i < daemon.events.length; i++) { const t1 = new Date(daemon.events[i - 1].created).getTime(); const t2 = new Date(daemon.events[i].created).getTime(); expect(t1 >= t2).toBeTruthy(); } }); });
8,949
32.773585
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/service-daemon-list/service-daemon-list.component.ts
import { HttpParams } from '@angular/common/http'; import { AfterViewInit, ChangeDetectorRef, Component, Input, OnChanges, OnDestroy, OnInit, QueryList, TemplateRef, ViewChild, ViewChildren } from '@angular/core'; import _ from 'lodash'; import { Observable, Subscription } from 'rxjs'; import { take } from 'rxjs/operators'; import { CephServiceService } from '~/app/shared/api/ceph-service.service'; import { DaemonService } from '~/app/shared/api/daemon.service'; import { HostService } from '~/app/shared/api/host.service'; import { OrchestratorService } from '~/app/shared/api/orchestrator.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { TableComponent } from '~/app/shared/datatable/table/table.component'; import { Icons } from '~/app/shared/enum/icons.enum'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { Daemon } from '~/app/shared/models/daemon.interface'; import { Permissions } from '~/app/shared/models/permissions'; import { CephServiceSpec } from '~/app/shared/models/service.interface'; import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe'; import { RelativeDatePipe } from '~/app/shared/pipes/relative-date.pipe'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { NotificationService } from '~/app/shared/services/notification.service'; @Component({ selector: 'cd-service-daemon-list', templateUrl: './service-daemon-list.component.html', styleUrls: ['./service-daemon-list.component.scss'] }) export class ServiceDaemonListComponent implements OnInit, OnChanges, AfterViewInit, OnDestroy { @ViewChild('statusTpl', { static: true }) statusTpl: TemplateRef<any>; @ViewChild('listTpl', { static: true }) listTpl: TemplateRef<any>; @ViewChild('cpuTpl', { static: true }) cpuTpl: TemplateRef<any>; @ViewChildren('daemonsTable') daemonsTableTpls: QueryList<TemplateRef<TableComponent>>; @Input() serviceName?: string; @Input() hostname?: string; @Input() hiddenColumns: string[] = []; @Input() flag?: string; total = 100; warningThreshold = 0.8; errorThreshold = 0.9; icons = Icons; daemons: Daemon[] = []; services: Array<CephServiceSpec> = []; columns: CdTableColumn[] = []; serviceColumns: CdTableColumn[] = []; tableActions: CdTableAction[]; selection = new CdTableSelection(); permissions: Permissions; hasOrchestrator = false; showDocPanel = false; private daemonsTable: TableComponent; private daemonsTableTplsSub: Subscription; private serviceSub: Subscription; constructor( private hostService: HostService, private cephServiceService: CephServiceService, private orchService: OrchestratorService, private relativeDatePipe: RelativeDatePipe, private dimlessBinary: DimlessBinaryPipe, public actionLabels: ActionLabelsI18n, private authStorageService: AuthStorageService, private daemonService: DaemonService, private notificationService: NotificationService, private cdRef: ChangeDetectorRef ) {} ngOnInit() { this.permissions = this.authStorageService.getPermissions(); this.tableActions = [ { permission: 'update', icon: Icons.start, click: () => this.daemonAction('start'), name: this.actionLabels.START, disable: () => this.actionDisabled('start') }, { permission: 'update', icon: Icons.stop, click: () => this.daemonAction('stop'), name: this.actionLabels.STOP, disable: () => this.actionDisabled('stop') }, { permission: 'update', icon: Icons.restart, click: () => this.daemonAction('restart'), name: this.actionLabels.RESTART, disable: () => this.actionDisabled('restart') }, { permission: 'update', icon: Icons.deploy, click: () => this.daemonAction('redeploy'), name: this.actionLabels.REDEPLOY, disable: () => this.actionDisabled('redeploy') } ]; this.columns = [ { name: $localize`Hostname`, prop: 'hostname', flexGrow: 2, filterable: true }, { name: $localize`Daemon name`, prop: 'daemon_name', flexGrow: 1, filterable: true }, { name: $localize`Version`, prop: 'version', flexGrow: 1, filterable: true }, { name: $localize`Status`, prop: 'status_desc', flexGrow: 1, filterable: true, cellTemplate: this.statusTpl }, { name: $localize`Last Refreshed`, prop: 'last_refresh', pipe: this.relativeDatePipe, flexGrow: 1 }, { name: $localize`CPU Usage`, prop: 'cpu_percentage', flexGrow: 1, cellTemplate: this.cpuTpl }, { name: $localize`Memory Usage`, prop: 'memory_usage', flexGrow: 1, pipe: this.dimlessBinary, cellClass: 'text-right' }, { name: $localize`Daemon Events`, prop: 'events', flexGrow: 2, cellTemplate: this.listTpl } ]; this.serviceColumns = [ { name: $localize`Service Name`, prop: 'service_name', flexGrow: 2, filterable: true }, { name: $localize`Service Type`, prop: 'service_type', flexGrow: 1, filterable: true }, { name: $localize`Service Events`, prop: 'events', flexGrow: 5, cellTemplate: this.listTpl } ]; this.orchService.status().subscribe((data: { available: boolean }) => { this.hasOrchestrator = data.available; this.showDocPanel = !data.available; }); this.columns = this.columns.filter((col: any) => { return !this.hiddenColumns.includes(col.prop); }); setTimeout(() => { this.cdRef.detectChanges(); }, 1000); } ngOnChanges() { if (!_.isUndefined(this.daemonsTable)) { this.daemonsTable.reloadData(); } } ngAfterViewInit() { this.daemonsTableTplsSub = this.daemonsTableTpls.changes.subscribe( (tableRefs: QueryList<TableComponent>) => { this.daemonsTable = tableRefs.first; } ); } ngOnDestroy() { if (this.daemonsTableTplsSub) { this.daemonsTableTplsSub.unsubscribe(); } if (this.serviceSub) { this.serviceSub.unsubscribe(); } } getStatusClass(row: Daemon): string { return _.get( { '-1': 'badge-danger', '0': 'badge-warning', '1': 'badge-success' }, row.status, 'badge-dark' ); } getDaemons(context: CdTableFetchDataContext) { let observable: Observable<Daemon[]>; if (this.hostname) { observable = this.hostService.getDaemons(this.hostname); } else if (this.serviceName) { observable = this.cephServiceService.getDaemons(this.serviceName); } else { this.daemons = []; return; } observable.subscribe( (daemons: Daemon[]) => { this.daemons = daemons; this.sortDaemonEvents(); }, () => { this.daemons = []; context.error(); } ); } sortDaemonEvents() { this.daemons.forEach((daemon: any) => { daemon.events?.sort((event1: any, event2: any) => { return new Date(event2.created).getTime() - new Date(event1.created).getTime(); }); }); } getServices(context: CdTableFetchDataContext) { this.serviceSub = this.cephServiceService .list(new HttpParams({ fromObject: { limit: -1, offset: 0 } }), this.serviceName) .observable.subscribe( (services: CephServiceSpec[]) => { this.services = services; }, () => { this.services = []; context.error(); } ); } trackByFn(_index: any, item: any) { return item.created; } updateSelection(selection: CdTableSelection) { this.selection = selection; } daemonAction(actionType: string) { this.daemonService .action(this.selection.first()?.daemon_name, actionType) .pipe(take(1)) .subscribe({ next: (resp) => { this.notificationService.show( NotificationType.success, `Daemon ${actionType} scheduled`, resp.body.toString() ); }, error: (resp) => { this.notificationService.show( NotificationType.error, 'Daemon action failed', resp.body.toString() ); } }); } actionDisabled(actionType: string) { if (this.selection?.hasSelection) { const daemon = this.selection.selected[0]; if (daemon.daemon_type === 'mon' || daemon.daemon_type === 'mgr') { return true; // don't allow actions on mon and mgr, dashboard requires them. } switch (actionType) { case 'start': if (daemon.status_desc === 'running') { return true; } break; case 'stop': if (daemon.status_desc === 'stopped') { return true; } break; } return false; } return true; // if no selection then disable everything } }
9,692
26.151261
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/service-details/service-details.component.html
<ng-container *ngIf="selection"> <cd-service-daemon-list [serviceName]="selection['service_name']"> </cd-service-daemon-list> </ng-container>
146
28.4
68
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/service-details/service-details.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { NgxPipeFunctionModule } from 'ngx-pipe-function'; import { ToastrModule } from 'ngx-toastr'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { SummaryService } from '~/app/shared/services/summary.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { ServiceDaemonListComponent } from '../service-daemon-list/service-daemon-list.component'; import { ServiceDetailsComponent } from './service-details.component'; describe('ServiceDetailsComponent', () => { let component: ServiceDetailsComponent; let fixture: ComponentFixture<ServiceDetailsComponent>; configureTestBed({ imports: [ HttpClientTestingModule, RouterTestingModule, SharedModule, NgbNavModule, NgxPipeFunctionModule, ToastrModule.forRoot() ], declarations: [ServiceDetailsComponent, ServiceDaemonListComponent], providers: [{ provide: SummaryService, useValue: { subscribeOnce: jest.fn() } }] }); beforeEach(() => { fixture = TestBed.createComponent(ServiceDetailsComponent); component = fixture.componentInstance; component.selection = new CdTableSelection(); }); it('should create', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); });
1,604
35.477273
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/service-details/service-details.component.ts
import { Component, Input } from '@angular/core'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { Permissions } from '~/app/shared/models/permissions'; @Component({ selector: 'cd-service-details', templateUrl: './service-details.component.html', styleUrls: ['./service-details.component.scss'] }) export class ServiceDetailsComponent { @Input() permissions: Permissions; @Input() selection: CdTableSelection; }
464
24.833333
74
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/service-form/service-form.component.html
<cd-modal [pageURL]="pageURL" [modalRef]="activeModal"> <span class="modal-title" i18n>{{ action | titlecase }} {{ resource | upperFirst }}</span> <ng-container class="modal-content"> <form #frm="ngForm" [formGroup]="serviceForm" novalidate> <div class="modal-body"> <cd-alert-panel *ngIf="serviceForm.controls.service_type.value === 'rgw' && showRealmCreationForm" type="info" spacingClass="mb-3" i18n> <a class="text-decoration-underline" (click)="createMultisiteSetup()"> Click here</a> to create a new realm/zonegroup/zone </cd-alert-panel> <!-- Service type --> <div class="form-group row"> <label class="cd-col-form-label required" for="service_type" i18n>Type</label> <div class="cd-col-form-input"> <select id="service_type" name="service_type" class="form-select" formControlName="service_type" (change)="getServiceIds($event.target.value)"> <option i18n [ngValue]="null">-- Select a service type --</option> <option *ngFor="let serviceType of serviceTypes" [value]="serviceType"> {{ serviceType }} </option> </select> <span class="invalid-feedback" *ngIf="serviceForm.showError('service_type', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- backend_service --> <div *ngIf="serviceForm.controls.service_type.value === 'ingress'" class="form-group row"> <label i18n class="cd-col-form-label" [ngClass]="{'required': ['ingress'].includes(serviceForm.controls.service_type.value)}" for="backend_service">Backend Service</label> <div class="cd-col-form-input"> <select id="backend_service" name="backend_service" class="form-select" formControlName="backend_service" (change)="prePopulateId()"> <option *ngIf="services === null" [ngValue]="null" i18n>Loading...</option> <option *ngIf="services !== null && services.length === 0" [ngValue]="null" i18n>-- No service available --</option> <option *ngIf="services !== null && services.length > 0" [ngValue]="null" i18n>-- Select an existing service --</option> <option *ngFor="let service of services" [value]="service.service_name">{{ service.service_name }}</option> </select> <span class="invalid-feedback" *ngIf="serviceForm.showError('backend_service', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- Service id --> <div class="form-group row" *ngIf="serviceForm.controls.service_type.value !== 'snmp-gateway'"> <label class="cd-col-form-label" [ngClass]="{'required': ['mds', 'rgw', 'nfs', 'iscsi', 'ingress'].includes(serviceForm.controls.service_type.value)}" for="service_id"> <span i18n>Id</span> <cd-helper i18n>Used in the service name which is &lt;service_type.service_id&gt;</cd-helper> </label> <div class="cd-col-form-input"> <input id="service_id" class="form-control" type="text" formControlName="service_id"> <span class="invalid-feedback" *ngIf="serviceForm.showError('service_id', frm, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('service_id', frm, 'uniqueName')" i18n>This service id is already in use.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('service_id', frm, 'mdsPattern')" i18n>MDS service id must start with a letter and contain alphanumeric characters or '.', '-', and '_'</span> </div> </div> <div class="form-group row" *ngIf="serviceForm.controls.service_type.value === 'rgw'"> <label class="cd-col-form-label" for="realm_name" i18n>Realm</label> <div class="cd-col-form-input"> <select class="form-select" id="realm_name" formControlName="realm_name" name="realm_name" [attr.disabled]="realmList.length === 0 || editing ? true : null"> <option *ngIf="realmList.length === 0" i18n selected>-- No realm available --</option> <option *ngFor="let realm of realmList" [value]="realm.name"> {{ realm.name }} </option> </select> </div> </div> <div class="form-group row" *ngIf="serviceForm.controls.service_type.value === 'rgw'"> <label class="cd-col-form-label" for="zonegroup_name" i18n>Zonegroup</label> <div class="cd-col-form-input"> <select class="form-select" id="zonegroup_name" formControlName="zonegroup_name" name="zonegroup_name" [attr.disabled]="zonegroupList.length === 0 || editing ? true : null"> <option *ngFor="let zonegroup of zonegroupList" [value]="zonegroup.name"> {{ zonegroup.name }} </option> </select> </div> </div> <div class="form-group row" *ngIf="serviceForm.controls.service_type.value === 'rgw'"> <label class="cd-col-form-label" for="zone_name" i18n>Zone</label> <div class="cd-col-form-input"> <select class="form-select" id="zone_name" formControlName="zone_name" name="zone_name" [attr.disabled]="zoneList.length === 0 || editing ? true : null"> <option *ngFor="let zone of zoneList" [value]="zone.name"> {{ zone.name }} </option> </select> </div> </div> <!-- unmanaged --> <div class="form-group row"> <div class="cd-col-form-offset"> <div class="custom-control custom-checkbox"> <input class="custom-control-input" id="unmanaged" type="checkbox" formControlName="unmanaged"> <label class="custom-control-label" for="unmanaged" i18n>Unmanaged</label> <cd-helper i18n>If set to true, the orchestrator will not start nor stop any daemon associated with this service. Placement and all other properties will be ignored.</cd-helper> </div> </div> </div> <!-- Placement --> <div *ngIf="!serviceForm.controls.unmanaged.value" class="form-group row"> <label class="cd-col-form-label" for="placement" i18n>Placement</label> <div class="cd-col-form-input"> <select id="placement" class="form-select" formControlName="placement"> <option i18n value="hosts">Hosts</option> <option i18n value="label">Label</option> </select> </div> </div> <!-- Label --> <div *ngIf="!serviceForm.controls.unmanaged.value && serviceForm.controls.placement.value === 'label'" class="form-group row"> <label i18n class="cd-col-form-label" for="label">Label</label> <div class="cd-col-form-input"> <input id="label" class="form-control" type="text" formControlName="label" [ngbTypeahead]="searchLabels" (focus)="labelFocus.next($any($event).target.value)" (click)="labelClick.next($any($event).target.value)"> <span class="invalid-feedback" *ngIf="serviceForm.showError('label', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- Hosts --> <div *ngIf="!serviceForm.controls.unmanaged.value && serviceForm.controls.placement.value === 'hosts'" class="form-group row"> <label class="cd-col-form-label" for="hosts" i18n>Hosts</label> <div class="cd-col-form-input"> <cd-select-badges id="hosts" [data]="serviceForm.controls.hosts.value" [options]="hosts.options" [messages]="hosts.messages"> </cd-select-badges> </div> </div> <!-- count --> <div *ngIf="!serviceForm.controls.unmanaged.value" class="form-group row"> <label class="cd-col-form-label" for="count"> <span i18n>Count</span> <cd-helper i18n>Only that number of daemons will be created.</cd-helper> </label> <div class="cd-col-form-input"> <input id="count" class="form-control" type="number" formControlName="count" min="1"> <span class="invalid-feedback" *ngIf="serviceForm.showError('count', frm, 'min')" i18n>The value must be at least 1.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('count', frm, 'pattern')" i18n>The entered value needs to be a number.</span> </div> </div> <!-- RGW --> <ng-container *ngIf="!serviceForm.controls.unmanaged.value && serviceForm.controls.service_type.value === 'rgw'"> <!-- rgw_frontend_port --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="rgw_frontend_port">Port</label> <div class="cd-col-form-input"> <input id="rgw_frontend_port" class="form-control" type="number" formControlName="rgw_frontend_port" min="1" max="65535"> <span class="invalid-feedback" *ngIf="serviceForm.showError('rgw_frontend_port', frm, 'pattern')" i18n>The entered value needs to be a number.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('rgw_frontend_port', frm, 'min')" i18n>The value must be at least 1.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('rgw_frontend_port', frm, 'max')" i18n>The value cannot exceed 65535.</span> </div> </div> </ng-container> <!-- iSCSI --> <!-- pool --> <div class="form-group row" *ngIf="serviceForm.controls.service_type.value === 'iscsi'"> <label i18n class="cd-col-form-label required" for="pool">Pool</label> <div class="cd-col-form-input"> <select id="pool" name="pool" class="form-select" formControlName="pool"> <option *ngIf="pools === null" [ngValue]="null" i18n>Loading...</option> <option *ngIf="pools && pools.length === 0" [ngValue]="null" i18n>-- No pools available --</option> <option *ngIf="pools && pools.length > 0" [ngValue]="null" i18n>-- Select a pool --</option> <option *ngFor="let pool of pools" [value]="pool.pool_name">{{ pool.pool_name }}</option> </select> <span class="invalid-feedback" *ngIf="serviceForm.showError('pool', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- fields in iSCSI which are hidden when unmanaged is true --> <ng-container *ngIf="!serviceForm.controls.unmanaged.value && serviceForm.controls.service_type.value === 'iscsi'"> <!-- trusted_ip_list --> <div class="form-group row"> <label class="cd-col-form-label" for="trusted_ip_list"> <span i18n>Trusted IPs</span> <cd-helper> <span i18n>Comma separated list of IP addresses.</span> <br> <span i18n>Please add the <b>Ceph Manager</b> IP addresses here, otherwise the iSCSI gateways can't be reached.</span> </cd-helper> </label> <div class="cd-col-form-input"> <input id="trusted_ip_list" class="form-control" type="text" formControlName="trusted_ip_list"> </div> </div> <!-- api_port --> <div class="form-group row"> <label i18n class="cd-col-form-label" for="api_port">Port</label> <div class="cd-col-form-input"> <input id="api_port" class="form-control" type="number" formControlName="api_port" min="1" max="65535"> <span class="invalid-feedback" *ngIf="serviceForm.showError('api_port', frm, 'pattern')" i18n>The entered value needs to be a number.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('api_port', frm, 'min')" i18n>The value must be at least 1.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('api_port', frm, 'max')" i18n>The value cannot exceed 65535.</span> </div> </div> <!-- api_user --> <div class="form-group row"> <label i18n class="cd-col-form-label" [ngClass]="{'required': ['iscsi'].includes(serviceForm.controls.service_type.value)}" for="api_user">User</label> <div class="cd-col-form-input"> <input id="api_user" class="form-control" type="text" formControlName="api_user"> <span class="invalid-feedback" *ngIf="serviceForm.showError('api_user', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- api_password --> <div class="form-group row"> <label i18n class="cd-col-form-label" [ngClass]="{'required': ['iscsi'].includes(serviceForm.controls.service_type.value)}" for="api_password">Password</label> <div class="cd-col-form-input"> <div class="input-group"> <input id="api_password" class="form-control" type="password" autocomplete="new-password" formControlName="api_password"> <button type="button" class="btn btn-light" cdPasswordButton="api_password"> </button> <cd-copy-2-clipboard-button source="api_password"> </cd-copy-2-clipboard-button> <span class="invalid-feedback" *ngIf="serviceForm.showError('api_password', frm, 'required')" i18n>This field is required.</span> </div> </div> </div> </ng-container> <!-- Ingress --> <ng-container *ngIf="serviceForm.controls.service_type.value === 'ingress'"> <!-- virtual_ip --> <div class="form-group row"> <label class="cd-col-form-label" [ngClass]="{'required': ['ingress'].includes(serviceForm.controls.service_type.value)}" for="virtual_ip"> <span i18n>Virtual IP</span> <cd-helper> <span i18n>The virtual IP address and subnet (in CIDR notation) where the ingress service will be available.</span> </cd-helper> </label> <div class="cd-col-form-input"> <input id="virtual_ip" class="form-control" type="text" formControlName="virtual_ip"> <span class="invalid-feedback" *ngIf="serviceForm.showError('virtual_ip', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- frontend_port --> <div class="form-group row"> <label class="cd-col-form-label" [ngClass]="{'required': ['ingress'].includes(serviceForm.controls.service_type.value)}" for="frontend_port"> <span i18n>Frontend Port</span> <cd-helper> <span i18n>The port used to access the ingress service.</span> </cd-helper> </label> <div class="cd-col-form-input"> <input id="frontend_port" class="form-control" type="number" formControlName="frontend_port" min="1" max="65535"> <span class="invalid-feedback" *ngIf="serviceForm.showError('frontend_port', frm, 'pattern')" i18n>The entered value needs to be a number.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('frontend_port', frm, 'min')" i18n>The value must be at least 1.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('frontend_port', frm, 'max')" i18n>The value cannot exceed 65535.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('frontend_port', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- monitor_port --> <div class="form-group row"> <label class="cd-col-form-label" [ngClass]="{'required': ['ingress'].includes(serviceForm.controls.service_type.value)}" for="monitor_port"> <span i18n>Monitor Port</span> <cd-helper> <span i18n>The port used by haproxy for load balancer status.</span> </cd-helper> </label> <div class="cd-col-form-input"> <input id="monitor_port" class="form-control" type="number" formControlName="monitor_port" min="1" max="65535"> <span class="invalid-feedback" *ngIf="serviceForm.showError('monitor_port', frm, 'pattern')" i18n>The entered value needs to be a number.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('monitor_port', frm, 'min')" i18n>The value must be at least 1.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('monitor_port', frm, 'max')" i18n>The value cannot exceed 65535.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('monitor_port', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- virtual_interface_networks --> <div class="form-group row" *ngIf="!serviceForm.controls.unmanaged.value"> <label class="cd-col-form-label" for="virtual_interface_networks"> <span i18n>CIDR Networks</span> <cd-helper> <span i18n>A list of networks to identify which network interface to use for the virtual IP address.</span> </cd-helper> </label> <div class="cd-col-form-input"> <input id="virtual_interface_networks" class="form-control" type="text" formControlName="virtual_interface_networks"> </div> </div> </ng-container> <!-- SNMP-Gateway --> <ng-container *ngIf="serviceForm.controls.service_type.value === 'snmp-gateway'"> <!-- snmp-version --> <div class="form-group row"> <label class="cd-col-form-label required" for="snmp_version" i18n>Version</label> <div class="cd-col-form-input"> <select id="snmp_version" name="snmp_version" class="form-select" formControlName="snmp_version" (change)="clearValidations()"> <option i18n [ngValue]="null">-- Select SNMP version --</option> <option *ngFor="let snmpVersion of ['V2c', 'V3']" [value]="snmpVersion">{{ snmpVersion }}</option> </select> <span class="invalid-feedback" *ngIf="serviceForm.showError('snmp_version', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- Destination --> <div class="form-group row"> <label class="cd-col-form-label required" for="snmp_destination"> <span i18n>Destination</span> <cd-helper> <span i18n>Must be of the format hostname:port.</span> </cd-helper> </label> <div class="cd-col-form-input"> <input id="snmp_destination" class="form-control" type="text" formControlName="snmp_destination"> <span class="invalid-feedback" *ngIf="serviceForm.showError('snmp_destination', frm, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('snmp_destination', frm, 'snmpDestinationPattern')" i18n>The value does not match the pattern: <strong>hostname:port</strong></span> </div> </div> <!-- Engine id for snmp V3 --> <div class="form-group row" *ngIf="serviceForm.controls.snmp_version.value === 'V3'"> <label class="cd-col-form-label required" for="engine_id"> <span i18n>Engine Id</span> <cd-helper> <span i18n>Unique identifier for the device (in hex).</span> </cd-helper> </label> <div class="cd-col-form-input"> <input id="engine_id" class="form-control" type="text" formControlName="engine_id"> <span class="invalid-feedback" *ngIf="serviceForm.showError('engine_id', frm, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('engine_id', frm, 'snmpEngineIdPattern')" i18n>The value does not match the pattern: <strong>Must be in hexadecimal and length must be multiple of 2 with min value = 10 amd max value = 64.</strong></span> </div> </div> <!-- Auth protocol for snmp V3 --> <div class="form-group row" *ngIf="serviceForm.controls.snmp_version.value === 'V3'"> <label class="cd-col-form-label required" for="auth_protocol" i18n>Auth Protocol</label> <div class="cd-col-form-input"> <select id="auth_protocol" name="auth_protocol" class="form-select" formControlName="auth_protocol"> <option i18n [ngValue]="null">-- Select auth protocol --</option> <option *ngFor="let authProtocol of ['SHA', 'MD5']" [value]="authProtocol"> {{ authProtocol }} </option> </select> <span class="invalid-feedback" *ngIf="serviceForm.showError('auth_protocol', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- Privacy protocol for snmp V3 --> <div class="form-group row" *ngIf="serviceForm.controls.snmp_version.value === 'V3'"> <label class="cd-col-form-label" for="privacy_protocol" i18n>Privacy Protocol</label> <div class="cd-col-form-input"> <select id="privacy_protocol" name="privacy_protocol" class="form-select" formControlName="privacy_protocol"> <option i18n [ngValue]="null">-- Select privacy protocol --</option> <option *ngFor="let privacyProtocol of ['DES', 'AES']" [value]="privacyProtocol"> {{ privacyProtocol }} </option> </select> </div> </div> <!-- Credentials --> <fieldset> <legend i18n>Credentials</legend> <!-- snmp v2c snmp_community --> <div class="form-group row" *ngIf="serviceForm.controls.snmp_version.value === 'V2c'"> <label class="cd-col-form-label required" for="snmp_community"> <span i18n>SNMP Community</span> </label> <div class="cd-col-form-input"> <input id="snmp_community" class="form-control" type="text" formControlName="snmp_community"> <span class="invalid-feedback" *ngIf="serviceForm.showError('snmp_community', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- snmp v3 auth username --> <div class="form-group row" *ngIf="serviceForm.controls.snmp_version.value === 'V3'"> <label class="cd-col-form-label required" for="snmp_v3_auth_username"> <span i18n>Username</span> </label> <div class="cd-col-form-input"> <input id="snmp_v3_auth_username" class="form-control" type="text" formControlName="snmp_v3_auth_username"> <span class="invalid-feedback" *ngIf="serviceForm.showError('snmp_v3_auth_username', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- snmp v3 auth password --> <div class="form-group row" *ngIf="serviceForm.controls.snmp_version.value === 'V3'"> <label class="cd-col-form-label required" for="snmp_v3_auth_password"> <span i18n>Password</span> </label> <div class="cd-col-form-input"> <input id="snmp_v3_auth_password" class="form-control" type="password" formControlName="snmp_v3_auth_password"> <span class="invalid-feedback" *ngIf="serviceForm.showError('snmp_v3_auth_password', frm, 'required')" i18n>This field is required.</span> </div> </div> <!-- snmp v3 priv password --> <div class="form-group row" *ngIf="serviceForm.controls.snmp_version.value === 'V3' && serviceForm.controls.privacy_protocol.value !== null && serviceForm.controls.privacy_protocol.value !== undefined"> <label class="cd-col-form-label required" for="snmp_v3_priv_password"> <span i18n>Encryption</span> </label> <div class="cd-col-form-input"> <input id="snmp_v3_priv_password" class="form-control" type="password" formControlName="snmp_v3_priv_password"> <span class="invalid-feedback" *ngIf="serviceForm.showError('snmp_v3_priv_password', frm, 'required')" i18n>This field is required.</span> </div> </div> </fieldset> </ng-container> <!-- RGW, Ingress & iSCSI --> <ng-container *ngIf="!serviceForm.controls.unmanaged.value && ['rgw', 'iscsi', 'ingress'].includes(serviceForm.controls.service_type.value)"> <!-- ssl --> <div class="form-group row"> <div class="cd-col-form-offset"> <div class="custom-control custom-checkbox"> <input class="custom-control-input" id="ssl" type="checkbox" formControlName="ssl"> <label class="custom-control-label" for="ssl" i18n>SSL</label> </div> </div> </div> <!-- ssl_cert --> <div *ngIf="serviceForm.controls.ssl.value" class="form-group row"> <label class="cd-col-form-label" for="ssl_cert"> <span i18n>Certificate</span> <cd-helper i18n>The SSL certificate in PEM format.</cd-helper> </label> <div class="cd-col-form-input"> <textarea id="ssl_cert" class="form-control resize-vertical text-monospace text-pre" formControlName="ssl_cert" rows="5"> </textarea> <input type="file" (change)="fileUpload($event.target.files, 'ssl_cert')"> <span class="invalid-feedback" *ngIf="serviceForm.showError('ssl_cert', frm, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('ssl_cert', frm, 'pattern')" i18n>Invalid SSL certificate.</span> </div> </div> <!-- ssl_key --> <div *ngIf="serviceForm.controls.ssl.value && !(['rgw', 'ingress'].includes(serviceForm.controls.service_type.value))" class="form-group row"> <label class="cd-col-form-label" for="ssl_key"> <span i18n>Private key</span> <cd-helper i18n>The SSL private key in PEM format.</cd-helper> </label> <div class="cd-col-form-input"> <textarea id="ssl_key" class="form-control resize-vertical text-monospace text-pre" formControlName="ssl_key" rows="5"> </textarea> <input type="file" (change)="fileUpload($event.target.files,'ssl_key')"> <span class="invalid-feedback" *ngIf="serviceForm.showError('ssl_key', frm, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('ssl_key', frm, 'pattern')" i18n>Invalid SSL private key.</span> </div> </div> </ng-container> <!-- Grafana --> <ng-container *ngIf="serviceForm.controls.service_type.value === 'grafana'"> <div class="form-group row"> <label class="cd-col-form-label" for="grafana_port"> <span i18n>Grafana Port</span> <cd-helper> <span i18n>The default port used by grafana.</span> </cd-helper> </label> <div class="cd-col-form-input"> <input id="grafana_port" class="form-control" type="number" formControlName="grafana_port" min="1" max="65535"> <span class="invalid-feedback" *ngIf="serviceForm.showError('grafana_port', frm, 'pattern')" i18n>The entered value needs to be a number.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('grafana_port', frm, 'min')" i18n>The value must be at least 1.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('grafana_port', frm, 'max')" i18n>The value cannot exceed 65535.</span> <span class="invalid-feedback" *ngIf="serviceForm.showError('grafana_port', frm, 'required')" i18n>This field is required.</span> </div> </div> <div class="form-group row"> <label i18n class="cd-col-form-label" for="grafana_admin_password"> <span>Grafana Password</span> <cd-helper>The password of the default Grafana Admin. Set once on first-run.</cd-helper> </label> <div class="cd-col-form-input"> <div class="input-group"> <input id="grafana_admin_password" class="form-control" type="password" autocomplete="new-password" [attr.disabled]="editing ? true:null" formControlName="grafana_admin_password"> <span class="input-group-append"> <button type="button" class="btn btn-light" cdPasswordButton="grafana_admin_password"> </button> <cd-copy-2-clipboard-button source="grafana_admin_password"> </cd-copy-2-clipboard-button> </span> </div> </div> </div> </ng-container> </div> <div class="modal-footer"> <div class="text-right"> <cd-form-button-panel (submitActionEvent)="onSubmit()" [form]="serviceForm" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"></cd-form-button-panel> </div> </div> </form> </ng-container> </cd-modal>
36,861
43.681212
191
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/service-form/service-form.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal, NgbTypeaheadModule } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { CephServiceService } from '~/app/shared/api/ceph-service.service'; import { PaginateObservable } from '~/app/shared/api/paginate.model'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FormHelper } from '~/testing/unit-test-helper'; import { ServiceFormComponent } from './service-form.component'; describe('ServiceFormComponent', () => { let component: ServiceFormComponent; let fixture: ComponentFixture<ServiceFormComponent>; let cephServiceService: CephServiceService; let form: CdFormGroup; let formHelper: FormHelper; configureTestBed({ declarations: [ServiceFormComponent], providers: [NgbActiveModal], imports: [ HttpClientTestingModule, NgbTypeaheadModule, ReactiveFormsModule, RouterTestingModule, SharedModule, ToastrModule.forRoot() ] }); beforeEach(() => { fixture = TestBed.createComponent(ServiceFormComponent); component = fixture.componentInstance; component.ngOnInit(); form = component.serviceForm; formHelper = new FormHelper(form); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('should test form', () => { beforeEach(() => { cephServiceService = TestBed.inject(CephServiceService); spyOn(cephServiceService, 'create').and.stub(); }); it('should test placement (host)', () => { formHelper.setValue('service_type', 'crash'); formHelper.setValue('placement', 'hosts'); formHelper.setValue('hosts', ['mgr0', 'mon0', 'osd0']); formHelper.setValue('count', 2); component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'crash', placement: { hosts: ['mgr0', 'mon0', 'osd0'], count: 2 }, unmanaged: false }); }); it('should test placement (label)', () => { formHelper.setValue('service_type', 'mgr'); formHelper.setValue('placement', 'label'); formHelper.setValue('label', 'foo'); component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'mgr', placement: { label: 'foo' }, unmanaged: false }); }); it('should submit valid count', () => { formHelper.setValue('count', 1); component.onSubmit(); formHelper.expectValid('count'); }); it('should submit invalid count (1)', () => { formHelper.setValue('count', 0); component.onSubmit(); formHelper.expectError('count', 'min'); }); it('should submit invalid count (2)', () => { formHelper.setValue('count', 'abc'); component.onSubmit(); formHelper.expectError('count', 'pattern'); }); it('should test unmanaged', () => { formHelper.setValue('service_type', 'mgr'); formHelper.setValue('service_id', 'svc'); formHelper.setValue('placement', 'label'); formHelper.setValue('label', 'bar'); formHelper.setValue('unmanaged', true); component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'mgr', service_id: 'svc', placement: {}, unmanaged: true }); }); it('should test various services', () => { _.forEach( ['alertmanager', 'crash', 'mds', 'mgr', 'mon', 'node-exporter', 'prometheus', 'rbd-mirror'], (serviceType) => { formHelper.setValue('service_type', serviceType); component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: serviceType, placement: {}, unmanaged: false }); } ); }); describe('should test service grafana', () => { beforeEach(() => { formHelper.setValue('service_type', 'grafana'); }); it('should sumbit grafana', () => { component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'grafana', placement: {}, unmanaged: false, initial_admin_password: null, port: null }); }); it('should sumbit grafana with custom port and initial password', () => { formHelper.setValue('grafana_port', 1234); formHelper.setValue('grafana_admin_password', 'foo'); component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'grafana', placement: {}, unmanaged: false, initial_admin_password: 'foo', port: 1234 }); }); }); describe('should test service nfs', () => { beforeEach(() => { formHelper.setValue('service_type', 'nfs'); }); it('should submit nfs', () => { component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'nfs', placement: {}, unmanaged: false }); }); }); describe('should test service rgw', () => { beforeEach(() => { formHelper.setValue('service_type', 'rgw'); formHelper.setValue('service_id', 'svc'); }); it('should test rgw valid service id', () => { formHelper.setValue('service_id', 'svc.realm.zone'); formHelper.expectValid('service_id'); formHelper.setValue('service_id', 'svc'); formHelper.expectValid('service_id'); }); it('should submit rgw with realm, zonegroup and zone', () => { formHelper.setValue('service_id', 'svc'); formHelper.setValue('realm_name', 'my-realm'); formHelper.setValue('zone_name', 'my-zone'); formHelper.setValue('zonegroup_name', 'my-zonegroup'); component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'rgw', service_id: 'svc', rgw_realm: 'my-realm', rgw_zone: 'my-zone', rgw_zonegroup: 'my-zonegroup', placement: {}, unmanaged: false, ssl: false }); }); it('should submit rgw with port and ssl enabled', () => { formHelper.setValue('rgw_frontend_port', 1234); formHelper.setValue('ssl', true); component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'rgw', service_id: 'svc', rgw_realm: null, rgw_zone: null, rgw_zonegroup: null, placement: {}, unmanaged: false, rgw_frontend_port: 1234, rgw_frontend_ssl_certificate: '', ssl: true }); }); it('should submit valid rgw port (1)', () => { formHelper.setValue('rgw_frontend_port', 1); component.onSubmit(); formHelper.expectValid('rgw_frontend_port'); }); it('should submit valid rgw port (2)', () => { formHelper.setValue('rgw_frontend_port', 65535); component.onSubmit(); formHelper.expectValid('rgw_frontend_port'); }); it('should submit invalid rgw port (1)', () => { formHelper.setValue('rgw_frontend_port', 0); fixture.detectChanges(); formHelper.expectError('rgw_frontend_port', 'min'); }); it('should submit invalid rgw port (2)', () => { formHelper.setValue('rgw_frontend_port', 65536); fixture.detectChanges(); formHelper.expectError('rgw_frontend_port', 'max'); }); it('should submit invalid rgw port (3)', () => { formHelper.setValue('rgw_frontend_port', 'abc'); component.onSubmit(); formHelper.expectError('rgw_frontend_port', 'pattern'); }); it('should submit rgw w/o port', () => { formHelper.setValue('ssl', false); component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'rgw', service_id: 'svc', rgw_realm: null, rgw_zone: null, rgw_zonegroup: null, placement: {}, unmanaged: false, ssl: false }); }); it('should not show private key field', () => { formHelper.setValue('ssl', true); fixture.detectChanges(); const ssl_key = fixture.debugElement.query(By.css('#ssl_key')); expect(ssl_key).toBeNull(); }); it('should test .pem file', () => { const pemCert = ` -----BEGIN CERTIFICATE----- iJ5IbgzlKPssdYwuAEI3yPZxX/g5vKBrgcyD3LttLL/DlElq/1xCnwVrv7WROSNu -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- mn/S7BNBEC7AGe5ajmN+8hBTGdACUXe8rwMNrtTy/MwBZ0VpJsAAjJh+aptZh5yB -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- x4Ea7kGVgx9kWh5XjWz9wjZvY49UKIT5ppIAWPMbLl3UpfckiuNhTA== -----END RSA PRIVATE KEY-----`; formHelper.setValue('ssl', true); formHelper.setValue('ssl_cert', pemCert); fixture.detectChanges(); formHelper.expectValid('ssl_cert'); }); }); describe('should test service iscsi', () => { beforeEach(() => { formHelper.setValue('service_type', 'iscsi'); formHelper.setValue('pool', 'xyz'); formHelper.setValue('api_user', 'user'); formHelper.setValue('api_password', 'password'); formHelper.setValue('ssl', false); }); it('should submit iscsi', () => { component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'iscsi', placement: {}, unmanaged: false, pool: 'xyz', api_user: 'user', api_password: 'password', api_secure: false }); }); it('should submit iscsi with trusted ips', () => { formHelper.setValue('ssl', true); formHelper.setValue('trusted_ip_list', ' 172.16.0.5, 192.1.1.10 '); component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'iscsi', placement: {}, unmanaged: false, pool: 'xyz', api_user: 'user', api_password: 'password', api_secure: true, ssl_cert: '', ssl_key: '', trusted_ip_list: '172.16.0.5, 192.1.1.10' }); }); it('should submit iscsi with port', () => { formHelper.setValue('api_port', 456); component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'iscsi', placement: {}, unmanaged: false, pool: 'xyz', api_user: 'user', api_password: 'password', api_secure: false, api_port: 456 }); }); it('should submit valid iscsi port (1)', () => { formHelper.setValue('api_port', 1); component.onSubmit(); formHelper.expectValid('api_port'); }); it('should submit valid iscsi port (2)', () => { formHelper.setValue('api_port', 65535); component.onSubmit(); formHelper.expectValid('api_port'); }); it('should submit invalid iscsi port (1)', () => { formHelper.setValue('api_port', 0); fixture.detectChanges(); formHelper.expectError('api_port', 'min'); }); it('should submit invalid iscsi port (2)', () => { formHelper.setValue('api_port', 65536); fixture.detectChanges(); formHelper.expectError('api_port', 'max'); }); it('should submit invalid iscsi port (3)', () => { formHelper.setValue('api_port', 'abc'); component.onSubmit(); formHelper.expectError('api_port', 'pattern'); }); it('should throw error when there is no pool', () => { formHelper.expectErrorChange('pool', '', 'required'); }); }); describe('should test service ingress', () => { beforeEach(() => { formHelper.setValue('service_type', 'ingress'); formHelper.setValue('backend_service', 'rgw.foo'); formHelper.setValue('virtual_ip', '192.168.20.1/24'); formHelper.setValue('ssl', false); }); it('should submit ingress', () => { component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'ingress', placement: {}, unmanaged: false, backend_service: 'rgw.foo', service_id: 'rgw.foo', virtual_ip: '192.168.20.1/24', virtual_interface_networks: null, ssl: false }); }); it('should pre-populate the service id', () => { component.prePopulateId(); const prePopulatedID = component.serviceForm.getValue('service_id'); expect(prePopulatedID).toBe('rgw.foo'); }); it('should submit valid frontend and monitor port', () => { // min value formHelper.setValue('frontend_port', 1); formHelper.setValue('monitor_port', 1); fixture.detectChanges(); formHelper.expectValid('frontend_port'); formHelper.expectValid('monitor_port'); // max value formHelper.setValue('frontend_port', 65535); formHelper.setValue('monitor_port', 65535); fixture.detectChanges(); formHelper.expectValid('frontend_port'); formHelper.expectValid('monitor_port'); }); it('should submit invalid frontend and monitor port', () => { // min formHelper.setValue('frontend_port', 0); formHelper.setValue('monitor_port', 0); fixture.detectChanges(); formHelper.expectError('frontend_port', 'min'); formHelper.expectError('monitor_port', 'min'); // max formHelper.setValue('frontend_port', 65536); formHelper.setValue('monitor_port', 65536); fixture.detectChanges(); formHelper.expectError('frontend_port', 'max'); formHelper.expectError('monitor_port', 'max'); // pattern formHelper.setValue('frontend_port', 'abc'); formHelper.setValue('monitor_port', 'abc'); component.onSubmit(); formHelper.expectError('frontend_port', 'pattern'); formHelper.expectError('monitor_port', 'pattern'); }); it('should not show private key field with ssl enabled', () => { formHelper.setValue('ssl', true); fixture.detectChanges(); const ssl_key = fixture.debugElement.query(By.css('#ssl_key')); expect(ssl_key).toBeNull(); }); it('should test .pem file with ssl enabled', () => { const pemCert = ` -----BEGIN CERTIFICATE----- iJ5IbgzlKPssdYwuAEI3yPZxX/g5vKBrgcyD3LttLL/DlElq/1xCnwVrv7WROSNu -----END CERTIFICATE----- -----BEGIN CERTIFICATE----- mn/S7BNBEC7AGe5ajmN+8hBTGdACUXe8rwMNrtTy/MwBZ0VpJsAAjJh+aptZh5yB -----END CERTIFICATE----- -----BEGIN RSA PRIVATE KEY----- x4Ea7kGVgx9kWh5XjWz9wjZvY49UKIT5ppIAWPMbLl3UpfckiuNhTA== -----END RSA PRIVATE KEY-----`; formHelper.setValue('ssl', true); formHelper.setValue('ssl_cert', pemCert); fixture.detectChanges(); formHelper.expectValid('ssl_cert'); }); }); describe('should test service snmp-gateway', () => { beforeEach(() => { formHelper.setValue('service_type', 'snmp-gateway'); formHelper.setValue('snmp_destination', '192.168.20.1:8443'); }); it('should test snmp-gateway service with V2c', () => { formHelper.setValue('snmp_version', 'V2c'); formHelper.setValue('snmp_community', 'public'); component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'snmp-gateway', placement: {}, unmanaged: false, snmp_version: 'V2c', snmp_destination: '192.168.20.1:8443', credentials: { snmp_community: 'public' } }); }); it('should test snmp-gateway service with V3', () => { formHelper.setValue('snmp_version', 'V3'); formHelper.setValue('engine_id', '800C53F00000'); formHelper.setValue('auth_protocol', 'SHA'); formHelper.setValue('privacy_protocol', 'DES'); formHelper.setValue('snmp_v3_auth_username', 'testuser'); formHelper.setValue('snmp_v3_auth_password', 'testpass'); formHelper.setValue('snmp_v3_priv_password', 'testencrypt'); component.onSubmit(); expect(cephServiceService.create).toHaveBeenCalledWith({ service_type: 'snmp-gateway', placement: {}, unmanaged: false, snmp_version: 'V3', snmp_destination: '192.168.20.1:8443', engine_id: '800C53F00000', auth_protocol: 'SHA', privacy_protocol: 'DES', credentials: { snmp_v3_auth_username: 'testuser', snmp_v3_auth_password: 'testpass', snmp_v3_priv_password: 'testencrypt' } }); }); it('should submit invalid snmp destination', () => { formHelper.setValue('snmp_version', 'V2c'); formHelper.setValue('snmp_destination', '192.168.20.1'); formHelper.setValue('snmp_community', 'public'); formHelper.expectError('snmp_destination', 'snmpDestinationPattern'); }); it('should submit invalid snmp engine id', () => { formHelper.setValue('snmp_version', 'V3'); formHelper.setValue('snmp_destination', '192.168.20.1'); formHelper.setValue('engine_id', 'AABBCCDDE'); formHelper.setValue('auth_protocol', 'SHA'); formHelper.setValue('privacy_protocol', 'DES'); formHelper.setValue('snmp_v3_auth_username', 'testuser'); formHelper.setValue('snmp_v3_auth_password', 'testpass'); formHelper.expectError('engine_id', 'snmpEngineIdPattern'); }); }); describe('should test service mds', () => { beforeEach(() => { formHelper.setValue('service_type', 'mds'); const paginate_obs = new PaginateObservable<any>(of({})); spyOn(cephServiceService, 'list').and.returnValue(paginate_obs); }); it('should test mds valid service id', () => { formHelper.setValue('service_id', 'svc123'); formHelper.expectValid('service_id'); formHelper.setValue('service_id', 'svc_id-1'); formHelper.expectValid('service_id'); }); it('should test mds invalid service id', () => { formHelper.setValue('service_id', '123'); formHelper.expectError('service_id', 'mdsPattern'); formHelper.setValue('service_id', '123svc'); formHelper.expectError('service_id', 'mdsPattern'); formHelper.setValue('service_id', 'svc#1'); formHelper.expectError('service_id', 'mdsPattern'); }); }); describe('check edit fields', () => { beforeEach(() => { component.editing = true; }); it('should check whether edit field is correctly loaded', () => { const paginate_obs = new PaginateObservable<any>(of({})); const cephServiceSpy = spyOn(cephServiceService, 'list').and.returnValue(paginate_obs); component.ngOnInit(); expect(cephServiceSpy).toBeCalledTimes(2); expect(component.action).toBe('Edit'); const serviceType = fixture.debugElement.query(By.css('#service_type')).nativeElement; const serviceId = fixture.debugElement.query(By.css('#service_id')).nativeElement; expect(serviceType.disabled).toBeTruthy(); expect(serviceId.disabled).toBeTruthy(); }); }); }); });
20,236
33.126476
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/cluster/services/service-form/service-form.component.ts
import { HttpParams } from '@angular/common/http'; import { Component, Input, OnInit, ViewChild } from '@angular/core'; import { AbstractControl, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { NgbActiveModal, NgbModalRef, NgbTypeahead } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { forkJoin, merge, Observable, Subject, Subscription } from 'rxjs'; import { debounceTime, distinctUntilChanged, filter, map } from 'rxjs/operators'; import { CreateRgwServiceEntitiesComponent } from '~/app/ceph/rgw/create-rgw-service-entities/create-rgw-service-entities.component'; import { RgwRealm, RgwZonegroup, RgwZone } from '~/app/ceph/rgw/models/rgw-multisite'; import { CephServiceService } from '~/app/shared/api/ceph-service.service'; import { HostService } from '~/app/shared/api/host.service'; import { PoolService } from '~/app/shared/api/pool.service'; 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 { SelectMessages } from '~/app/shared/components/select/select-messages.model'; import { SelectOption } from '~/app/shared/components/select/select-option.model'; import { ActionLabelsI18n, TimerServiceInterval, URLVerbs } from '~/app/shared/constants/app.constants'; 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 { CephServiceSpec } from '~/app/shared/models/service.interface'; import { ModalService } from '~/app/shared/services/modal.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { TimerService } from '~/app/shared/services/timer.service'; @Component({ selector: 'cd-service-form', templateUrl: './service-form.component.html', styleUrls: ['./service-form.component.scss'] }) export class ServiceFormComponent extends CdForm implements OnInit { public sub = new Subscription(); readonly MDS_SVC_ID_PATTERN = /^[a-zA-Z_.-][a-zA-Z0-9_.-]*$/; readonly SNMP_DESTINATION_PATTERN = /^[^\:]+:[0-9]/; readonly SNMP_ENGINE_ID_PATTERN = /^[0-9A-Fa-f]{10,64}/g; readonly INGRESS_SUPPORTED_SERVICE_TYPES = ['rgw', 'nfs']; @ViewChild(NgbTypeahead, { static: false }) typeahead: NgbTypeahead; @Input() hiddenServices: string[] = []; @Input() editing = false; @Input() serviceName: string; @Input() serviceType: string; serviceForm: CdFormGroup; action: string; resource: string; serviceTypes: string[] = []; serviceIds: string[] = []; hosts: any; labels: string[]; labelClick = new Subject<string>(); labelFocus = new Subject<string>(); pools: Array<object>; services: Array<CephServiceSpec> = []; pageURL: string; serviceList: CephServiceSpec[]; multisiteInfo: object[] = []; defaultRealmId = ''; defaultZonegroupId = ''; defaultZoneId = ''; realmList: RgwRealm[] = []; zonegroupList: RgwZonegroup[] = []; zoneList: RgwZone[] = []; bsModalRef: NgbModalRef; defaultZonegroup: RgwZonegroup; showRealmCreationForm = false; defaultsInfo: { defaultRealmName: string; defaultZonegroupName: string; defaultZoneName: string }; realmNames: string[]; zonegroupNames: string[]; zoneNames: string[]; constructor( public actionLabels: ActionLabelsI18n, private cephServiceService: CephServiceService, private formBuilder: CdFormBuilder, private hostService: HostService, private poolService: PoolService, private router: Router, private taskWrapperService: TaskWrapperService, public timerService: TimerService, public timerServiceVariable: TimerServiceInterval, public rgwRealmService: RgwRealmService, public rgwZonegroupService: RgwZonegroupService, public rgwZoneService: RgwZoneService, public rgwMultisiteService: RgwMultisiteService, private route: ActivatedRoute, public activeModal: NgbActiveModal, public modalService: ModalService ) { super(); this.resource = $localize`service`; this.hosts = { options: [], messages: new SelectMessages({ empty: $localize`There are no hosts.`, filter: $localize`Filter hosts` }) }; this.createForm(); } createForm() { this.serviceForm = this.formBuilder.group({ // Global service_type: [null, [Validators.required]], service_id: [ null, [ CdValidators.composeIf( { service_type: 'mds' }, [ Validators.required, CdValidators.custom('mdsPattern', (value: string) => { if (_.isEmpty(value)) { return false; } return !this.MDS_SVC_ID_PATTERN.test(value); }) ] ), CdValidators.requiredIf({ service_type: 'nfs' }), CdValidators.requiredIf({ service_type: 'iscsi' }), CdValidators.requiredIf({ service_type: 'ingress' }), CdValidators.composeIf( { service_type: 'rgw' }, [Validators.required] ), CdValidators.custom('uniqueName', (service_id: string) => { return this.serviceIds && this.serviceIds.includes(service_id); }) ] ], placement: ['hosts'], label: [ null, [ CdValidators.requiredIf({ placement: 'label', unmanaged: false }) ] ], hosts: [[]], count: [null, [CdValidators.number(false)]], unmanaged: [false], // iSCSI pool: [ null, [ CdValidators.requiredIf({ service_type: 'iscsi' }) ] ], // RGW rgw_frontend_port: [null, [CdValidators.number(false)]], realm_name: [null], zonegroup_name: [null], zone_name: [null], // iSCSI trusted_ip_list: [null], api_port: [null, [CdValidators.number(false)]], api_user: [ null, [ CdValidators.requiredIf({ service_type: 'iscsi', unmanaged: false }) ] ], api_password: [ null, [ CdValidators.requiredIf({ service_type: 'iscsi', unmanaged: false }) ] ], // Ingress backend_service: [ null, [ CdValidators.requiredIf({ service_type: 'ingress' }) ] ], virtual_ip: [ null, [ CdValidators.requiredIf({ service_type: 'ingress' }) ] ], frontend_port: [ null, [ CdValidators.number(false), CdValidators.requiredIf({ service_type: 'ingress' }) ] ], monitor_port: [ null, [ CdValidators.number(false), CdValidators.requiredIf({ service_type: 'ingress' }) ] ], virtual_interface_networks: [null], // RGW, Ingress & iSCSI ssl: [false], ssl_cert: [ '', [ CdValidators.composeIf( { service_type: 'rgw', unmanaged: false, ssl: true }, [Validators.required, CdValidators.pemCert()] ), CdValidators.composeIf( { service_type: 'iscsi', unmanaged: false, ssl: true }, [Validators.required, CdValidators.sslCert()] ), CdValidators.composeIf( { service_type: 'ingress', unmanaged: false, ssl: true }, [Validators.required, CdValidators.pemCert()] ) ] ], ssl_key: [ '', [ CdValidators.composeIf( { service_type: 'iscsi', unmanaged: false, ssl: true }, [Validators.required, CdValidators.sslPrivKey()] ) ] ], // snmp-gateway snmp_version: [ null, [ CdValidators.requiredIf({ service_type: 'snmp-gateway' }) ] ], snmp_destination: [ null, { validators: [ CdValidators.requiredIf({ service_type: 'snmp-gateway' }), CdValidators.custom('snmpDestinationPattern', (value: string) => { if (_.isEmpty(value)) { return false; } return !this.SNMP_DESTINATION_PATTERN.test(value); }) ] } ], engine_id: [ null, [ CdValidators.requiredIf({ service_type: 'snmp-gateway' }), CdValidators.custom('snmpEngineIdPattern', (value: string) => { if (_.isEmpty(value)) { return false; } return !this.SNMP_ENGINE_ID_PATTERN.test(value); }) ] ], auth_protocol: [ 'SHA', [ CdValidators.requiredIf({ service_type: 'snmp-gateway' }) ] ], privacy_protocol: [null], snmp_community: [ null, [ CdValidators.requiredIf({ snmp_version: 'V2c' }) ] ], snmp_v3_auth_username: [ null, [ CdValidators.requiredIf({ service_type: 'snmp-gateway' }) ] ], snmp_v3_auth_password: [ null, [ CdValidators.requiredIf({ service_type: 'snmp-gateway' }) ] ], snmp_v3_priv_password: [ null, [ CdValidators.requiredIf({ privacy_protocol: { op: '!empty' } }) ] ], grafana_port: [null, [CdValidators.number(false)]], grafana_admin_password: [null] }); } ngOnInit(): void { this.action = this.actionLabels.CREATE; if (this.router.url.includes('services/(modal:create')) { this.pageURL = 'services'; } else if (this.router.url.includes('services/(modal:edit')) { this.editing = true; this.pageURL = 'services'; this.route.params.subscribe((params: { type: string; name: string }) => { this.serviceName = params.name; this.serviceType = params.type; }); } this.cephServiceService .list(new HttpParams({ fromObject: { limit: -1, offset: 0 } })) .observable.subscribe((services: CephServiceSpec[]) => { this.serviceList = services; this.services = services.filter((service: any) => this.INGRESS_SUPPORTED_SERVICE_TYPES.includes(service.service_type) ); }); this.cephServiceService.getKnownTypes().subscribe((resp: Array<string>) => { // Remove service types: // osd - This is deployed a different way. // container - This should only be used in the CLI. this.hiddenServices.push('osd', 'container'); this.serviceTypes = _.difference(resp, this.hiddenServices).sort(); }); this.hostService.list('false').subscribe((resp: object[]) => { const options: SelectOption[] = []; _.forEach(resp, (host: object) => { if (_.get(host, 'sources.orchestrator', false)) { const option = new SelectOption(false, _.get(host, 'hostname'), ''); options.push(option); } }); this.hosts.options = [...options]; }); this.hostService.getLabels().subscribe((resp: string[]) => { this.labels = resp; }); this.poolService.getList().subscribe((resp: Array<object>) => { this.pools = resp; }); if (this.editing) { this.action = this.actionLabels.EDIT; this.disableForEditing(this.serviceType); this.cephServiceService .list(new HttpParams({ fromObject: { limit: -1, offset: 0 } }), this.serviceName) .observable.subscribe((response: CephServiceSpec[]) => { const formKeys = ['service_type', 'service_id', 'unmanaged']; formKeys.forEach((keys) => { this.serviceForm.get(keys).setValue(response[0][keys]); }); if (!response[0]['unmanaged']) { const placementKey = Object.keys(response[0]['placement'])[0]; let placementValue: string; ['hosts', 'label'].indexOf(placementKey) >= 0 ? (placementValue = placementKey) : (placementValue = 'hosts'); this.serviceForm.get('placement').setValue(placementValue); this.serviceForm.get('count').setValue(response[0]['placement']['count']); if (response[0]?.placement[placementValue]) { this.serviceForm.get(placementValue).setValue(response[0]?.placement[placementValue]); } } switch (this.serviceType) { case 'iscsi': const specKeys = ['pool', 'api_password', 'api_user', 'trusted_ip_list', 'api_port']; specKeys.forEach((key) => { this.serviceForm.get(key).setValue(response[0].spec[key]); }); this.serviceForm.get('ssl').setValue(response[0].spec?.api_secure); if (response[0].spec?.api_secure) { this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert); this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key); } break; case 'rgw': this.serviceForm .get('rgw_frontend_port') .setValue(response[0].spec?.rgw_frontend_port); this.getServiceIds( 'rgw', response[0].spec?.rgw_realm, response[0].spec?.rgw_zonegroup, response[0].spec?.rgw_zone ); this.serviceForm.get('ssl').setValue(response[0].spec?.ssl); if (response[0].spec?.ssl) { this.serviceForm .get('ssl_cert') .setValue(response[0].spec?.rgw_frontend_ssl_certificate); } break; case 'ingress': const ingressSpecKeys = [ 'backend_service', 'virtual_ip', 'frontend_port', 'monitor_port', 'virtual_interface_networks', 'ssl' ]; ingressSpecKeys.forEach((key) => { this.serviceForm.get(key).setValue(response[0].spec[key]); }); if (response[0].spec?.ssl) { this.serviceForm.get('ssl_cert').setValue(response[0].spec?.ssl_cert); this.serviceForm.get('ssl_key').setValue(response[0].spec?.ssl_key); } break; case 'snmp-gateway': const snmpCommonSpecKeys = ['snmp_version', 'snmp_destination']; snmpCommonSpecKeys.forEach((key) => { this.serviceForm.get(key).setValue(response[0].spec[key]); }); if (this.serviceForm.getValue('snmp_version') === 'V3') { const snmpV3SpecKeys = [ 'engine_id', 'auth_protocol', 'privacy_protocol', 'snmp_v3_auth_username', 'snmp_v3_auth_password', 'snmp_v3_priv_password' ]; snmpV3SpecKeys.forEach((key) => { if (key !== null) { if ( key === 'snmp_v3_auth_username' || key === 'snmp_v3_auth_password' || key === 'snmp_v3_priv_password' ) { this.serviceForm.get(key).setValue(response[0].spec['credentials'][key]); } else { this.serviceForm.get(key).setValue(response[0].spec[key]); } } }); } else { this.serviceForm .get('snmp_community') .setValue(response[0].spec['credentials']['snmp_community']); } break; case 'grafana': this.serviceForm.get('grafana_port').setValue(response[0].spec.port); this.serviceForm .get('grafana_admin_password') .setValue(response[0].spec.initial_admin_password); break; } }); } } getDefaultsEntities( defaultRealmId: string, defaultZonegroupId: string, defaultZoneId: string ): { defaultRealmName: string; defaultZonegroupName: string; defaultZoneName: string } { const defaultRealm = this.realmList.find((x: { id: string }) => x.id === defaultRealmId); const defaultZonegroup = this.zonegroupList.find( (x: { id: string }) => x.id === defaultZonegroupId ); const defaultZone = this.zoneList.find((x: { id: string }) => x.id === defaultZoneId); const defaultRealmName = defaultRealm !== undefined ? defaultRealm.name : null; const defaultZonegroupName = defaultZonegroup !== undefined ? defaultZonegroup.name : 'default'; const defaultZoneName = defaultZone !== undefined ? defaultZone.name : 'default'; if (defaultZonegroupName === 'default' && !this.zonegroupNames.includes(defaultZonegroupName)) { const defaultZonegroup = new RgwZonegroup(); defaultZonegroup.name = 'default'; this.zonegroupList.push(defaultZonegroup); } if (defaultZoneName === 'default' && !this.zoneNames.includes(defaultZoneName)) { const defaultZone = new RgwZone(); defaultZone.name = 'default'; this.zoneList.push(defaultZone); } return { defaultRealmName: defaultRealmName, defaultZonegroupName: defaultZonegroupName, defaultZoneName: defaultZoneName }; } getServiceIds( selectedServiceType: string, realm_name?: string, zonegroup_name?: string, zone_name?: string ) { this.serviceIds = this.serviceList ?.filter((service) => service['service_type'] === selectedServiceType) .map((service) => service['service_id']); if (selectedServiceType === 'rgw') { const observables = [ this.rgwRealmService.getAllRealmsInfo(), this.rgwZonegroupService.getAllZonegroupsInfo(), this.rgwZoneService.getAllZonesInfo() ]; this.sub = forkJoin(observables).subscribe( (multisiteInfo: [object, object, object]) => { this.multisiteInfo = multisiteInfo; this.realmList = this.multisiteInfo[0] !== undefined && this.multisiteInfo[0].hasOwnProperty('realms') ? this.multisiteInfo[0]['realms'] : []; this.zonegroupList = this.multisiteInfo[1] !== undefined && this.multisiteInfo[1].hasOwnProperty('zonegroups') ? this.multisiteInfo[1]['zonegroups'] : []; this.zoneList = this.multisiteInfo[2] !== undefined && this.multisiteInfo[2].hasOwnProperty('zones') ? this.multisiteInfo[2]['zones'] : []; this.realmNames = this.realmList.map((realm) => { return realm['name']; }); this.zonegroupNames = this.zonegroupList.map((zonegroup) => { return zonegroup['name']; }); this.zoneNames = this.zoneList.map((zone) => { return zone['name']; }); this.defaultRealmId = multisiteInfo[0]['default_realm']; this.defaultZonegroupId = multisiteInfo[1]['default_zonegroup']; this.defaultZoneId = multisiteInfo[2]['default_zone']; this.defaultsInfo = this.getDefaultsEntities( this.defaultRealmId, this.defaultZonegroupId, this.defaultZoneId ); if (!this.editing) { this.serviceForm.get('realm_name').setValue(this.defaultsInfo['defaultRealmName']); this.serviceForm .get('zonegroup_name') .setValue(this.defaultsInfo['defaultZonegroupName']); this.serviceForm.get('zone_name').setValue(this.defaultsInfo['defaultZoneName']); } else { if (realm_name && !this.realmNames.includes(realm_name)) { const realm = new RgwRealm(); realm.name = realm_name; this.realmList.push(realm); } if (zonegroup_name && !this.zonegroupNames.includes(zonegroup_name)) { const zonegroup = new RgwZonegroup(); zonegroup.name = zonegroup_name; this.zonegroupList.push(zonegroup); } if (zone_name && !this.zoneNames.includes(zone_name)) { const zone = new RgwZone(); zone.name = zone_name; this.zoneList.push(zone); } if (zonegroup_name === undefined && zone_name === undefined) { zonegroup_name = 'default'; zone_name = 'default'; } this.serviceForm.get('realm_name').setValue(realm_name); this.serviceForm.get('zonegroup_name').setValue(zonegroup_name); this.serviceForm.get('zone_name').setValue(zone_name); } if (this.realmList.length === 0) { this.showRealmCreationForm = true; } else { this.showRealmCreationForm = false; } }, (_error) => { const defaultZone = new RgwZone(); defaultZone.name = 'default'; const defaultZonegroup = new RgwZonegroup(); defaultZonegroup.name = 'default'; this.zoneList.push(defaultZone); this.zonegroupList.push(defaultZonegroup); } ); } } disableForEditing(serviceType: string) { const disableForEditKeys = ['service_type', 'service_id']; disableForEditKeys.forEach((key) => { this.serviceForm.get(key).disable(); }); switch (serviceType) { case 'ingress': this.serviceForm.get('backend_service').disable(); } } searchLabels = (text$: Observable<string>) => { return merge( text$.pipe(debounceTime(200), distinctUntilChanged()), this.labelFocus, this.labelClick.pipe(filter(() => !this.typeahead.isPopupOpen())) ).pipe( map((value) => this.labels .filter((label: string) => label.toLowerCase().indexOf(value.toLowerCase()) > -1) .slice(0, 10) ) ); }; fileUpload(files: FileList, controlName: string) { const file: File = files[0]; const reader = new FileReader(); reader.addEventListener('load', (event: ProgressEvent<FileReader>) => { const control: AbstractControl = this.serviceForm.get(controlName); control.setValue(event.target.result); control.markAsDirty(); control.markAsTouched(); control.updateValueAndValidity(); }); reader.readAsText(file, 'utf8'); } prePopulateId() { const control: AbstractControl = this.serviceForm.get('service_id'); const backendService = this.serviceForm.getValue('backend_service'); // Set Id as read-only control.reset({ value: backendService, disabled: true }); } onSubmit() { const self = this; const values: object = this.serviceForm.getRawValue(); const serviceType: string = values['service_type']; let taskUrl = `service/${URLVerbs.CREATE}`; if (this.editing) { taskUrl = `service/${URLVerbs.EDIT}`; } const serviceSpec: object = { service_type: serviceType, placement: {}, unmanaged: values['unmanaged'] }; let svcId: string; if (serviceType === 'rgw') { serviceSpec['rgw_realm'] = values['realm_name'] ? values['realm_name'] : null; serviceSpec['rgw_zonegroup'] = values['zonegroup_name'] !== 'default' ? values['zonegroup_name'] : null; serviceSpec['rgw_zone'] = values['zone_name'] !== 'default' ? values['zone_name'] : null; svcId = values['service_id']; } else { svcId = values['service_id']; } const serviceId: string = svcId; let serviceName: string = serviceType; if (_.isString(serviceId) && !_.isEmpty(serviceId)) { serviceName = `${serviceType}.${serviceId}`; serviceSpec['service_id'] = serviceId; } // These services has some fields to be // filled out even if unmanaged is true switch (serviceType) { case 'ingress': serviceSpec['backend_service'] = values['backend_service']; serviceSpec['service_id'] = values['backend_service']; if (_.isNumber(values['frontend_port']) && values['frontend_port'] > 0) { serviceSpec['frontend_port'] = values['frontend_port']; } if (_.isString(values['virtual_ip']) && !_.isEmpty(values['virtual_ip'])) { serviceSpec['virtual_ip'] = values['virtual_ip'].trim(); } if (_.isNumber(values['monitor_port']) && values['monitor_port'] > 0) { serviceSpec['monitor_port'] = values['monitor_port']; } break; case 'iscsi': serviceSpec['pool'] = values['pool']; break; case 'snmp-gateway': serviceSpec['credentials'] = {}; serviceSpec['snmp_version'] = values['snmp_version']; serviceSpec['snmp_destination'] = values['snmp_destination']; if (values['snmp_version'] === 'V3') { serviceSpec['engine_id'] = values['engine_id']; serviceSpec['auth_protocol'] = values['auth_protocol']; serviceSpec['credentials']['snmp_v3_auth_username'] = values['snmp_v3_auth_username']; serviceSpec['credentials']['snmp_v3_auth_password'] = values['snmp_v3_auth_password']; if (values['privacy_protocol'] !== null) { serviceSpec['privacy_protocol'] = values['privacy_protocol']; serviceSpec['credentials']['snmp_v3_priv_password'] = values['snmp_v3_priv_password']; } } else { serviceSpec['credentials']['snmp_community'] = values['snmp_community']; } break; } if (!values['unmanaged']) { switch (values['placement']) { case 'hosts': if (values['hosts'].length > 0) { serviceSpec['placement']['hosts'] = values['hosts']; } break; case 'label': serviceSpec['placement']['label'] = values['label']; break; } if (_.isNumber(values['count']) && values['count'] > 0) { serviceSpec['placement']['count'] = values['count']; } switch (serviceType) { case 'rgw': if (_.isNumber(values['rgw_frontend_port']) && values['rgw_frontend_port'] > 0) { serviceSpec['rgw_frontend_port'] = values['rgw_frontend_port']; } serviceSpec['ssl'] = values['ssl']; if (values['ssl']) { serviceSpec['rgw_frontend_ssl_certificate'] = values['ssl_cert']?.trim(); } break; case 'iscsi': if (_.isString(values['trusted_ip_list']) && !_.isEmpty(values['trusted_ip_list'])) { serviceSpec['trusted_ip_list'] = values['trusted_ip_list'].trim(); } if (_.isNumber(values['api_port']) && values['api_port'] > 0) { serviceSpec['api_port'] = values['api_port']; } serviceSpec['api_user'] = values['api_user']; serviceSpec['api_password'] = values['api_password']; serviceSpec['api_secure'] = values['ssl']; if (values['ssl']) { serviceSpec['ssl_cert'] = values['ssl_cert']?.trim(); serviceSpec['ssl_key'] = values['ssl_key']?.trim(); } break; case 'ingress': serviceSpec['ssl'] = values['ssl']; if (values['ssl']) { serviceSpec['ssl_cert'] = values['ssl_cert']?.trim(); serviceSpec['ssl_key'] = values['ssl_key']?.trim(); } serviceSpec['virtual_interface_networks'] = values['virtual_interface_networks']; break; case 'grafana': serviceSpec['port'] = values['grafana_port']; serviceSpec['initial_admin_password'] = values['grafana_admin_password']; } } this.taskWrapperService .wrapTaskAroundCall({ task: new FinishedTask(taskUrl, { service_name: serviceName }), call: this.editing ? this.cephServiceService.update(serviceSpec) : this.cephServiceService.create(serviceSpec) }) .subscribe({ error() { self.serviceForm.setErrors({ cdSubmitButton: true }); }, complete: () => { this.pageURL === 'services' ? this.router.navigate([this.pageURL, { outlets: { modal: null } }]) : this.activeModal.close(); } }); } clearValidations() { const snmpVersion = this.serviceForm.getValue('snmp_version'); const privacyProtocol = this.serviceForm.getValue('privacy_protocol'); if (snmpVersion === 'V3') { this.serviceForm.get('snmp_community').clearValidators(); } else { this.serviceForm.get('engine_id').clearValidators(); this.serviceForm.get('auth_protocol').clearValidators(); this.serviceForm.get('privacy_protocol').clearValidators(); this.serviceForm.get('snmp_v3_auth_username').clearValidators(); this.serviceForm.get('snmp_v3_auth_password').clearValidators(); } if (privacyProtocol === null) { this.serviceForm.get('snmp_v3_priv_password').clearValidators(); } } createMultisiteSetup() { this.bsModalRef = this.modalService.show(CreateRgwServiceEntitiesComponent, { size: 'lg' }); this.bsModalRef.componentInstance.submitAction.subscribe(() => { this.getServiceIds('rgw'); }); } }
30,588
34.038946
133
ts