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/shared/api/monitor.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MonitorService { constructor(private http: HttpClient) {} getMonitor() { return this.http.get('api/monitor'); } }
272
18.5
50
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/motd.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { MotdService } from '~/app/shared/api/motd.service'; import { configureTestBed } from '~/testing/unit-test-helper'; describe('MotdService', () => { let service: MotdService; let httpTesting: HttpTestingController; configureTestBed({ imports: [HttpClientTestingModule], providers: [MotdService] }); beforeEach(() => { service = TestBed.inject(MotdService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should get MOTD', () => { service.get().subscribe(); const req = httpTesting.expectOne('ui-api/motd'); expect(req.request.method).toBe('GET'); }); });
897
24.657143
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/motd.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; export interface Motd { message: string; md5: string; severity: 'info' | 'warning' | 'danger'; // The expiration date in ISO 8601. Does not expire if empty. expires: string; } @Injectable({ providedIn: 'root' }) export class MotdService { private url = 'ui-api/motd'; constructor(private http: HttpClient) {} get(): Observable<Motd | null> { return this.http.get<Motd | null>(this.url); } }
550
20.192308
63
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/nfs.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { NfsService } from './nfs.service'; describe('NfsService', () => { let service: NfsService; let httpTesting: HttpTestingController; configureTestBed({ providers: [NfsService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(NfsService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call list', () => { service.list().subscribe(); const req = httpTesting.expectOne('api/nfs-ganesha/export'); expect(req.request.method).toBe('GET'); }); it('should call get', () => { service.get('cluster_id', 'export_id').subscribe(); const req = httpTesting.expectOne('api/nfs-ganesha/export/cluster_id/export_id'); expect(req.request.method).toBe('GET'); }); it('should call create', () => { service.create('foo').subscribe(); const req = httpTesting.expectOne('api/nfs-ganesha/export'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual('foo'); }); it('should call update', () => { service.update('cluster_id', 1, 'foo').subscribe(); const req = httpTesting.expectOne('api/nfs-ganesha/export/cluster_id/1'); expect(req.request.body).toEqual('foo'); expect(req.request.method).toBe('PUT'); }); it('should call delete', () => { service.delete('hostName', 'exportId').subscribe(); const req = httpTesting.expectOne('api/nfs-ganesha/export/hostName/exportId'); expect(req.request.method).toBe('DELETE'); }); it('should call lsDir', () => { service.lsDir('a', 'foo_dir').subscribe(); const req = httpTesting.expectOne('ui-api/nfs-ganesha/lsdir/a?root_dir=foo_dir'); expect(req.request.method).toBe('GET'); }); it('should not call lsDir if volume is not provided', fakeAsync(() => { service.lsDir('', 'foo_dir').subscribe({ error: (error: string) => expect(error).toEqual('Please specify a filesystem volume.') }); tick(); httpTesting.expectNone('ui-api/nfs-ganesha/lsdir/?root_dir=foo_dir'); })); });
2,392
30.906667
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/nfs.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, throwError } from 'rxjs'; import { NfsFSAbstractionLayer } from '~/app/ceph/nfs/models/nfs.fsal'; import { ApiClient } from '~/app/shared/api/api-client'; export interface Directory { paths: string[]; } @Injectable({ providedIn: 'root' }) export class NfsService extends ApiClient { apiPath = 'api/nfs-ganesha'; uiApiPath = 'ui-api/nfs-ganesha'; nfsAccessType = [ { value: 'RW', help: $localize`Allows all operations` }, { value: 'RO', help: $localize`Allows only operations that do not modify the server` }, { value: 'NONE', help: $localize`Allows no access at all` } ]; nfsFsal: NfsFSAbstractionLayer[] = [ { value: 'CEPH', descr: $localize`CephFS`, disabled: false }, { value: 'RGW', descr: $localize`Object Gateway`, disabled: false } ]; nfsSquash = { no_root_squash: ['no_root_squash', 'noidsquash', 'none'], root_id_squash: ['root_id_squash', 'rootidsquash', 'rootid'], root_squash: ['root_squash', 'rootsquash', 'root'], all_squash: ['all_squash', 'allsquash', 'all', 'allanonymous', 'all_anonymous'] }; constructor(private http: HttpClient) { super(); } list() { return this.http.get(`${this.apiPath}/export`); } get(clusterId: string, exportId: string) { return this.http.get(`${this.apiPath}/export/${clusterId}/${exportId}`); } create(nfs: any) { return this.http.post(`${this.apiPath}/export`, nfs, { headers: { Accept: this.getVersionHeaderValue(2, 0) }, observe: 'response' }); } update(clusterId: string, id: number, nfs: any) { return this.http.put(`${this.apiPath}/export/${clusterId}/${id}`, nfs, { headers: { Accept: this.getVersionHeaderValue(2, 0) }, observe: 'response' }); } delete(clusterId: string, exportId: string) { return this.http.delete(`${this.apiPath}/export/${clusterId}/${exportId}`, { headers: { Accept: this.getVersionHeaderValue(2, 0) }, observe: 'response' }); } listClusters() { return this.http.get(`${this.apiPath}/cluster`, { headers: { Accept: this.getVersionHeaderValue(0, 1) } }); } lsDir(fs_name: string, root_dir: string): Observable<Directory> { if (!fs_name) { return throwError($localize`Please specify a filesystem volume.`); } return this.http.get<Directory>(`${this.uiApiPath}/lsdir/${fs_name}?root_dir=${root_dir}`); } fsals() { return this.http.get(`${this.uiApiPath}/fsals`); } filesystems() { return this.http.get(`${this.uiApiPath}/cephfs/filesystems`); } }
2,750
24.238532
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/orchestrator.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { OrchestratorService } from './orchestrator.service'; describe('OrchestratorService', () => { let service: OrchestratorService; let httpTesting: HttpTestingController; const uiApiPath = 'ui-api/orchestrator'; configureTestBed({ providers: [OrchestratorService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(OrchestratorService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call status', () => { service.status().subscribe(); const req = httpTesting.expectOne(`${uiApiPath}/status`); expect(req.request.method).toBe('GET'); }); });
987
26.444444
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/orchestrator.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import _ from 'lodash'; import { Observable } from 'rxjs'; import { OrchestratorFeature } from '../models/orchestrator.enum'; import { OrchestratorStatus } from '../models/orchestrator.interface'; @Injectable({ providedIn: 'root' }) export class OrchestratorService { private url = 'ui-api/orchestrator'; disableMessages = { noOrchestrator: $localize`The feature is disabled because Orchestrator is not available.`, missingFeature: $localize`The Orchestrator backend doesn't support this feature.` }; constructor(private http: HttpClient) {} status(): Observable<OrchestratorStatus> { return this.http.get<OrchestratorStatus>(`${this.url}/status`); } hasFeature(status: OrchestratorStatus, features: OrchestratorFeature[]): boolean { return _.every(features, (feature) => _.get(status.features, `${feature}.available`)); } getTableActionDisableDesc( status: OrchestratorStatus, features: OrchestratorFeature[] ): boolean | string { if (!status) { return false; } if (!status.available) { return this.disableMessages.noOrchestrator; } if (!this.hasFeature(status, features)) { return this.disableMessages.missingFeature; } return false; } getName() { return this.http.get(`${this.url}/get_name`); } }
1,406
26.588235
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/osd.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { OsdService } from './osd.service'; describe('OsdService', () => { let service: OsdService; let httpTesting: HttpTestingController; configureTestBed({ providers: [OsdService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(OsdService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call create', () => { const trackingId = 'all_hdd, host1_ssd'; const post_data = { method: 'drive_groups', data: [ { service_name: 'osd', service_id: 'all_hdd', host_pattern: '*', data_devices: { rotational: true } }, { service_name: 'osd', service_id: 'host1_ssd', host_pattern: 'host1', data_devices: { rotational: false } } ], tracking_id: trackingId }; service.create(post_data.data, trackingId).subscribe(); const req = httpTesting.expectOne('api/osd'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual(post_data); }); it('should call delete', () => { const id = 1; service.delete(id, true, true).subscribe(); const req = httpTesting.expectOne(`api/osd/${id}?preserve_id=true&force=true`); expect(req.request.method).toBe('DELETE'); }); it('should call getList', () => { service.getList().subscribe(); const req = httpTesting.expectOne('api/osd'); expect(req.request.method).toBe('GET'); }); it('should call getDetails', () => { service.getDetails(1).subscribe(); const req = httpTesting.expectOne('api/osd/1'); expect(req.request.method).toBe('GET'); }); it('should call scrub, with deep=true', () => { service.scrub('foo', true).subscribe(); const req = httpTesting.expectOne('api/osd/foo/scrub?deep=true'); expect(req.request.method).toBe('POST'); }); it('should call scrub, with deep=false', () => { service.scrub('foo', false).subscribe(); const req = httpTesting.expectOne('api/osd/foo/scrub?deep=false'); expect(req.request.method).toBe('POST'); }); it('should call getFlags', () => { service.getFlags().subscribe(); const req = httpTesting.expectOne('api/osd/flags'); expect(req.request.method).toBe('GET'); }); it('should call updateFlags', () => { service.updateFlags(['foo']).subscribe(); const req = httpTesting.expectOne('api/osd/flags'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ flags: ['foo'] }); }); it('should call updateIndividualFlags to update individual flags', () => { const flags = { noin: true, noout: true }; const ids = [0, 1]; service.updateIndividualFlags(flags, ids).subscribe(); const req = httpTesting.expectOne('api/osd/flags/individual'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ flags: flags, ids: ids }); }); it('should mark the OSD out', () => { service.markOut(1).subscribe(); const req = httpTesting.expectOne('api/osd/1/mark'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ action: 'out' }); }); it('should mark the OSD in', () => { service.markIn(1).subscribe(); const req = httpTesting.expectOne('api/osd/1/mark'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ action: 'in' }); }); it('should mark the OSD down', () => { service.markDown(1).subscribe(); const req = httpTesting.expectOne('api/osd/1/mark'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ action: 'down' }); }); it('should reweight an OSD', () => { service.reweight(1, 0.5).subscribe(); const req = httpTesting.expectOne('api/osd/1/reweight'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ weight: 0.5 }); }); it('should update OSD', () => { service.update(1, 'hdd').subscribe(); const req = httpTesting.expectOne('api/osd/1'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ device_class: 'hdd' }); }); it('should mark an OSD lost', () => { service.markLost(1).subscribe(); const req = httpTesting.expectOne('api/osd/1/mark'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ action: 'lost' }); }); it('should purge an OSD', () => { service.purge(1).subscribe(); const req = httpTesting.expectOne('api/osd/1/purge'); expect(req.request.method).toBe('POST'); }); it('should destroy an OSD', () => { service.destroy(1).subscribe(); const req = httpTesting.expectOne('api/osd/1/destroy'); expect(req.request.method).toBe('POST'); }); it('should return if it is safe to destroy an OSD', () => { service.safeToDestroy('[0,1]').subscribe(); const req = httpTesting.expectOne('api/osd/safe_to_destroy?ids=[0,1]'); expect(req.request.method).toBe('GET'); }); it('should call the devices endpoint to retrieve smart data', () => { service.getDevices(1).subscribe(); const req = httpTesting.expectOne('api/osd/1/devices'); expect(req.request.method).toBe('GET'); }); it('should call getDeploymentOptions', () => { service.getDeploymentOptions().subscribe(); const req = httpTesting.expectOne('ui-api/osd/deployment_options'); expect(req.request.method).toBe('GET'); }); });
5,832
30.701087
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/osd.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import _ from 'lodash'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { CdDevice } from '../models/devices'; import { InventoryDeviceType } from '../models/inventory-device-type.model'; import { DeploymentOptions } from '../models/osd-deployment-options'; import { OsdSettings } from '../models/osd-settings'; import { SmartDataResponseV1 } from '../models/smart'; import { DeviceService } from '../services/device.service'; @Injectable({ providedIn: 'root' }) export class OsdService { private path = 'api/osd'; private uiPath = 'ui-api/osd'; osdDevices: InventoryDeviceType[] = []; osdRecvSpeedModalPriorities = { KNOWN_PRIORITIES: [ { name: null, text: $localize`-- Select the priority --`, values: { osd_max_backfills: null, osd_recovery_max_active: null, osd_recovery_max_single_start: null, osd_recovery_sleep: null } }, { name: 'low', text: $localize`Low`, values: { osd_max_backfills: 1, osd_recovery_max_active: 1, osd_recovery_max_single_start: 1, osd_recovery_sleep: 0.5 } }, { name: 'default', text: $localize`Default`, values: { osd_max_backfills: 1, osd_recovery_max_active: 3, osd_recovery_max_single_start: 1, osd_recovery_sleep: 0 } }, { name: 'high', text: $localize`High`, values: { osd_max_backfills: 4, osd_recovery_max_active: 4, osd_recovery_max_single_start: 4, osd_recovery_sleep: 0 } } ] }; constructor(private http: HttpClient, private deviceService: DeviceService) {} create(driveGroups: Object[], trackingId: string, method = 'drive_groups') { const request = { method: method, data: driveGroups, tracking_id: trackingId }; return this.http.post(this.path, request, { observe: 'response' }); } getList() { return this.http.get(`${this.path}`); } getOsdSettings(): Observable<OsdSettings> { return this.http.get<OsdSettings>(`${this.path}/settings`, { headers: { Accept: 'application/vnd.ceph.api.v0.1+json' } }); } getDetails(id: number) { interface OsdData { osd_map: { [key: string]: any }; osd_metadata: { [key: string]: any }; smart: { [device_identifier: string]: any }; } return this.http.get<OsdData>(`${this.path}/${id}`); } /** * @param id OSD ID */ getSmartData(id: number) { return this.http.get<SmartDataResponseV1>(`${this.path}/${id}/smart`); } scrub(id: string, deep: boolean) { return this.http.post(`${this.path}/${id}/scrub?deep=${deep}`, null); } getDeploymentOptions() { return this.http.get<DeploymentOptions>(`${this.uiPath}/deployment_options`); } getFlags() { return this.http.get(`${this.path}/flags`); } updateFlags(flags: string[]) { return this.http.put(`${this.path}/flags`, { flags: flags }); } updateIndividualFlags(flags: { [flag: string]: boolean }, ids: number[]) { return this.http.put(`${this.path}/flags/individual`, { flags: flags, ids: ids }); } markOut(id: number) { return this.http.put(`${this.path}/${id}/mark`, { action: 'out' }); } markIn(id: number) { return this.http.put(`${this.path}/${id}/mark`, { action: 'in' }); } markDown(id: number) { return this.http.put(`${this.path}/${id}/mark`, { action: 'down' }); } reweight(id: number, weight: number) { return this.http.post(`${this.path}/${id}/reweight`, { weight: weight }); } update(id: number, deviceClass: string) { return this.http.put(`${this.path}/${id}`, { device_class: deviceClass }); } markLost(id: number) { return this.http.put(`${this.path}/${id}/mark`, { action: 'lost' }); } purge(id: number) { return this.http.post(`${this.path}/${id}/purge`, null); } destroy(id: number) { return this.http.post(`${this.path}/${id}/destroy`, null); } delete(id: number, preserveId?: boolean, force?: boolean) { const params = { preserve_id: preserveId ? 'true' : 'false', force: force ? 'true' : 'false' }; return this.http.delete(`${this.path}/${id}`, { observe: 'response', params: params }); } safeToDestroy(ids: string) { interface SafeToDestroyResponse { active: number[]; missing_stats: number[]; stored_pgs: number[]; is_safe_to_destroy: boolean; message?: string; } return this.http.get<SafeToDestroyResponse>(`${this.path}/safe_to_destroy?ids=${ids}`); } safeToDelete(ids: string) { interface SafeToDeleteResponse { is_safe_to_delete: boolean; message?: string; } return this.http.get<SafeToDeleteResponse>(`${this.path}/safe_to_delete?svc_ids=${ids}`); } getDevices(osdId: number) { return this.http .get<CdDevice[]>(`${this.path}/${osdId}/devices`) .pipe(map((devices) => devices.map((device) => this.deviceService.prepareDevice(device)))); } }
5,236
26.418848
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/paginate.model.ts
import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; export class PaginateObservable<Type> { observable: Observable<Type>; count: number; constructor(obs: Observable<Type>) { this.observable = obs.pipe( map((response: any) => { this.count = Number(response.headers?.get('X-Total-Count')); return response['body']; }) ); } }
390
22
68
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/performance-counter.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { PerformanceCounterService } from './performance-counter.service'; describe('PerformanceCounterService', () => { let service: PerformanceCounterService; let httpTesting: HttpTestingController; configureTestBed({ providers: [PerformanceCounterService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(PerformanceCounterService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call list', () => { service.list().subscribe(); const req = httpTesting.expectOne('api/perf_counters'); expect(req.request.method).toBe('GET'); }); it('should call get', () => { let result; service.get('foo', '1').subscribe((resp) => { result = resp; }); const req = httpTesting.expectOne('api/perf_counters/foo/1'); expect(req.request.method).toBe('GET'); req.flush({ counters: [{ foo: 'bar' }] }); expect(result).toEqual([{ foo: 'bar' }]); }); });
1,312
27.543478
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/performance-counter.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { of as observableOf } from 'rxjs'; import { mergeMap } from 'rxjs/operators'; import { cdEncode } from '../decorators/cd-encode'; @cdEncode @Injectable({ providedIn: 'root' }) export class PerformanceCounterService { private url = 'api/perf_counters'; constructor(private http: HttpClient) {} list() { return this.http.get(this.url); } get(service_type: string, service_id: string) { return this.http.get(`${this.url}/${service_type}/${service_id}`).pipe( mergeMap((resp: any) => { return observableOf(resp['counters']); }) ); } }
686
21.9
75
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/pool.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdConfigurationSourceField } from '../models/configuration'; import { RbdConfigurationService } from '../services/rbd-configuration.service'; import { PoolService } from './pool.service'; describe('PoolService', () => { let service: PoolService; let httpTesting: HttpTestingController; const apiPath = 'api/pool'; configureTestBed({ providers: [PoolService, RbdConfigurationService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(PoolService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call getList', () => { service.getList().subscribe(); const req = httpTesting.expectOne(`${apiPath}?stats=true`); expect(req.request.method).toBe('GET'); }); it('should call getInfo', () => { service.getInfo().subscribe(); const req = httpTesting.expectOne(`ui-${apiPath}/info`); expect(req.request.method).toBe('GET'); }); it('should call create', () => { const pool = { pool: 'somePool' }; service.create(pool).subscribe(); const req = httpTesting.expectOne(apiPath); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual(pool); }); it('should call update', () => { service.update({ pool: 'somePool', application_metadata: [] }).subscribe(); const req = httpTesting.expectOne(`${apiPath}/somePool`); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ application_metadata: [] }); }); it('should call delete', () => { service.delete('somePool').subscribe(); const req = httpTesting.expectOne(`${apiPath}/somePool`); expect(req.request.method).toBe('DELETE'); }); it('should call list without parameter', fakeAsync(() => { let result; service.list().then((resp) => (result = resp)); const req = httpTesting.expectOne(`${apiPath}?attrs=`); expect(req.request.method).toBe('GET'); req.flush(['foo', 'bar']); tick(); expect(result).toEqual(['foo', 'bar']); })); it('should call list with a list', fakeAsync(() => { let result; service.list(['foo']).then((resp) => (result = resp)); const req = httpTesting.expectOne(`${apiPath}?attrs=foo`); expect(req.request.method).toBe('GET'); req.flush(['foo', 'bar']); tick(); expect(result).toEqual(['foo', 'bar']); })); it('should test injection of data from getConfiguration()', fakeAsync(() => { const pool = 'foo'; let value; service.getConfiguration(pool).subscribe((next) => (value = next)); const req = httpTesting.expectOne(`${apiPath}/${pool}/configuration`); expect(req.request.method).toBe('GET'); req.flush([ { name: 'rbd_qos_bps_limit', value: '60', source: RbdConfigurationSourceField.global }, { name: 'rbd_qos_iops_limit', value: '0', source: RbdConfigurationSourceField.global } ]); tick(); expect(value).toEqual([ { description: 'The desired limit of IO bytes per second.', displayName: 'BPS Limit', name: 'rbd_qos_bps_limit', source: RbdConfigurationSourceField.global, type: 0, value: '60' }, { description: 'The desired limit of IO operations per second.', displayName: 'IOPS Limit', name: 'rbd_qos_iops_limit', source: RbdConfigurationSourceField.global, type: 1, value: '0' } ]); })); });
3,838
29.959677
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/pool.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { cdEncode } from '../decorators/cd-encode'; import { RbdConfigurationEntry } from '../models/configuration'; import { RbdConfigurationService } from '../services/rbd-configuration.service'; @cdEncode @Injectable({ providedIn: 'root' }) export class PoolService { apiPath = 'api/pool'; constructor(private http: HttpClient, private rbdConfigurationService: RbdConfigurationService) {} create(pool: any) { return this.http.post(this.apiPath, pool, { observe: 'response' }); } update(pool: any) { let name: string; if (pool.hasOwnProperty('srcpool')) { name = pool.srcpool; delete pool.srcpool; } else { name = pool.pool; delete pool.pool; } return this.http.put(`${this.apiPath}/${encodeURIComponent(name)}`, pool, { observe: 'response' }); } delete(name: string) { return this.http.delete(`${this.apiPath}/${name}`, { observe: 'response' }); } get(poolName: string) { return this.http.get(`${this.apiPath}/${poolName}`); } getList() { return this.http.get(`${this.apiPath}?stats=true`); } getConfiguration(poolName: string): Observable<RbdConfigurationEntry[]> { return this.http.get<RbdConfigurationEntry[]>(`${this.apiPath}/${poolName}/configuration`).pipe( // Add static data maintained in RbdConfigurationService map((values) => values.map((entry) => Object.assign(entry, this.rbdConfigurationService.getOptionByName(entry.name)) ) ) ); } getInfo() { return this.http.get(`ui-${this.apiPath}/info`); } list(attrs: string[] = []) { const attrsStr = attrs.join(','); return this.http .get(`${this.apiPath}?attrs=${attrsStr}`) .toPromise() .then((resp: any) => { return resp; }); } }
1,976
25.36
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/prometheus.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { AlertmanagerNotification } from '../models/prometheus-alerts'; import { PrometheusService } from './prometheus.service'; import { SettingsService } from './settings.service'; describe('PrometheusService', () => { let service: PrometheusService; let httpTesting: HttpTestingController; configureTestBed({ providers: [PrometheusService, SettingsService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(PrometheusService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should get alerts', () => { service.getAlerts().subscribe(); const req = httpTesting.expectOne('api/prometheus'); expect(req.request.method).toBe('GET'); }); it('should get silences', () => { service.getSilences().subscribe(); const req = httpTesting.expectOne('api/prometheus/silences'); expect(req.request.method).toBe('GET'); }); it('should set a silence', () => { const silence = { id: 'someId', matchers: [ { name: 'getZero', value: 0, isRegex: false } ], startsAt: '2019-01-25T14:32:46.646300974Z', endsAt: '2019-01-25T18:32:46.646300974Z', createdBy: 'someCreator', comment: 'for testing purpose' }; service.setSilence(silence).subscribe(); const req = httpTesting.expectOne('api/prometheus/silence'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual(silence); }); it('should expire a silence', () => { service.expireSilence('someId').subscribe(); const req = httpTesting.expectOne('api/prometheus/silence/someId'); expect(req.request.method).toBe('DELETE'); }); it('should call getNotificationSince without a notification', () => { service.getNotifications().subscribe(); const req = httpTesting.expectOne('api/prometheus/notifications?from=last'); expect(req.request.method).toBe('GET'); }); it('should call getNotificationSince with notification', () => { service.getNotifications({ id: '42' } as AlertmanagerNotification).subscribe(); const req = httpTesting.expectOne('api/prometheus/notifications?from=42'); expect(req.request.method).toBe('GET'); }); describe('test getRules()', () => { let data: {}; // Subset of PrometheusRuleGroup to keep the tests concise. beforeEach(() => { data = { groups: [ { name: 'test', rules: [ { name: 'load_0', type: 'alerting' }, { name: 'load_1', type: 'alerting' }, { name: 'load_2', type: 'alerting' } ] }, { name: 'recording_rule', rules: [ { name: 'node_memory_MemUsed_percent', type: 'recording' } ] } ] }; }); it('should get rules without applying filters', () => { service.getRules().subscribe((rules) => { expect(rules).toEqual(data); }); const req = httpTesting.expectOne('api/prometheus/rules'); expect(req.request.method).toBe('GET'); req.flush(data); }); it('should get rewrite rules only', () => { service.getRules('rewrites').subscribe((rules) => { expect(rules).toEqual({ groups: [ { name: 'test', rules: [] }, { name: 'recording_rule', rules: [] } ] }); }); const req = httpTesting.expectOne('api/prometheus/rules'); expect(req.request.method).toBe('GET'); req.flush(data); }); it('should get alerting rules only', () => { service.getRules('alerting').subscribe((rules) => { expect(rules).toEqual({ groups: [ { name: 'test', rules: [ { name: 'load_0', type: 'alerting' }, { name: 'load_1', type: 'alerting' }, { name: 'load_2', type: 'alerting' } ] }, { name: 'recording_rule', rules: [] } ] }); }); const req = httpTesting.expectOne('api/prometheus/rules'); expect(req.request.method).toBe('GET'); req.flush(data); }); }); describe('ifAlertmanagerConfigured', () => { let x: any; let host: string; const receiveConfig = () => { const req = httpTesting.expectOne('ui-api/prometheus/alertmanager-api-host'); expect(req.request.method).toBe('GET'); req.flush({ value: host }); }; beforeEach(() => { x = false; TestBed.inject(SettingsService)['settings'] = {}; service.ifAlertmanagerConfigured( (v) => (x = v), () => (x = []) ); host = 'http://localhost:9093'; }); it('changes x in a valid case', () => { expect(x).toBe(false); receiveConfig(); expect(x).toBe(host); }); it('does changes x an empty array in a invalid case', () => { host = ''; receiveConfig(); expect(x).toEqual([]); }); it('disables the set setting', () => { receiveConfig(); service.disableAlertmanagerConfig(); x = false; service.ifAlertmanagerConfigured((v) => (x = v)); expect(x).toBe(false); }); }); describe('ifPrometheusConfigured', () => { let x: any; let host: string; const receiveConfig = () => { const req = httpTesting.expectOne('ui-api/prometheus/prometheus-api-host'); expect(req.request.method).toBe('GET'); req.flush({ value: host }); }; beforeEach(() => { x = false; TestBed.inject(SettingsService)['settings'] = {}; service.ifPrometheusConfigured( (v) => (x = v), () => (x = []) ); host = 'http://localhost:9090'; }); it('changes x in a valid case', () => { expect(x).toBe(false); receiveConfig(); expect(x).toBe(host); }); it('does changes x an empty array in a invalid case', () => { host = ''; receiveConfig(); expect(x).toEqual([]); }); it('disables the set setting', () => { receiveConfig(); service.disablePrometheusConfig(); x = false; service.ifPrometheusConfigured((v) => (x = v)); expect(x).toBe(false); }); }); });
6,817
26.491935
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/prometheus.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; import { AlertmanagerSilence } from '../models/alertmanager-silence'; import { AlertmanagerAlert, AlertmanagerNotification, PrometheusRuleGroup } from '../models/prometheus-alerts'; @Injectable({ providedIn: 'root' }) export class PrometheusService { private baseURL = 'api/prometheus'; private settingsKey = { alertmanager: 'ui-api/prometheus/alertmanager-api-host', prometheus: 'ui-api/prometheus/prometheus-api-host' }; private settings: { [url: string]: string } = {}; constructor(private http: HttpClient) {} getPrometheusData(params: any): any { return this.http.get<any>(`${this.baseURL}/data`, { params }); } ifAlertmanagerConfigured(fn: (value?: string) => void, elseFn?: () => void): void { this.ifSettingConfigured(this.settingsKey.alertmanager, fn, elseFn); } disableAlertmanagerConfig(): void { this.disableSetting(this.settingsKey.alertmanager); } ifPrometheusConfigured(fn: (value?: string) => void, elseFn?: () => void): void { this.ifSettingConfigured(this.settingsKey.prometheus, fn, elseFn); } disablePrometheusConfig(): void { this.disableSetting(this.settingsKey.prometheus); } getAlerts(params = {}): Observable<AlertmanagerAlert[]> { return this.http.get<AlertmanagerAlert[]>(this.baseURL, { params }); } getSilences(params = {}): Observable<AlertmanagerSilence[]> { return this.http.get<AlertmanagerSilence[]>(`${this.baseURL}/silences`, { params }); } getRules( type: 'all' | 'alerting' | 'rewrites' = 'all' ): Observable<{ groups: PrometheusRuleGroup[] }> { return this.http.get<{ groups: PrometheusRuleGroup[] }>(`${this.baseURL}/rules`).pipe( map((rules) => { if (['alerting', 'rewrites'].includes(type)) { rules.groups.map((group) => { group.rules = group.rules.filter((rule) => rule.type === type); }); } return rules; }) ); } setSilence(silence: AlertmanagerSilence) { return this.http.post<object>(`${this.baseURL}/silence`, silence, { observe: 'response' }); } expireSilence(silenceId: string) { return this.http.delete(`${this.baseURL}/silence/${silenceId}`, { observe: 'response' }); } getNotifications( notification?: AlertmanagerNotification ): Observable<AlertmanagerNotification[]> { const url = `${this.baseURL}/notifications?from=${ notification && notification.id ? notification.id : 'last' }`; return this.http.get<AlertmanagerNotification[]>(url); } ifSettingConfigured(url: string, fn: (value?: string) => void, elseFn?: () => void): void { const setting = this.settings[url]; if (setting === undefined) { this.http.get(url).subscribe( (data: any) => { this.settings[url] = this.getSettingsValue(data); this.ifSettingConfigured(url, fn, elseFn); }, (resp) => { if (resp.status !== 401) { this.settings[url] = ''; } } ); } else if (setting !== '') { fn(setting); } else { if (elseFn) { elseFn(); } } } // Easiest way to stop reloading external content that can't be reached disableSetting(url: string) { this.settings[url] = ''; } private getSettingsValue(data: any): string { return data.value || data.instance || ''; } }
3,529
28.663866
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rbd-mirroring.service.spec.ts
import { HttpRequest } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController, TestRequest } from '@angular/common/http/testing'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RbdMirroringService } from './rbd-mirroring.service'; describe('RbdMirroringService', () => { let service: RbdMirroringService; let httpTesting: HttpTestingController; let getMirroringSummaryCalls: () => TestRequest[]; let flushCalls: (call: TestRequest) => void; const summary: Record<string, any> = { status: 0, content_data: { daemons: [], pools: [], image_error: [], image_syncing: [], image_ready: [] }, executing_tasks: [{}] }; configureTestBed({ providers: [RbdMirroringService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(RbdMirroringService); httpTesting = TestBed.inject(HttpTestingController); getMirroringSummaryCalls = () => { return httpTesting.match((request: HttpRequest<any>) => { return request.url.match(/api\/block\/mirroring\/summary/) && request.method === 'GET'; }); }; flushCalls = (call: TestRequest) => { if (!call.cancelled) { call.flush(summary); } }; }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should periodically poll summary', fakeAsync(() => { const subs = service.startPolling(); tick(); const calledWith: any[] = []; service.subscribeSummary((data) => { calledWith.push(data); }); tick(service.REFRESH_INTERVAL * 2); const calls = getMirroringSummaryCalls(); expect(calls.length).toEqual(3); calls.forEach((call: TestRequest) => flushCalls(call)); expect(calledWith).toEqual([summary]); subs.unsubscribe(); })); it('should get pool config', () => { service.getPool('poolName').subscribe(); const req = httpTesting.expectOne('api/block/mirroring/pool/poolName'); expect(req.request.method).toBe('GET'); }); it('should update pool config', () => { const request = { mirror_mode: 'pool' }; service.updatePool('poolName', request).subscribe(); const req = httpTesting.expectOne('api/block/mirroring/pool/poolName'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual(request); }); it('should get site name', () => { service.getSiteName().subscribe(); const req = httpTesting.expectOne('api/block/mirroring/site_name'); expect(req.request.method).toBe('GET'); }); it('should set site name', () => { service.setSiteName('site-a').subscribe(); const req = httpTesting.expectOne('api/block/mirroring/site_name'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ site_name: 'site-a' }); }); it('should create bootstrap token', () => { service.createBootstrapToken('poolName').subscribe(); const req = httpTesting.expectOne('api/block/mirroring/pool/poolName/bootstrap/token'); expect(req.request.method).toBe('POST'); }); it('should import bootstrap token', () => { service.importBootstrapToken('poolName', 'rx', 'token-1234').subscribe(); const req = httpTesting.expectOne('api/block/mirroring/pool/poolName/bootstrap/peer'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ direction: 'rx', token: 'token-1234' }); }); it('should get peer config', () => { service.getPeer('poolName', 'peerUUID').subscribe(); const req = httpTesting.expectOne('api/block/mirroring/pool/poolName/peer/peerUUID'); expect(req.request.method).toBe('GET'); }); it('should add peer config', () => { const request = { cluster_name: 'remote', client_id: 'admin', mon_host: 'localhost', key: '1234' }; service.addPeer('poolName', request).subscribe(); const req = httpTesting.expectOne('api/block/mirroring/pool/poolName/peer'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual(request); }); it('should update peer config', () => { const request = { cluster_name: 'remote' }; service.updatePeer('poolName', 'peerUUID', request).subscribe(); const req = httpTesting.expectOne('api/block/mirroring/pool/poolName/peer/peerUUID'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual(request); }); it('should delete peer config', () => { service.deletePeer('poolName', 'peerUUID').subscribe(); const req = httpTesting.expectOne('api/block/mirroring/pool/poolName/peer/peerUUID'); expect(req.request.method).toBe('DELETE'); }); });
4,861
28.466667
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rbd-mirroring.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable, Subscription } from 'rxjs'; import { filter } from 'rxjs/operators'; import { cdEncode, cdEncodeNot } from '../decorators/cd-encode'; import { MirroringSummary } from '../models/mirroring-summary'; import { TimerService } from '../services/timer.service'; @cdEncode @Injectable({ providedIn: 'root' }) export class RbdMirroringService { readonly REFRESH_INTERVAL = 30000; // Observable sources private summaryDataSource = new BehaviorSubject<MirroringSummary>(null); // Observable streams summaryData$ = this.summaryDataSource.asObservable(); constructor(private http: HttpClient, private timerService: TimerService) {} startPolling(): Subscription { return this.timerService .get(() => this.retrieveSummaryObservable(), this.REFRESH_INTERVAL) .subscribe(this.retrieveSummaryObserver()); } refresh(): Subscription { return this.retrieveSummaryObservable().subscribe(this.retrieveSummaryObserver()); } private retrieveSummaryObservable(): Observable<MirroringSummary> { return this.http.get('api/block/mirroring/summary'); } private retrieveSummaryObserver(): (data: MirroringSummary) => void { return (data: any) => { this.summaryDataSource.next(data); }; } /** * Subscribes to the summaryData, * which is updated periodically or when a new task is created. */ subscribeSummary( next: (summary: MirroringSummary) => void, error?: (error: any) => void ): Subscription { return this.summaryData$.pipe(filter((value) => !!value)).subscribe(next, error); } getPool(poolName: string) { return this.http.get(`api/block/mirroring/pool/${poolName}`); } updatePool(poolName: string, request: any) { return this.http.put(`api/block/mirroring/pool/${poolName}`, request, { observe: 'response' }); } getSiteName() { return this.http.get(`api/block/mirroring/site_name`); } setSiteName(@cdEncodeNot siteName: string) { return this.http.put( `api/block/mirroring/site_name`, { site_name: siteName }, { observe: 'response' } ); } createBootstrapToken(poolName: string) { return this.http.post(`api/block/mirroring/pool/${poolName}/bootstrap/token`, {}); } importBootstrapToken( poolName: string, @cdEncodeNot direction: string, @cdEncodeNot token: string ) { const request = { direction: direction, token: token }; return this.http.post(`api/block/mirroring/pool/${poolName}/bootstrap/peer`, request, { observe: 'response' }); } getPeer(poolName: string, peerUUID: string) { return this.http.get(`api/block/mirroring/pool/${poolName}/peer/${peerUUID}`); } getPeerForPool(poolName: string) { return this.http.get(`api/block/mirroring/pool/${poolName}/peer`); } addPeer(poolName: string, request: any) { return this.http.post(`api/block/mirroring/pool/${poolName}/peer`, request, { observe: 'response' }); } updatePeer(poolName: string, peerUUID: string, request: any) { return this.http.put(`api/block/mirroring/pool/${poolName}/peer/${peerUUID}`, request, { observe: 'response' }); } deletePeer(poolName: string, peerUUID: string) { return this.http.delete(`api/block/mirroring/pool/${poolName}/peer/${peerUUID}`, { observe: 'response' }); } }
3,463
28.109244
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rbd.model.ts
import { RbdConfigurationEntry } from '../models/configuration'; export interface RbdPool { pool_name: string; status: number; value: RbdImage[]; headers: any; } export interface RbdImage { disk_usage: number; stripe_unit: number; name: string; parent: any; pool_name: string; num_objs: number; block_name_prefix: string; snapshots: any[]; obj_size: number; data_pool: string; total_disk_usage: number; features: number; configuration: RbdConfigurationEntry[]; timestamp: string; id: string; features_name: string[]; stripe_count: number; order: number; size: number; }
618
18.967742
64
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rbd.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { configureTestBed } from '~/testing/unit-test-helper'; import { ImageSpec } from '../models/image-spec'; import { RbdConfigurationService } from '../services/rbd-configuration.service'; import { RbdService } from './rbd.service'; describe('RbdService', () => { let service: RbdService; let httpTesting: HttpTestingController; configureTestBed({ providers: [RbdService, RbdConfigurationService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(RbdService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call create', () => { service.create('foo').subscribe(); const req = httpTesting.expectOne('api/block/image'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual('foo'); }); it('should call delete', () => { service.delete(new ImageSpec('poolName', null, 'rbdName')).subscribe(); const req = httpTesting.expectOne('api/block/image/poolName%2FrbdName'); expect(req.request.method).toBe('DELETE'); }); it('should call update', () => { service.update(new ImageSpec('poolName', null, 'rbdName'), 'foo').subscribe(); const req = httpTesting.expectOne('api/block/image/poolName%2FrbdName'); expect(req.request.body).toEqual('foo'); expect(req.request.method).toBe('PUT'); }); it('should call get', () => { service.get(new ImageSpec('poolName', null, 'rbdName')).subscribe(); const req = httpTesting.expectOne('api/block/image/poolName%2FrbdName'); expect(req.request.method).toBe('GET'); }); it('should call list', () => { /* tslint:disable:no-empty */ const context = new CdTableFetchDataContext(() => {}); service.list(context.toParams()).subscribe(); const req = httpTesting.expectOne('api/block/image?offset=0&limit=10&search=&sort=+name'); expect(req.request.method).toBe('GET'); }); it('should call copy', () => { service.copy(new ImageSpec('poolName', null, 'rbdName'), 'foo').subscribe(); const req = httpTesting.expectOne('api/block/image/poolName%2FrbdName/copy'); expect(req.request.body).toEqual('foo'); expect(req.request.method).toBe('POST'); }); it('should call flatten', () => { service.flatten(new ImageSpec('poolName', null, 'rbdName')).subscribe(); const req = httpTesting.expectOne('api/block/image/poolName%2FrbdName/flatten'); expect(req.request.body).toEqual(null); expect(req.request.method).toBe('POST'); }); it('should call defaultFeatures', () => { service.defaultFeatures().subscribe(); const req = httpTesting.expectOne('api/block/image/default_features'); expect(req.request.method).toBe('GET'); }); it('should call cloneFormatVersion', () => { service.cloneFormatVersion().subscribe(); const req = httpTesting.expectOne('api/block/image/clone_format_version'); expect(req.request.method).toBe('GET'); }); it('should call createSnapshot', () => { service .createSnapshot(new ImageSpec('poolName', null, 'rbdName'), 'snapshotName', false) .subscribe(); const req = httpTesting.expectOne('api/block/image/poolName%2FrbdName/snap'); expect(req.request.body).toEqual({ snapshot_name: 'snapshotName', mirrorImageSnapshot: false }); expect(req.request.method).toBe('POST'); }); it('should call renameSnapshot', () => { service .renameSnapshot(new ImageSpec('poolName', null, 'rbdName'), 'snapshotName', 'foo') .subscribe(); const req = httpTesting.expectOne('api/block/image/poolName%2FrbdName/snap/snapshotName'); expect(req.request.body).toEqual({ new_snap_name: 'foo' }); expect(req.request.method).toBe('PUT'); }); it('should call protectSnapshot', () => { service .protectSnapshot(new ImageSpec('poolName', null, 'rbdName'), 'snapshotName', true) .subscribe(); const req = httpTesting.expectOne('api/block/image/poolName%2FrbdName/snap/snapshotName'); expect(req.request.body).toEqual({ is_protected: true }); expect(req.request.method).toBe('PUT'); }); it('should call rollbackSnapshot', () => { service .rollbackSnapshot(new ImageSpec('poolName', null, 'rbdName'), 'snapshotName') .subscribe(); const req = httpTesting.expectOne( 'api/block/image/poolName%2FrbdName/snap/snapshotName/rollback' ); expect(req.request.body).toEqual(null); expect(req.request.method).toBe('POST'); }); it('should call cloneSnapshot', () => { service .cloneSnapshot(new ImageSpec('poolName', null, 'rbdName'), 'snapshotName', null) .subscribe(); const req = httpTesting.expectOne('api/block/image/poolName%2FrbdName/snap/snapshotName/clone'); expect(req.request.body).toEqual(null); expect(req.request.method).toBe('POST'); }); it('should call deleteSnapshot', () => { service.deleteSnapshot(new ImageSpec('poolName', null, 'rbdName'), 'snapshotName').subscribe(); const req = httpTesting.expectOne('api/block/image/poolName%2FrbdName/snap/snapshotName'); expect(req.request.method).toBe('DELETE'); }); it('should call moveTrash', () => { service.moveTrash(new ImageSpec('poolName', null, 'rbdName'), 1).subscribe(); const req = httpTesting.expectOne('api/block/image/poolName%2FrbdName/move_trash'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ delay: 1 }); }); describe('should compose image spec', () => { it('with namespace', () => { expect(new ImageSpec('mypool', 'myns', 'myimage').toString()).toBe('mypool/myns/myimage'); }); it('without namespace', () => { expect(new ImageSpec('mypool', null, 'myimage').toString()).toBe('mypool/myimage'); }); }); describe('should parse image spec', () => { it('with namespace', () => { const imageSpec = ImageSpec.fromString('mypool/myns/myimage'); expect(imageSpec.poolName).toBe('mypool'); expect(imageSpec.namespace).toBe('myns'); expect(imageSpec.imageName).toBe('myimage'); }); it('without namespace', () => { const imageSpec = ImageSpec.fromString('mypool/myimage'); expect(imageSpec.poolName).toBe('mypool'); expect(imageSpec.namespace).toBeNull(); expect(imageSpec.imageName).toBe('myimage'); }); }); });
6,706
35.254054
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rbd.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import _ from 'lodash'; import { map } from 'rxjs/operators'; import { ApiClient } from '~/app/shared/api/api-client'; import { cdEncode, cdEncodeNot } from '../decorators/cd-encode'; import { ImageSpec } from '../models/image-spec'; import { RbdConfigurationService } from '../services/rbd-configuration.service'; import { RbdPool } from './rbd.model'; @cdEncode @Injectable({ providedIn: 'root' }) export class RbdService extends ApiClient { constructor(private http: HttpClient, private rbdConfigurationService: RbdConfigurationService) { super(); } isRBDPool(pool: any) { return _.indexOf(pool.application_metadata, 'rbd') !== -1 && !pool.pool_name.includes('/'); } create(rbd: any) { return this.http.post('api/block/image', rbd, { observe: 'response' }); } delete(imageSpec: ImageSpec) { return this.http.delete(`api/block/image/${imageSpec.toStringEncoded()}`, { observe: 'response' }); } update(imageSpec: ImageSpec, rbd: any) { return this.http.put(`api/block/image/${imageSpec.toStringEncoded()}`, rbd, { observe: 'response' }); } get(imageSpec: ImageSpec) { return this.http.get(`api/block/image/${imageSpec.toStringEncoded()}`); } list(params: any) { return this.http .get<RbdPool[]>('api/block/image', { params: params, headers: { Accept: this.getVersionHeaderValue(2, 0) }, observe: 'response' }) .pipe( map((response: any) => { return response['body'].map((pool: any) => { pool.value.map((image: any) => { if (!image.configuration) { return image; } image.configuration.map((option: any) => Object.assign(option, this.rbdConfigurationService.getOptionByName(option.name)) ); return image; }); pool['headers'] = response.headers; return pool; }); }) ); } copy(imageSpec: ImageSpec, rbd: any) { return this.http.post(`api/block/image/${imageSpec.toStringEncoded()}/copy`, rbd, { observe: 'response' }); } flatten(imageSpec: ImageSpec) { return this.http.post(`api/block/image/${imageSpec.toStringEncoded()}/flatten`, null, { observe: 'response' }); } defaultFeatures() { return this.http.get('api/block/image/default_features'); } cloneFormatVersion() { return this.http.get<number>('api/block/image/clone_format_version'); } createSnapshot( imageSpec: ImageSpec, @cdEncodeNot snapshotName: string, mirrorImageSnapshot: boolean ) { const request = { snapshot_name: snapshotName, mirrorImageSnapshot: mirrorImageSnapshot }; return this.http.post(`api/block/image/${imageSpec.toStringEncoded()}/snap`, request, { observe: 'response' }); } renameSnapshot(imageSpec: ImageSpec, snapshotName: string, @cdEncodeNot newSnapshotName: string) { const request = { new_snap_name: newSnapshotName }; return this.http.put( `api/block/image/${imageSpec.toStringEncoded()}/snap/${snapshotName}`, request, { observe: 'response' } ); } protectSnapshot(imageSpec: ImageSpec, snapshotName: string, @cdEncodeNot isProtected: boolean) { const request = { is_protected: isProtected }; return this.http.put( `api/block/image/${imageSpec.toStringEncoded()}/snap/${snapshotName}`, request, { observe: 'response' } ); } rollbackSnapshot(imageSpec: ImageSpec, snapshotName: string) { return this.http.post( `api/block/image/${imageSpec.toStringEncoded()}/snap/${snapshotName}/rollback`, null, { observe: 'response' } ); } cloneSnapshot(imageSpec: ImageSpec, snapshotName: string, request: any) { return this.http.post( `api/block/image/${imageSpec.toStringEncoded()}/snap/${snapshotName}/clone`, request, { observe: 'response' } ); } deleteSnapshot(imageSpec: ImageSpec, snapshotName: string) { return this.http.delete(`api/block/image/${imageSpec.toStringEncoded()}/snap/${snapshotName}`, { observe: 'response' }); } listTrash() { return this.http.get(`api/block/image/trash/`); } createNamespace(pool: string, namespace: string) { const request = { namespace: namespace }; return this.http.post(`api/block/pool/${pool}/namespace`, request, { observe: 'response' }); } listNamespaces(pool: string) { return this.http.get(`api/block/pool/${pool}/namespace/`); } deleteNamespace(pool: string, namespace: string) { return this.http.delete(`api/block/pool/${pool}/namespace/${namespace}`, { observe: 'response' }); } moveTrash(imageSpec: ImageSpec, delay: number) { return this.http.post( `api/block/image/${imageSpec.toStringEncoded()}/move_trash`, { delay: delay }, { observe: 'response' } ); } purgeTrash(poolName: string) { return this.http.post(`api/block/image/trash/purge/?pool_name=${poolName}`, null, { observe: 'response' }); } restoreTrash(imageSpec: ImageSpec, @cdEncodeNot newImageName: string) { return this.http.post( `api/block/image/trash/${imageSpec.toStringEncoded()}/restore`, { new_image_name: newImageName }, { observe: 'response' } ); } removeTrash(imageSpec: ImageSpec, force = false) { return this.http.delete( `api/block/image/trash/${imageSpec.toStringEncoded()}/?force=${force}`, { observe: 'response' } ); } }
5,712
27.004902
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-bucket.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed, RgwHelper } from '~/testing/unit-test-helper'; import { RgwBucketService } from './rgw-bucket.service'; describe('RgwBucketService', () => { let service: RgwBucketService; let httpTesting: HttpTestingController; configureTestBed({ providers: [RgwBucketService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(RgwBucketService); httpTesting = TestBed.inject(HttpTestingController); RgwHelper.selectDaemon(); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call list', () => { service.list().subscribe(); const req = httpTesting.expectOne(`api/rgw/bucket?${RgwHelper.DAEMON_QUERY_PARAM}&stats=false`); expect(req.request.method).toBe('GET'); }); it('should call list with stats and user id', () => { service.list(true, 'test-name').subscribe(); const req = httpTesting.expectOne( `api/rgw/bucket?${RgwHelper.DAEMON_QUERY_PARAM}&stats=true&uid=test-name` ); expect(req.request.method).toBe('GET'); }); it('should call get', () => { service.get('foo').subscribe(); const req = httpTesting.expectOne(`api/rgw/bucket/foo?${RgwHelper.DAEMON_QUERY_PARAM}`); expect(req.request.method).toBe('GET'); }); it('should call create', () => { service .create( 'foo', 'bar', 'default', 'default-placement', false, 'COMPLIANCE', '5', true, 'aws:kms', 'qwerty1' ) .subscribe(); const req = httpTesting.expectOne( `api/rgw/bucket?bucket=foo&uid=bar&zonegroup=default&placement_target=default-placement&lock_enabled=false&lock_mode=COMPLIANCE&lock_retention_period_days=5&encryption_state=true&encryption_type=aws%253Akms&key_id=qwerty1&${RgwHelper.DAEMON_QUERY_PARAM}` ); expect(req.request.method).toBe('POST'); }); it('should call update', () => { service .update( 'foo', 'bar', 'baz', 'Enabled', true, 'aws:kms', 'qwerty1', 'Enabled', '1', '223344', 'GOVERNANCE', '10' ) .subscribe(); const req = httpTesting.expectOne( `api/rgw/bucket/foo?${RgwHelper.DAEMON_QUERY_PARAM}&bucket_id=bar&uid=baz&versioning_state=Enabled&encryption_state=true&encryption_type=aws%253Akms&key_id=qwerty1&mfa_delete=Enabled&mfa_token_serial=1&mfa_token_pin=223344&lock_mode=GOVERNANCE&lock_retention_period_days=10` ); expect(req.request.method).toBe('PUT'); }); it('should call delete, with purgeObjects = true', () => { service.delete('foo').subscribe(); const req = httpTesting.expectOne( `api/rgw/bucket/foo?${RgwHelper.DAEMON_QUERY_PARAM}&purge_objects=true` ); expect(req.request.method).toBe('DELETE'); }); it('should call delete, with purgeObjects = false', () => { service.delete('foo', false).subscribe(); const req = httpTesting.expectOne( `api/rgw/bucket/foo?${RgwHelper.DAEMON_QUERY_PARAM}&purge_objects=false` ); expect(req.request.method).toBe('DELETE'); }); it('should call exists', () => { let result; service.exists('foo').subscribe((resp) => { result = resp; }); const req = httpTesting.expectOne(`api/rgw/bucket/foo?${RgwHelper.DAEMON_QUERY_PARAM}`); expect(req.request.method).toBe('GET'); req.flush(['foo', 'bar']); expect(result).toBe(true); }); it('should convert lock retention period to days', () => { expect(service.getLockDays({ lock_retention_period_years: 1000 })).toBe(365242); expect(service.getLockDays({ lock_retention_period_days: 5 })).toBe(5); expect(service.getLockDays({})).toBe(0); }); });
3,967
30.244094
280
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-bucket.service.ts
import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import _ from 'lodash'; import { of as observableOf } from 'rxjs'; import { catchError, mapTo } from 'rxjs/operators'; import { ApiClient } from '~/app/shared/api/api-client'; import { RgwDaemonService } from '~/app/shared/api/rgw-daemon.service'; import { cdEncode } from '~/app/shared/decorators/cd-encode'; @cdEncode @Injectable({ providedIn: 'root' }) export class RgwBucketService extends ApiClient { private url = 'api/rgw/bucket'; constructor(private http: HttpClient, private rgwDaemonService: RgwDaemonService) { super(); } /** * Get the list of buckets. * @return Observable<Object[]> */ list(stats: boolean = false, uid: string = '') { return this.rgwDaemonService.request((params: HttpParams) => { params = params.append('stats', stats.toString()); if (uid) { params = params.append('uid', uid); } return this.http.get(this.url, { headers: { Accept: this.getVersionHeaderValue(1, 1) }, params: params }); }); } get(bucket: string) { return this.rgwDaemonService.request((params: HttpParams) => { return this.http.get(`${this.url}/${bucket}`, { params: params }); }); } create( bucket: string, uid: string, zonegroup: string, placementTarget: string, lockEnabled: boolean, lock_mode: 'GOVERNANCE' | 'COMPLIANCE', lock_retention_period_days: string, encryption_state: boolean, encryption_type: string, key_id: string ) { return this.rgwDaemonService.request((params: HttpParams) => { return this.http.post(this.url, null, { params: new HttpParams({ fromObject: { bucket, uid, zonegroup, placement_target: placementTarget, lock_enabled: String(lockEnabled), lock_mode, lock_retention_period_days, encryption_state: String(encryption_state), encryption_type, key_id, daemon_name: params.get('daemon_name') } }) }); }); } update( bucket: string, bucketId: string, uid: string, versioningState: string, encryptionState: boolean, encryptionType: string, keyId: string, mfaDelete: string, mfaTokenSerial: string, mfaTokenPin: string, lockMode: 'GOVERNANCE' | 'COMPLIANCE', lockRetentionPeriodDays: string ) { return this.rgwDaemonService.request((params: HttpParams) => { params = params.appendAll({ bucket_id: bucketId, uid: uid, versioning_state: versioningState, encryption_state: String(encryptionState), encryption_type: encryptionType, key_id: keyId, mfa_delete: mfaDelete, mfa_token_serial: mfaTokenSerial, mfa_token_pin: mfaTokenPin, lock_mode: lockMode, lock_retention_period_days: lockRetentionPeriodDays }); return this.http.put(`${this.url}/${bucket}`, null, { params: params }); }); } delete(bucket: string, purgeObjects = true) { return this.rgwDaemonService.request((params: HttpParams) => { params = params.append('purge_objects', purgeObjects ? 'true' : 'false'); return this.http.delete(`${this.url}/${bucket}`, { params: params }); }); } /** * Check if the specified bucket exists. * @param {string} bucket The bucket name to check. * @return Observable<boolean> */ exists(bucket: string) { return this.get(bucket).pipe( mapTo(true), catchError((error: Event) => { if (_.isFunction(error.preventDefault)) { error.preventDefault(); } return observableOf(false); }) ); } getLockDays(bucketData: object): number { if (bucketData['lock_retention_period_years'] > 0) { return Math.floor(bucketData['lock_retention_period_years'] * 365.242); } return bucketData['lock_retention_period_days'] || 0; } setEncryptionConfig( encryption_type: string, kms_provider: string, auth_method: string, secret_engine: string, secret_path: string, namespace: string, address: string, token: string, owner: string, ssl_cert: string, client_cert: string, client_key: string ) { return this.rgwDaemonService.request((params: HttpParams) => { params = params.appendAll({ encryption_type: encryption_type, kms_provider: kms_provider, auth_method: auth_method, secret_engine: secret_engine, secret_path: secret_path, namespace: namespace, address: address, token: token, owner: owner, ssl_cert: ssl_cert, client_cert: client_cert, client_key: client_key }); return this.http.put(`${this.url}/setEncryptionConfig`, null, { params: params }); }); } getEncryption(bucket: string) { return this.rgwDaemonService.request((params: HttpParams) => { return this.http.get(`${this.url}/${bucket}/getEncryption`, { params: params }); }); } deleteEncryption(bucket: string) { return this.rgwDaemonService.request((params: HttpParams) => { return this.http.get(`${this.url}/${bucket}/deleteEncryption`, { params: params }); }); } getEncryptionConfig() { return this.rgwDaemonService.request((params: HttpParams) => { return this.http.get(`${this.url}/getEncryptionConfig`, { params: params }); }); } }
5,571
27.721649
89
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-daemon.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { of } from 'rxjs'; import { RgwDaemon } from '~/app/ceph/rgw/models/rgw-daemon'; import { configureTestBed, RgwHelper } from '~/testing/unit-test-helper'; import { RgwDaemonService } from './rgw-daemon.service'; describe('RgwDaemonService', () => { let service: RgwDaemonService; let httpTesting: HttpTestingController; let selectDaemonSpy: jasmine.Spy; const daemonList: Array<RgwDaemon> = RgwHelper.getDaemonList(); const retrieveDaemonList = (reqDaemonList: RgwDaemon[], daemon: RgwDaemon) => { service .request((params) => of(params)) .subscribe((params) => expect(params.get('daemon_name')).toBe(daemon.id)); const listReq = httpTesting.expectOne('api/rgw/daemon'); listReq.flush(reqDaemonList); tick(); expect(service['selectedDaemon'].getValue()).toEqual(daemon); }; configureTestBed({ providers: [RgwDaemonService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(RgwDaemonService); selectDaemonSpy = spyOn(service, 'selectDaemon').and.callThrough(); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should get daemon list', () => { service.list().subscribe(); const req = httpTesting.expectOne('api/rgw/daemon'); req.flush(daemonList); expect(req.request.method).toBe('GET'); expect(service['daemons'].getValue()).toEqual(daemonList); }); it('should call "get daemon"', () => { service.get('foo').subscribe(); const req = httpTesting.expectOne('api/rgw/daemon/foo'); expect(req.request.method).toBe('GET'); }); it('should call request and not select any daemon from empty daemon list', fakeAsync(() => { expect(() => retrieveDaemonList([], null)).toThrowError('No RGW daemons found!'); expect(selectDaemonSpy).toHaveBeenCalledTimes(0); })); it('should call request and select default daemon from daemon list', fakeAsync(() => { retrieveDaemonList(daemonList, daemonList[1]); expect(selectDaemonSpy).toHaveBeenCalledTimes(1); expect(selectDaemonSpy).toHaveBeenCalledWith(daemonList[1]); })); it('should call request and select first daemon from daemon list that has no default', fakeAsync(() => { const noDefaultDaemonList = daemonList.map((daemon) => { daemon.default = false; return daemon; }); retrieveDaemonList(noDefaultDaemonList, noDefaultDaemonList[0]); expect(selectDaemonSpy).toHaveBeenCalledTimes(1); expect(selectDaemonSpy).toHaveBeenCalledWith(noDefaultDaemonList[0]); })); it('should update default daemon if not exist in daemon list', fakeAsync(() => { const tmpDaemonList = [...daemonList]; service.selectDaemon(tmpDaemonList[1]); // Select 'default' daemon. tmpDaemonList.splice(1, 1); // Remove 'default' daemon. tmpDaemonList[0].default = true; // Set new 'default' daemon. service.list().subscribe(); const testReq = httpTesting.expectOne('api/rgw/daemon'); testReq.flush(tmpDaemonList); expect(service['selectedDaemon'].getValue()).toEqual(tmpDaemonList[0]); })); });
3,365
35.989011
106
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-daemon.service.ts
import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import _ from 'lodash'; import { BehaviorSubject, Observable, of, throwError } from 'rxjs'; import { mergeMap, take, tap } from 'rxjs/operators'; import { RgwDaemon } from '~/app/ceph/rgw/models/rgw-daemon'; import { cdEncode } from '~/app/shared/decorators/cd-encode'; @cdEncode @Injectable({ providedIn: 'root' }) export class RgwDaemonService { private url = 'api/rgw/daemon'; private daemons = new BehaviorSubject<RgwDaemon[]>([]); daemons$ = this.daemons.asObservable(); private selectedDaemon = new BehaviorSubject<RgwDaemon>(null); selectedDaemon$ = this.selectedDaemon.asObservable(); constructor(private http: HttpClient) {} list(): Observable<RgwDaemon[]> { return this.http.get<RgwDaemon[]>(this.url).pipe( tap((daemons: RgwDaemon[]) => { this.daemons.next(daemons); const selectedDaemon = this.selectedDaemon.getValue(); // Set or re-select the default daemon if the current one is not // in the list anymore. if (_.isEmpty(selectedDaemon) || undefined === _.find(daemons, { id: selectedDaemon.id })) { this.selectDefaultDaemon(daemons); } }) ); } get(id: string) { return this.http.get(`${this.url}/${id}`); } selectDaemon(daemon: RgwDaemon) { this.selectedDaemon.next(daemon); } private selectDefaultDaemon(daemons: RgwDaemon[]): RgwDaemon { if (daemons.length === 0) { return null; } for (const daemon of daemons) { if (daemon.default) { this.selectDaemon(daemon); return daemon; } } this.selectDaemon(daemons[0]); return daemons[0]; } request(next: (params: HttpParams) => Observable<any>) { return this.selectedDaemon.pipe( mergeMap((daemon: RgwDaemon) => // If there is no selected daemon, retrieve daemon list so default daemon will be selected. _.isEmpty(daemon) ? this.list().pipe( mergeMap((daemons) => _.isEmpty(daemons) ? throwError('No RGW daemons found!') : this.selectedDaemon$ ) ) : of(daemon) ), take(1), mergeMap((daemon: RgwDaemon) => { let params = new HttpParams(); params = params.append('daemon_name', daemon.id); return next(params); }) ); } setMultisiteConfig(realm_name: string, zonegroup_name: string, zone_name: string) { return this.request((params: HttpParams) => { params = params.appendAll({ realm_name: realm_name, zonegroup_name: zonegroup_name, zone_name: zone_name }); return this.http.put(`${this.url}/set_multisite_config`, null, { params: params }); }); } }
2,814
28.946809
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-multisite.service.ts
import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { RgwRealm, RgwZone, RgwZonegroup } from '~/app/ceph/rgw/models/rgw-multisite'; import { RgwDaemonService } from './rgw-daemon.service'; @Injectable({ providedIn: 'root' }) export class RgwMultisiteService { private url = 'ui-api/rgw/multisite'; constructor(private http: HttpClient, public rgwDaemonService: RgwDaemonService) {} migrate(realm: RgwRealm, zonegroup: RgwZonegroup, zone: RgwZone) { return this.rgwDaemonService.request((params: HttpParams) => { params = params.appendAll({ realm_name: realm.name, zonegroup_name: zonegroup.name, zone_name: zone.name, zonegroup_endpoints: zonegroup.endpoints, zone_endpoints: zone.endpoints, access_key: zone.system_key.access_key, secret_key: zone.system_key.secret_key }); return this.http.put(`${this.url}/migrate`, null, { params: params }); }); } }
1,011
33.896552
86
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-realm.service.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RgwRealmService } from './rgw-realm.service'; describe('RgwRealmService', () => { let service: RgwRealmService; configureTestBed({ imports: [HttpClientTestingModule] }); beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(RgwRealmService); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
570
23.826087
71
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-realm.service.ts
import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { RgwRealm } from '~/app/ceph/rgw/models/rgw-multisite'; import { Icons } from '../enum/icons.enum'; import { RgwDaemonService } from './rgw-daemon.service'; @Injectable({ providedIn: 'root' }) export class RgwRealmService { private url = 'api/rgw/realm'; constructor(private http: HttpClient, public rgwDaemonService: RgwDaemonService) {} create(realm: RgwRealm, defaultRealm: boolean) { let requestBody = { realm_name: realm.name, default: defaultRealm }; return this.http.post(`${this.url}`, requestBody); } update(realm: RgwRealm, defaultRealm: boolean, newRealmName: string) { let requestBody = { realm_name: realm.name, default: defaultRealm, new_realm_name: newRealmName }; return this.http.put(`${this.url}/${realm.name}`, requestBody); } list(): Observable<object> { return this.http.get<object>(`${this.url}`); } get(realm: RgwRealm): Observable<object> { return this.http.get(`${this.url}/${realm.name}`); } getAllRealmsInfo(): Observable<object> { return this.http.get(`${this.url}/get_all_realms_info`); } delete(realmName: string): Observable<any> { let params = new HttpParams(); params = params.appendAll({ realm_name: realmName }); return this.http.delete(`${this.url}/${realmName}`, { params: params }); } getRealmTree(realm: RgwRealm, defaultRealmId: string) { let nodes = {}; let realmIds = []; nodes['id'] = realm.id; realmIds.push(realm.id); nodes['name'] = realm.name; nodes['info'] = realm; nodes['is_default'] = realm.id === defaultRealmId ? true : false; nodes['icon'] = Icons.reweight; nodes['type'] = 'realm'; return { nodes: nodes, realmIds: realmIds }; } importRealmToken(realm_token: string, zone_name: string) { return this.rgwDaemonService.request((params: HttpParams) => { params = params.appendAll({ realm_token: realm_token, zone_name: zone_name }); return this.http.post(`${this.url}/import_realm_token`, null, { params: params }); }); } getRealmTokens() { return this.rgwDaemonService.request(() => { return this.http.get(`${this.url}/get_realm_tokens`); }); } }
2,403
27.282353
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-site.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed, RgwHelper } from '~/testing/unit-test-helper'; import { RgwSiteService } from './rgw-site.service'; describe('RgwSiteService', () => { let service: RgwSiteService; let httpTesting: HttpTestingController; configureTestBed({ providers: [RgwSiteService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(RgwSiteService); httpTesting = TestBed.inject(HttpTestingController); RgwHelper.selectDaemon(); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should contain site endpoint in GET request', () => { service.get().subscribe(); const req = httpTesting.expectOne(`${service['url']}?${RgwHelper.DAEMON_QUERY_PARAM}`); expect(req.request.method).toBe('GET'); }); it('should add query param in GET request', () => { const query = 'placement-targets'; service.get(query).subscribe(); httpTesting.expectOne( `${service['url']}?${RgwHelper.DAEMON_QUERY_PARAM}&query=placement-targets` ); }); });
1,260
27.659091
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-site.service.ts
import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { map, mergeMap } from 'rxjs/operators'; import { RgwDaemon } from '~/app/ceph/rgw/models/rgw-daemon'; import { RgwDaemonService } from '~/app/shared/api/rgw-daemon.service'; import { cdEncode } from '~/app/shared/decorators/cd-encode'; @cdEncode @Injectable({ providedIn: 'root' }) export class RgwSiteService { private url = 'api/rgw/site'; constructor(private http: HttpClient, private rgwDaemonService: RgwDaemonService) {} get(query?: string) { return this.rgwDaemonService.request((params: HttpParams) => { if (query) { params = params.append('query', query); } return this.http.get(this.url, { params: params }); }); } isDefaultRealm(): Observable<boolean> { return this.get('default-realm').pipe( mergeMap((defaultRealm: string) => this.rgwDaemonService.selectedDaemon$.pipe( map((selectedDaemon: RgwDaemon) => selectedDaemon.realm_name === defaultRealm) ) ) ); } }
1,123
27.820513
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-user.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { of as observableOf, throwError } from 'rxjs'; import { configureTestBed, RgwHelper } from '~/testing/unit-test-helper'; import { RgwUserService } from './rgw-user.service'; describe('RgwUserService', () => { let service: RgwUserService; let httpTesting: HttpTestingController; configureTestBed({ imports: [HttpClientTestingModule], providers: [RgwUserService] }); beforeEach(() => { service = TestBed.inject(RgwUserService); httpTesting = TestBed.inject(HttpTestingController); RgwHelper.selectDaemon(); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call list with empty result', () => { let result; service.list().subscribe((resp) => { result = resp; }); const req = httpTesting.expectOne(`api/rgw/user?${RgwHelper.DAEMON_QUERY_PARAM}`); expect(req.request.method).toBe('GET'); req.flush([]); expect(result).toEqual([]); }); it('should call list with result', () => { let result; service.list().subscribe((resp) => { result = resp; }); let req = httpTesting.expectOne(`api/rgw/user?${RgwHelper.DAEMON_QUERY_PARAM}`); expect(req.request.method).toBe('GET'); req.flush(['foo', 'bar']); req = httpTesting.expectOne(`api/rgw/user/foo?${RgwHelper.DAEMON_QUERY_PARAM}`); expect(req.request.method).toBe('GET'); req.flush({ name: 'foo' }); req = httpTesting.expectOne(`api/rgw/user/bar?${RgwHelper.DAEMON_QUERY_PARAM}`); expect(req.request.method).toBe('GET'); req.flush({ name: 'bar' }); expect(result).toEqual([{ name: 'foo' }, { name: 'bar' }]); }); it('should call enumerate', () => { service.enumerate().subscribe(); const req = httpTesting.expectOne(`api/rgw/user?${RgwHelper.DAEMON_QUERY_PARAM}`); expect(req.request.method).toBe('GET'); }); it('should call get', () => { service.get('foo').subscribe(); const req = httpTesting.expectOne(`api/rgw/user/foo?${RgwHelper.DAEMON_QUERY_PARAM}`); expect(req.request.method).toBe('GET'); }); it('should call getQuota', () => { service.getQuota('foo').subscribe(); const req = httpTesting.expectOne(`api/rgw/user/foo/quota?${RgwHelper.DAEMON_QUERY_PARAM}`); expect(req.request.method).toBe('GET'); }); it('should call update', () => { service.update('foo', { xxx: 'yyy' }).subscribe(); const req = httpTesting.expectOne(`api/rgw/user/foo?${RgwHelper.DAEMON_QUERY_PARAM}&xxx=yyy`); expect(req.request.method).toBe('PUT'); }); it('should call updateQuota', () => { service.updateQuota('foo', { xxx: 'yyy' }).subscribe(); const req = httpTesting.expectOne( `api/rgw/user/foo/quota?${RgwHelper.DAEMON_QUERY_PARAM}&xxx=yyy` ); expect(req.request.method).toBe('PUT'); }); it('should call create', () => { service.create({ foo: 'bar' }).subscribe(); const req = httpTesting.expectOne(`api/rgw/user?${RgwHelper.DAEMON_QUERY_PARAM}&foo=bar`); expect(req.request.method).toBe('POST'); }); it('should call delete', () => { service.delete('foo').subscribe(); const req = httpTesting.expectOne(`api/rgw/user/foo?${RgwHelper.DAEMON_QUERY_PARAM}`); expect(req.request.method).toBe('DELETE'); }); it('should call createSubuser', () => { service.createSubuser('foo', { xxx: 'yyy' }).subscribe(); const req = httpTesting.expectOne( `api/rgw/user/foo/subuser?${RgwHelper.DAEMON_QUERY_PARAM}&xxx=yyy` ); expect(req.request.method).toBe('POST'); }); it('should call deleteSubuser', () => { service.deleteSubuser('foo', 'bar').subscribe(); const req = httpTesting.expectOne( `api/rgw/user/foo/subuser/bar?${RgwHelper.DAEMON_QUERY_PARAM}` ); expect(req.request.method).toBe('DELETE'); }); it('should call addCapability', () => { service.addCapability('foo', 'bar', 'baz').subscribe(); const req = httpTesting.expectOne( `api/rgw/user/foo/capability?${RgwHelper.DAEMON_QUERY_PARAM}&type=bar&perm=baz` ); expect(req.request.method).toBe('POST'); }); it('should call deleteCapability', () => { service.deleteCapability('foo', 'bar', 'baz').subscribe(); const req = httpTesting.expectOne( `api/rgw/user/foo/capability?${RgwHelper.DAEMON_QUERY_PARAM}&type=bar&perm=baz` ); expect(req.request.method).toBe('DELETE'); }); it('should call addS3Key', () => { service.addS3Key('foo', { xxx: 'yyy' }).subscribe(); const req = httpTesting.expectOne( `api/rgw/user/foo/key?${RgwHelper.DAEMON_QUERY_PARAM}&key_type=s3&xxx=yyy` ); expect(req.request.method).toBe('POST'); }); it('should call deleteS3Key', () => { service.deleteS3Key('foo', 'bar').subscribe(); const req = httpTesting.expectOne( `api/rgw/user/foo/key?${RgwHelper.DAEMON_QUERY_PARAM}&key_type=s3&access_key=bar` ); expect(req.request.method).toBe('DELETE'); }); it('should call exists with an existent uid', (done) => { spyOn(service, 'get').and.returnValue(observableOf({})); service.exists('foo').subscribe((res) => { expect(res).toBe(true); done(); }); }); it('should call exists with a non existent uid', (done) => { spyOn(service, 'get').and.returnValue(throwError('bar')); service.exists('baz').subscribe((res) => { expect(res).toBe(false); done(); }); }); });
5,579
31.631579
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-user.service.ts
import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import _ from 'lodash'; import { forkJoin as observableForkJoin, Observable, of as observableOf } from 'rxjs'; import { catchError, mapTo, mergeMap } from 'rxjs/operators'; import { RgwDaemonService } from '~/app/shared/api/rgw-daemon.service'; import { cdEncode } from '~/app/shared/decorators/cd-encode'; @cdEncode @Injectable({ providedIn: 'root' }) export class RgwUserService { private url = 'api/rgw/user'; constructor(private http: HttpClient, private rgwDaemonService: RgwDaemonService) {} /** * Get the list of users. * @return {Observable<Object[]>} */ list() { return this.enumerate().pipe( mergeMap((uids: string[]) => { if (uids.length > 0) { return observableForkJoin( uids.map((uid: string) => { return this.get(uid); }) ); } return observableOf([]); }) ); } /** * Get the list of usernames. * @return {Observable<string[]>} */ enumerate() { return this.rgwDaemonService.request((params: HttpParams) => { return this.http.get(this.url, { params: params }); }); } enumerateEmail() { return this.rgwDaemonService.request((params: HttpParams) => { return this.http.get(`${this.url}/get_emails`, { params: params }); }); } get(uid: string) { return this.rgwDaemonService.request((params: HttpParams) => { return this.http.get(`${this.url}/${uid}`, { params: params }); }); } getQuota(uid: string) { return this.rgwDaemonService.request((params: HttpParams) => { return this.http.get(`${this.url}/${uid}/quota`, { params: params }); }); } create(args: Record<string, any>) { return this.rgwDaemonService.request((params: HttpParams) => { _.keys(args).forEach((key) => { params = params.append(key, args[key]); }); return this.http.post(this.url, null, { params: params }); }); } update(uid: string, args: Record<string, any>) { return this.rgwDaemonService.request((params: HttpParams) => { _.keys(args).forEach((key) => { params = params.append(key, args[key]); }); return this.http.put(`${this.url}/${uid}`, null, { params: params }); }); } updateQuota(uid: string, args: Record<string, string>) { return this.rgwDaemonService.request((params: HttpParams) => { _.keys(args).forEach((key) => { params = params.append(key, args[key]); }); return this.http.put(`${this.url}/${uid}/quota`, null, { params: params }); }); } delete(uid: string) { return this.rgwDaemonService.request((params: HttpParams) => { return this.http.delete(`${this.url}/${uid}`, { params: params }); }); } createSubuser(uid: string, args: Record<string, string>) { return this.rgwDaemonService.request((params: HttpParams) => { _.keys(args).forEach((key) => { params = params.append(key, args[key]); }); return this.http.post(`${this.url}/${uid}/subuser`, null, { params: params }); }); } deleteSubuser(uid: string, subuser: string) { return this.rgwDaemonService.request((params: HttpParams) => { return this.http.delete(`${this.url}/${uid}/subuser/${subuser}`, { params: params }); }); } addCapability(uid: string, type: string, perm: string) { return this.rgwDaemonService.request((params: HttpParams) => { params = params.append('type', type); params = params.append('perm', perm); return this.http.post(`${this.url}/${uid}/capability`, null, { params: params }); }); } deleteCapability(uid: string, type: string, perm: string) { return this.rgwDaemonService.request((params: HttpParams) => { params = params.append('type', type); params = params.append('perm', perm); return this.http.delete(`${this.url}/${uid}/capability`, { params: params }); }); } addS3Key(uid: string, args: Record<string, string>) { return this.rgwDaemonService.request((params: HttpParams) => { params = params.append('key_type', 's3'); _.keys(args).forEach((key) => { params = params.append(key, args[key]); }); return this.http.post(`${this.url}/${uid}/key`, null, { params: params }); }); } deleteS3Key(uid: string, accessKey: string) { return this.rgwDaemonService.request((params: HttpParams) => { params = params.append('key_type', 's3'); params = params.append('access_key', accessKey); return this.http.delete(`${this.url}/${uid}/key`, { params: params }); }); } /** * Check if the specified user ID exists. * @param {string} uid The user ID to check. * @return {Observable<boolean>} */ exists(uid: string): Observable<boolean> { return this.get(uid).pipe( mapTo(true), catchError((error: Event) => { if (_.isFunction(error.preventDefault)) { error.preventDefault(); } return observableOf(false); }) ); } // Using @cdEncodeNot would be the preferred way here, but this // causes an error: https://tracker.ceph.com/issues/37505 // Use decodeURIComponent as workaround. // emailExists(@cdEncodeNot email: string): Observable<boolean> { emailExists(email: string): Observable<boolean> { email = decodeURIComponent(email); return this.enumerateEmail().pipe( mergeMap((resp: any[]) => { const index = _.indexOf(resp, email); return observableOf(-1 !== index); }) ); } }
5,621
30.233333
91
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-zone.service.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RgwZoneService } from './rgw-zone.service'; describe('RgwZoneService', () => { let service: RgwZoneService; configureTestBed({ imports: [HttpClientTestingModule] }); beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(RgwZoneService); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
565
23.608696
71
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-zone.service.ts
import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { RgwRealm, RgwZone, RgwZonegroup } from '~/app/ceph/rgw/models/rgw-multisite'; import { Icons } from '../enum/icons.enum'; @Injectable({ providedIn: 'root' }) export class RgwZoneService { private url = 'api/rgw/zone'; constructor(private http: HttpClient) {} create( zone: RgwZone, zonegroup: RgwZonegroup, defaultZone: boolean, master: boolean, endpoints: string ) { let params = new HttpParams(); params = params.appendAll({ zone_name: zone.name, zonegroup_name: zonegroup.name, default: defaultZone, master: master, zone_endpoints: endpoints, access_key: zone.system_key.access_key, secret_key: zone.system_key.secret_key }); return this.http.post(`${this.url}`, null, { params: params }); } list(): Observable<object> { return this.http.get<object>(`${this.url}`); } get(zone: RgwZone): Observable<object> { return this.http.get(`${this.url}/${zone.name}`); } getAllZonesInfo(): Observable<object> { return this.http.get(`${this.url}/get_all_zones_info`); } delete( zoneName: string, deletePools: boolean, pools: Set<string>, zonegroupName: string ): Observable<any> { let params = new HttpParams(); params = params.appendAll({ zone_name: zoneName, delete_pools: deletePools, pools: Array.from(pools.values()), zonegroup_name: zonegroupName }); return this.http.delete(`${this.url}/${zoneName}`, { params: params }); } update( zone: RgwZone, zonegroup: RgwZonegroup, newZoneName: string, defaultZone?: boolean, master?: boolean, endpoints?: string, placementTarget?: string, dataPool?: string, indexPool?: string, dataExtraPool?: string, storageClass?: string, dataPoolClass?: string, compression?: string ) { let requestBody = { zone_name: zone.name, zonegroup_name: zonegroup.name, new_zone_name: newZoneName, default: defaultZone, master: master, zone_endpoints: endpoints, access_key: zone.system_key.access_key, secret_key: zone.system_key.secret_key, placement_target: placementTarget, data_pool: dataPool, index_pool: indexPool, data_extra_pool: dataExtraPool, storage_class: storageClass, data_pool_class: dataPoolClass, compression: compression }; return this.http.put(`${this.url}/${zone.name}`, requestBody); } getZoneTree( zone: RgwZone, defaultZoneId: string, zones: RgwZone[], zonegroup?: RgwZonegroup, realm?: RgwRealm ) { let nodes = {}; let zoneIds = []; nodes['id'] = zone.id; zoneIds.push(zone.id); nodes['name'] = zone.name; nodes['type'] = 'zone'; nodes['name'] = zone.name; nodes['info'] = zone; nodes['icon'] = Icons.deploy; nodes['zone_zonegroup'] = zonegroup; nodes['parent'] = zonegroup ? zonegroup.name : ''; nodes['second_parent'] = realm ? realm.name : ''; nodes['is_default'] = zone.id === defaultZoneId ? true : false; nodes['endpoints'] = zone.endpoints; nodes['is_master'] = zonegroup && zonegroup.master_zone === zone.id ? true : false; nodes['type'] = 'zone'; const zoneNames = zones.map((zone: RgwZone) => { return zone['name']; }); nodes['secondary_zone'] = !zoneNames.includes(zone.name) ? true : false; const zoneInfo = zones.filter((zoneInfo) => zoneInfo.name === zone.name); if (zoneInfo && zoneInfo.length > 0) { const access_key = zoneInfo[0].system_key['access_key']; const secret_key = zoneInfo[0].system_key['secret_key']; nodes['access_key'] = access_key ? access_key : ''; nodes['secret_key'] = secret_key ? secret_key : ''; nodes['user'] = access_key && access_key !== '' ? true : false; } if (nodes['access_key'] === '' || nodes['access_key'] === 'null') { nodes['show_warning'] = true; nodes['warning_message'] = 'Access/Secret keys not found'; } else { nodes['show_warning'] = false; } if (nodes['endpoints'] && nodes['endpoints'].length === 0) { nodes['show_warning'] = true; nodes['warning_message'] = nodes['warning_message'] + '\n' + 'Endpoints not configured'; } return { nodes: nodes, zoneIds: zoneIds }; } getPoolNames() { return this.http.get(`${this.url}/get_pool_names`); } createSystemUser(userName: string, zone: string) { let requestBody = { userName: userName, zoneName: zone }; return this.http.put(`${this.url}/create_system_user`, requestBody); } getUserList(zoneName: string) { let params = new HttpParams(); params = params.appendAll({ zoneName: zoneName }); return this.http.get(`${this.url}/get_user_list`, { params: params }); } }
4,990
28.532544
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-zonegroup.service.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RgwZonegroupService } from './rgw-zonegroup.service'; describe('RgwZonegroupService', () => { let service: RgwZonegroupService; configureTestBed({ imports: [HttpClientTestingModule] }); beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(RgwZonegroupService); }); it('should be created', () => { expect(service).toBeTruthy(); }); });
590
24.695652
71
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/rgw-zonegroup.service.ts
import { HttpClient, HttpParams } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { RgwRealm, RgwZonegroup } from '~/app/ceph/rgw/models/rgw-multisite'; import { Icons } from '../enum/icons.enum'; @Injectable({ providedIn: 'root' }) export class RgwZonegroupService { private url = 'api/rgw/zonegroup'; constructor(private http: HttpClient) {} create(realm: RgwRealm, zonegroup: RgwZonegroup, defaultZonegroup: boolean, master: boolean) { let params = new HttpParams(); params = params.appendAll({ realm_name: realm.name, zonegroup_name: zonegroup.name, default: defaultZonegroup, master: master, zonegroup_endpoints: zonegroup.endpoints }); return this.http.post(`${this.url}`, null, { params: params }); } update( realm: RgwRealm, zonegroup: RgwZonegroup, newZonegroupName: string, defaultZonegroup?: boolean, master?: boolean, removedZones?: string[], addedZones?: string[] ) { let requestBody = { zonegroup_name: zonegroup.name, realm_name: realm.name, new_zonegroup_name: newZonegroupName, default: defaultZonegroup, master: master, zonegroup_endpoints: zonegroup.endpoints, placement_targets: zonegroup.placement_targets, remove_zones: removedZones, add_zones: addedZones }; return this.http.put(`${this.url}/${zonegroup.name}`, requestBody); } list(): Observable<object> { return this.http.get<object>(`${this.url}`); } get(zonegroup: RgwZonegroup): Observable<object> { return this.http.get(`${this.url}/${zonegroup.name}`); } getAllZonegroupsInfo(): Observable<object> { return this.http.get(`${this.url}/get_all_zonegroups_info`); } delete(zonegroupName: string, deletePools: boolean, pools: Set<string>): Observable<any> { let params = new HttpParams(); params = params.appendAll({ zonegroup_name: zonegroupName, delete_pools: deletePools, pools: Array.from(pools.values()) }); return this.http.delete(`${this.url}/${zonegroupName}`, { params: params }); } getZonegroupTree(zonegroup: RgwZonegroup, defaultZonegroupId: string, realm?: RgwRealm) { let nodes = {}; nodes['id'] = zonegroup.id; nodes['name'] = zonegroup.name; nodes['info'] = zonegroup; nodes['icon'] = Icons.cubes; nodes['is_master'] = zonegroup.is_master; nodes['parent'] = realm ? realm.name : ''; nodes['is_default'] = zonegroup.id === defaultZonegroupId ? true : false; nodes['type'] = 'zonegroup'; nodes['endpoints'] = zonegroup.endpoints; nodes['master_zone'] = zonegroup.master_zone; nodes['zones'] = zonegroup.zones; nodes['placement_targets'] = zonegroup.placement_targets; nodes['default_placement'] = zonegroup.default_placement; if (nodes['endpoints'].length === 0) { nodes['show_warning'] = true; nodes['warning_message'] = 'Endpoints not configured'; } return nodes; } }
3,038
31.329787
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/role.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { RoleService } from './role.service'; describe('RoleService', () => { let service: RoleService; let httpTesting: HttpTestingController; configureTestBed({ providers: [RoleService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(RoleService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call list', () => { service.list().subscribe(); const req = httpTesting.expectOne('api/role'); expect(req.request.method).toBe('GET'); }); it('should call delete', () => { service.delete('role1').subscribe(); const req = httpTesting.expectOne('api/role/role1'); expect(req.request.method).toBe('DELETE'); }); it('should call get', () => { service.get('role1').subscribe(); const req = httpTesting.expectOne('api/role/role1'); expect(req.request.method).toBe('GET'); }); it('should call clone', () => { service.clone('foo', 'bar').subscribe(); const req = httpTesting.expectOne('api/role/foo/clone'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ new_name: 'bar' }); }); it('should check if role name exists', () => { let exists: boolean; service.exists('role1').subscribe((res: boolean) => { exists = res; }); const req = httpTesting.expectOne('api/role'); expect(req.request.method).toBe('GET'); req.flush([{ name: 'role0' }, { name: 'role1' }]); expect(exists).toBeTruthy(); }); it('should check if role name does not exist', () => { let exists: boolean; service.exists('role2').subscribe((res: boolean) => { exists = res; }); const req = httpTesting.expectOne('api/role'); expect(req.request.method).toBe('GET'); req.flush([{ name: 'role0' }, { name: 'role1' }]); expect(exists).toBeFalsy(); }); });
2,204
28.013158
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/role.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, of as observableOf } from 'rxjs'; import { mergeMap } from 'rxjs/operators'; import { RoleFormModel } from '~/app/core/auth/role-form/role-form.model'; @Injectable({ providedIn: 'root' }) export class RoleService { constructor(private http: HttpClient) {} list() { return this.http.get('api/role'); } delete(name: string) { return this.http.delete(`api/role/${name}`); } get(name: string) { return this.http.get(`api/role/${name}`); } create(role: RoleFormModel) { return this.http.post(`api/role`, role); } clone(name: string, newName: string) { return this.http.post(`api/role/${name}/clone`, { new_name: newName }); } update(role: RoleFormModel) { return this.http.put(`api/role/${role.name}`, role); } exists(name: string): Observable<boolean> { return this.list().pipe( mergeMap((roles: Array<RoleFormModel>) => { const exists = roles.some((currentRole: RoleFormModel) => { return currentRole.name === name; }); return observableOf(exists); }) ); } }
1,192
22.86
75
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/scope.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { ScopeService } from './scope.service'; describe('ScopeService', () => { let service: ScopeService; let httpTesting: HttpTestingController; configureTestBed({ providers: [ScopeService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(ScopeService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call list', () => { service.list().subscribe(); const req = httpTesting.expectOne('ui-api/scope'); expect(req.request.method).toBe('GET'); }); });
891
24.485714
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/scope.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ScopeService { constructor(private http: HttpClient) {} list() { return this.http.get('ui-api/scope'); } }
265
18
50
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/settings.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { fakeAsync, TestBed, tick } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { SettingsService } from './settings.service'; describe('SettingsService', () => { let service: SettingsService; let httpTesting: HttpTestingController; const exampleUrl = 'api/settings/something'; const exampleValue = 'http://localhost:3000'; configureTestBed({ providers: [SettingsService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(SettingsService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call validateGrafanaDashboardUrl', () => { service.validateGrafanaDashboardUrl('s').subscribe(); const req = httpTesting.expectOne('api/grafana/validation/s'); expect(req.request.method).toBe('GET'); }); describe('getSettingsValue', () => { const testMethod = (data: object, expected: string) => { expect(service['getSettingsValue'](data)).toBe(expected); }; it('should explain the logic of the method', () => { expect('' || undefined).toBe(undefined); expect(undefined || '').toBe(''); expect('test' || undefined || '').toBe('test'); }); it('should test the method for empty string values', () => { testMethod({}, ''); testMethod({ wrongAttribute: 'test' }, ''); testMethod({ value: '' }, ''); testMethod({ instance: '' }, ''); }); it('should test the method for non empty string values', () => { testMethod({ value: 'test' }, 'test'); testMethod({ instance: 'test' }, 'test'); }); }); describe('isSettingConfigured', () => { let increment: number; const testConfig = (url: string, value: string) => { service.ifSettingConfigured( url, (setValue) => { expect(setValue).toBe(value); increment++; }, () => { increment--; } ); }; const expectSettingsApiCall = (url: string, value: object, isSet: string) => { testConfig(url, isSet); const req = httpTesting.expectOne(url); expect(req.request.method).toBe('GET'); req.flush(value); tick(); expect(increment).toBe(isSet !== '' ? 1 : -1); expect(service['settings'][url]).toBe(isSet); }; beforeEach(() => { increment = 0; }); it(`should return true if 'value' does not contain an empty string`, fakeAsync(() => { expectSettingsApiCall(exampleUrl, { value: exampleValue }, exampleValue); })); it(`should return false if 'value' does contain an empty string`, fakeAsync(() => { expectSettingsApiCall(exampleUrl, { value: '' }, ''); })); it(`should return true if 'instance' does not contain an empty string`, fakeAsync(() => { expectSettingsApiCall(exampleUrl, { value: exampleValue }, exampleValue); })); it(`should return false if 'instance' does contain an empty string`, fakeAsync(() => { expectSettingsApiCall(exampleUrl, { instance: '' }, ''); })); it(`should return false if the api object is empty`, fakeAsync(() => { expectSettingsApiCall(exampleUrl, {}, ''); })); it(`should call the API once even if it is called multiple times`, fakeAsync(() => { expectSettingsApiCall(exampleUrl, { value: exampleValue }, exampleValue); testConfig(exampleUrl, exampleValue); httpTesting.expectNone(exampleUrl); expect(increment).toBe(2); })); }); it('should disable a set setting', () => { service['settings'] = { [exampleUrl]: exampleValue }; service.disableSetting(exampleUrl); expect(service['settings']).toEqual({ [exampleUrl]: '' }); }); it('should return the specified settings (1)', () => { let result; service.getValues('foo,bar').subscribe((resp) => { result = resp; }); const req = httpTesting.expectOne('api/settings?names=foo,bar'); expect(req.request.method).toBe('GET'); req.flush([ { name: 'foo', default: '', type: 'str', value: 'test' }, { name: 'bar', default: 0, type: 'int', value: 2 } ]); expect(result).toEqual({ foo: 'test', bar: 2 }); }); it('should return the specified settings (2)', () => { service.getValues(['abc', 'xyz']).subscribe(); const req = httpTesting.expectOne('api/settings?names=abc,xyz'); expect(req.request.method).toBe('GET'); }); it('should return standard settings', () => { service.getStandardSettings().subscribe(); const req = httpTesting.expectOne('ui-api/standard_settings'); expect(req.request.method).toBe('GET'); }); });
4,884
30.516129
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/settings.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import _ from 'lodash'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; class SettingResponse { name: string; default: any; type: string; value: any; } @Injectable({ providedIn: 'root' }) export class SettingsService { constructor(private http: HttpClient) {} private settings: { [url: string]: string } = {}; getValues(names: string | string[]): Observable<{ [key: string]: any }> { if (_.isArray(names)) { names = names.join(','); } return this.http.get(`api/settings?names=${names}`).pipe( map((resp: SettingResponse[]) => { const result = {}; _.forEach(resp, (option: SettingResponse) => { _.set(result, option.name, option.value); }); return result; }) ); } ifSettingConfigured(url: string, fn: (value?: string) => void, elseFn?: () => void): void { const setting = this.settings[url]; if (setting === undefined) { this.http.get(url).subscribe( (data: any) => { this.settings[url] = this.getSettingsValue(data); this.ifSettingConfigured(url, fn, elseFn); }, (resp) => { if (resp.status !== 401) { this.settings[url] = ''; } } ); } else if (setting !== '') { fn(setting); } else { if (elseFn) { elseFn(); } } } // Easiest way to stop reloading external content that can't be reached disableSetting(url: string) { this.settings[url] = ''; } private getSettingsValue(data: any): string { return data.value || data.instance || ''; } validateGrafanaDashboardUrl(uid: string) { return this.http.get(`api/grafana/validation/${uid}`); } getStandardSettings(): Observable<{ [key: string]: any }> { return this.http.get('ui-api/standard_settings'); } }
1,952
24.038462
93
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/telemetry.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { TelemetryService } from './telemetry.service'; describe('TelemetryService', () => { let service: TelemetryService; let httpTesting: HttpTestingController; configureTestBed({ imports: [HttpClientTestingModule], providers: [TelemetryService] }); beforeEach(() => { service = TestBed.inject(TelemetryService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call getReport', () => { service.getReport().subscribe(); const req = httpTesting.expectOne('api/telemetry/report'); expect(req.request.method).toBe('GET'); }); it('should call enable to enable module', () => { service.enable(true).subscribe(); const req = httpTesting.expectOne('api/telemetry'); expect(req.request.method).toBe('PUT'); expect(req.request.body.enable).toBe(true); expect(req.request.body.license_name).toBe('sharing-1-0'); }); it('should call enable to disable module', () => { service.enable(false).subscribe(); const req = httpTesting.expectOne('api/telemetry'); expect(req.request.method).toBe('PUT'); expect(req.request.body.enable).toBe(false); expect(req.request.body.license_name).toBeUndefined(); }); it('should call enable to enable module by default', () => { service.enable().subscribe(); const req = httpTesting.expectOne('api/telemetry'); expect(req.request.method).toBe('PUT'); expect(req.request.body.enable).toBe(true); expect(req.request.body.license_name).toBe('sharing-1-0'); }); });
1,863
30.59322
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/telemetry.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class TelemetryService { private url = 'api/telemetry'; constructor(private http: HttpClient) {} getReport() { return this.http.get(`${this.url}/report`); } enable(enable: boolean = true) { const body = { enable: enable }; if (enable) { body['license_name'] = 'sharing-1-0'; } return this.http.put(`${this.url}`, body); } }
506
20.125
50
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/upgrade.service.spec.ts
import { UpgradeService } from './upgrade.service'; import { configureTestBed } from '~/testing/unit-test-helper'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { SummaryService } from '../services/summary.service'; import { BehaviorSubject } from 'rxjs'; export class SummaryServiceMock { summaryDataSource = new BehaviorSubject({ version: 'ceph version 18.1.3-12222-gcd0cd7cb ' + '(b8193bb4cda16ccc5b028c3e1df62bc72350a15d) reef (dev)' }); summaryData$ = this.summaryDataSource.asObservable(); subscribe(call: any) { return this.summaryData$.subscribe(call); } } describe('UpgradeService', () => { let service: UpgradeService; let httpTesting: HttpTestingController; configureTestBed({ imports: [HttpClientTestingModule], providers: [UpgradeService, { provide: SummaryService, useClass: SummaryServiceMock }] }); beforeEach(() => { service = TestBed.inject(UpgradeService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call upgrade list', () => { service.list().subscribe(); const req = httpTesting.expectOne('api/cluster/upgrade'); expect(req.request.method).toBe('GET'); }); it('should not show any version if the registry versions are older than the cluster version', () => { const upgradeInfoPayload = { image: 'quay.io/ceph-test/ceph', registry: 'quay.io', versions: ['18.1.0', '18.1.1', '18.1.2'] }; const expectedVersions: string[] = []; expect(service.versionAvailableForUpgrades(upgradeInfoPayload).versions).toEqual( expectedVersions ); }); });
1,842
29.213115
103
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/upgrade.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { ApiClient } from './api-client'; import { map } from 'rxjs/operators'; import { SummaryService } from '../services/summary.service'; import { UpgradeInfoInterface } from '../models/upgrade.interface'; @Injectable({ providedIn: 'root' }) export class UpgradeService extends ApiClient { baseURL = 'api/cluster/upgrade'; constructor(private http: HttpClient, private summaryService: SummaryService) { super(); } list() { return this.http.get(this.baseURL).pipe( map((resp: UpgradeInfoInterface) => { return this.versionAvailableForUpgrades(resp); }) ); } // Filter out versions that are older than the current cluster version // Only allow upgrades to the same major version versionAvailableForUpgrades(upgradeInfo: UpgradeInfoInterface): UpgradeInfoInterface { let version = ''; this.summaryService.subscribe((summary) => { version = summary.version.replace('ceph version ', '').split('-')[0]; }); const upgradableVersions = upgradeInfo.versions.filter((targetVersion) => { const cVersion = version.split('.'); const tVersion = targetVersion.split('.'); return ( cVersion[0] === tVersion[0] && (cVersion[1] < tVersion[1] || cVersion[2] < tVersion[2]) ); }); upgradeInfo.versions = upgradableVersions; return upgradeInfo; } }
1,450
31.244444
95
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/user.service.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { UserFormModel } from '~/app/core/auth/user-form/user-form.model'; import { configureTestBed } from '~/testing/unit-test-helper'; import { UserService } from './user.service'; describe('UserService', () => { let service: UserService; let httpTesting: HttpTestingController; configureTestBed({ providers: [UserService], imports: [HttpClientTestingModule] }); beforeEach(() => { service = TestBed.inject(UserService); httpTesting = TestBed.inject(HttpTestingController); }); afterEach(() => { httpTesting.verify(); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should call create', () => { const user = new UserFormModel(); user.username = 'user0'; user.password = 'pass0'; user.name = 'User 0'; user.email = '[email protected]'; user.roles = ['administrator']; service.create(user).subscribe(); const req = httpTesting.expectOne('api/user'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual(user); }); it('should call delete', () => { service.delete('user0').subscribe(); const req = httpTesting.expectOne('api/user/user0'); expect(req.request.method).toBe('DELETE'); }); it('should call update', () => { const user = new UserFormModel(); user.username = 'user0'; user.password = 'pass0'; user.name = 'User 0'; user.email = '[email protected]'; user.roles = ['administrator']; service.update(user).subscribe(); const req = httpTesting.expectOne('api/user/user0'); expect(req.request.body).toEqual(user); expect(req.request.method).toBe('PUT'); }); it('should call get', () => { service.get('user0').subscribe(); const req = httpTesting.expectOne('api/user/user0'); expect(req.request.method).toBe('GET'); }); it('should call list', () => { service.list().subscribe(); const req = httpTesting.expectOne('api/user'); expect(req.request.method).toBe('GET'); }); it('should call changePassword', () => { service.changePassword('user0', 'foo', 'bar').subscribe(); const req = httpTesting.expectOne('api/user/user0/change_password'); expect(req.request.body).toEqual({ old_password: 'foo', new_password: 'bar' }); expect(req.request.method).toBe('POST'); }); it('should call validatePassword', () => { service.validatePassword('foo').subscribe(); const req = httpTesting.expectOne('api/user/validate_password'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ password: 'foo', old_password: null, username: null }); }); it('should call validatePassword (incl. name)', () => { service.validatePassword('foo_bar', 'bar').subscribe(); const req = httpTesting.expectOne('api/user/validate_password'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ password: 'foo_bar', username: 'bar', old_password: null }); }); it('should call validatePassword (incl. old password)', () => { service.validatePassword('foo', null, 'foo').subscribe(); const req = httpTesting.expectOne('api/user/validate_password'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ password: 'foo', old_password: 'foo', username: null }); }); });
3,479
32.142857
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/api/user.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, of as observableOf } from 'rxjs'; import { catchError, mapTo } from 'rxjs/operators'; import { UserFormModel } from '~/app/core/auth/user-form/user-form.model'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(private http: HttpClient) {} list() { return this.http.get('api/user'); } delete(username: string) { return this.http.delete(`api/user/${username}`); } get(username: string) { return this.http.get(`api/user/${username}`); } create(user: UserFormModel) { return this.http.post(`api/user`, user); } update(user: UserFormModel) { return this.http.put(`api/user/${user.username}`, user); } changePassword(username: string, oldPassword: string, newPassword: string) { // Note, the specified user MUST be logged in to be able to change // the password. The backend ensures that the password of another // user can not be changed, otherwise an error will be thrown. return this.http.post(`api/user/${username}/change_password`, { old_password: oldPassword, new_password: newPassword }); } validateUserName(user_name: string): Observable<boolean> { return this.get(user_name).pipe( mapTo(true), catchError((error) => { error.preventDefault(); return observableOf(false); }) ); } validatePassword(password: string, username: string = null, oldPassword: string = null) { return this.http.post('api/user/validate_password', { password: password, username: username, old_password: oldPassword }); } }
1,708
26.126984
91
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/classes/cd-helper.class.spec.ts
import { CdHelperClass } from './cd-helper.class'; class MockClass { n = 42; o = { x: 'something', y: [1, 2, 3], z: true }; b: boolean; } describe('CdHelperClass', () => { describe('updateChanged', () => { let old: MockClass; let used: MockClass; let structure = { n: 42, o: { x: 'something', y: [1, 2, 3], z: true } } as any; beforeEach(() => { old = new MockClass(); used = new MockClass(); structure = { n: 42, o: { x: 'something', y: [1, 2, 3], z: true } }; }); it('should not update anything', () => { CdHelperClass.updateChanged(used, structure); expect(used).toEqual(old); }); it('should only change n', () => { CdHelperClass.updateChanged(used, { n: 17 }); expect(used.n).not.toEqual(old.n); expect(used.n).toBe(17); }); it('should update o on change of o.y', () => { CdHelperClass.updateChanged(used, structure); structure.o.y.push(4); expect(used.o.y).toEqual(old.o.y); CdHelperClass.updateChanged(used, structure); expect(used.o.y).toEqual([1, 2, 3, 4]); }); it('should change b, o and n', () => { structure.o.x.toUpperCase(); structure.n++; structure.b = true; CdHelperClass.updateChanged(used, structure); expect(used).toEqual(structure); }); }); });
1,461
20.820896
51
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/classes/cd-helper.class.ts
import _ from 'lodash'; export class CdHelperClass { /** * Simple way to only update variables if they have really changed and not just the reference * * @param componentThis - In order to update the variables if necessary * @param change - The variable name (attribute of the object) is followed by the current value * it would update even if it equals */ static updateChanged(componentThis: any, change: { [publicVarName: string]: any }) { let hasChanges = false; Object.keys(change).forEach((publicVarName) => { const data = change[publicVarName]; if (!_.isEqual(data, componentThis[publicVarName])) { componentThis[publicVarName] = data; hasChanges = true; } }); return hasChanges; } static cdVersionHeader(major_ver: string, minor_ver: string) { return `application/vnd.ceph.api.v${major_ver}.${minor_ver}+json`; } }
924
30.896552
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/classes/crush.node.selection.class.spec.ts
import { FormControl } from '@angular/forms'; import _ from 'lodash'; import { configureTestBed, Mocks } from '~/testing/unit-test-helper'; import { CrushNode } from '../models/crush-node'; import { CrushNodeSelectionClass } from './crush.node.selection.class'; describe('CrushNodeSelectionService', () => { const nodes = Mocks.getCrushMap(); let service: CrushNodeSelectionClass; let controls: { root: FormControl; failure: FormControl; device: FormControl; }; // Object contains functions to get something const get = { nodeByName: (name: string): CrushNode => nodes.find((node) => node.name === name), nodesByNames: (names: string[]): CrushNode[] => names.map(get.nodeByName) }; // Expects that are used frequently const assert = { formFieldValues: (root: CrushNode, failureDomain: string, device: string) => { expect(controls.root.value).toEqual(root); expect(controls.failure.value).toBe(failureDomain); expect(controls.device.value).toBe(device); }, valuesOnRootChange: ( rootName: string, expectedFailureDomain: string, expectedDevice: string ) => { const node = get.nodeByName(rootName); controls.root.setValue(node); assert.formFieldValues(node, expectedFailureDomain, expectedDevice); }, failureDomainNodes: ( failureDomains: { [failureDomain: string]: CrushNode[] }, expected: { [failureDomains: string]: string[] | CrushNode[] } ) => { expect(Object.keys(failureDomains)).toEqual(Object.keys(expected)); Object.keys(failureDomains).forEach((key) => { if (_.isString(expected[key][0])) { expect(failureDomains[key]).toEqual(get.nodesByNames(expected[key] as string[])); } else { expect(failureDomains[key]).toEqual(expected[key]); } }); } }; configureTestBed({ providers: [CrushNodeSelectionClass] }); beforeEach(() => { controls = { root: new FormControl(null), failure: new FormControl(''), device: new FormControl('') }; // Normally this should be extended by the class using it service = new CrushNodeSelectionClass(); // Therefore to get it working correctly use "this" instead of "service" service.initCrushNodeSelection(nodes, controls.root, controls.failure, controls.device); }); it('should be created', () => { expect(service).toBeTruthy(); expect(nodes.length).toBe(12); }); describe('lists', () => { afterEach(() => { // The available buckets should not change expect(service.buckets).toEqual( get.nodesByNames(['default', 'hdd-rack', 'mix-host', 'ssd-host', 'ssd-rack']) ); }); it('has the following lists after init', () => { assert.failureDomainNodes(service.failureDomains, { host: ['ssd-host', 'mix-host'], osd: ['osd.1', 'osd.0', 'osd.2'], rack: ['hdd-rack', 'ssd-rack'], 'osd-rack': ['osd2.0', 'osd2.1', 'osd3.0', 'osd3.1'] }); expect(service.devices).toEqual(['hdd', 'ssd']); }); it('has the following lists after selection of ssd-host', () => { controls.root.setValue(get.nodeByName('ssd-host')); assert.failureDomainNodes(service.failureDomains, { // Not host as it only exist once osd: ['osd.1', 'osd.0', 'osd.2'] }); expect(service.devices).toEqual(['ssd']); }); it('has the following lists after selection of mix-host', () => { controls.root.setValue(get.nodeByName('mix-host')); expect(service.devices).toEqual(['hdd', 'ssd']); assert.failureDomainNodes(service.failureDomains, { rack: ['hdd-rack', 'ssd-rack'], 'osd-rack': ['osd2.0', 'osd2.1', 'osd3.0', 'osd3.1'] }); }); }); describe('selection', () => { it('selects the first root after init automatically', () => { assert.formFieldValues(get.nodeByName('default'), 'osd-rack', ''); }); it('should select all values automatically by selecting "ssd-host" as root', () => { assert.valuesOnRootChange('ssd-host', 'osd', 'ssd'); }); it('selects automatically the most common failure domain', () => { // Select mix-host as mix-host has multiple failure domains (osd-rack and rack) assert.valuesOnRootChange('mix-host', 'osd-rack', ''); }); it('should override automatic selections', () => { assert.formFieldValues(get.nodeByName('default'), 'osd-rack', ''); assert.valuesOnRootChange('ssd-host', 'osd', 'ssd'); assert.valuesOnRootChange('mix-host', 'osd-rack', ''); }); it('should not override manual selections if possible', () => { controls.failure.setValue('rack'); controls.failure.markAsDirty(); controls.device.setValue('ssd'); controls.device.markAsDirty(); assert.valuesOnRootChange('mix-host', 'rack', 'ssd'); }); it('should preselect device by domain selection', () => { controls.failure.setValue('osd'); assert.formFieldValues(get.nodeByName('default'), 'osd', 'ssd'); }); }); describe('get available OSDs count', () => { it('should have 4 available OSDs with the default selection', () => { expect(service.deviceCount).toBe(4); }); it('should reduce available OSDs to 2 if a device type is set', () => { controls.device.setValue('ssd'); controls.device.markAsDirty(); expect(service.deviceCount).toBe(2); }); it('should show 3 OSDs when selecting "ssd-host"', () => { assert.valuesOnRootChange('ssd-host', 'osd', 'ssd'); expect(service.deviceCount).toBe(3); }); }); describe('search tree', () => { it('returns the following list after searching for mix-host', () => { const subNodes = CrushNodeSelectionClass.search(nodes, 'mix-host'); expect(subNodes).toEqual( get.nodesByNames([ 'mix-host', 'hdd-rack', 'osd2.0', 'osd2.1', 'ssd-rack', 'osd3.0', 'osd3.1' ]) ); }); it('returns the following list after searching for mix-host with SSDs', () => { const subNodes = CrushNodeSelectionClass.search(nodes, 'mix-host~ssd'); expect(subNodes.map((n) => n.name)).toEqual(['mix-host', 'ssd-rack', 'osd3.0', 'osd3.1']); }); it('returns an empty array if node can not be found', () => { expect(CrushNodeSelectionClass.search(nodes, 'not-there')).toEqual([]); }); it('returns the following list after searching for mix-host failure domains', () => { const subNodes = CrushNodeSelectionClass.search(nodes, 'mix-host'); assert.failureDomainNodes(CrushNodeSelectionClass.getFailureDomains(subNodes), { host: ['mix-host'], rack: ['hdd-rack', 'ssd-rack'], 'osd-rack': ['osd2.0', 'osd2.1', 'osd3.0', 'osd3.1'] }); }); it('returns the following list after searching for mix-host failure domains for a specific type', () => { const subNodes = CrushNodeSelectionClass.search(nodes, 'mix-host~hdd'); const hddHost = _.cloneDeep(get.nodesByNames(['mix-host'])[0]); hddHost.children = [-4]; assert.failureDomainNodes(CrushNodeSelectionClass.getFailureDomains(subNodes), { host: [hddHost], rack: ['hdd-rack'], 'osd-rack': ['osd2.0', 'osd2.1'] }); const ssdHost = _.cloneDeep(get.nodesByNames(['mix-host'])[0]); ssdHost.children = [-5]; assert.failureDomainNodes( CrushNodeSelectionClass.searchFailureDomains(nodes, 'mix-host~ssd'), { host: [ssdHost], rack: ['ssd-rack'], 'osd-rack': ['osd3.0', 'osd3.1'] } ); }); }); });
7,717
33.923077
109
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/classes/crush.node.selection.class.ts
import { AbstractControl } from '@angular/forms'; import _ from 'lodash'; import { CrushNode } from '../models/crush-node'; export class CrushNodeSelectionClass { private nodes: CrushNode[] = []; private idTree: { [id: number]: CrushNode } = {}; private allDevices: string[] = []; private controls: { root: AbstractControl; failure: AbstractControl; device: AbstractControl; }; buckets: CrushNode[] = []; failureDomains: { [type: string]: CrushNode[] } = {}; failureDomainKeys: string[] = []; devices: string[] = []; deviceCount = 0; static searchFailureDomains( nodes: CrushNode[], s: string ): { [failureDomain: string]: CrushNode[] } { return this.getFailureDomains(this.search(nodes, s)); } /** * Filters crush map for a node and it's tree. * The node name as provided in crush rules attribute item_name is supported. * This means that '$name~$deviceType' can be used and will result in a crush map * that only include buckets with the specified device in use as their leaf. */ static search(nodes: CrushNode[], s: string): CrushNode[] { const [search, deviceType] = s.split('~'); // Used inside item_name in crush rules const node = nodes.find((n) => ['name', 'id', 'type'].some((attr) => n[attr] === search)); if (!node) { return []; } nodes = this.getSubNodes(node, this.createIdTreeFromNodes(nodes)); if (deviceType) { nodes = this.filterNodesByDeviceType(nodes, deviceType); } return nodes; } static createIdTreeFromNodes(nodes: CrushNode[]): { [id: number]: CrushNode } { const idTree = {}; nodes.forEach((node) => { idTree[node.id] = node; }); return idTree; } static getSubNodes(node: CrushNode, idTree: { [id: number]: CrushNode }): CrushNode[] { let subNodes = [node]; // Includes parent node if (!node.children) { return subNodes; } node.children.forEach((id) => { const childNode = idTree[id]; subNodes = subNodes.concat(this.getSubNodes(childNode, idTree)); }); return subNodes; } static filterNodesByDeviceType(nodes: CrushNode[], deviceType: string): any { let doNotInclude = nodes .filter((n) => n.device_class && n.device_class !== deviceType) .map((n) => n.id); let foundNewNode: boolean; let childrenToRemove = doNotInclude; // Filters out all unwanted nodes do { foundNewNode = false; nodes = nodes.filter((n) => !doNotInclude.includes(n.id)); // Unwanted nodes // Find nodes where all children were filtered const toRemoveNext: number[] = []; nodes.forEach((n) => { if (n.children && n.children.every((id) => doNotInclude.includes(id))) { toRemoveNext.push(n.id); foundNewNode = true; } }); if (foundNewNode) { doNotInclude = toRemoveNext; // Reduces array length childrenToRemove = childrenToRemove.concat(toRemoveNext); } } while (foundNewNode); // Removes filtered out children in all left nodes with children nodes = _.cloneDeep(nodes); // Clone objects to not change original objects nodes = nodes.map((n) => { if (!n.children) { return n; } n.children = n.children.filter((id) => !childrenToRemove.includes(id)); return n; }); return nodes; } static getFailureDomains(nodes: CrushNode[]): { [failureDomain: string]: CrushNode[] } { const domains = {}; nodes.forEach((node) => { const type = node.type; if (!domains[type]) { domains[type] = []; } domains[type].push(node); }); return domains; } initCrushNodeSelection( nodes: CrushNode[], rootControl: AbstractControl, failureControl: AbstractControl, deviceControl: AbstractControl ) { this.nodes = nodes; this.idTree = CrushNodeSelectionClass.createIdTreeFromNodes(nodes); nodes.forEach((node) => { this.idTree[node.id] = node; }); this.buckets = _.sortBy( nodes.filter((n) => n.children), 'name' ); this.controls = { root: rootControl, failure: failureControl, device: deviceControl }; this.preSelectRoot(); this.controls.root.valueChanges.subscribe(() => this.onRootChange()); this.controls.failure.valueChanges.subscribe(() => this.onFailureDomainChange()); this.controls.device.valueChanges.subscribe(() => this.onDeviceChange()); } private preSelectRoot() { const rootNode = this.nodes.find((node) => node.type === 'root'); this.silentSet(this.controls.root, rootNode); this.onRootChange(); } private silentSet(control: AbstractControl, value: any) { control.setValue(value, { emitEvent: false }); } private onRootChange() { const nodes = CrushNodeSelectionClass.getSubNodes(this.controls.root.value, this.idTree); const domains = CrushNodeSelectionClass.getFailureDomains(nodes); Object.keys(domains).forEach((type) => { if (domains[type].length <= 1) { delete domains[type]; } }); this.failureDomains = domains; this.failureDomainKeys = Object.keys(domains).sort(); this.updateFailureDomain(); } private updateFailureDomain() { let failureDomain = this.getIncludedCustomValue( this.controls.failure, Object.keys(this.failureDomains) ); if (failureDomain === '') { failureDomain = this.setMostCommonDomain(this.controls.failure); } this.updateDevices(failureDomain); } private getIncludedCustomValue(control: AbstractControl, includedIn: string[]) { return control.dirty && includedIn.includes(control.value) ? control.value : ''; } private setMostCommonDomain(failureControl: AbstractControl): string { let winner = { n: 0, type: '' }; Object.keys(this.failureDomains).forEach((type) => { const n = this.failureDomains[type].length; if (winner.n < n) { winner = { n, type }; } }); this.silentSet(failureControl, winner.type); return winner.type; } private onFailureDomainChange() { this.updateDevices(); } private updateDevices(failureDomain: string = this.controls.failure.value) { const subNodes = _.flatten( this.failureDomains[failureDomain].map((node) => CrushNodeSelectionClass.getSubNodes(node, this.idTree) ) ); this.allDevices = subNodes.filter((n) => n.device_class).map((n) => n.device_class); this.devices = _.uniq(this.allDevices).sort(); const device = this.devices.length === 1 ? this.devices[0] : this.getIncludedCustomValue(this.controls.device, this.devices); this.silentSet(this.controls.device, device); this.onDeviceChange(device); } private onDeviceChange(deviceType: string = this.controls.device.value) { this.deviceCount = deviceType === '' ? this.allDevices.length : this.allDevices.filter((type) => type === deviceType).length; } }
6,996
30.518018
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/classes/css-helper.ts
export class CssHelper { propertyValue(propertyName: string): string { return getComputedStyle(document.body).getPropertyValue(`--${propertyName}`); } }
161
26
81
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/classes/list-with-details.class.ts
import { NgZone } from '@angular/core'; import { TableStatus } from './table-status'; export class ListWithDetails { expandedRow: any; staleTimeout: number; tableStatus: TableStatus; constructor(protected ngZone?: NgZone) {} setExpandedRow(expandedRow: any) { this.expandedRow = expandedRow; } setTableRefreshTimeout() { clearTimeout(this.staleTimeout); this.ngZone.runOutsideAngular(() => { this.staleTimeout = window.setTimeout(() => { this.ngZone.run(() => { this.tableStatus = new TableStatus( 'warning', $localize`The user list data might be stale. If needed, you can manually reload it.` ); }); }, 10000); }); } }
729
23.333333
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/classes/table-status-view-cache.spec.ts
import { ViewCacheStatus } from '../enum/view-cache-status.enum'; import { TableStatusViewCache } from './table-status-view-cache'; describe('TableStatusViewCache', () => { it('should create an instance', () => { const ts = new TableStatusViewCache(); expect(ts).toBeTruthy(); expect(ts).toEqual({ msg: '', type: 'light' }); }); it('should create a ValueStale instance', () => { let ts = new TableStatusViewCache(ViewCacheStatus.ValueStale); expect(ts).toEqual({ type: 'warning', msg: 'Displaying previously cached data.' }); ts = new TableStatusViewCache(ViewCacheStatus.ValueStale, 'foo bar'); expect(ts).toEqual({ type: 'warning', msg: 'Displaying previously cached data for foo bar.' }); }); it('should create a ValueNone instance', () => { let ts = new TableStatusViewCache(ViewCacheStatus.ValueNone); expect(ts).toEqual({ type: 'info', msg: 'Retrieving data. Please wait...' }); ts = new TableStatusViewCache(ViewCacheStatus.ValueNone, 'foo bar'); expect(ts).toEqual({ type: 'info', msg: 'Retrieving data for foo bar. Please wait...' }); }); it('should create a ValueException instance', () => { let ts = new TableStatusViewCache(ViewCacheStatus.ValueException); expect(ts).toEqual({ type: 'danger', msg: 'Could not load data. Please check the cluster health.' }); ts = new TableStatusViewCache(ViewCacheStatus.ValueException, 'foo bar'); expect(ts).toEqual({ type: 'danger', msg: 'Could not load data for foo bar. Please check the cluster health.' }); }); });
1,582
37.609756
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/classes/table-status-view-cache.ts
import { ViewCacheStatus } from '../enum/view-cache-status.enum'; import { TableStatus } from './table-status'; export class TableStatusViewCache extends TableStatus { constructor(status: ViewCacheStatus = ViewCacheStatus.ValueOk, statusFor: string = '') { super(); switch (status) { case ViewCacheStatus.ValueOk: this.type = 'light'; this.msg = ''; break; case ViewCacheStatus.ValueNone: this.type = 'info'; this.msg = (statusFor ? $localize`Retrieving data for ${statusFor}.` : $localize`Retrieving data.`) + ' ' + $localize`Please wait...`; break; case ViewCacheStatus.ValueStale: this.type = 'warning'; this.msg = statusFor ? $localize`Displaying previously cached data for ${statusFor}.` : $localize`Displaying previously cached data.`; break; case ViewCacheStatus.ValueException: this.type = 'danger'; this.msg = (statusFor ? $localize`Could not load data for ${statusFor}.` : $localize`Could not load data.`) + ' ' + $localize`Please check the cluster health.`; break; } } }
1,224
31.236842
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/classes/table-status.spec.ts
import { TableStatus } from './table-status'; describe('TableStatus', () => { it('should create an instance', () => { const ts = new TableStatus(); expect(ts).toBeTruthy(); expect(ts).toEqual({ msg: '', type: 'light' }); }); it('should create with parameters', () => { const ts = new TableStatus('danger', 'foo'); expect(ts).toBeTruthy(); expect(ts).toEqual({ msg: 'foo', type: 'danger' }); }); });
433
26.125
55
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/classes/table-status.ts
export class TableStatus { constructor(public type: 'info' | 'warning' | 'danger' | 'light' = 'light', public msg = '') {} }
127
31
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/components.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { NgbAlertModule, NgbDatepickerModule, NgbDropdownModule, NgbPopoverModule, NgbProgressbarModule, NgbTimepickerModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'; import { ClickOutsideModule } from 'ng-click-outside'; import { ChartsModule } from 'ng2-charts'; import { SimplebarAngularModule } from 'simplebar-angular'; import { MotdComponent } from '~/app/shared/components/motd/motd.component'; import { DirectivesModule } from '../directives/directives.module'; import { PipesModule } from '../pipes/pipes.module'; import { AlertPanelComponent } from './alert-panel/alert-panel.component'; import { BackButtonComponent } from './back-button/back-button.component'; import { CdLabelComponent } from './cd-label/cd-label.component'; import { ColorClassFromTextPipe } from './cd-label/color-class-from-text.pipe'; import { ConfigOptionComponent } from './config-option/config-option.component'; import { ConfirmationModalComponent } from './confirmation-modal/confirmation-modal.component'; import { Copy2ClipboardButtonComponent } from './copy2clipboard-button/copy2clipboard-button.component'; import { CriticalConfirmationModalComponent } from './critical-confirmation-modal/critical-confirmation-modal.component'; import { CustomLoginBannerComponent } from './custom-login-banner/custom-login-banner.component'; import { DateTimePickerComponent } from './date-time-picker/date-time-picker.component'; import { DocComponent } from './doc/doc.component'; import { DownloadButtonComponent } from './download-button/download-button.component'; import { FormButtonPanelComponent } from './form-button-panel/form-button-panel.component'; import { FormModalComponent } from './form-modal/form-modal.component'; import { GrafanaComponent } from './grafana/grafana.component'; import { HelperComponent } from './helper/helper.component'; import { LanguageSelectorComponent } from './language-selector/language-selector.component'; import { LoadingPanelComponent } from './loading-panel/loading-panel.component'; import { ModalComponent } from './modal/modal.component'; import { NotificationsSidebarComponent } from './notifications-sidebar/notifications-sidebar.component'; import { OrchestratorDocPanelComponent } from './orchestrator-doc-panel/orchestrator-doc-panel.component'; import { PwdExpirationNotificationComponent } from './pwd-expiration-notification/pwd-expiration-notification.component'; import { RefreshSelectorComponent } from './refresh-selector/refresh-selector.component'; import { SelectBadgesComponent } from './select-badges/select-badges.component'; import { SelectComponent } from './select/select.component'; import { SparklineComponent } from './sparkline/sparkline.component'; import { SubmitButtonComponent } from './submit-button/submit-button.component'; import { TelemetryNotificationComponent } from './telemetry-notification/telemetry-notification.component'; import { UsageBarComponent } from './usage-bar/usage-bar.component'; import { WizardComponent } from './wizard/wizard.component'; @NgModule({ imports: [ CommonModule, FormsModule, ReactiveFormsModule, NgbAlertModule, NgbPopoverModule, NgbProgressbarModule, NgbTooltipModule, ChartsModule, ReactiveFormsModule, PipesModule, DirectivesModule, NgbDropdownModule, ClickOutsideModule, SimplebarAngularModule, RouterModule, NgbDatepickerModule, NgbTimepickerModule ], declarations: [ SparklineComponent, HelperComponent, SelectBadgesComponent, SubmitButtonComponent, UsageBarComponent, LoadingPanelComponent, ModalComponent, NotificationsSidebarComponent, CriticalConfirmationModalComponent, ConfirmationModalComponent, LanguageSelectorComponent, GrafanaComponent, SelectComponent, BackButtonComponent, RefreshSelectorComponent, ConfigOptionComponent, AlertPanelComponent, FormModalComponent, PwdExpirationNotificationComponent, TelemetryNotificationComponent, OrchestratorDocPanelComponent, DateTimePickerComponent, DocComponent, Copy2ClipboardButtonComponent, DownloadButtonComponent, FormButtonPanelComponent, MotdComponent, WizardComponent, CustomLoginBannerComponent, CdLabelComponent, ColorClassFromTextPipe ], providers: [], exports: [ SparklineComponent, HelperComponent, SelectBadgesComponent, SubmitButtonComponent, BackButtonComponent, LoadingPanelComponent, UsageBarComponent, ModalComponent, NotificationsSidebarComponent, LanguageSelectorComponent, GrafanaComponent, SelectComponent, RefreshSelectorComponent, ConfigOptionComponent, AlertPanelComponent, PwdExpirationNotificationComponent, TelemetryNotificationComponent, OrchestratorDocPanelComponent, DateTimePickerComponent, DocComponent, Copy2ClipboardButtonComponent, DownloadButtonComponent, FormButtonPanelComponent, MotdComponent, WizardComponent, CustomLoginBannerComponent, CdLabelComponent ] }) export class ComponentsModule {}
5,341
37.710145
121
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/alert-panel/alert-panel.component.html
<ngb-alert type="{{ bootstrapClass }}" [dismissible]="dismissible" (closed)="onClose()" [ngClass]="spacingClass"> <table> <ng-container *ngIf="size === 'normal'; else slim"> <tr> <td *ngIf="showIcon" rowspan="2" class="alert-panel-icon"> <i [ngClass]="[icons.large3x]" class="alert-{{ bootstrapClass }} {{ typeIcon }}" aria-hidden="true"></i> </td> <td *ngIf="showTitle" class="alert-panel-title">{{ title }}</td> </tr> <tr> <td class="alert-panel-text"> <ng-container *ngTemplateOutlet="content"></ng-container> </td> </tr> </ng-container> <ng-template #slim> <tr> <td *ngIf="showIcon" class="alert-panel-icon"> <i class="alert-{{ bootstrapClass }} {{ typeIcon }}" aria-hidden="true"></i> </td> <td *ngIf="showTitle" class="alert-panel-title">{{ title }}</td> <td class="alert-panel-text"> <ng-container *ngTemplateOutlet="content"></ng-container> </td> </tr> </ng-template> </table> </ngb-alert> <ng-template #content> <ng-content></ng-content> </ng-template>
1,273
27.954545
67
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/alert-panel/alert-panel.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { NgbAlertModule } from '@ng-bootstrap/ng-bootstrap'; import { configureTestBed } from '~/testing/unit-test-helper'; import { AlertPanelComponent } from './alert-panel.component'; describe('AlertPanelComponent', () => { let component: AlertPanelComponent; let fixture: ComponentFixture<AlertPanelComponent>; configureTestBed({ declarations: [AlertPanelComponent], imports: [NgbAlertModule] }); beforeEach(() => { fixture = TestBed.createComponent(AlertPanelComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
725
25.888889
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/alert-panel/alert-panel.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { Icons } from '~/app/shared/enum/icons.enum'; @Component({ selector: 'cd-alert-panel', templateUrl: './alert-panel.component.html', styleUrls: ['./alert-panel.component.scss'] }) export class AlertPanelComponent implements OnInit { @Input() title = ''; @Input() bootstrapClass = ''; @Input() type: 'warning' | 'error' | 'info' | 'success' | 'danger'; @Input() typeIcon: Icons | string; @Input() size: 'slim' | 'normal' = 'normal'; @Input() showIcon = true; @Input() showTitle = true; @Input() dismissible = false; @Input() spacingClass = ''; /** * The event that is triggered when the close button (x) has been * pressed. */ @Output() dismissed = new EventEmitter(); icons = Icons; ngOnInit() { switch (this.type) { case 'warning': this.title = this.title || $localize`Warning`; this.typeIcon = this.typeIcon || Icons.warning; this.bootstrapClass = this.bootstrapClass || 'warning'; break; case 'error': this.title = this.title || $localize`Error`; this.typeIcon = this.typeIcon || Icons.destroyCircle; this.bootstrapClass = this.bootstrapClass || 'danger'; break; case 'info': this.title = this.title || $localize`Information`; this.typeIcon = this.typeIcon || Icons.infoCircle; this.bootstrapClass = this.bootstrapClass || 'info'; break; case 'success': this.title = this.title || $localize`Success`; this.typeIcon = this.typeIcon || Icons.check; this.bootstrapClass = this.bootstrapClass || 'success'; break; case 'danger': this.title = this.title || $localize`Danger`; this.typeIcon = this.typeIcon || Icons.warning; this.bootstrapClass = this.bootstrapClass || 'danger'; break; } } onClose(): void { this.dismissed.emit(); } }
1,995
26.342466
79
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/back-button/back-button.component.html
<button class="btn btn-light tc_backButton" aria-label="Back" (click)="back()" type="button"> {{ name }} </button>
141
19.285714
43
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/back-button/back-button.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { BackButtonComponent } from './back-button.component'; describe('BackButtonComponent', () => { let component: BackButtonComponent; let fixture: ComponentFixture<BackButtonComponent>; configureTestBed({ imports: [RouterTestingModule], declarations: [BackButtonComponent] }); beforeEach(() => { fixture = TestBed.createComponent(BackButtonComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
731
27.153846
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/back-button/back-button.component.ts
import { Location } from '@angular/common'; import { Component, EventEmitter, Input, Output } from '@angular/core'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; @Component({ selector: 'cd-back-button', templateUrl: './back-button.component.html', styleUrls: ['./back-button.component.scss'] }) export class BackButtonComponent { @Output() backAction = new EventEmitter(); @Input() name: string = this.actionLabels.CANCEL; constructor(private location: Location, private actionLabels: ActionLabelsI18n) {} back() { if (this.backAction.observers.length === 0) { this.location.back(); } else { this.backAction.emit(); } } }
693
26.76
84
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/cd-label/cd-label.component.html
<span *ngIf="!key; else key_value" class="badge badge-{{value}}" ngClass="{{value | colorClassFromText}}"> {{ value }} </span> <ng-template #key_value> <span class="badge badge-background-primary badge-{{key}}-{{value}}"> {{ key }}: {{ value }} </span> </ng-template>
295
23.666667
71
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/cd-label/cd-label.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { CdLabelComponent } from './cd-label.component'; import { ColorClassFromTextPipe } from './color-class-from-text.pipe'; describe('CdLabelComponent', () => { let component: CdLabelComponent; let fixture: ComponentFixture<CdLabelComponent>; beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [CdLabelComponent, ColorClassFromTextPipe] }).compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(CdLabelComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
722
26.807692
70
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/cd-label/cd-label.component.ts
import { Component, Input } from '@angular/core'; @Component({ selector: 'cd-label', templateUrl: './cd-label.component.html', styleUrls: ['./cd-label.component.scss'] }) export class CdLabelComponent { @Input() key?: string; @Input() value?: string; }
264
21.083333
49
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/cd-label/color-class-from-text.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'colorClassFromText' }) export class ColorClassFromTextPipe implements PipeTransform { readonly cssClasses: string[] = [ 'badge-cd-label-green', 'badge-cd-label-cyan', 'badge-cd-label-purple', 'badge-cd-label-light-blue', 'badge-cd-label-gold', 'badge-cd-label-light-green' ]; transform(text: string): string { let hash = 0; let charCode = 0; if (text) { for (let i = 0; i < text.length; i++) { charCode = text.charCodeAt(i); // eslint-disable-next-line no-bitwise hash = Math.abs((hash << 5) - hash + charCode); } } return this.cssClasses[hash % this.cssClasses.length]; } }
735
24.37931
62
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/config-option/config-option.component.html
<div [formGroup]="optionsFormGroup"> <div *ngFor="let option of options; let last = last"> <div class="form-group row pt-2" *ngIf="option.type === 'bool'"> <label class="cd-col-form-label" [for]="option.name"> <b>{{ option.text }}</b> <br> <span class="text-muted"> {{ option.desc }} <cd-helper *ngIf="option.long_desc"> {{ option.long_desc }}</cd-helper> </span> </label> <div class="cd-col-form-input"> <div class="custom-control custom-checkbox"> <input class="custom-control-input" type="checkbox" [id]="option.name" [formControlName]="option.name"> <label class="custom-control-label" [for]="option.name"></label> </div> </div> </div> <div class="form-group row pt-2" *ngIf="option.type !== 'bool'"> <label class="cd-col-form-label" [for]="option.name">{{ option.text }} <br> <span class="text-muted"> {{ option.desc }} <cd-helper *ngIf="option.long_desc"> {{ option.long_desc }}</cd-helper> </span> </label> <div class="cd-col-form-input"> <div class="input-group"> <input class="form-control" [type]="option.additionalTypeInfo.inputType" [id]="option.name" [placeholder]="option.additionalTypeInfo.humanReadable" [formControlName]="option.name" [step]="getStep(option.type, optionsForm.getValue(option.name))"> <button class="btn btn-light" type="button" data-toggle="button" title="Remove the custom configuration value. The default configuration will be inherited and used instead." (click)="resetValue(option.name)" i18n-title *ngIf="optionsFormShowReset"> <i [ngClass]="[icons.erase]" aria-hidden="true"></i> </button> </div> <span class="invalid-feedback" *ngIf="optionsForm.showError(option.name, optionsFormDir, 'pattern')"> {{ option.additionalTypeInfo.patternHelpText }}</span> <span class="invalid-feedback" *ngIf="optionsForm.showError(option.name, optionsFormDir, 'invalidUuid')"> {{ option.additionalTypeInfo.patternHelpText }}</span> <span class="invalid-feedback" *ngIf="optionsForm.showError(option.name, optionsFormDir, 'max')" i18n>The entered value is too high! It must not be greater than {{ option.maxValue }}.</span> <span class="invalid-feedback" *ngIf="optionsForm.showError(option.name, optionsFormDir, 'min')" i18n>The entered value is too low! It must not be lower than {{ option.minValue }}.</span> </div> </div> <hr *ngIf="!last" class="my-2"> </div> </div>
3,046
39.092105
126
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/config-option/config-option.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { NgbPopoverModule } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { of as observableOf } from 'rxjs'; import { ConfigurationService } from '~/app/shared/api/configuration.service'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { configureTestBed } from '~/testing/unit-test-helper'; import { HelperComponent } from '../helper/helper.component'; import { ConfigOptionComponent } from './config-option.component'; describe('ConfigOptionComponent', () => { let component: ConfigOptionComponent; let fixture: ComponentFixture<ConfigOptionComponent>; let configurationService: ConfigurationService; let oNames: Array<string>; configureTestBed({ declarations: [ConfigOptionComponent, HelperComponent], imports: [NgbPopoverModule, ReactiveFormsModule, HttpClientTestingModule], providers: [ConfigurationService] }); beforeEach(() => { fixture = TestBed.createComponent(ConfigOptionComponent); component = fixture.componentInstance; fixture.detectChanges(); configurationService = TestBed.inject(ConfigurationService); const configOptions: Record<string, any> = [ { name: 'osd_scrub_auto_repair_num_errors', type: 'uint', level: 'advanced', desc: 'Maximum number of detected errors to automatically repair', long_desc: '', default: 5, daemon_default: '', tags: [], services: [], see_also: ['osd_scrub_auto_repair'], min: '', max: '', can_update_at_runtime: true, flags: [] }, { name: 'osd_debug_deep_scrub_sleep', type: 'float', level: 'dev', desc: 'Inject an expensive sleep during deep scrub IO to make it easier to induce preemption', long_desc: '', default: 0, daemon_default: '', tags: [], services: [], see_also: [], min: '', max: '', can_update_at_runtime: true, flags: [] }, { name: 'osd_heartbeat_interval', type: 'int', level: 'advanced', desc: 'Interval (in seconds) between peer pings', long_desc: '', default: 6, daemon_default: '', tags: [], services: [], see_also: [], min: 1, max: 86400, can_update_at_runtime: true, flags: [], value: [ { section: 'osd', value: 6 } ] }, { name: 'bluestore_compression_algorithm', type: 'str', level: 'advanced', desc: 'Default compression algorithm to use when writing object data', long_desc: 'This controls the default compressor to use (if any) if the ' + 'per-pool property is not set. Note that zstd is *not* recommended for ' + 'bluestore due to high CPU overhead when compressing small amounts of data.', default: 'snappy', daemon_default: '', tags: [], services: [], see_also: [], enum_values: ['', 'snappy', 'zlib', 'zstd', 'lz4'], min: '', max: '', can_update_at_runtime: true, flags: ['runtime'] }, { name: 'rbd_discard_on_zeroed_write_same', type: 'bool', level: 'advanced', desc: 'discard data on zeroed write same instead of writing zero', long_desc: '', default: true, daemon_default: '', tags: [], services: ['rbd'], see_also: [], min: '', max: '', can_update_at_runtime: true, flags: [] }, { name: 'rbd_journal_max_payload_bytes', type: 'size', level: 'advanced', desc: 'maximum journal payload size before splitting', long_desc: '', daemon_default: '', tags: [], services: ['rbd'], see_also: [], min: '', max: '', can_update_at_runtime: true, flags: [], default: '16384' }, { name: 'cluster_addr', type: 'addr', level: 'basic', desc: 'cluster-facing address to bind to', long_desc: '', daemon_default: '', tags: ['network'], services: ['osd'], see_also: [], min: '', max: '', can_update_at_runtime: false, flags: [], default: '-' }, { name: 'fsid', type: 'uuid', level: 'basic', desc: 'cluster fsid (uuid)', long_desc: '', daemon_default: '', tags: ['service'], services: ['common'], see_also: [], min: '', max: '', can_update_at_runtime: false, flags: ['no_mon_update'], default: '00000000-0000-0000-0000-000000000000' }, { name: 'mgr_tick_period', type: 'secs', level: 'advanced', desc: 'Period in seconds of beacon messages to monitor', long_desc: '', daemon_default: '', tags: [], services: ['mgr'], see_also: [], min: '', max: '', can_update_at_runtime: true, flags: [], default: '2' } ]; spyOn(configurationService, 'filter').and.returnValue(observableOf(configOptions)); oNames = _.map(configOptions, 'name'); component.optionNames = oNames; component.optionsForm = new CdFormGroup({}); component.optionsFormGroupName = 'testFormGroupName'; component.ngOnInit(); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('optionNameToText', () => { it('should format config option names correctly', () => { const configOptionNames = { osd_scrub_auto_repair_num_errors: 'Scrub Auto Repair Num Errors', osd_debug_deep_scrub_sleep: 'Debug Deep Scrub Sleep', osd_heartbeat_interval: 'Heartbeat Interval', bluestore_compression_algorithm: 'Bluestore Compression Algorithm', rbd_discard_on_zeroed_write_same: 'Rbd Discard On Zeroed Write Same', rbd_journal_max_payload_bytes: 'Rbd Journal Max Payload Bytes', cluster_addr: 'Cluster Addr', fsid: 'Fsid', mgr_tick_period: 'Tick Period' }; component.options.forEach((option) => { expect(option.text).toEqual(configOptionNames[option.name]); }); }); }); describe('createForm', () => { it('should set the optionsFormGroupName correctly', () => { expect(component.optionsFormGroupName).toEqual('testFormGroupName'); }); it('should create a FormControl for every config option', () => { component.options.forEach((option) => { expect(Object.keys(component.optionsFormGroup.controls)).toContain(option.name); }); }); }); describe('loadStorageData', () => { it('should create a list of config options by names', () => { expect(component.options.length).toEqual(9); component.options.forEach((option) => { expect(oNames).toContain(option.name); }); }); it('should add all needed attributes to every config option', () => { component.options.forEach((option) => { const optionKeys = Object.keys(option); expect(optionKeys).toContain('text'); expect(optionKeys).toContain('additionalTypeInfo'); expect(optionKeys).toContain('value'); if (option.type !== 'bool' && option.type !== 'str') { expect(optionKeys).toContain('patternHelpText'); } if (option.name === 'osd_heartbeat_interval') { expect(optionKeys).toContain('maxValue'); expect(optionKeys).toContain('minValue'); } }); }); it('should set minValue and maxValue correctly', () => { component.options.forEach((option) => { if (option.name === 'osd_heartbeat_interval') { expect(option.minValue).toEqual(1); expect(option.maxValue).toEqual(86400); } }); }); it('should set the value attribute correctly', () => { component.options.forEach((option) => { if (option.name === 'osd_heartbeat_interval') { const value = option.value; expect(value).toBeDefined(); expect(value).toEqual({ section: 'osd', value: 6 }); } else { expect(option.value).toBeUndefined(); } }); }); it('should set the FormControl value correctly', () => { component.options.forEach((option) => { const value = component.optionsFormGroup.getValue(option.name); if (option.name === 'osd_heartbeat_interval') { expect(value).toBeDefined(); expect(value).toEqual(6); } else { expect(value).toBeNull(); } }); }); }); });
9,069
29.641892
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/config-option/config-option.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { FormControl, NgForm } from '@angular/forms'; import _ from 'lodash'; import { ConfigurationService } from '~/app/shared/api/configuration.service'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { ConfigOptionTypes } from './config-option.types'; @Component({ selector: 'cd-config-option', templateUrl: './config-option.component.html', styleUrls: ['./config-option.component.scss'] }) export class ConfigOptionComponent implements OnInit { @Input() optionNames: Array<string> = []; @Input() optionsForm: CdFormGroup = new CdFormGroup({}); @Input() optionsFormDir: NgForm = new NgForm([], []); @Input() optionsFormGroupName = ''; @Input() optionsFormShowReset = true; icons = Icons; options: Array<any> = []; optionsFormGroup: CdFormGroup = new CdFormGroup({}); constructor(private configService: ConfigurationService) {} private static optionNameToText(optionName: string): string { const sections = ['mon', 'mgr', 'osd', 'mds', 'client']; return optionName .split('_') .filter((c, index) => index !== 0 || !sections.includes(c)) .map((c) => c.charAt(0).toUpperCase() + c.substring(1)) .join(' '); } ngOnInit() { this.createForm(); this.loadStoredData(); } private createForm() { this.optionsForm.addControl(this.optionsFormGroupName, this.optionsFormGroup); this.optionNames.forEach((optionName) => { this.optionsFormGroup.addControl(optionName, new FormControl(null)); }); } getStep(type: string, value: any): number | undefined { return ConfigOptionTypes.getTypeStep(type, value); } private loadStoredData() { this.configService.filter(this.optionNames).subscribe((data: any) => { this.options = data.map((configOption: any) => { const formControl = this.optionsForm.get(configOption.name); const typeValidators = ConfigOptionTypes.getTypeValidators(configOption); configOption.additionalTypeInfo = ConfigOptionTypes.getType(configOption.type); // Set general information and value configOption.text = ConfigOptionComponent.optionNameToText(configOption.name); configOption.value = _.find(configOption.value, (p) => { return p.section === 'osd'; // TODO: Can handle any other section }); if (configOption.value) { if (configOption.additionalTypeInfo.name === 'bool') { formControl.setValue(configOption.value.value === 'true'); } else { formControl.setValue(configOption.value.value); } } // Set type information and validators if (typeValidators) { configOption.patternHelpText = typeValidators.patternHelpText; if ('max' in typeValidators && typeValidators.max !== '') { configOption.maxValue = typeValidators.max; } if ('min' in typeValidators && typeValidators.min !== '') { configOption.minValue = typeValidators.min; } formControl.setValidators(typeValidators.validators); } return configOption; }); }); } saveValues() { const options = {}; this.optionNames.forEach((optionName) => { const optionValue = this.optionsForm.getValue(optionName); if (optionValue !== null && optionValue !== '') { options[optionName] = { section: 'osd', // TODO: Can handle any other section value: optionValue }; } }); return this.configService.bulkCreate({ options: options }); } resetValue(optionName: string) { this.configService.delete(optionName, 'osd').subscribe( // TODO: Can handle any other section () => { const formControl = this.optionsForm.get(optionName); formControl.reset(); } ); } }
3,959
31.727273
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/config-option/config-option.model.ts
export class ConfigFormModel { name: string; desc: string; long_desc: string; type: string; value: Array<any>; default: any; daemon_default: any; min: any; max: any; services: Array<string>; }
213
15.461538
30
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/config-option/config-option.types.spec.ts
import { ConfigFormModel } from './config-option.model'; import { ConfigOptionTypes } from './config-option.types'; describe('ConfigOptionTypes', () => { describe('getType', () => { it('should return uint type', () => { const ret = ConfigOptionTypes.getType('uint'); expect(ret).toBeTruthy(); expect(ret.name).toBe('uint'); expect(ret.inputType).toBe('number'); expect(ret.humanReadable).toBe('Unsigned integer value'); expect(ret.defaultMin).toBe(0); expect(ret.patternHelpText).toBe('The entered value needs to be an unsigned number.'); expect(ret.isNumberType).toBe(true); expect(ret.allowsNegative).toBe(false); }); it('should return int type', () => { const ret = ConfigOptionTypes.getType('int'); expect(ret).toBeTruthy(); expect(ret.name).toBe('int'); expect(ret.inputType).toBe('number'); expect(ret.humanReadable).toBe('Integer value'); expect(ret.defaultMin).toBeUndefined(); expect(ret.patternHelpText).toBe('The entered value needs to be a number.'); expect(ret.isNumberType).toBe(true); expect(ret.allowsNegative).toBe(true); }); it('should return size type', () => { const ret = ConfigOptionTypes.getType('size'); expect(ret).toBeTruthy(); expect(ret.name).toBe('size'); expect(ret.inputType).toBe('number'); expect(ret.humanReadable).toBe('Unsigned integer value (>=16bit)'); expect(ret.defaultMin).toBe(0); expect(ret.patternHelpText).toBe('The entered value needs to be a unsigned number.'); expect(ret.isNumberType).toBe(true); expect(ret.allowsNegative).toBe(false); }); it('should return secs type', () => { const ret = ConfigOptionTypes.getType('secs'); expect(ret).toBeTruthy(); expect(ret.name).toBe('secs'); expect(ret.inputType).toBe('number'); expect(ret.humanReadable).toBe('Number of seconds'); expect(ret.defaultMin).toBe(1); expect(ret.patternHelpText).toBe('The entered value needs to be a number >= 1.'); expect(ret.isNumberType).toBe(true); expect(ret.allowsNegative).toBe(false); }); it('should return float type', () => { const ret = ConfigOptionTypes.getType('float'); expect(ret).toBeTruthy(); expect(ret.name).toBe('float'); expect(ret.inputType).toBe('number'); expect(ret.humanReadable).toBe('Double value'); expect(ret.defaultMin).toBeUndefined(); expect(ret.patternHelpText).toBe('The entered value needs to be a number or decimal.'); expect(ret.isNumberType).toBe(true); expect(ret.allowsNegative).toBe(true); }); it('should return str type', () => { const ret = ConfigOptionTypes.getType('str'); expect(ret).toBeTruthy(); expect(ret.name).toBe('str'); expect(ret.inputType).toBe('text'); expect(ret.humanReadable).toBe('Text'); expect(ret.defaultMin).toBeUndefined(); expect(ret.patternHelpText).toBeUndefined(); expect(ret.isNumberType).toBe(false); expect(ret.allowsNegative).toBeUndefined(); }); it('should return addr type', () => { const ret = ConfigOptionTypes.getType('addr'); expect(ret).toBeTruthy(); expect(ret.name).toBe('addr'); expect(ret.inputType).toBe('text'); expect(ret.humanReadable).toBe('IPv4 or IPv6 address'); expect(ret.defaultMin).toBeUndefined(); expect(ret.patternHelpText).toBe('The entered value needs to be a valid IP address.'); expect(ret.isNumberType).toBe(false); expect(ret.allowsNegative).toBeUndefined(); }); it('should return uuid type', () => { const ret = ConfigOptionTypes.getType('uuid'); expect(ret).toBeTruthy(); expect(ret.name).toBe('uuid'); expect(ret.inputType).toBe('text'); expect(ret.humanReadable).toBe('UUID'); expect(ret.defaultMin).toBeUndefined(); expect(ret.patternHelpText).toBe( 'The entered value is not a valid UUID, e.g.: 67dcac9f-2c03-4d6c-b7bd-1210b3a259a8' ); expect(ret.isNumberType).toBe(false); expect(ret.allowsNegative).toBeUndefined(); }); it('should return bool type', () => { const ret = ConfigOptionTypes.getType('bool'); expect(ret).toBeTruthy(); expect(ret.name).toBe('bool'); expect(ret.inputType).toBe('checkbox'); expect(ret.humanReadable).toBe('Boolean value'); expect(ret.defaultMin).toBeUndefined(); expect(ret.patternHelpText).toBeUndefined(); expect(ret.isNumberType).toBe(false); expect(ret.allowsNegative).toBeUndefined(); }); it('should throw an error for unknown type', () => { expect(() => ConfigOptionTypes.getType('unknown')).toThrowError( 'Found unknown type "unknown" for config option.' ); }); }); describe('getTypeValidators', () => { it('should return two validators for type uint, secs and size', () => { const types = ['uint', 'size', 'secs']; types.forEach((valType) => { const configOption = new ConfigFormModel(); configOption.type = valType; const ret = ConfigOptionTypes.getTypeValidators(configOption); expect(ret).toBeTruthy(); expect(ret.validators.length).toBe(2); }); }); it('should return a validator for types float, int, addr and uuid', () => { const types = ['float', 'int', 'addr', 'uuid']; types.forEach((valType) => { const configOption = new ConfigFormModel(); configOption.type = valType; const ret = ConfigOptionTypes.getTypeValidators(configOption); expect(ret).toBeTruthy(); expect(ret.validators.length).toBe(1); }); }); it('should return undefined for type bool and str', () => { const types = ['str', 'bool']; types.forEach((valType) => { const configOption = new ConfigFormModel(); configOption.type = valType; const ret = ConfigOptionTypes.getTypeValidators(configOption); expect(ret).toBeUndefined(); }); }); it('should return a pattern and a min validator', () => { const configOption = new ConfigFormModel(); configOption.type = 'int'; configOption.min = 2; const ret = ConfigOptionTypes.getTypeValidators(configOption); expect(ret).toBeTruthy(); expect(ret.validators.length).toBe(2); expect(ret.min).toBe(2); expect(ret.max).toBeUndefined(); }); it('should return a pattern and a max validator', () => { const configOption = new ConfigFormModel(); configOption.type = 'int'; configOption.max = 5; const ret = ConfigOptionTypes.getTypeValidators(configOption); expect(ret).toBeTruthy(); expect(ret.validators.length).toBe(2); expect(ret.min).toBeUndefined(); expect(ret.max).toBe(5); }); it('should return multiple validators', () => { const configOption = new ConfigFormModel(); configOption.type = 'float'; configOption.max = 5.2; configOption.min = 1.5; const ret = ConfigOptionTypes.getTypeValidators(configOption); expect(ret).toBeTruthy(); expect(ret.validators.length).toBe(3); expect(ret.min).toBe(1.5); expect(ret.max).toBe(5.2); }); it( 'should return a pattern help text for type uint, int, size, secs, ' + 'float, addr and uuid', () => { const types = ['uint', 'int', 'size', 'secs', 'float', 'addr', 'uuid']; types.forEach((valType) => { const configOption = new ConfigFormModel(); configOption.type = valType; const ret = ConfigOptionTypes.getTypeValidators(configOption); expect(ret).toBeTruthy(); expect(ret.patternHelpText).toBeDefined(); }); } ); }); describe('getTypeStep', () => { it('should return the correct step for type uint and value 0', () => { const ret = ConfigOptionTypes.getTypeStep('uint', 0); expect(ret).toBe(1); }); it('should return the correct step for type int and value 1', () => { const ret = ConfigOptionTypes.getTypeStep('int', 1); expect(ret).toBe(1); }); it('should return the correct step for type int and value null', () => { const ret = ConfigOptionTypes.getTypeStep('int', null); expect(ret).toBe(1); }); it('should return the correct step for type size and value 2', () => { const ret = ConfigOptionTypes.getTypeStep('size', 2); expect(ret).toBe(1); }); it('should return the correct step for type secs and value 3', () => { const ret = ConfigOptionTypes.getTypeStep('secs', 3); expect(ret).toBe(1); }); it('should return the correct step for type float and value 1', () => { const ret = ConfigOptionTypes.getTypeStep('float', 1); expect(ret).toBe(0.1); }); it('should return the correct step for type float and value 0.1', () => { const ret = ConfigOptionTypes.getTypeStep('float', 0.1); expect(ret).toBe(0.1); }); it('should return the correct step for type float and value 0.02', () => { const ret = ConfigOptionTypes.getTypeStep('float', 0.02); expect(ret).toBe(0.01); }); it('should return the correct step for type float and value 0.003', () => { const ret = ConfigOptionTypes.getTypeStep('float', 0.003); expect(ret).toBe(0.001); }); it('should return the correct step for type float and value null', () => { const ret = ConfigOptionTypes.getTypeStep('float', null); expect(ret).toBe(0.1); }); it('should return undefined for unknown type', () => { const ret = ConfigOptionTypes.getTypeStep('unknown', 1); expect(ret).toBeUndefined(); }); }); });
9,811
34.941392
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/config-option/config-option.types.ts
import { Validators } from '@angular/forms'; import _ from 'lodash'; import { CdValidators } from '~/app/shared/forms/cd-validators'; import { ConfigFormModel } from './config-option.model'; export class ConfigOptionTypes { // TODO: I18N private static knownTypes: Array<any> = [ { name: 'uint', inputType: 'number', humanReadable: 'Unsigned integer value', defaultMin: 0, patternHelpText: 'The entered value needs to be an unsigned number.', isNumberType: true, allowsNegative: false }, { name: 'int', inputType: 'number', humanReadable: 'Integer value', patternHelpText: 'The entered value needs to be a number.', isNumberType: true, allowsNegative: true }, { name: 'size', inputType: 'number', humanReadable: 'Unsigned integer value (>=16bit)', defaultMin: 0, patternHelpText: 'The entered value needs to be a unsigned number.', isNumberType: true, allowsNegative: false }, { name: 'secs', inputType: 'number', humanReadable: 'Number of seconds', defaultMin: 1, patternHelpText: 'The entered value needs to be a number >= 1.', isNumberType: true, allowsNegative: false }, { name: 'float', inputType: 'number', humanReadable: 'Double value', patternHelpText: 'The entered value needs to be a number or decimal.', isNumberType: true, allowsNegative: true }, { name: 'str', inputType: 'text', humanReadable: 'Text', isNumberType: false }, { name: 'addr', inputType: 'text', humanReadable: 'IPv4 or IPv6 address', patternHelpText: 'The entered value needs to be a valid IP address.', isNumberType: false }, { name: 'uuid', inputType: 'text', humanReadable: 'UUID', patternHelpText: 'The entered value is not a valid UUID, e.g.: 67dcac9f-2c03-4d6c-b7bd-1210b3a259a8', isNumberType: false }, { name: 'bool', inputType: 'checkbox', humanReadable: 'Boolean value', isNumberType: false } ]; public static getType(type: string): any { const currentType = _.find(this.knownTypes, (t) => { return t.name === type; }); if (currentType !== undefined) { return currentType; } throw new Error('Found unknown type "' + type + '" for config option.'); } public static getTypeValidators(configOption: ConfigFormModel): any { const typeParams = ConfigOptionTypes.getType(configOption.type); if (typeParams.name === 'bool' || typeParams.name === 'str') { return; } const typeValidators: Record<string, any> = { validators: [], patternHelpText: typeParams.patternHelpText }; if (typeParams.isNumberType) { if (configOption.max && configOption.max !== '') { typeValidators['max'] = configOption.max; typeValidators.validators.push(Validators.max(configOption.max)); } if (configOption.min && configOption.min !== '') { typeValidators['min'] = configOption.min; typeValidators.validators.push(Validators.min(configOption.min)); } else if ('defaultMin' in typeParams) { typeValidators['min'] = typeParams.defaultMin; typeValidators.validators.push(Validators.min(typeParams.defaultMin)); } if (configOption.type === 'float') { typeValidators.validators.push(CdValidators.decimalNumber()); } else { typeValidators.validators.push(CdValidators.number(typeParams.allowsNegative)); } } else if (configOption.type === 'addr') { typeValidators.validators = [CdValidators.ip()]; } else if (configOption.type === 'uuid') { typeValidators.validators = [CdValidators.uuid()]; } return typeValidators; } public static getTypeStep(type: string, value: number): number | undefined { const numberTypes = ['uint', 'int', 'size', 'secs']; if (numberTypes.includes(type)) { return 1; } if (type === 'float') { if (value !== null) { const stringVal = value.toString(); if (stringVal.indexOf('.') !== -1) { // Value type float and contains decimal characters const decimal = value.toString().split('.'); return Math.pow(10, -decimal[1].length); } } return 0.1; } return undefined; } }
4,426
28.912162
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/confirmation-modal/confirmation-modal.component.html
<cd-modal (hide)="cancel()"> <ng-container class="modal-title"> <span class="text-warning" *ngIf="warning"> <i class="fa fa-exclamation-triangle fa-1x"></i> </span>{{ titleText }}</ng-container> <ng-container class="modal-content"> <form name="confirmationForm" #formDir="ngForm" [formGroup]="confirmationForm" novalidate> <div class="modal-body"> <ng-container *ngTemplateOutlet="bodyTpl; context: bodyContext"></ng-container> <p *ngIf="description"> {{description}} </p> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="onSubmit(confirmationForm.value)" (backActionEvent)="boundCancel()" [form]="confirmationForm" [submitText]="buttonText" [showCancel]="showCancel" [showSubmit]="showSubmit"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
1,073
36.034483
87
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/confirmation-modal/confirmation-modal.component.spec.ts
import { Component, NgModule, NO_ERRORS_SCHEMA, TemplateRef, ViewChild } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal, NgbModalModule, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { ModalService } from '~/app/shared/services/modal.service'; import { configureTestBed, FixtureHelper } from '~/testing/unit-test-helper'; import { BackButtonComponent } from '../back-button/back-button.component'; import { FormButtonPanelComponent } from '../form-button-panel/form-button-panel.component'; import { ModalComponent } from '../modal/modal.component'; import { SubmitButtonComponent } from '../submit-button/submit-button.component'; import { ConfirmationModalComponent } from './confirmation-modal.component'; @NgModule({}) export class MockModule {} @Component({ template: `<ng-template #fillTpl>Template based description.</ng-template>` }) class MockComponent { @ViewChild('fillTpl', { static: true }) fillTpl: TemplateRef<any>; modalRef: NgbModalRef; returnValue: any; // Normally private, but public is needed by tests constructor(public modalService: ModalService) {} private openModal(extendBaseState = {}) { this.modalRef = this.modalService.show( ConfirmationModalComponent, Object.assign( { titleText: 'Title is a must have', buttonText: 'Action label', bodyTpl: this.fillTpl, description: 'String based description.', onSubmit: () => { this.returnValue = 'The submit action has to hide manually.'; } }, extendBaseState ) ); } basicModal() { this.openModal(); } customCancelModal() { this.openModal({ onCancel: () => (this.returnValue = 'If you have todo something besides hiding the modal.') }); } } describe('ConfirmationModalComponent', () => { let component: ConfirmationModalComponent; let fixture: ComponentFixture<ConfirmationModalComponent>; let mockComponent: MockComponent; let mockFixture: ComponentFixture<MockComponent>; let fh: FixtureHelper; const expectReturnValue = (v: string) => expect(mockComponent.returnValue).toBe(v); configureTestBed({ declarations: [ ConfirmationModalComponent, BackButtonComponent, MockComponent, ModalComponent, SubmitButtonComponent, FormButtonPanelComponent ], schemas: [NO_ERRORS_SCHEMA], imports: [ReactiveFormsModule, MockModule, RouterTestingModule, NgbModalModule], providers: [NgbActiveModal, SubmitButtonComponent, FormButtonPanelComponent] }); beforeEach(() => { fh = new FixtureHelper(); mockFixture = TestBed.createComponent(MockComponent); mockComponent = mockFixture.componentInstance; mockFixture.detectChanges(); spyOn(TestBed.inject(ModalService), 'show').and.callFake((_modalComp, config) => { fixture = TestBed.createComponent(ConfirmationModalComponent); component = fixture.componentInstance; component = Object.assign(component, config); component.activeModal = { close: () => true } as any; spyOn(component.activeModal, 'close').and.callThrough(); fh.updateFixture(fixture); }); }); it('should create', () => { mockComponent.basicModal(); expect(component).toBeTruthy(); }); describe('Throws errors', () => { const expectError = (config: object, expected: string) => { mockComponent.basicModal(); component = Object.assign(component, config); expect(() => component.ngOnInit()).toThrowError(expected); }; it('has no submit action defined', () => { expectError( { onSubmit: undefined }, 'No submit action defined' ); }); it('has no title defined', () => { expectError( { titleText: undefined }, 'No title defined' ); }); it('has no action name defined', () => { expectError( { buttonText: undefined }, 'No action name defined' ); }); it('has no description defined', () => { expectError( { bodyTpl: undefined, description: undefined }, 'No description defined' ); }); }); describe('basics', () => { beforeEach(() => { mockComponent.basicModal(); spyOn(component, 'onSubmit').and.callThrough(); }); it('should show the correct title', () => { expect(fh.getText('.modal-title')).toBe('Title is a must have'); }); it('should show the correct action name', () => { expect(fh.getText('.tc_submitButton')).toBe('Action label'); }); it('should use the correct submit action', () => { // In order to ignore the `ElementRef` usage of `SubmitButtonComponent` spyOn(fh.getElementByCss('.tc_submitButton').componentInstance, 'focusButton'); fh.clickElement('.tc_submitButton'); expect(component.onSubmit).toHaveBeenCalledTimes(1); expect(component.activeModal.close).toHaveBeenCalledTimes(0); expectReturnValue('The submit action has to hide manually.'); }); it('should use the default cancel action', () => { fh.clickElement('.tc_backButton'); expect(component.onSubmit).toHaveBeenCalledTimes(0); expect(component.activeModal.close).toHaveBeenCalledTimes(1); expectReturnValue(undefined); }); it('should show the description', () => { expect(fh.getText('.modal-body')).toBe( 'Template based description. String based description.' ); }); }); });
5,754
29.94086
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/confirmation-modal/confirmation-modal.component.ts
import { Component, OnDestroy, OnInit, TemplateRef } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'cd-confirmation-modal', templateUrl: './confirmation-modal.component.html', styleUrls: ['./confirmation-modal.component.scss'] }) export class ConfirmationModalComponent implements OnInit, OnDestroy { // Needed buttonText: string; titleText: string; onSubmit: Function; // One of them is needed bodyTpl?: TemplateRef<any>; description?: TemplateRef<any>; // Optional warning = false; bodyData?: object; onCancel?: Function; bodyContext?: object; showSubmit = true; showCancel = true; // Component only boundCancel = this.cancel.bind(this); confirmationForm: FormGroup; private canceled = false; constructor(public activeModal: NgbActiveModal) { this.confirmationForm = new FormGroup({}); } ngOnInit() { this.bodyContext = this.bodyContext || {}; this.bodyContext['$implicit'] = this.bodyData; if (!this.onSubmit) { throw new Error('No submit action defined'); } else if (!this.buttonText) { throw new Error('No action name defined'); } else if (!this.titleText) { throw new Error('No title defined'); } else if (!this.bodyTpl && !this.description) { throw new Error('No description defined'); } } ngOnDestroy() { if (this.onCancel && this.canceled) { this.onCancel(); } } cancel() { this.canceled = true; this.activeModal.close(); } stopLoadingSpinner() { this.confirmationForm.setErrors({ cdSubmitButton: true }); } }
1,677
24.044776
74
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/copy2clipboard-button/copy2clipboard-button.component.html
<button (click)="onClick()" type="button" class="btn btn-light" i18n-title title="Copy to Clipboard"> <i [ngClass]="[icons.clipboard]"></i> </button>
184
22.125
39
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/copy2clipboard-button/copy2clipboard-button.component.spec.ts
import { TestBed } from '@angular/core/testing'; import * as BrowserDetect from 'detect-browser'; import { ToastrService } from 'ngx-toastr'; import { configureTestBed } from '~/testing/unit-test-helper'; import { Copy2ClipboardButtonComponent } from './copy2clipboard-button.component'; describe('Copy2ClipboardButtonComponent', () => { let component: Copy2ClipboardButtonComponent; configureTestBed({ providers: [ { provide: ToastrService, useValue: { error: () => true, success: () => true } } ] }); it('should create an instance', () => { component = new Copy2ClipboardButtonComponent(null); expect(component).toBeTruthy(); }); describe('test onClick behaviours', () => { let toastrService: ToastrService; let queryFn: jasmine.Spy; let writeTextFn: jasmine.Spy; beforeEach(() => { toastrService = TestBed.inject(ToastrService); component = new Copy2ClipboardButtonComponent(toastrService); spyOn<any>(component, 'getText').and.returnValue('foo'); Object.assign(navigator, { permissions: { query: jest.fn() }, clipboard: { writeText: jest.fn() } }); queryFn = spyOn(navigator.permissions, 'query'); }); it('should not call permissions API', () => { spyOn(BrowserDetect, 'detect').and.returnValue({ name: 'firefox' }); writeTextFn = spyOn(navigator.clipboard, 'writeText').and.returnValue( new Promise<void>((resolve, _) => { resolve(); }) ); component.onClick(); expect(queryFn).not.toHaveBeenCalled(); expect(writeTextFn).toHaveBeenCalledWith('foo'); }); it('should call permissions API', () => { spyOn(BrowserDetect, 'detect').and.returnValue({ name: 'chrome' }); component.onClick(); expect(queryFn).toHaveBeenCalled(); }); }); });
1,919
28.090909
82
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/copy2clipboard-button/copy2clipboard-button.component.ts
import { Component, HostListener, Input } from '@angular/core'; import { detect } from 'detect-browser'; import { ToastrService } from 'ngx-toastr'; import { Icons } from '~/app/shared/enum/icons.enum'; @Component({ selector: 'cd-copy-2-clipboard-button', templateUrl: './copy2clipboard-button.component.html', styleUrls: ['./copy2clipboard-button.component.scss'] }) export class Copy2ClipboardButtonComponent { @Input() private source: string; @Input() byId = true; icons = Icons; constructor(private toastr: ToastrService) {} private getText(): string { const element = document.getElementById(this.source) as HTMLInputElement; return element.value; } @HostListener('click') onClick() { try { const browser = detect(); const text = this.byId ? this.getText() : this.source; const toastrFn = () => { this.toastr.success('Copied text to the clipboard successfully.'); }; if (['firefox', 'ie', 'ios', 'safari'].includes(browser.name)) { // Various browsers do not support the `Permissions API`. // https://developer.mozilla.org/en-US/docs/Web/API/Permissions_API#Browser_compatibility navigator.clipboard.writeText(text).then(() => toastrFn()); } else { // Checking if we have the clipboard-write permission navigator.permissions .query({ name: 'clipboard-write' as PermissionName }) .then((result: any) => { if (result.state === 'granted' || result.state === 'prompt') { navigator.clipboard.writeText(text).then(() => toastrFn()); } }); } } catch (_) { this.toastr.error('Failed to copy text to the clipboard.'); } } }
1,740
30.089286
97
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component.html
<cd-modal #modal [modalRef]="activeModal"> <ng-container class="modal-title"> <ng-container *ngTemplateOutlet="deletionHeading"></ng-container> </ng-container> <ng-container class="modal-content"> <form name="deletionForm" #formDir="ngForm" [formGroup]="deletionForm" novalidate> <div class="modal-body"> <ng-container *ngTemplateOutlet="bodyTemplate; context: bodyContext"></ng-container> <div class="question"> <span *ngIf="itemNames; else noNames"> <p *ngIf="itemNames.length === 1; else manyNames" i18n>Are you sure that you want to {{ actionDescription | lowercase }} <strong>{{ itemNames[0] }}</strong>?</p> <ng-template #manyNames> <p i18n>Are you sure that you want to {{ actionDescription | lowercase }} the selected items?</p> <ul> <li *ngFor="let itemName of itemNames"><strong>{{ itemName }}</strong></li> </ul> </ng-template > </span> <ng-template #noNames> <p i18n>Are you sure that you want to {{ actionDescription | lowercase }} the selected {{ itemDescription }}?</p> </ng-template> <ng-container *ngTemplateOutlet="childFormGroupTemplate; context:{form:deletionForm}"></ng-container> <div class="form-group"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" name="confirmation" id="confirmation" formControlName="confirmation" autofocus> <label class="custom-control-label" for="confirmation" i18n>Yes, I am sure.</label> </div> </div> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="callSubmitAction()" [form]="deletionForm" [submitText]="(actionDescription | titlecase) + ' ' + itemDescription"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal> <ng-template #deletionHeading> {{ actionDescription | titlecase }} {{ itemDescription }} </ng-template>
2,340
40.803571
126
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component.spec.ts
import { Component, NgModule, NO_ERRORS_SCHEMA, TemplateRef, ViewChild } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { NgForm, ReactiveFormsModule } from '@angular/forms'; import { NgbActiveModal, NgbModalModule, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { Observable, Subscriber, timer as observableTimer } from 'rxjs'; import { DirectivesModule } from '~/app/shared/directives/directives.module'; import { ModalService } from '~/app/shared/services/modal.service'; import { configureTestBed, modalServiceShow } from '~/testing/unit-test-helper'; import { AlertPanelComponent } from '../alert-panel/alert-panel.component'; import { LoadingPanelComponent } from '../loading-panel/loading-panel.component'; import { CriticalConfirmationModalComponent } from './critical-confirmation-modal.component'; @NgModule({}) export class MockModule {} @Component({ template: ` <button type="button" class="btn btn-danger" (click)="openCtrlDriven()"> <i class="fa fa-times"></i>Deletion Ctrl-Test <ng-template #ctrlDescription> The spinner is handled by the controller if you have use the modal as ViewChild in order to use it's functions to stop the spinner or close the dialog. </ng-template> </button> <button type="button" class="btn btn-danger" (click)="openModalDriven()"> <i class="fa fa-times"></i>Deletion Modal-Test <ng-template #modalDescription> The spinner is handled by the modal if your given deletion function returns a Observable. </ng-template> </button> ` }) class MockComponent { @ViewChild('ctrlDescription', { static: true }) ctrlDescription: TemplateRef<any>; @ViewChild('modalDescription', { static: true }) modalDescription: TemplateRef<any>; someData = [1, 2, 3, 4, 5]; finished: number[]; ctrlRef: NgbModalRef; modalRef: NgbModalRef; // Normally private - public was needed for the tests constructor(public modalService: ModalService) {} openCtrlDriven() { this.ctrlRef = this.modalService.show(CriticalConfirmationModalComponent, { submitAction: this.fakeDeleteController.bind(this), bodyTemplate: this.ctrlDescription }); } openModalDriven() { this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { submitActionObservable: this.fakeDelete(), bodyTemplate: this.modalDescription }); } finish() { this.finished = [6, 7, 8, 9]; } fakeDelete() { return (): Observable<any> => { return new Observable((observer: Subscriber<any>) => { observableTimer(100).subscribe(() => { observer.next(this.finish()); observer.complete(); }); }); }; } fakeDeleteController() { observableTimer(100).subscribe(() => { this.finish(); this.ctrlRef.close(); }); } } describe('CriticalConfirmationModalComponent', () => { let mockComponent: MockComponent; let component: CriticalConfirmationModalComponent; let mockFixture: ComponentFixture<MockComponent>; configureTestBed( { declarations: [ MockComponent, CriticalConfirmationModalComponent, LoadingPanelComponent, AlertPanelComponent ], schemas: [NO_ERRORS_SCHEMA], imports: [ReactiveFormsModule, MockModule, DirectivesModule, NgbModalModule], providers: [NgbActiveModal] }, [CriticalConfirmationModalComponent] ); beforeEach(() => { mockFixture = TestBed.createComponent(MockComponent); mockComponent = mockFixture.componentInstance; spyOn(mockComponent.modalService, 'show').and.callFake((_modalComp, config) => { const data = modalServiceShow(CriticalConfirmationModalComponent, config); component = data.componentInstance; return data; }); mockComponent.openCtrlDriven(); mockFixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should throw an error if no action is defined', () => { component = Object.assign(component, { submitAction: null, submitActionObservable: null }); expect(() => component.ngOnInit()).toThrowError('No submit action defined'); }); it('should test if the ctrl driven mock is set correctly through mock component', () => { expect(component.bodyTemplate).toBeTruthy(); expect(component.submitAction).toBeTruthy(); expect(component.submitActionObservable).not.toBeTruthy(); }); it('should test if the modal driven mock is set correctly through mock component', () => { mockComponent.openModalDriven(); expect(component.bodyTemplate).toBeTruthy(); expect(component.submitActionObservable).toBeTruthy(); expect(component.submitAction).not.toBeTruthy(); }); describe('component functions', () => { const changeValue = (value: boolean) => { const ctrl = component.deletionForm.get('confirmation'); ctrl.setValue(value); ctrl.markAsDirty(); ctrl.updateValueAndValidity(); mockFixture.detectChanges(); }; it('should test hideModal', () => { expect(component.activeModal).toBeTruthy(); expect(component.hideModal).toBeTruthy(); spyOn(component.activeModal, 'close').and.callThrough(); expect(component.activeModal.close).not.toHaveBeenCalled(); component.hideModal(); expect(component.activeModal.close).toHaveBeenCalled(); }); describe('validate confirmation', () => { const testValidation = (submitted: boolean, error: string, expected: boolean) => { expect( component.deletionForm.showError('confirmation', <NgForm>{ submitted: submitted }, error) ).toBe(expected); }; beforeEach(() => { component.deletionForm.reset(); }); it('should test empty values', () => { component.deletionForm.reset(); testValidation(false, undefined, false); testValidation(true, 'required', true); component.deletionForm.reset(); changeValue(true); changeValue(false); testValidation(true, 'required', true); }); }); describe('deletion call', () => { beforeEach(() => { spyOn(component, 'stopLoadingSpinner').and.callThrough(); spyOn(component, 'hideModal').and.callThrough(); }); describe('Controller driven', () => { beforeEach(() => { spyOn(component, 'submitAction').and.callThrough(); spyOn(mockComponent.ctrlRef, 'close').and.callThrough(); }); it('should test fake deletion that closes modal', fakeAsync(() => { // Before deletionCall expect(component.submitAction).not.toHaveBeenCalled(); // During deletionCall component.callSubmitAction(); expect(component.stopLoadingSpinner).not.toHaveBeenCalled(); expect(component.hideModal).not.toHaveBeenCalled(); expect(mockComponent.ctrlRef.close).not.toHaveBeenCalled(); expect(component.submitAction).toHaveBeenCalled(); expect(mockComponent.finished).toBe(undefined); // After deletionCall tick(2000); expect(component.hideModal).not.toHaveBeenCalled(); expect(mockComponent.ctrlRef.close).toHaveBeenCalled(); expect(mockComponent.finished).toEqual([6, 7, 8, 9]); })); }); describe('Modal driven', () => { beforeEach(() => { mockComponent.openModalDriven(); spyOn(component, 'stopLoadingSpinner').and.callThrough(); spyOn(component, 'hideModal').and.callThrough(); spyOn(mockComponent, 'fakeDelete').and.callThrough(); }); it('should delete and close modal', fakeAsync(() => { // During deletionCall component.callSubmitAction(); expect(mockComponent.finished).toBe(undefined); expect(component.hideModal).not.toHaveBeenCalled(); // After deletionCall tick(2000); expect(mockComponent.finished).toEqual([6, 7, 8, 9]); expect(component.stopLoadingSpinner).not.toHaveBeenCalled(); expect(component.hideModal).toHaveBeenCalled(); })); }); }); }); });
8,300
34.173729
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { Observable } from 'rxjs'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { SubmitButtonComponent } from '../submit-button/submit-button.component'; @Component({ selector: 'cd-deletion-modal', templateUrl: './critical-confirmation-modal.component.html', styleUrls: ['./critical-confirmation-modal.component.scss'] }) export class CriticalConfirmationModalComponent implements OnInit { @ViewChild(SubmitButtonComponent, { static: true }) submitButton: SubmitButtonComponent; bodyTemplate: TemplateRef<any>; bodyContext: object; submitActionObservable: () => Observable<any>; submitAction: Function; deletionForm: CdFormGroup; itemDescription: 'entry'; itemNames: string[]; actionDescription = 'delete'; childFormGroup: CdFormGroup; childFormGroupTemplate: TemplateRef<any>; constructor(public activeModal: NgbActiveModal) {} ngOnInit() { const controls = { confirmation: new FormControl(false, [Validators.requiredTrue]) }; if (this.childFormGroup) { controls['child'] = this.childFormGroup; } this.deletionForm = new CdFormGroup(controls); if (!(this.submitAction || this.submitActionObservable)) { throw new Error('No submit action defined'); } } callSubmitAction() { if (this.submitActionObservable) { this.submitActionObservable().subscribe({ error: this.stopLoadingSpinner.bind(this), complete: this.hideModal.bind(this) }); } else { this.submitAction(); } } hideModal() { this.activeModal.close(); } stopLoadingSpinner() { this.deletionForm.setErrors({ cdSubmitButton: true }); } }
1,870
28.234375
81
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/custom-login-banner/custom-login-banner.component.html
<p class="login-text" *ngIf="bannerText$ | async as bannerText">{{ bannerText }}</p>
88
28.666667
65
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/custom-login-banner/custom-login-banner.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { CustomLoginBannerComponent } from './custom-login-banner.component'; describe('CustomLoginBannerComponent', () => { let component: CustomLoginBannerComponent; let fixture: ComponentFixture<CustomLoginBannerComponent>; configureTestBed({ declarations: [CustomLoginBannerComponent], imports: [HttpClientTestingModule] }); beforeEach(() => { fixture = TestBed.createComponent(CustomLoginBannerComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
794
29.576923
77
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/custom-login-banner/custom-login-banner.component.ts
import { Component, OnInit } from '@angular/core'; import _ from 'lodash'; import { Observable } from 'rxjs'; import { CustomLoginBannerService } from '~/app/shared/api/custom-login-banner.service'; @Component({ selector: 'cd-custom-login-banner', templateUrl: './custom-login-banner.component.html', styleUrls: ['./custom-login-banner.component.scss'] }) export class CustomLoginBannerComponent implements OnInit { bannerText$: Observable<string>; constructor(private customLoginBannerService: CustomLoginBannerService) {} ngOnInit(): void { this.bannerText$ = this.customLoginBannerService.getBannerText(); } }
635
29.285714
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/date-time-picker/date-time-picker.component.html
<div class="d-flex justify-content-center"> <ngb-datepicker #dp [(ngModel)]="date" [minDate]="minDate" (ngModelChange)="onModelChange()"></ngb-datepicker> </div> <div class="d-flex justify-content-center" *ngIf="hasTime"> <ngb-timepicker [seconds]="hasSeconds" [(ngModel)]="time" (ngModelChange)="onModelChange()"></ngb-timepicker> </div>
439
30.428571
69
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/date-time-picker/date-time-picker.component.spec.ts
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { FormControl, FormsModule } from '@angular/forms'; import { NgbDatepickerModule, NgbTimepickerModule } from '@ng-bootstrap/ng-bootstrap'; import { configureTestBed } from '~/testing/unit-test-helper'; import { DateTimePickerComponent } from './date-time-picker.component'; describe('DateTimePickerComponent', () => { let component: DateTimePickerComponent; let fixture: ComponentFixture<DateTimePickerComponent>; configureTestBed({ declarations: [DateTimePickerComponent], imports: [NgbDatepickerModule, NgbTimepickerModule, FormsModule] }); beforeEach(() => { spyOn(Date, 'now').and.returnValue(new Date('2022-02-22T00:00:00.00')); fixture = TestBed.createComponent(DateTimePickerComponent); component = fixture.componentInstance; }); it('should create with correct datetime', fakeAsync(() => { component.control = new FormControl('2022-02-26 00:00:00'); fixture.detectChanges(); tick(); expect(component).toBeTruthy(); expect(component.control.value).toBe('2022-02-26 00:00:00'); })); it('should update control value if datetime is not valid', fakeAsync(() => { component.control = new FormControl('not valid'); fixture.detectChanges(); tick(); expect(component.control.value).toBe('2022-02-22 00:00:00'); })); it('should init with only date enabled', () => { component.control = new FormControl(); component.hasTime = false; fixture.detectChanges(); expect(component.format).toBe('YYYY-MM-DD'); }); it('should init with time enabled', () => { component.control = new FormControl(); component.hasSeconds = false; fixture.detectChanges(); expect(component.format).toBe('YYYY-MM-DD HH:mm'); }); it('should init with seconds enabled', () => { component.control = new FormControl(); fixture.detectChanges(); expect(component.format).toBe('YYYY-MM-DD HH:mm:ss'); }); });
2,002
32.949153
86
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/date-time-picker/date-time-picker.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { NgbCalendar, NgbDateStruct, NgbTimeStruct } from '@ng-bootstrap/ng-bootstrap'; import moment from 'moment'; import { Subscription } from 'rxjs'; @Component({ selector: 'cd-date-time-picker', templateUrl: './date-time-picker.component.html', styleUrls: ['./date-time-picker.component.scss'] }) export class DateTimePickerComponent implements OnInit { @Input() control: FormControl; @Input() hasSeconds = true; @Input() hasTime = true; format: string; minDate: NgbDateStruct; date: NgbDateStruct; time: NgbTimeStruct; sub: Subscription; constructor(private calendar: NgbCalendar) {} ngOnInit() { this.minDate = this.calendar.getToday(); if (!this.hasTime) { this.format = 'YYYY-MM-DD'; } else if (this.hasSeconds) { this.format = 'YYYY-MM-DD HH:mm:ss'; } else { this.format = 'YYYY-MM-DD HH:mm'; } let mom = moment(this.control?.value, this.format); if (!mom.isValid() || mom.isBefore(moment())) { mom = moment(); } this.date = { year: mom.year(), month: mom.month() + 1, day: mom.date() }; this.time = { hour: mom.hour(), minute: mom.minute(), second: mom.second() }; this.onModelChange(); } onModelChange() { if (this.date) { const datetime = Object.assign({}, this.date, this.time); datetime.month--; setTimeout(() => { this.control.setValue(moment(datetime).format(this.format)); }); } else { setTimeout(() => { this.control.setValue(''); }); } } }
1,647
23.235294
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/doc/doc.component.html
<a href="{{ docUrl }}" target="_blank">{{ docText }}</a>
60
19.333333
36
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/doc/doc.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { CephReleaseNamePipe } from '~/app/shared/pipes/ceph-release-name.pipe'; import { configureTestBed } from '~/testing/unit-test-helper'; import { DocComponent } from './doc.component'; describe('DocComponent', () => { let component: DocComponent; let fixture: ComponentFixture<DocComponent>; configureTestBed({ declarations: [DocComponent], imports: [HttpClientTestingModule], providers: [CephReleaseNamePipe] }); beforeEach(() => { fixture = TestBed.createComponent(DocComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
813
28.071429
80
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/doc/doc.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { DocService } from '~/app/shared/services/doc.service'; @Component({ selector: 'cd-doc', templateUrl: './doc.component.html', styleUrls: ['./doc.component.scss'] }) export class DocComponent implements OnInit { @Input() section: string; @Input() docText = $localize`documentation`; @Input() noSubscribe: boolean; docUrl: string; constructor(private docService: DocService) {} ngOnInit() { if (this.noSubscribe) { this.docUrl = this.docService.urlGenerator(this.section); } else { this.docService.subscribeOnce(this.section, (url: string) => { this.docUrl = url; }); } } }
701
23.206897
68
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/download-button/download-button.component.html
<div ngbDropdown placement="bottom-right"> <button type="button" [title]="title" class="btn btn-light dropdown-toggle-split" ngbDropdownToggle> <i [ngClass]="[icons.download]"></i> </button> <div ngbDropdownMenu> <button ngbDropdownItem (click)="download('json')" *ngIf="objectItem"> <i [ngClass]="[icons.json]"></i> <span>JSON</span> </button> <button ngbDropdownItem (click)="download()" *ngIf="textItem"> <i [ngClass]="[icons.text]"></i> <span>Text</span> </button> </div> </div>
618
24.791667
53
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/download-button/download-button.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { TextToDownloadService } from '~/app/shared/services/text-to-download.service'; import { configureTestBed } from '~/testing/unit-test-helper'; import { DownloadButtonComponent } from './download-button.component'; describe('DownloadButtonComponent', () => { let component: DownloadButtonComponent; let fixture: ComponentFixture<DownloadButtonComponent>; configureTestBed({ declarations: [DownloadButtonComponent], providers: [TextToDownloadService] }); beforeEach(() => { fixture = TestBed.createComponent(DownloadButtonComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should call download function', () => { component.objectItem = { testA: 'testA', testB: 'testB' }; const downloadSpy = spyOn(TestBed.inject(TextToDownloadService), 'download'); component.fileName = `${'reportText.json'}_${new Date().toLocaleDateString()}`; component.download('json'); expect(downloadSpy).toHaveBeenCalledWith( JSON.stringify(component.objectItem, null, 2), `${component.fileName}.json` ); }); });
1,259
30.5
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/download-button/download-button.component.ts
import { Component, Input } from '@angular/core'; import { Icons } from '~/app/shared/enum/icons.enum'; import { TextToDownloadService } from '~/app/shared/services/text-to-download.service'; @Component({ selector: 'cd-download-button', templateUrl: './download-button.component.html', styleUrls: ['./download-button.component.scss'] }) export class DownloadButtonComponent { @Input() objectItem: object; @Input() textItem: string; @Input() fileName: any; @Input() title = $localize`Download`; icons = Icons; constructor(private textToDownloadService: TextToDownloadService) {} download(format?: string) { this.fileName = `${this.fileName}_${new Date().toLocaleDateString()}`; if (format === 'json') { this.textToDownloadService.download( JSON.stringify(this.objectItem, null, 2), `${this.fileName}.json` ); } else { this.textToDownloadService.download(this.textItem, `${this.fileName}.txt`); } } }
975
29.5
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/form-button-panel/form-button-panel.component.html
<div [class]="wrappingClass"> <cd-back-button *ngIf="showCancel" class="m-2" (backAction)="backAction()" [name]="cancelText"></cd-back-button> <cd-submit-button *ngIf="showSubmit" (submitAction)="submitAction()" [disabled]="disabled" [form]="form" [ariaLabel]="submitText" data-cy="submitBtn">{{ submitText }}</cd-submit-button> </div>
494
37.076923
75
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/form-button-panel/form-button-panel.component.spec.ts
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { FormButtonPanelComponent } from './form-button-panel.component'; describe('FormButtonPanelComponent', () => { let component: FormButtonPanelComponent; let fixture: ComponentFixture<FormButtonPanelComponent>; configureTestBed({ declarations: [FormButtonPanelComponent], schemas: [NO_ERRORS_SCHEMA] }); beforeEach(() => { fixture = TestBed.createComponent(FormButtonPanelComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
751
27.923077
73
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/form-button-panel/form-button-panel.component.ts
import { Location } from '@angular/common'; import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core'; import { FormGroup, NgForm } from '@angular/forms'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { ModalService } from '~/app/shared/services/modal.service'; import { SubmitButtonComponent } from '../submit-button/submit-button.component'; @Component({ selector: 'cd-form-button-panel', templateUrl: './form-button-panel.component.html', styleUrls: ['./form-button-panel.component.scss'] }) export class FormButtonPanelComponent { @ViewChild(SubmitButtonComponent) submitButton: SubmitButtonComponent; @Output() submitActionEvent = new EventEmitter(); @Output() backActionEvent = new EventEmitter(); @Input() form: FormGroup | NgForm; @Input() showSubmit = true; @Input() showCancel = true; @Input() wrappingClass = ''; @Input() btnClass = ''; @Input() submitText: string = this.actionLabels.CREATE; @Input() cancelText: string = this.actionLabels.CANCEL; @Input() disabled = false; constructor( private location: Location, private actionLabels: ActionLabelsI18n, private modalService: ModalService ) {} submitAction() { this.submitActionEvent.emit(); } backAction() { if (this.backActionEvent.observers.length === 0) { if (this.modalService.hasOpenModals()) { this.modalService.dismissAll(); } else { this.location.back(); } } else { this.backActionEvent.emit(); } } }
1,569
24.322581
82
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/components/form-modal/form-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container *ngIf="titleText" class="modal-title"> {{ titleText }} </ng-container> <ng-container class="modal-content"> <form [formGroup]="formGroup" #formDir="ngForm" novalidate> <div class="modal-body"> <p *ngIf="message">{{ message }}</p> <ng-container *ngFor="let field of fields"> <div class="form-group row cd-{{field.name}}-form-group"> <label *ngIf="field.label" class="cd-col-form-label" [ngClass]="{'required': field?.required === true}" [for]="field.name"> {{ field.label }} </label> <div [ngClass]="{'cd-col-form-input': field.label, 'col-sm-12': !field.label}"> <input *ngIf="['text', 'number'].includes(field.type)" [type]="field.type" class="form-control" [id]="field.name" [name]="field.name" [formControlName]="field.name"> <input *ngIf="field.type === 'binary'" type="text" class="form-control" [id]="field.name" [name]="field.name" [formControlName]="field.name" cdDimlessBinary> <select *ngIf="field.type === 'select'" class="form-select" [id]="field.name" [formControlName]="field.name"> <option *ngIf="field?.typeConfig?.placeholder" [ngValue]="null"> {{ field?.typeConfig?.placeholder }} </option> <option *ngFor="let option of field?.typeConfig?.options" [value]="option.value"> {{ option.text }} </option> </select> <cd-select-badges *ngIf="field.type === 'select-badges'" [id]="field.name" [data]="field.value" [customBadges]="field?.typeConfig?.customBadges" [options]="field?.typeConfig?.options" [messages]="field?.typeConfig?.messages"> </cd-select-badges> <span *ngIf="formGroup.showError(field.name, formDir)" class="invalid-feedback"> {{ getError(field) }} </span> </div> </div> </ng-container> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="onSubmitForm(formGroup.value)" [form]="formGroup" [submitText]="submitButtonText"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
2,956
41.242857
91
html