Search is not available for this dataset
repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-user-capabilities.ts
|
export enum RgwUserAvailableCapability {
USERS = 'users',
BUCKETS = 'buckets',
METADATA = 'metadata',
USAGE = 'usage',
ZONE = 'zone'
}
export class RgwUserCapabilities {
static readonly capabilities = RgwUserAvailableCapability;
static getAll(): string[] {
return Object.values(RgwUserCapabilities.capabilities);
}
}
| 339 | 20.25 | 60 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-user-capability.ts
|
export class RgwUserCapability {
type: string;
perm: string;
}
| 67 | 12.6 | 32 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-user-s3-key.ts
|
export class RgwUserS3Key {
user: string;
generate_key?: boolean;
access_key: string;
secret_key: string;
}
| 116 | 15.714286 | 27 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-user-subuser.ts
|
export class RgwUserSubuser {
id: string;
permissions: string;
generate_secret?: boolean;
secret_key?: string;
}
| 121 | 16.428571 | 29 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-user-swift-key.ts
|
export class RgwUserSwiftKey {
user: string;
secret_key: string;
}
| 71 | 13.4 | 30 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-multisite-zone-deletion-form/rgw-multisite-zone-deletion-form.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">Delete Zone</ng-container>
<ng-container class="modal-content">
<form name="zoneForm"
[formGroup]="zoneForm"
novalidate>
<div class="modal-body ms-4">
<label i18n>
This will delete your <strong>{{zone?.name}}</strong> Zone.
</label>
<ng-container *ngIf="includedPools.size">
<label class="mt-3"
i18n>
Do you want to delete the associated pools with the <strong>{{zone?.name}}</strong> Zone?</label>
<label class="mb-4"
i18n>
This will delete the following pools and any data stored in these pools:</label>
<strong *ngFor="let pool of includedPools"
class="block">{{ pool }}</strong>
<div class="form-group">
<div class="custom-control custom-checkbox mt-2">
<input type="checkbox"
class="custom-control-input"
name="deletePools"
id="deletePools"
formControlName="deletePools"
(change)="showDangerText()">
<label class="custom-control-label"
for="deletePools"
i18n>Yes, I want to delete the pools.</label>
</div>
<div *ngIf="displayText"
class="me-4">
<cd-alert-panel type="danger"
i18n>
This will delete all the data in the pools!
</cd-alert-panel>
</div>
</div>
</ng-container>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="submit()"
[form]="zoneForm"
[submitText]="actionLabels.DELETE">
</cd-form-button-panel>
</div>
</form>
</ng-container>
</cd-modal>
| 2,032 | 35.963636 | 111 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-multisite-zone-deletion-form/rgw-multisite-zone-deletion-form.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { RgwZone } from '../rgw-multisite';
import { RgwMultisiteZoneDeletionFormComponent } from './rgw-multisite-zone-deletion-form.component';
describe('RgwMultisiteZoneDeletionFormComponent', () => {
let component: RgwMultisiteZoneDeletionFormComponent;
let fixture: ComponentFixture<RgwMultisiteZoneDeletionFormComponent>;
configureTestBed({
declarations: [RgwMultisiteZoneDeletionFormComponent],
imports: [SharedModule, HttpClientTestingModule, ToastrModule.forRoot(), RouterTestingModule],
providers: [NgbActiveModal]
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwMultisiteZoneDeletionFormComponent);
component = fixture.componentInstance;
component.zone = new RgwZone();
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,271 | 37.545455 | 101 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-multisite-zone-deletion-form/rgw-multisite-zone-deletion-form.component.ts
|
import { AfterViewInit, Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { PoolService } from '~/app/shared/api/pool.service';
import { RgwZoneService } from '~/app/shared/api/rgw-zone.service';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { NotificationService } from '~/app/shared/services/notification.service';
@Component({
selector: 'cd-rgw-multisite-zone-deletion-form',
templateUrl: './rgw-multisite-zone-deletion-form.component.html',
styleUrls: ['./rgw-multisite-zone-deletion-form.component.scss']
})
export class RgwMultisiteZoneDeletionFormComponent implements OnInit, AfterViewInit {
zoneData$: any;
poolList$: any;
zone: any;
zoneForm: CdFormGroup;
displayText: boolean = false;
includedPools: Set<string> = new Set<string>();
constructor(
public activeModal: NgbActiveModal,
public actionLabels: ActionLabelsI18n,
public notificationService: NotificationService,
private rgwZoneService: RgwZoneService,
private poolService: PoolService
) {
this.createForm();
}
ngOnInit(): void {
this.zoneData$ = this.rgwZoneService.get(this.zone);
this.poolList$ = this.poolService.getList();
}
ngAfterViewInit(): void {
this.updateIncludedPools();
}
createForm() {
this.zoneForm = new CdFormGroup({
deletePools: new FormControl(false)
});
}
submit() {
this.rgwZoneService
.delete(this.zone.name, this.zoneForm.value.deletePools, this.includedPools, this.zone.parent)
.subscribe(
() => {
this.notificationService.show(
NotificationType.success,
$localize`Zone: '${this.zone.name}' deleted successfully`
);
this.activeModal.close();
},
() => {
this.zoneForm.setErrors({ cdSubmitButton: true });
}
);
}
showDangerText() {
this.displayText = !this.displayText;
}
updateIncludedPools(): void {
if (!this.zoneData$ || !this.poolList$) {
return;
}
this.zoneData$.subscribe((data: any) => {
this.poolList$.subscribe((poolList: any) => {
for (const pool of poolList) {
for (const zonePool of Object.values(data)) {
if (typeof zonePool === 'string' && zonePool.includes(pool.pool_name)) {
this.includedPools.add(pool.pool_name);
} else if (Array.isArray(zonePool) && zonePool[0].val) {
for (const item of zonePool) {
const val = item.val;
if (val.storage_classes.STANDARD.data_pool === pool.pool_name) {
this.includedPools.add(val.storage_classes.STANDARD.data_pool);
}
if (val.data_extra_pool === pool.pool_name) {
this.includedPools.add(val.data_extra_pool);
}
if (val.index_pool === pool.pool_name) {
this.includedPools.add(val.index_pool);
}
}
}
}
}
});
});
}
}
| 3,282 | 31.83 | 100 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-multisite-zonegroup-deletion-form/rgw-multisite-zonegroup-deletion-form.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">Delete Zonegroup</ng-container>
<ng-container class="modal-content">
<form name="zonegroupForm"
[formGroup]="zonegroupForm"
novalidate>
<div class="modal-body ms-4">
<label i18n>
This will delete your <strong>{{zonegroup?.name}}</strong> Zonegroup.
</label>
<ng-container *ngIf="zonesList.length > 0">
<label class="mt-3"
i18n>
Do you want to delete the associated zones and pools with the <strong>{{zonegroup?.name}}</strong> Zonegroup?</label>
<ng-container *ngIf="includedPools.size > 0">
<label i18n>
This will delete the following:</label>
</ng-container>
<strong class="mt-3 mb-2 h5 block">Zones:</strong>
<div id="scroll">
<strong *ngFor="let zone of zonesList"
class="block">{{zone}}</strong>
</div>
<ng-container *ngIf="includedPools.size > 0">
<strong class="mt-3 mb-2 h5 block">Pools:</strong>
<div id="scroll"
class="mb-2">
<strong *ngFor="let pool of includedPools"
class="block">{{ pool }}</strong>
</div>
</ng-container>
<div class="form-group">
<div class="custom-control custom-checkbox mt-2">
<input type="checkbox"
class="custom-control-input"
name="deletePools"
id="deletePools"
formControlName="deletePools"
(change)="showDangerText()">
<ng-container *ngIf="includedPools.size > 0 else noPoolsConfirmation">
<label class="custom-control-label"
for="deletePools"
i18n>Yes, I want to delete the zones and their pools.</label>
</ng-container>
</div>
<div *ngIf="displayText"
class="me-4">
<cd-alert-panel type="danger"
i18n>
This will delete all the data in the pools!
</cd-alert-panel>
</div>
</div>
</ng-container>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="submit()"
[form]="zonegroupForm"
[submitText]="actionLabels.DELETE ">
</cd-form-button-panel>
</div>
</form>
</ng-container>
</cd-modal>
<ng-template #noPoolsConfirmation>
<label class="custom-control-label"
for="deletePools"
i18n>Yes, I want to delete the zones.</label>
</ng-template>
| 2,844 | 36.434211 | 131 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-multisite-zonegroup-deletion-form/rgw-multisite-zonegroup-deletion-form.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { RgwZonegroup } from '../rgw-multisite';
import { RgwMultisiteZonegroupDeletionFormComponent } from './rgw-multisite-zonegroup-deletion-form.component';
describe('RgwMultisiteZonegroupDeletionFormComponent', () => {
let component: RgwMultisiteZonegroupDeletionFormComponent;
let fixture: ComponentFixture<RgwMultisiteZonegroupDeletionFormComponent>;
configureTestBed({
declarations: [RgwMultisiteZonegroupDeletionFormComponent],
imports: [SharedModule, HttpClientTestingModule, ToastrModule.forRoot(), RouterTestingModule],
providers: [NgbActiveModal]
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwMultisiteZonegroupDeletionFormComponent);
component = fixture.componentInstance;
component.zonegroup = new RgwZonegroup();
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,321 | 39.060606 | 111 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/models/rgw-multisite-zonegroup-deletion-form/rgw-multisite-zonegroup-deletion-form.component.ts
|
import { AfterViewInit, Component, OnInit } from '@angular/core';
import { FormControl } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { PoolService } from '~/app/shared/api/pool.service';
import { RgwZoneService } from '~/app/shared/api/rgw-zone.service';
import { RgwZonegroupService } from '~/app/shared/api/rgw-zonegroup.service';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { NotificationService } from '~/app/shared/services/notification.service';
@Component({
selector: 'cd-rgw-multisite-zonegroup-deletion-form',
templateUrl: './rgw-multisite-zonegroup-deletion-form.component.html',
styleUrls: ['./rgw-multisite-zonegroup-deletion-form.component.scss']
})
export class RgwMultisiteZonegroupDeletionFormComponent implements OnInit, AfterViewInit {
zonegroupData$: any;
poolList$: any;
zonesPools: Array<any> = [];
zonegroup: any;
zonesList: Array<any> = [];
zonegroupForm: CdFormGroup;
displayText: boolean = false;
includedPools: Set<string> = new Set<string>();
constructor(
public activeModal: NgbActiveModal,
public actionLabels: ActionLabelsI18n,
public notificationService: NotificationService,
private rgwZonegroupService: RgwZonegroupService,
private poolService: PoolService,
private rgwZoneService: RgwZoneService
) {
this.createForm();
}
ngOnInit(): void {
this.zonegroupData$ = this.rgwZonegroupService.get(this.zonegroup);
this.poolList$ = this.poolService.getList();
}
ngAfterViewInit(): void {
this.updateIncludedPools();
}
createForm() {
this.zonegroupForm = new CdFormGroup({
deletePools: new FormControl(false)
});
}
submit() {
this.rgwZonegroupService
.delete(this.zonegroup.name, this.zonegroupForm.value.deletePools, this.includedPools)
.subscribe(() => {
this.notificationService.show(
NotificationType.success,
$localize`Zone: '${this.zonegroup.name}' deleted successfully`
);
this.activeModal.close();
});
}
showDangerText() {
if (this.includedPools.size > 0) {
this.displayText = !this.displayText;
}
}
updateIncludedPools(): void {
if (!this.zonegroupData$ || !this.poolList$) {
return;
}
this.zonegroupData$.subscribe((zgData: any) => {
for (const zone of zgData.zones) {
this.zonesList.push(zone.name);
this.rgwZoneService.get(zone).subscribe((zonesPools: any) => {
this.poolList$.subscribe((poolList: any) => {
for (const zonePool of Object.values(zonesPools)) {
for (const pool of poolList) {
if (typeof zonePool === 'string' && zonePool.includes(pool.pool_name)) {
this.includedPools.add(pool.pool_name);
} else if (Array.isArray(zonePool) && zonePool[0].val) {
for (const item of zonePool) {
const val = item.val;
if (val.storage_classes.STANDARD.data_pool === pool.pool_name) {
this.includedPools.add(val.storage_classes.STANDARD.data_pool);
}
if (val.data_extra_pool === pool.pool_name) {
this.includedPools.add(val.data_extra_pool);
}
if (val.index_pool === pool.pool_name) {
this.includedPools.add(val.index_pool);
}
}
}
}
}
});
});
}
});
}
}
| 3,742 | 33.981308 | 92 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-bucket-details/rgw-bucket-details.component.html
|
<ng-container *ngIf="selection">
<table class="table table-striped table-bordered">
<tbody>
<tr>
<td i18n
class="bold w-25">Name</td>
<td class="w-75">{{ selection.bid }}</td>
</tr>
<tr>
<td i18n
class="bold">ID</td>
<td>{{ selection.id }}</td>
</tr>
<tr>
<td i18n
class="bold">Owner</td>
<td>{{ selection.owner }}</td>
</tr>
<tr>
<td i18n
class="bold">Index type</td>
<td>{{ selection.index_type }}</td>
</tr>
<tr>
<td i18n
class="bold">Placement rule</td>
<td>{{ selection.placement_rule }}</td>
</tr>
<tr>
<td i18n
class="bold">Marker</td>
<td>{{ selection.marker }}</td>
</tr>
<tr>
<td i18n
class="bold">Maximum marker</td>
<td>{{ selection.max_marker }}</td>
</tr>
<tr>
<td i18n
class="bold">Version</td>
<td>{{ selection.ver }}</td>
</tr>
<tr>
<td i18n
class="bold">Master version</td>
<td>{{ selection.master_ver }}</td>
</tr>
<tr>
<td i18n
class="bold">Modification time</td>
<td>{{ selection.mtime | cdDate }}</td>
</tr>
<tr>
<td i18n
class="bold">Zonegroup</td>
<td>{{ selection.zonegroup }}</td>
</tr>
<tr>
<td i18n
class="bold">Versioning</td>
<td>{{ selection.versioning }}</td>
</tr>
<tr>
<td i18n
class="bold">Encryption</td>
<td>{{ selection.encryption }}</td>
</tr>
<tr>
<td i18n
class="bold">MFA Delete</td>
<td>{{ selection.mfa_delete }}</td>
</tr>
</tbody>
</table>
<!-- Bucket quota -->
<div *ngIf="selection.bucket_quota">
<legend i18n>Bucket quota</legend>
<table class="table table-striped table-bordered">
<tbody>
<tr>
<td i18n
class="bold w-25">Enabled</td>
<td class="w-75">{{ selection.bucket_quota.enabled | booleanText }}</td>
</tr>
<tr>
<td i18n
class="bold">Maximum size</td>
<td *ngIf="selection.bucket_quota.max_size <= -1"
i18n>Unlimited</td>
<td *ngIf="selection.bucket_quota.max_size > -1">
{{ selection.bucket_quota.max_size | dimless }}
</td>
</tr>
<tr>
<td i18n
class="bold">Maximum objects</td>
<td *ngIf="selection.bucket_quota.max_objects <= -1"
i18n>Unlimited</td>
<td *ngIf="selection.bucket_quota.max_objects > -1">
{{ selection.bucket_quota.max_objects }}
</td>
</tr>
</tbody>
</table>
</div>
<!-- Locking -->
<legend i18n>Locking</legend>
<table class="table table-striped table-bordered">
<tbody>
<tr>
<td i18n
class="bold w-25">Enabled</td>
<td class="w-75">{{ selection.lock_enabled | booleanText }}</td>
</tr>
<ng-container *ngIf="selection.lock_enabled">
<tr>
<td i18n
class="bold">Mode</td>
<td>{{ selection.lock_mode }}</td>
</tr>
<tr>
<td i18n
class="bold">Days</td>
<td>{{ selection.lock_retention_period_days }}</td>
</tr>
</ng-container>
</tbody>
</table>
</ng-container>
| 3,545 | 25.661654 | 82 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-bucket-details/rgw-bucket-details.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { of } from 'rxjs';
import { RgwBucketService } from '~/app/shared/api/rgw-bucket.service';
import { CdTableSelection } from '~/app/shared/models/cd-table-selection';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { RgwBucketDetailsComponent } from './rgw-bucket-details.component';
describe('RgwBucketDetailsComponent', () => {
let component: RgwBucketDetailsComponent;
let fixture: ComponentFixture<RgwBucketDetailsComponent>;
let rgwBucketService: RgwBucketService;
let rgwBucketServiceGetSpy: jasmine.Spy;
configureTestBed({
declarations: [RgwBucketDetailsComponent],
imports: [SharedModule, HttpClientTestingModule]
});
beforeEach(() => {
rgwBucketService = TestBed.inject(RgwBucketService);
rgwBucketServiceGetSpy = spyOn(rgwBucketService, 'get');
rgwBucketServiceGetSpy.and.returnValue(of(null));
fixture = TestBed.createComponent(RgwBucketDetailsComponent);
component = fixture.componentInstance;
component.selection = new CdTableSelection();
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should retrieve bucket full info', () => {
component.selection = { bid: 'bucket' };
component.ngOnChanges();
expect(rgwBucketServiceGetSpy).toHaveBeenCalled();
});
});
| 1,527 | 34.534884 | 75 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-bucket-details/rgw-bucket-details.component.ts
|
import { Component, Input, OnChanges } from '@angular/core';
import { RgwBucketService } from '~/app/shared/api/rgw-bucket.service';
@Component({
selector: 'cd-rgw-bucket-details',
templateUrl: './rgw-bucket-details.component.html',
styleUrls: ['./rgw-bucket-details.component.scss']
})
export class RgwBucketDetailsComponent implements OnChanges {
@Input()
selection: any;
constructor(private rgwBucketService: RgwBucketService) {}
ngOnChanges() {
if (this.selection) {
this.rgwBucketService.get(this.selection.bid).subscribe((bucket: object) => {
bucket['lock_retention_period_days'] = this.rgwBucketService.getLockDays(bucket);
this.selection = bucket;
});
}
}
}
| 722 | 27.92 | 89 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-bucket-form/rgw-bucket-form.component.html
|
<div class="cd-col-form"
*cdFormLoading="loading">
<form name="bucketForm"
#frm="ngForm"
[formGroup]="bucketForm"
novalidate>
<div class="card">
<div i18n="form title"
class="card-header">{{ action | titlecase }} {{ resource | upperFirst }}</div>
<div class="card-body">
<!-- Id -->
<div class="form-group row"
*ngIf="editing">
<label i18n
class="cd-col-form-label"
for="id">Id</label>
<div class="cd-col-form-input">
<input id="id"
name="id"
class="form-control"
type="text"
formControlName="id"
readonly>
</div>
</div>
<!-- Name -->
<div class="form-group row">
<label class="cd-col-form-label"
[ngClass]="{required: !editing}"
for="bid"
i18n>Name</label>
<div class="cd-col-form-input">
<input id="bid"
name="bid"
class="form-control"
type="text"
i18n-placeholder
placeholder="Name..."
formControlName="bid"
[readonly]="editing"
[autofocus]="!editing">
<span class="invalid-feedback"
*ngIf="bucketForm.showError('bid', frm, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="bucketForm.showError('bid', frm, 'bucketNameInvalid')"
i18n>Bucket names can only contain lowercase letters, numbers, periods and hyphens.</span>
<span class="invalid-feedback"
*ngIf="bucketForm.showError('bid', frm, 'bucketNameNotAllowed')"
i18n>The chosen name is already in use.</span>
<span class="invalid-feedback"
*ngIf="bucketForm.showError('bid', frm, 'containsUpperCase')"
i18n>Bucket names must not contain uppercase characters or underscores.</span>
<span class="invalid-feedback"
*ngIf="bucketForm.showError('bid', frm, 'lowerCaseOrNumber')"
i18n>Each label must start and end with a lowercase letter or a number.</span>
<span class="invalid-feedback"
*ngIf="bucketForm.showError('bid', frm, 'ipAddress')"
i18n>Bucket names cannot be formatted as IP address.</span>
<span class="invalid-feedback"
*ngIf="bucketForm.showError('bid', frm, 'onlyLowerCaseAndNumbers')"
i18n>Bucket labels cannot be empty and can only contain lowercase letters, numbers and hyphens.</span>
<span class="invalid-feedback"
*ngIf="bucketForm.showError('bid', frm, 'shouldBeInRange')"
i18n>Bucket names must be 3 to 63 characters long.</span>
</div>
</div>
<!-- Owner -->
<div class="form-group row">
<label class="cd-col-form-label required"
for="owner"
i18n>Owner</label>
<div class="cd-col-form-input">
<select id="owner"
name="owner"
class="form-select"
formControlName="owner"
[autofocus]="editing">
<option i18n
*ngIf="owners === null"
[ngValue]="null">Loading...</option>
<option i18n
*ngIf="owners !== null"
[ngValue]="null">-- Select a user --</option>
<option *ngFor="let owner of owners"
[value]="owner">{{ owner }}</option>
</select>
<span class="invalid-feedback"
*ngIf="bucketForm.showError('owner', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
<!-- Placement target -->
<div class="form-group row">
<label class="cd-col-form-label"
[ngClass]="{required: !editing}"
for="placement-target"
i18n>Placement target</label>
<div class="cd-col-form-input">
<ng-template #placementTargetSelect>
<select id="placement-target"
name="placement-target"
formControlName="placement-target"
class="form-select">
<option i18n
*ngIf="placementTargets === null"
[ngValue]="null">Loading...</option>
<option i18n
*ngIf="placementTargets !== null"
[ngValue]="null">-- Select a placement target --</option>
<option *ngFor="let placementTarget of placementTargets"
[value]="placementTarget.name">{{ placementTarget.description }}</option>
</select>
<span class="invalid-feedback"
*ngIf="bucketForm.showError('placement-target', frm, 'required')"
i18n>This field is required.</span>
</ng-template>
<ng-container *ngIf="editing; else placementTargetSelect">
<input id="placement-target"
name="placement-target"
formControlName="placement-target"
class="form-control"
type="text"
readonly>
</ng-container>
</div>
</div>
<!-- Versioning -->
<fieldset *ngIf="editing">
<legend class="cd-header"
i18n>Versioning</legend>
<div class="form-group row">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input type="checkbox"
class="custom-control-input"
id="versioning"
name="versioning"
formControlName="versioning"
(change)="setMfaDeleteValidators()">
<label class="custom-control-label"
for="versioning"
i18n>Enabled</label>
<cd-helper>
<span i18n>Enables versioning for the objects in the bucket.</span>
</cd-helper>
</div>
</div>
</div>
</fieldset>
<!-- Multi-Factor Authentication -->
<fieldset *ngIf="editing">
<!-- MFA Delete -->
<legend class="cd-header"
i18n>Multi-Factor Authentication</legend>
<div class="form-group row">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input type="checkbox"
class="custom-control-input"
id="mfa-delete"
name="mfa-delete"
formControlName="mfa-delete"
(change)="setMfaDeleteValidators()">
<label class="custom-control-label"
for="mfa-delete"
i18n>Delete enabled</label>
<cd-helper>
<span i18n>Enables MFA (multi-factor authentication) Delete, which requires additional authentication for changing the bucket versioning state.</span>
</cd-helper>
</div>
</div>
</div>
<div *ngIf="areMfaCredentialsRequired()"
class="form-group row">
<label i18n
class="cd-col-form-label"
for="mfa-token-serial">Token Serial Number</label>
<div class="cd-col-form-input">
<input type="text"
id="mfa-token-serial"
name="mfa-token-serial"
formControlName="mfa-token-serial"
class="form-control">
<span class="invalid-feedback"
*ngIf="bucketForm.showError('mfa-token-serial', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
<div *ngIf="areMfaCredentialsRequired()"
class="form-group row">
<label i18n
class="cd-col-form-label"
for="mfa-token-pin">Token PIN</label>
<div class="cd-col-form-input">
<input type="text"
id="mfa-token-pin"
name="mfa-token-pin"
formControlName="mfa-token-pin"
class="form-control">
<span class="invalid-feedback"
*ngIf="bucketForm.showError('mfa-token-pin', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</fieldset>
<!-- Locking -->
<fieldset>
<legend class="cd-header"
i18n>Locking</legend>
<!-- Locking enabled -->
<div class="form-group row">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
id="lock_enabled"
formControlName="lock_enabled"
type="checkbox">
<label class="custom-control-label"
for="lock_enabled"
i18n>Enabled</label>
<cd-helper>
<span i18n>Enables locking for the objects in the bucket. Locking can only be enabled while creating a bucket.</span>
</cd-helper>
</div>
</div>
</div>
<!-- Locking mode -->
<div *ngIf="bucketForm.getValue('lock_enabled')"
class="form-group row">
<label class="cd-col-form-label"
for="lock_mode"
i18n>Mode</label>
<div class="cd-col-form-input">
<select class="form-select"
formControlName="lock_mode"
name="lock_mode"
id="lock_mode">
<option i18n
value="COMPLIANCE">Compliance</option>
<option i18n
value="GOVERNANCE">Governance</option>
</select>
</div>
</div>
<!-- Retention period (days) -->
<div *ngIf="bucketForm.getValue('lock_enabled')"
class="form-group row">
<label class="cd-col-form-label"
for="lock_retention_period_days">
<ng-container i18n>Days</ng-container>
<cd-helper i18n>The number of days that you want to specify for the default retention period that will be applied to new objects placed in this bucket.</cd-helper>
</label>
<div class="cd-col-form-input">
<input class="form-control"
type="number"
id="lock_retention_period_days"
formControlName="lock_retention_period_days"
min="0">
<span class="invalid-feedback"
*ngIf="bucketForm.showError('lock_retention_period_days', frm, 'pattern')"
i18n>The entered value must be a positive integer.</span>
<span class="invalid-feedback"
*ngIf="bucketForm.showError('lock_retention_period_days', frm, 'lockDays')"
i18n>Retention Days must be a positive integer.</span>
</div>
</div>
</fieldset>
<fieldset>
<legend class="cd-header"
i18n>Security</legend>
<div class="form-group row">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="form-check-input"
id="encryption_enabled"
name="encryption_enabled"
formControlName="encryption_enabled"
type="checkbox"
[attr.disabled]="!kmsVaultConfig && !s3VaultConfig ? true : null">
<label class="form-check-label"
for="encryption_enabled"
i18n>Encryption</label>
<cd-helper aria-label="toggle encryption helper">
<span i18n>Enables encryption for the objects in the bucket.
To enable encryption on a bucket you need to set the configuration values for SSE-S3 or SSE-KMS.
To set the configuration values <a href="#/rgw/bucket/create"
(click)="openConfigModal()"
aria-label="click here">Click here</a></span>
</cd-helper>
</div>
</div>
</div>
<div *ngIf="bucketForm.getValue('encryption_enabled')">
<div class="form-group row">
<div class="cd-col-form-offset">
<div class="custom-control custom-radio custom-control-inline ps-5">
<input class="form-check-input"
formControlName="encryption_type"
id="sse_S3_enabled"
type="radio"
name="encryption_type"
value="AES256"
[attr.disabled]="!s3VaultConfig ? true : null">
<label class="form-control-label"
for="sse_S3_enabled"
i18n>SSE-S3 Encryption</label>
</div>
</div>
</div>
<div class="form-group row">
<div class="cd-col-form-offset">
<div class="custom-control custom-radio custom-control-inline ps-5">
<input class="form-check-input"
formControlName="encryption_type"
id="kms_enabled"
name="encryption_type"
value="aws:kms"
[attr.disabled]="!kmsVaultConfig ? true : null"
type="radio">
<label class="form-control-label"
for="kms_enabled"
i18n>Connect to an external key management service</label>
</div>
</div>
</div>
<div *ngIf="bucketForm.getValue('encryption_type') === 'aws:kms'">
<div class="form-group row">
<label class="cd-col-form-label required"
for="kms_provider"
i18n>KMS Provider</label>
<div class="cd-col-form-input">
<select id="kms_provider"
name="kms_provider"
class="form-select"
formControlName="kms_provider"
[autofocus]="editing">
<option i18n
*ngIf="kmsProviders !== null"
[ngValue]="null">-- Select a provider --</option>
<option *ngFor="let provider of kmsProviders"
[value]="provider">{{ provider }}</option>
</select>
<span class="invalid-feedback"
*ngIf="bucketForm.showError('kms_provider', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</div>
<div *ngIf="bucketForm.getValue('encryption_type') === 'aws:kms'">
<div class="form-group row">
<label class="cd-col-form-label required"
for="keyId"
i18n>Key Id
</label>
<div class="cd-col-form-input">
<input id="keyId"
name="keyId"
class="form-control"
type="text"
formControlName="keyId">
<span class="invalid-feedback"
*ngIf="bucketForm.showError('keyId', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</div>
</div>
</fieldset>
</div>
<div class="card-footer">
<cd-form-button-panel (submitActionEvent)="submit()"
[form]="bucketForm"
[submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"
wrappingClass="text-right"></cd-form-button-panel>
</div>
</div>
</form>
</div>
| 17,243 | 42.326633 | 177 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-bucket-form/rgw-bucket-form.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import _ from 'lodash';
import { ToastrModule } from 'ngx-toastr';
import { of as observableOf } from 'rxjs';
import { RgwBucketService } from '~/app/shared/api/rgw-bucket.service';
import { RgwSiteService } from '~/app/shared/api/rgw-site.service';
import { RgwUserService } from '~/app/shared/api/rgw-user.service';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { NotificationService } from '~/app/shared/services/notification.service';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed, FormHelper } from '~/testing/unit-test-helper';
import { RgwBucketMfaDelete } from '../models/rgw-bucket-mfa-delete';
import { RgwBucketVersioning } from '../models/rgw-bucket-versioning';
import { RgwBucketFormComponent } from './rgw-bucket-form.component';
describe('RgwBucketFormComponent', () => {
let component: RgwBucketFormComponent;
let fixture: ComponentFixture<RgwBucketFormComponent>;
let rgwBucketService: RgwBucketService;
let getPlacementTargetsSpy: jasmine.Spy;
let rgwBucketServiceGetSpy: jasmine.Spy;
let enumerateSpy: jasmine.Spy;
let formHelper: FormHelper;
configureTestBed({
declarations: [RgwBucketFormComponent],
imports: [
HttpClientTestingModule,
ReactiveFormsModule,
RouterTestingModule,
SharedModule,
ToastrModule.forRoot()
]
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwBucketFormComponent);
component = fixture.componentInstance;
rgwBucketService = TestBed.inject(RgwBucketService);
rgwBucketServiceGetSpy = spyOn(rgwBucketService, 'get');
getPlacementTargetsSpy = spyOn(TestBed.inject(RgwSiteService), 'get');
enumerateSpy = spyOn(TestBed.inject(RgwUserService), 'enumerate');
formHelper = new FormHelper(component.bucketForm);
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('bucketNameValidator', () => {
it('should validate empty name', fakeAsync(() => {
formHelper.expectErrorChange('bid', '', 'required', true);
}));
});
describe('zonegroup and placement targets', () => {
it('should get zonegroup and placement targets', () => {
const payload: Record<string, any> = {
zonegroup: 'default',
placement_targets: [
{
name: 'default-placement',
data_pool: 'default.rgw.buckets.data'
},
{
name: 'placement-target2',
data_pool: 'placement-target2.rgw.buckets.data'
}
]
};
getPlacementTargetsSpy.and.returnValue(observableOf(payload));
enumerateSpy.and.returnValue(observableOf([]));
fixture.detectChanges();
expect(component.zonegroup).toBe(payload.zonegroup);
const placementTargets = [];
for (const placementTarget of payload['placement_targets']) {
placementTarget[
'description'
] = `${placementTarget['name']} (pool: ${placementTarget['data_pool']})`;
placementTargets.push(placementTarget);
}
expect(component.placementTargets).toEqual(placementTargets);
});
});
describe('submit form', () => {
let notificationService: NotificationService;
beforeEach(() => {
spyOn(TestBed.inject(Router), 'navigate').and.stub();
notificationService = TestBed.inject(NotificationService);
spyOn(notificationService, 'show');
});
it('should validate name', () => {
component.editing = false;
component.createForm();
const control = component.bucketForm.get('bid');
expect(_.isFunction(control.asyncValidator)).toBeTruthy();
});
it('should not validate name', () => {
component.editing = true;
component.createForm();
const control = component.bucketForm.get('bid');
expect(control.asyncValidator).toBeNull();
});
it('tests create success notification', () => {
spyOn(rgwBucketService, 'create').and.returnValue(observableOf([]));
component.editing = false;
component.bucketForm.markAsDirty();
component.submit();
expect(notificationService.show).toHaveBeenCalledWith(
NotificationType.success,
`Created Object Gateway bucket 'null'`
);
});
it('tests update success notification', () => {
spyOn(rgwBucketService, 'update').and.returnValue(observableOf([]));
component.editing = true;
component.bucketForm.markAsDirty();
component.submit();
expect(notificationService.show).toHaveBeenCalledWith(
NotificationType.success,
`Updated Object Gateway bucket 'null'.`
);
});
});
describe('mfa credentials', () => {
const checkMfaCredentialsVisibility = (
fakeResponse: object,
versioningChecked: boolean,
mfaDeleteChecked: boolean,
expectedVisibility: boolean
) => {
component['route'].params = observableOf({ bid: 'bid' });
component.editing = true;
rgwBucketServiceGetSpy.and.returnValue(observableOf(fakeResponse));
enumerateSpy.and.returnValue(observableOf([]));
component.ngOnInit();
component.bucketForm.patchValue({
versioning: versioningChecked,
'mfa-delete': mfaDeleteChecked
});
fixture.detectChanges();
const mfaTokenSerial = fixture.debugElement.nativeElement.querySelector('#mfa-token-serial');
const mfaTokenPin = fixture.debugElement.nativeElement.querySelector('#mfa-token-pin');
if (expectedVisibility) {
expect(mfaTokenSerial).toBeTruthy();
expect(mfaTokenPin).toBeTruthy();
} else {
expect(mfaTokenSerial).toBeFalsy();
expect(mfaTokenPin).toBeFalsy();
}
};
it('inputs should be visible when required', () => {
checkMfaCredentialsVisibility(
{
versioning: RgwBucketVersioning.SUSPENDED,
mfa_delete: RgwBucketMfaDelete.DISABLED
},
false,
false,
false
);
checkMfaCredentialsVisibility(
{
versioning: RgwBucketVersioning.SUSPENDED,
mfa_delete: RgwBucketMfaDelete.DISABLED
},
true,
false,
false
);
checkMfaCredentialsVisibility(
{
versioning: RgwBucketVersioning.ENABLED,
mfa_delete: RgwBucketMfaDelete.DISABLED
},
false,
false,
false
);
checkMfaCredentialsVisibility(
{
versioning: RgwBucketVersioning.ENABLED,
mfa_delete: RgwBucketMfaDelete.ENABLED
},
true,
true,
false
);
checkMfaCredentialsVisibility(
{
versioning: RgwBucketVersioning.SUSPENDED,
mfa_delete: RgwBucketMfaDelete.DISABLED
},
false,
true,
true
);
checkMfaCredentialsVisibility(
{
versioning: RgwBucketVersioning.SUSPENDED,
mfa_delete: RgwBucketMfaDelete.ENABLED
},
false,
false,
true
);
checkMfaCredentialsVisibility(
{
versioning: RgwBucketVersioning.SUSPENDED,
mfa_delete: RgwBucketMfaDelete.ENABLED
},
true,
true,
true
);
checkMfaCredentialsVisibility(
{
versioning: RgwBucketVersioning.ENABLED,
mfa_delete: RgwBucketMfaDelete.ENABLED
},
false,
true,
true
);
});
});
describe('object locking', () => {
const expectPatternLockError = (value: string) => {
formHelper.setValue('lock_enabled', true, true);
formHelper.setValue('lock_retention_period_days', value);
formHelper.expectError('lock_retention_period_days', 'pattern');
};
const expectValidLockInputs = (enabled: boolean, mode: string, days: string) => {
formHelper.setValue('lock_enabled', enabled);
formHelper.setValue('lock_mode', mode);
formHelper.setValue('lock_retention_period_days', days);
['lock_enabled', 'lock_mode', 'lock_retention_period_days'].forEach((name) => {
const control = component.bucketForm.get(name);
expect(control.valid).toBeTruthy();
expect(control.errors).toBeNull();
});
};
it('should check lock enabled checkbox [mode=create]', () => {
component.createForm();
const control = component.bucketForm.get('lock_enabled');
expect(control.disabled).toBeFalsy();
});
it('should check lock enabled checkbox [mode=edit]', () => {
component.editing = true;
component.createForm();
const control = component.bucketForm.get('lock_enabled');
expect(control.disabled).toBeTruthy();
});
it('should have the "lockDays" error', () => {
formHelper.setValue('lock_enabled', true);
const control = component.bucketForm.get('lock_retention_period_days');
control.updateValueAndValidity();
expect(control.value).toBe(0);
expect(control.invalid).toBeTruthy();
formHelper.expectError(control, 'lockDays');
});
it('should have the "pattern" error [1]', () => {
expectPatternLockError('-1');
});
it('should have the "pattern" error [2]', () => {
expectPatternLockError('1.2');
});
it('should have valid values [1]', () => {
expectValidLockInputs(true, 'Governance', '1');
});
it('should have valid values [2]', () => {
expectValidLockInputs(false, 'Compliance', '2');
});
});
});
| 9,833 | 31.671096 | 99 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-bucket-form/rgw-bucket-form.component.ts
|
import { AfterViewChecked, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { AbstractControl, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import _ from 'lodash';
import { forkJoin } from 'rxjs';
import { RgwBucketService } from '~/app/shared/api/rgw-bucket.service';
import { RgwSiteService } from '~/app/shared/api/rgw-site.service';
import { RgwUserService } from '~/app/shared/api/rgw-user.service';
import { ActionLabelsI18n, URLVerbs } from '~/app/shared/constants/app.constants';
import { Icons } from '~/app/shared/enum/icons.enum';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdForm } from '~/app/shared/forms/cd-form';
import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { CdValidators } from '~/app/shared/forms/cd-validators';
import { ModalService } from '~/app/shared/services/modal.service';
import { NotificationService } from '~/app/shared/services/notification.service';
import { RgwBucketEncryptionModel } from '../models/rgw-bucket-encryption';
import { RgwBucketMfaDelete } from '../models/rgw-bucket-mfa-delete';
import { RgwBucketVersioning } from '../models/rgw-bucket-versioning';
import { RgwConfigModalComponent } from '../rgw-config-modal/rgw-config-modal.component';
@Component({
selector: 'cd-rgw-bucket-form',
templateUrl: './rgw-bucket-form.component.html',
styleUrls: ['./rgw-bucket-form.component.scss'],
providers: [RgwBucketEncryptionModel]
})
export class RgwBucketFormComponent extends CdForm implements OnInit, AfterViewChecked {
bucketForm: CdFormGroup;
editing = false;
owners: string[] = null;
kmsProviders: string[] = null;
action: string;
resource: string;
zonegroup: string;
placementTargets: object[] = [];
isVersioningAlreadyEnabled = false;
isMfaDeleteAlreadyEnabled = false;
icons = Icons;
kmsVaultConfig = false;
s3VaultConfig = false;
get isVersioningEnabled(): boolean {
return this.bucketForm.getValue('versioning');
}
get isMfaDeleteEnabled(): boolean {
return this.bucketForm.getValue('mfa-delete');
}
constructor(
private route: ActivatedRoute,
private router: Router,
private formBuilder: CdFormBuilder,
private rgwBucketService: RgwBucketService,
private rgwSiteService: RgwSiteService,
private modalService: ModalService,
private rgwUserService: RgwUserService,
private notificationService: NotificationService,
private rgwEncryptionModal: RgwBucketEncryptionModel,
public actionLabels: ActionLabelsI18n,
private readonly changeDetectorRef: ChangeDetectorRef
) {
super();
this.editing = this.router.url.startsWith(`/rgw/bucket/${URLVerbs.EDIT}`);
this.action = this.editing ? this.actionLabels.EDIT : this.actionLabels.CREATE;
this.resource = $localize`bucket`;
this.createForm();
}
ngAfterViewChecked(): void {
this.changeDetectorRef.detectChanges();
}
createForm() {
const self = this;
const lockDaysValidator = CdValidators.custom('lockDays', () => {
if (!self.bucketForm || !_.get(self.bucketForm.getRawValue(), 'lock_enabled')) {
return false;
}
const lockDays = Number(self.bucketForm.getValue('lock_retention_period_days'));
return !Number.isInteger(lockDays) || lockDays === 0;
});
this.bucketForm = this.formBuilder.group({
id: [null],
bid: [
null,
[Validators.required],
this.editing
? []
: [CdValidators.bucketName(), CdValidators.bucketExistence(false, this.rgwBucketService)]
],
owner: [null, [Validators.required]],
kms_provider: ['vault'],
'placement-target': [null, this.editing ? [] : [Validators.required]],
versioning: [null],
'mfa-delete': [null],
'mfa-token-serial': [''],
'mfa-token-pin': [''],
lock_enabled: [{ value: false, disabled: this.editing }],
encryption_enabled: [null],
encryption_type: [
null,
[
CdValidators.requiredIf({
encryption_enabled: true
})
]
],
keyId: [
null,
[
CdValidators.requiredIf({
encryption_type: 'aws:kms',
encryption_enabled: true
})
]
],
lock_mode: ['COMPLIANCE'],
lock_retention_period_days: [0, [CdValidators.number(false), lockDaysValidator]]
});
}
ngOnInit() {
const promises = {
owners: this.rgwUserService.enumerate()
};
this.kmsProviders = this.rgwEncryptionModal.kmsProviders;
this.rgwBucketService.getEncryptionConfig().subscribe((data) => {
this.kmsVaultConfig = data[0];
this.s3VaultConfig = data[1];
if (this.kmsVaultConfig && this.s3VaultConfig) {
this.bucketForm.get('encryption_type').setValue('');
} else if (this.kmsVaultConfig) {
this.bucketForm.get('encryption_type').setValue('aws:kms');
} else if (this.s3VaultConfig) {
this.bucketForm.get('encryption_type').setValue('AES256');
} else {
this.bucketForm.get('encryption_type').setValue('');
}
});
if (!this.editing) {
promises['getPlacementTargets'] = this.rgwSiteService.get('placement-targets');
}
// Process route parameters.
this.route.params.subscribe((params: { bid: string }) => {
if (params.hasOwnProperty('bid')) {
const bid = decodeURIComponent(params.bid);
promises['getBid'] = this.rgwBucketService.get(bid);
}
forkJoin(promises).subscribe((data: any) => {
// Get the list of possible owners.
this.owners = (<string[]>data.owners).sort();
// Get placement targets:
if (data['getPlacementTargets']) {
const placementTargets = data['getPlacementTargets'];
this.zonegroup = placementTargets['zonegroup'];
_.forEach(placementTargets['placement_targets'], (placementTarget) => {
placementTarget['description'] = `${placementTarget['name']} (${$localize`pool`}: ${
placementTarget['data_pool']
})`;
this.placementTargets.push(placementTarget);
});
// If there is only 1 placement target, select it by default:
if (this.placementTargets.length === 1) {
this.bucketForm.get('placement-target').setValue(this.placementTargets[0]['name']);
}
}
if (data['getBid']) {
const bidResp = data['getBid'];
// Get the default values (incl. the values from disabled fields).
const defaults = _.clone(this.bucketForm.getRawValue());
// Get the values displayed in the form. We need to do that to
// extract those key/value pairs from the response data, otherwise
// the Angular react framework will throw an error if there is no
// field for a given key.
let value: object = _.pick(bidResp, _.keys(defaults));
value['lock_retention_period_days'] = this.rgwBucketService.getLockDays(bidResp);
value['placement-target'] = bidResp['placement_rule'];
value['versioning'] = bidResp['versioning'] === RgwBucketVersioning.ENABLED;
value['mfa-delete'] = bidResp['mfa_delete'] === RgwBucketMfaDelete.ENABLED;
value['encryption_enabled'] = bidResp['encryption'] === 'Enabled';
// Append default values.
value = _.merge(defaults, value);
// Update the form.
this.bucketForm.setValue(value);
if (this.editing) {
this.isVersioningAlreadyEnabled = this.isVersioningEnabled;
this.isMfaDeleteAlreadyEnabled = this.isMfaDeleteEnabled;
this.setMfaDeleteValidators();
if (value['lock_enabled']) {
this.bucketForm.controls['versioning'].disable();
}
}
}
this.loadingReady();
});
});
}
goToListView() {
this.router.navigate(['/rgw/bucket']);
}
submit() {
// Exit immediately if the form isn't dirty.
if (this.bucketForm.getValue('encryption_enabled') == null) {
this.bucketForm.get('encryption_enabled').setValue(false);
this.bucketForm.get('encryption_type').setValue(null);
}
if (this.bucketForm.pristine) {
this.goToListView();
return;
}
const values = this.bucketForm.value;
if (this.editing) {
// Edit
const versioning = this.getVersioningStatus();
const mfaDelete = this.getMfaDeleteStatus();
this.rgwBucketService
.update(
values['bid'],
values['id'],
values['owner'],
versioning,
values['encryption_enabled'],
values['encryption_type'],
values['keyId'],
mfaDelete,
values['mfa-token-serial'],
values['mfa-token-pin'],
values['lock_mode'],
values['lock_retention_period_days']
)
.subscribe(
() => {
this.notificationService.show(
NotificationType.success,
$localize`Updated Object Gateway bucket '${values.bid}'.`
);
this.goToListView();
},
() => {
// Reset the 'Submit' button.
this.bucketForm.setErrors({ cdSubmitButton: true });
}
);
} else {
// Add
this.rgwBucketService
.create(
values['bid'],
values['owner'],
this.zonegroup,
values['placement-target'],
values['lock_enabled'],
values['lock_mode'],
values['lock_retention_period_days'],
values['encryption_enabled'],
values['encryption_type'],
values['keyId']
)
.subscribe(
() => {
this.notificationService.show(
NotificationType.success,
$localize`Created Object Gateway bucket '${values.bid}'`
);
this.goToListView();
},
() => {
// Reset the 'Submit' button.
this.bucketForm.setErrors({ cdSubmitButton: true });
}
);
}
}
areMfaCredentialsRequired() {
return (
this.isMfaDeleteEnabled !== this.isMfaDeleteAlreadyEnabled ||
(this.isMfaDeleteAlreadyEnabled &&
this.isVersioningEnabled !== this.isVersioningAlreadyEnabled)
);
}
setMfaDeleteValidators() {
const mfaTokenSerialControl = this.bucketForm.get('mfa-token-serial');
const mfaTokenPinControl = this.bucketForm.get('mfa-token-pin');
if (this.areMfaCredentialsRequired()) {
mfaTokenSerialControl.setValidators(Validators.required);
mfaTokenPinControl.setValidators(Validators.required);
} else {
mfaTokenSerialControl.setValidators(null);
mfaTokenPinControl.setValidators(null);
}
mfaTokenSerialControl.updateValueAndValidity();
mfaTokenPinControl.updateValueAndValidity();
}
getVersioningStatus() {
return this.isVersioningEnabled ? RgwBucketVersioning.ENABLED : RgwBucketVersioning.SUSPENDED;
}
getMfaDeleteStatus() {
return this.isMfaDeleteEnabled ? RgwBucketMfaDelete.ENABLED : RgwBucketMfaDelete.DISABLED;
}
fileUpload(files: FileList, controlName: string) {
const file: File = files[0];
const reader = new FileReader();
reader.addEventListener('load', () => {
const control: AbstractControl = this.bucketForm.get(controlName);
control.setValue(file);
control.markAsDirty();
control.markAsTouched();
control.updateValueAndValidity();
});
}
openConfigModal() {
const modalRef = this.modalService.show(RgwConfigModalComponent, null, { size: 'lg' });
modalRef.componentInstance.configForm
.get('encryptionType')
.setValue(this.bucketForm.getValue('encryption_type') || 'AES256');
}
}
| 12,000 | 34.193548 | 99 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-bucket-list/rgw-bucket-list.component.html
|
<cd-table #table
[autoReload]="false"
[data]="buckets"
[columns]="columns"
columnMode="flex"
selectionType="multiClick"
[hasDetails]="true"
(setExpandedRow)="setExpandedRow($event)"
(updateSelection)="updateSelection($event)"
identifier="bid"
(fetchData)="getBucketList($event)"
[status]="tableStatus">
<cd-table-actions class="table-actions"
[permission]="permission"
[selection]="selection"
[tableActions]="tableActions">
</cd-table-actions>
<cd-rgw-bucket-details cdTableDetail
[selection]="expandedRow">
</cd-rgw-bucket-details>
</cd-table>
<ng-template #bucketSizeTpl
let-row="row">
<cd-usage-bar *ngIf="row.bucket_quota.max_size > 0 && row.bucket_quota.enabled; else noSizeQuota"
[total]="row.bucket_quota.max_size"
[used]="row.bucket_size">
</cd-usage-bar>
<ng-template #noSizeQuota
i18n>No Limit</ng-template>
</ng-template>
<ng-template #bucketObjectTpl
let-row="row">
<cd-usage-bar *ngIf="row.bucket_quota.max_objects > 0 && row.bucket_quota.enabled; else noObjectQuota"
[total]="row.bucket_quota.max_objects"
[used]="row.num_objects"
[isBinary]="false">
</cd-usage-bar>
<ng-template #noObjectQuota
i18n>No Limit</ng-template>
</ng-template>
| 1,507 | 32.511111 | 104 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-bucket-list/rgw-bucket-list.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap';
import { of } from 'rxjs';
import { RgwBucketService } from '~/app/shared/api/rgw-bucket.service';
import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed, PermissionHelper } from '~/testing/unit-test-helper';
import { RgwBucketDetailsComponent } from '../rgw-bucket-details/rgw-bucket-details.component';
import { RgwBucketListComponent } from './rgw-bucket-list.component';
describe('RgwBucketListComponent', () => {
let component: RgwBucketListComponent;
let fixture: ComponentFixture<RgwBucketListComponent>;
let rgwBucketService: RgwBucketService;
let rgwBucketServiceListSpy: jasmine.Spy;
configureTestBed({
declarations: [RgwBucketListComponent, RgwBucketDetailsComponent],
imports: [
BrowserAnimationsModule,
RouterTestingModule,
SharedModule,
NgbNavModule,
HttpClientTestingModule
]
});
beforeEach(() => {
rgwBucketService = TestBed.inject(RgwBucketService);
rgwBucketServiceListSpy = spyOn(rgwBucketService, 'list');
rgwBucketServiceListSpy.and.returnValue(of([]));
fixture = TestBed.createComponent(RgwBucketListComponent);
component = fixture.componentInstance;
spyOn(component, 'setTableRefreshTimeout').and.stub();
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
expect(rgwBucketServiceListSpy).toHaveBeenCalledTimes(1);
});
it('should test all TableActions combinations', () => {
const permissionHelper: PermissionHelper = new PermissionHelper(component.permission);
const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions(
component.tableActions
);
expect(tableActions).toEqual({
'create,update,delete': {
actions: ['Create', 'Edit', 'Delete'],
primary: { multiple: 'Delete', executing: 'Edit', single: 'Edit', no: 'Create' }
},
'create,update': {
actions: ['Create', 'Edit'],
primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' }
},
'create,delete': {
actions: ['Create', 'Delete'],
primary: { multiple: 'Delete', executing: 'Create', single: 'Create', no: 'Create' }
},
create: {
actions: ['Create'],
primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' }
},
'update,delete': {
actions: ['Edit', 'Delete'],
primary: { multiple: 'Delete', executing: 'Edit', single: 'Edit', no: 'Edit' }
},
update: {
actions: ['Edit'],
primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' }
},
delete: {
actions: ['Delete'],
primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' }
},
'no-permissions': {
actions: [],
primary: { multiple: '', executing: '', single: '', no: '' }
}
});
});
it('should test if bucket data is tranformed correctly', () => {
rgwBucketServiceListSpy.and.returnValue(
of([
{
bucket: 'bucket',
owner: 'testid',
usage: {
'rgw.main': {
size_actual: 4,
num_objects: 2
},
'rgw.none': {
size_actual: 6,
num_objects: 6
}
},
bucket_quota: {
max_size: 20,
max_objects: 10,
enabled: true
}
}
])
);
component.getBucketList(null);
expect(rgwBucketServiceListSpy).toHaveBeenCalledTimes(2);
expect(component.buckets).toEqual([
{
bucket: 'bucket',
owner: 'testid',
usage: {
'rgw.main': { size_actual: 4, num_objects: 2 },
'rgw.none': { size_actual: 6, num_objects: 6 }
},
bucket_quota: {
max_size: 20,
max_objects: 10,
enabled: true
},
bucket_size: 4,
num_objects: 2,
size_usage: 0.2,
object_usage: 0.2
}
]);
});
it('should usage bars only if quota enabled', () => {
rgwBucketServiceListSpy.and.returnValue(
of([
{
bucket: 'bucket',
owner: 'testid',
bucket_quota: {
max_size: 1024,
max_objects: 10,
enabled: true
}
}
])
);
component.getBucketList(null);
expect(rgwBucketServiceListSpy).toHaveBeenCalledTimes(2);
fixture.detectChanges();
const usageBars = fixture.debugElement.nativeElement.querySelectorAll('cd-usage-bar');
expect(usageBars.length).toBe(2);
});
it('should not show any usage bars if quota disabled', () => {
rgwBucketServiceListSpy.and.returnValue(
of([
{
bucket: 'bucket',
owner: 'testid',
bucket_quota: {
max_size: 1024,
max_objects: 10,
enabled: false
}
}
])
);
component.getBucketList(null);
expect(rgwBucketServiceListSpy).toHaveBeenCalledTimes(2);
fixture.detectChanges();
const usageBars = fixture.debugElement.nativeElement.querySelectorAll('cd-usage-bar');
expect(usageBars.length).toBe(0);
});
});
| 5,723 | 30.977654 | 101 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-bucket-list/rgw-bucket-list.component.ts
|
import { Component, NgZone, OnInit, TemplateRef, ViewChild } from '@angular/core';
import _ from 'lodash';
import { forkJoin as observableForkJoin, Observable, Subscriber } from 'rxjs';
import { RgwBucketService } from '~/app/shared/api/rgw-bucket.service';
import { ListWithDetails } from '~/app/shared/classes/list-with-details.class';
import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { TableComponent } from '~/app/shared/datatable/table/table.component';
import { Icons } from '~/app/shared/enum/icons.enum';
import { CdTableAction } from '~/app/shared/models/cd-table-action';
import { CdTableColumn } from '~/app/shared/models/cd-table-column';
import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context';
import { CdTableSelection } from '~/app/shared/models/cd-table-selection';
import { Permission } from '~/app/shared/models/permissions';
import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe';
import { DimlessPipe } from '~/app/shared/pipes/dimless.pipe';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { ModalService } from '~/app/shared/services/modal.service';
import { URLBuilderService } from '~/app/shared/services/url-builder.service';
const BASE_URL = 'rgw/bucket';
@Component({
selector: 'cd-rgw-bucket-list',
templateUrl: './rgw-bucket-list.component.html',
styleUrls: ['./rgw-bucket-list.component.scss'],
providers: [{ provide: URLBuilderService, useValue: new URLBuilderService(BASE_URL) }]
})
export class RgwBucketListComponent extends ListWithDetails implements OnInit {
@ViewChild(TableComponent, { static: true })
table: TableComponent;
@ViewChild('bucketSizeTpl', { static: true })
bucketSizeTpl: TemplateRef<any>;
@ViewChild('bucketObjectTpl', { static: true })
bucketObjectTpl: TemplateRef<any>;
permission: Permission;
tableActions: CdTableAction[];
columns: CdTableColumn[] = [];
buckets: object[] = [];
selection: CdTableSelection = new CdTableSelection();
staleTimeout: number;
constructor(
private authStorageService: AuthStorageService,
private dimlessBinaryPipe: DimlessBinaryPipe,
private dimlessPipe: DimlessPipe,
private rgwBucketService: RgwBucketService,
private modalService: ModalService,
private urlBuilder: URLBuilderService,
public actionLabels: ActionLabelsI18n,
protected ngZone: NgZone
) {
super(ngZone);
}
ngOnInit() {
this.permission = this.authStorageService.getPermissions().rgw;
this.columns = [
{
name: $localize`Name`,
prop: 'bid',
flexGrow: 2
},
{
name: $localize`Owner`,
prop: 'owner',
flexGrow: 2.5
},
{
name: $localize`Used Capacity`,
prop: 'bucket_size',
flexGrow: 0.6,
pipe: this.dimlessBinaryPipe
},
{
name: $localize`Capacity Limit %`,
prop: 'size_usage',
cellTemplate: this.bucketSizeTpl,
flexGrow: 0.8
},
{
name: $localize`Objects`,
prop: 'num_objects',
flexGrow: 0.6,
pipe: this.dimlessPipe
},
{
name: $localize`Object Limit %`,
prop: 'object_usage',
cellTemplate: this.bucketObjectTpl,
flexGrow: 0.8
}
];
const getBucketUri = () =>
this.selection.first() && `${encodeURIComponent(this.selection.first().bid)}`;
const addAction: CdTableAction = {
permission: 'create',
icon: Icons.add,
routerLink: () => this.urlBuilder.getCreate(),
name: this.actionLabels.CREATE,
canBePrimary: (selection: CdTableSelection) => !selection.hasSelection
};
const editAction: CdTableAction = {
permission: 'update',
icon: Icons.edit,
routerLink: () => this.urlBuilder.getEdit(getBucketUri()),
name: this.actionLabels.EDIT
};
const deleteAction: CdTableAction = {
permission: 'delete',
icon: Icons.destroy,
click: () => this.deleteAction(),
disable: () => !this.selection.hasSelection,
name: this.actionLabels.DELETE,
canBePrimary: (selection: CdTableSelection) => selection.hasMultiSelection
};
this.tableActions = [addAction, editAction, deleteAction];
this.setTableRefreshTimeout();
}
transformBucketData() {
_.forEach(this.buckets, (bucketKey) => {
const maxBucketSize = bucketKey['bucket_quota']['max_size'];
const maxBucketObjects = bucketKey['bucket_quota']['max_objects'];
bucketKey['bucket_size'] = 0;
bucketKey['num_objects'] = 0;
if (!_.isEmpty(bucketKey['usage'])) {
bucketKey['bucket_size'] = bucketKey['usage']['rgw.main']['size_actual'];
bucketKey['num_objects'] = bucketKey['usage']['rgw.main']['num_objects'];
}
bucketKey['size_usage'] =
maxBucketSize > 0 ? bucketKey['bucket_size'] / maxBucketSize : undefined;
bucketKey['object_usage'] =
maxBucketObjects > 0 ? bucketKey['num_objects'] / maxBucketObjects : undefined;
});
}
getBucketList(context: CdTableFetchDataContext) {
this.setTableRefreshTimeout();
this.rgwBucketService.list(true).subscribe(
(resp: object[]) => {
this.buckets = resp;
this.transformBucketData();
},
() => {
context.error();
}
);
}
updateSelection(selection: CdTableSelection) {
this.selection = selection;
}
deleteAction() {
this.modalService.show(CriticalConfirmationModalComponent, {
itemDescription: this.selection.hasSingleSelection ? $localize`bucket` : $localize`buckets`,
itemNames: this.selection.selected.map((bucket: any) => bucket['bid']),
submitActionObservable: () => {
return new Observable((observer: Subscriber<any>) => {
// Delete all selected data table rows.
observableForkJoin(
this.selection.selected.map((bucket: any) => {
return this.rgwBucketService.delete(bucket.bid);
})
).subscribe({
error: (error) => {
// Forward the error to the observer.
observer.error(error);
// Reload the data table content because some deletions might
// have been executed successfully in the meanwhile.
this.table.refreshBtn();
},
complete: () => {
// Notify the observer that we are done.
observer.complete();
// Reload the data table content.
this.table.refreshBtn();
}
});
});
}
});
}
}
| 6,803 | 35 | 143 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-config-modal/rgw-config-modal.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">Update RGW Encryption Configurations</ng-container>
<ng-container class="modal-content">
<form name="configForm"
#frm="ngForm"
[formGroup]="configForm">
<div class="modal-body">
<div class="form-group row">
<label class="cd-col-form-label required"
for="encryptionType"
i18n>Encryption Type</label>
<div class="col-md-auto custom-checkbox form-check-inline ms-3">
<input class="form-check-input"
formControlName="encryptionType"
id="s3Enabled"
type="radio"
name="encryptionType"
value="AES256">
<label class="custom-check-label"
for="s3Enabled"
i18n>SSE-S3 Encryption</label>
</div>
<div class="col-md-auto custom-checkbox form-check-inline">
<input class="form-check-input"
formControlName="encryptionType"
id="kmsEnabled"
name="encryptionType"
value="aws:kms"
type="radio">
<label class="custom-check-label"
for="kmsEnabled"
i18n>SSE-KMS Encryption</label>
</div>
</div>
<div *ngIf="configForm.getValue('encryptionType') === 'aws:kms' || configForm.getValue('encryptionType') === 'AES256'">
<div class="form-group row">
<label class="cd-col-form-label required"
for="kms_provider"
i18n>Key management service provider</label>
<div class="cd-col-form-input">
<select id="kms_provider"
name="kms_provider"
class="form-select"
formControlName="kms_provider">
<option i18n
*ngIf="kmsProviders !== null"
[ngValue]="null">-- Select a provider --</option>
<option *ngFor="let provider of kmsProviders"
[value]="provider">{{ provider }}</option>
</select>
<span class="invalid-feedback"
*ngIf="configForm.showError('kms_provider', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</div>
<div *ngIf="configForm.getValue('encryptionType') === 'aws:kms' || configForm.getValue('encryptionType') === 'AES256'">
<div class="form-group row">
<label class="cd-col-form-label required"
for="auth_method"
i18n>Authentication Method</label>
<div class="cd-col-form-input">
<select id="auth_method"
name="auth_method"
class="form-select"
formControlName="auth_method">
<option *ngFor="let auth_method of authMethods"
[value]="auth_method">{{ auth_method }}</option>
</select>
<span class="invalid-feedback"
*ngIf="configForm.showError('auth_method', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</div>
<div *ngIf="configForm.getValue('encryptionType') === 'aws:kms' || configForm.getValue('encryptionType') === 'AES256'">
<div class="form-group row">
<label class="cd-col-form-label required"
for="secret_engine"
i18n>Secret Engine</label>
<div class="cd-col-form-input">
<select id="secret_engine"
name="secret_engine"
class="form-select"
formControlName="secret_engine">
<option *ngFor="let secret_engine of secretEngines"
[value]="secret_engine">{{ secret_engine }}</option>
</select>
<span class="invalid-feedback"
*ngIf="configForm.showError('secret_engine', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</div>
<div *ngIf="configForm.getValue('encryptionType') === 'aws:kms' || configForm.getValue('encryptionType') === 'AES256'">
<div class="form-group row">
<label class="cd-col-form-label"
for="secret_path"
i18n>Secret Path
</label>
<div class="cd-col-form-input">
<input id="secret_path"
name="secret_path"
class="form-control"
type="text"
formControlName="secret_path">
<span class="invalid-feedback"
*ngIf="configForm.showError('secret_path', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</div>
<div *ngIf="configForm.getValue('encryptionType') === 'aws:kms' || configForm.getValue('encryptionType') === 'AES256'">
<div class="form-group row">
<label class="cd-col-form-label"
for="namespace"
i18n>Namespace
</label>
<div class="cd-col-form-input">
<input id="namespace"
name="namespace"
class="form-control"
type="text"
formControlName="namespace">
</div>
</div>
</div>
<div *ngIf="configForm.getValue('encryptionType') === 'aws:kms' || configForm.getValue('encryptionType') === 'AES256'">
<div class="form-group row">
<label class="cd-col-form-label required"
for="address"
i18n>Vault Address
</label>
<div class="cd-col-form-input">
<input id="address"
name="address"
class="form-control"
formControlName="address"
placeholder="http://127.0.0.1:8000">
<span class="invalid-feedback"
*ngIf="configForm.showError('address', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</div>
<div *ngIf="configForm.getValue('auth_method') === 'token'"
class="form-group row">
<label class="cd-col-form-label required"
for="token">
<span i18n>Token</span>
<cd-helper i18n>
The token authentication method expects a Vault token to be present in a plaintext file.
</cd-helper>
</label>
<div class="cd-col-form-input">
<input type="file"
formControlName="token"
(change)="fileUpload($event.target.files, 'token')">
<span class="invalid-feedback"
*ngIf="configForm.showError('token', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
<div *ngIf="configForm.getValue('encryptionType') === 'aws:kms' || configForm.getValue('encryptionType') === 'AES256'">
<div class="form-group row">
<label class="cd-col-form-label"
for="ssl_cert">
<span i18n>CA Certificate</span>
<cd-helper i18n>The SSL certificate in PEM format.</cd-helper>
</label>
<div class="cd-col-form-input">
<input type="file"
formControlName="ssl_cert"
(change)="fileUpload($event.target.files, 'ssl_cert')">
<span class="invalid-feedback"
*ngIf="configForm.showError('ssl_cert', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</div>
<div *ngIf="configForm.getValue('encryptionType') === 'aws:kms' || configForm.getValue('encryptionType') === 'AES256'">
<div class="form-group row">
<label class="cd-col-form-label"
for="client_cert">
<span i18n>Client Certificate</span>
<cd-helper i18n>The Client certificate in PEM format.</cd-helper>
</label>
<div class="cd-col-form-input">
<input type="file"
formControlName="client_cert"
(change)="fileUpload($event.target.files, 'client_cert')">
<span class="invalid-feedback"
*ngIf="configForm.showError('client_cert', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</div>
<div *ngIf="configForm.getValue('encryptionType') === 'aws:kms' || configForm.getValue('encryptionType') === 'AES256'">
<div class="form-group row">
<label class="cd-col-form-label"
for="client_key">
<span i18n>Client Private Key</span>
<cd-helper i18n>The Client Private Key in PEM format.</cd-helper>
</label>
<div class="cd-col-form-input">
<input type="file"
(change)="fileUpload($event.target.files, 'client_key')">
<span class="invalid-feedback"
*ngIf="configForm.showError('client_key', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="onSubmit()"
[submitText]="actionLabels.SUBMIT"
[form]="configForm"></cd-form-button-panel>
</div>
</form>
</ng-container>
</cd-modal>
| 9,675 | 40 | 125 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-config-modal/rgw-config-modal.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { RgwConfigModalComponent } from './rgw-config-modal.component';
describe('RgwConfigModalComponent', () => {
let component: RgwConfigModalComponent;
let fixture: ComponentFixture<RgwConfigModalComponent>;
configureTestBed({
declarations: [RgwConfigModalComponent],
imports: [
SharedModule,
ReactiveFormsModule,
RouterTestingModule,
HttpClientTestingModule,
ToastrModule.forRoot()
],
providers: [NgbActiveModal]
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwConfigModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,203 | 29.871795 | 71 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-config-modal/rgw-config-modal.component.ts
|
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { AbstractControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { RgwBucketService } from '~/app/shared/api/rgw-bucket.service';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { CdValidators } from '~/app/shared/forms/cd-validators';
import { NotificationService } from '~/app/shared/services/notification.service';
import { RgwBucketEncryptionModel } from '../models/rgw-bucket-encryption';
@Component({
selector: 'cd-rgw-config-modal',
templateUrl: './rgw-config-modal.component.html',
styleUrls: ['./rgw-config-modal.component.scss'],
providers: [RgwBucketEncryptionModel]
})
export class RgwConfigModalComponent implements OnInit {
readonly vaultAddress = /^((https?:\/\/)|(www.))(?:([a-zA-Z]+)|(\d+\.\d+.\d+.\d+)):\d{4}$/;
kmsProviders: string[];
configForm: CdFormGroup;
@Output()
submitAction = new EventEmitter();
authMethods: string[];
secretEngines: string[];
constructor(
private formBuilder: CdFormBuilder,
public activeModal: NgbActiveModal,
private router: Router,
public actionLabels: ActionLabelsI18n,
private rgwBucketService: RgwBucketService,
private rgwEncryptionModal: RgwBucketEncryptionModel,
private notificationService: NotificationService
) {
this.createForm();
}
ngOnInit(): void {
this.kmsProviders = this.rgwEncryptionModal.kmsProviders;
this.authMethods = this.rgwEncryptionModal.authMethods;
this.secretEngines = this.rgwEncryptionModal.secretEngines;
}
createForm() {
this.configForm = this.formBuilder.group({
address: [
null,
[
Validators.required,
CdValidators.custom('vaultPattern', (value: string) => {
if (_.isEmpty(value)) {
return false;
}
return !this.vaultAddress.test(value);
})
]
],
kms_provider: ['vault', Validators.required],
encryptionType: ['aws:kms', Validators.required],
auth_method: ['token', Validators.required],
secret_engine: ['kv', Validators.required],
secret_path: ['/'],
namespace: [null],
token: [
null,
[
CdValidators.requiredIf({
auth_method: 'token'
})
]
],
ssl_cert: [null, CdValidators.sslCert()],
client_cert: [null, CdValidators.pemCert()],
client_key: [null, CdValidators.sslPrivKey()],
kmsEnabled: [{ value: false }],
s3Enabled: [{ value: false }]
});
}
fileUpload(files: FileList, controlName: string) {
const file: File = files[0];
const reader = new FileReader();
reader.addEventListener('load', () => {
const control: AbstractControl = this.configForm.get(controlName);
control.setValue(file);
control.markAsDirty();
control.markAsTouched();
control.updateValueAndValidity();
});
}
onSubmit() {
const values = this.configForm.value;
this.rgwBucketService
.setEncryptionConfig(
values['encryptionType'],
values['kms_provider'],
values['auth_method'],
values['secret_engine'],
values['secret_path'],
values['namespace'],
values['address'],
values['token'],
values['owner'],
values['ssl_cert'],
values['client_cert'],
values['client_key']
)
.subscribe({
next: () => {
this.notificationService.show(
NotificationType.success,
$localize`Updated RGW Encryption Configuration values`
);
},
error: (error: any) => {
this.notificationService.show(NotificationType.error, error);
this.configForm.setErrors({ cdSubmitButton: true });
},
complete: () => {
this.activeModal.close();
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
this.router.onSameUrlNavigation = 'reload';
this.router.navigate([this.router.url]);
}
});
}
}
| 4,432 | 31.357664 | 93 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-daemon-details/rgw-daemon-details.component.html
|
<ng-container *ngIf="selection">
<nav ngbNav
#nav="ngbNav"
class="nav-tabs"
cdStatefulTab="rgw-daemon-details">
<ng-container ngbNavItem="details">
<a ngbNavLink
i18n>Details</a>
<ng-template ngbNavContent>
<cd-table-key-value [data]="metadata"
(fetchData)="getMetaData()">
</cd-table-key-value>
</ng-template>
</ng-container>
<ng-container ngbNavItem="performance-counters">
<a ngbNavLink
i18n>Performance Counters</a>
<ng-template ngbNavContent>
<cd-table-performance-counter serviceType="rgw"
[serviceId]="serviceMapId">
</cd-table-performance-counter>
</ng-template>
</ng-container>
<ng-container ngbNavItem="performance-details"
*ngIf="grafanaPermission.read">
<a ngbNavLink
i18n>Performance Details</a>
<ng-template ngbNavContent>
<cd-grafana i18n-title
title="RGW instance details"
[grafanaPath]="'rgw-instance-detail?var-rgw_servers=rgw.' + this.serviceId"
[type]="'metrics'"
uid="x5ARzZtmk"
grafanaStyle="one">
</cd-grafana>
</ng-template>
</ng-container>
</nav>
<div [ngbNavOutlet]="nav"></div>
</ng-container>
| 1,386 | 32.02381 | 95 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-daemon-details/rgw-daemon-details.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap';
import { PerformanceCounterModule } from '~/app/ceph/performance-counter/performance-counter.module';
import { RgwDaemon } from '~/app/ceph/rgw/models/rgw-daemon';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { RgwDaemonDetailsComponent } from './rgw-daemon-details.component';
describe('RgwDaemonDetailsComponent', () => {
let component: RgwDaemonDetailsComponent;
let fixture: ComponentFixture<RgwDaemonDetailsComponent>;
configureTestBed({
declarations: [RgwDaemonDetailsComponent],
imports: [SharedModule, PerformanceCounterModule, HttpClientTestingModule, NgbNavModule]
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwDaemonDetailsComponent);
component = fixture.componentInstance;
component.selection = undefined;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should set service id and service map id on changes', () => {
const daemon = new RgwDaemon();
daemon.id = 'daemon1';
daemon.service_map_id = '4832';
component.selection = daemon;
component.ngOnChanges();
expect(component.serviceId).toBe(daemon.id);
expect(component.serviceMapId).toBe(daemon.service_map_id);
});
});
| 1,512 | 34.186047 | 101 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-daemon-details/rgw-daemon-details.component.ts
|
import { Component, Input, OnChanges } from '@angular/core';
import _ from 'lodash';
import { RgwDaemon } from '~/app/ceph/rgw/models/rgw-daemon';
import { RgwDaemonService } from '~/app/shared/api/rgw-daemon.service';
import { Permission } from '~/app/shared/models/permissions';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
@Component({
selector: 'cd-rgw-daemon-details',
templateUrl: './rgw-daemon-details.component.html',
styleUrls: ['./rgw-daemon-details.component.scss']
})
export class RgwDaemonDetailsComponent implements OnChanges {
metadata: any;
serviceId = '';
serviceMapId = '';
grafanaPermission: Permission;
@Input()
selection: RgwDaemon;
constructor(
private rgwDaemonService: RgwDaemonService,
private authStorageService: AuthStorageService
) {
this.grafanaPermission = this.authStorageService.getPermissions().grafana;
}
ngOnChanges() {
if (this.selection) {
this.serviceId = this.selection.id;
this.serviceMapId = this.selection.service_map_id;
}
}
getMetaData() {
if (_.isEmpty(this.serviceId)) {
return;
}
this.rgwDaemonService.get(this.serviceId).subscribe((resp: any) => {
this.metadata = resp['rgw_metadata'];
});
}
}
| 1,277 | 26.191489 | 80 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-daemon-list/rgw-daemon-list.component.html
|
<nav ngbNav
#nav="ngbNav"
class="nav-tabs">
<ng-container ngbNavItem>
<a ngbNavLink
i18n>Gateways List</a>
<ng-template ngbNavContent>
<cd-table [data]="daemons"
[columns]="columns"
columnMode="flex"
[hasDetails]="true"
(setExpandedRow)="setExpandedRow($event)"
(fetchData)="getDaemonList($event)">
<cd-rgw-daemon-details cdTableDetail
[selection]="expandedRow">
</cd-rgw-daemon-details>
</cd-table>
</ng-template>
</ng-container>
<ng-container ngbNavItem
*ngIf="grafanaPermission.read">
<a ngbNavLink
i18n>Overall Performance</a>
<ng-template ngbNavContent>
<cd-grafana i18n-title
title="RGW overview"
[grafanaPath]="'rgw-overview?'"
[type]="'metrics'"
uid="WAkugZpiz"
grafanaStyle="two">
</cd-grafana>
</ng-template>
</ng-container>
<ng-container ngbNavItem
*ngIf="grafanaPermission.read && isMultiSite">
<a ngbNavLink
i18n>Sync Performance</a>
<ng-template ngbNavContent>
<cd-grafana i18n-title
title="Radosgw sync overview"
[grafanaPath]="'radosgw-sync-overview?'"
[type]="'metrics'"
uid="rgw-sync-overview"
grafanaStyle="two">
</cd-grafana>
</ng-template>
</ng-container>
</nav>
<div [ngbNavOutlet]="nav"></div>
| 1,574 | 28.716981 | 62 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-daemon-list/rgw-daemon-list.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap';
import { of } from 'rxjs';
import { PerformanceCounterModule } from '~/app/ceph/performance-counter/performance-counter.module';
import { RgwDaemon } from '~/app/ceph/rgw/models/rgw-daemon';
import { RgwDaemonService } from '~/app/shared/api/rgw-daemon.service';
import { RgwSiteService } from '~/app/shared/api/rgw-site.service';
import { Permissions } from '~/app/shared/models/permissions';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed, TabHelper } from '~/testing/unit-test-helper';
import { RgwDaemonDetailsComponent } from '../rgw-daemon-details/rgw-daemon-details.component';
import { RgwDaemonListComponent } from './rgw-daemon-list.component';
describe('RgwDaemonListComponent', () => {
let component: RgwDaemonListComponent;
let fixture: ComponentFixture<RgwDaemonListComponent>;
let getPermissionsSpy: jasmine.Spy;
let getRealmsSpy: jasmine.Spy;
let listDaemonsSpy: jest.SpyInstance;
const permissions = new Permissions({ grafana: ['read'] });
const daemon: RgwDaemon = {
id: '8000',
service_map_id: '4803',
version: 'ceph version',
server_hostname: 'ceph',
realm_name: 'realm1',
zonegroup_name: 'zg1-realm1',
zone_name: 'zone1-zg1-realm1',
default: true,
port: 80
};
const expectTabsAndHeading = (length: number, heading: string) => {
const tabs = TabHelper.getTextContents(fixture);
expect(tabs.length).toEqual(length);
expect(tabs[length - 1]).toEqual(heading);
};
configureTestBed({
declarations: [RgwDaemonListComponent, RgwDaemonDetailsComponent],
imports: [
BrowserAnimationsModule,
HttpClientTestingModule,
NgbNavModule,
PerformanceCounterModule,
SharedModule,
RouterTestingModule
]
});
beforeEach(() => {
getPermissionsSpy = spyOn(TestBed.inject(AuthStorageService), 'getPermissions');
getPermissionsSpy.and.returnValue(new Permissions({}));
getRealmsSpy = spyOn(TestBed.inject(RgwSiteService), 'get');
getRealmsSpy.and.returnValue(of([]));
listDaemonsSpy = jest
.spyOn(TestBed.inject(RgwDaemonService), 'list')
.mockReturnValue(of([daemon]));
fixture = TestBed.createComponent(RgwDaemonListComponent);
component = fixture.componentInstance;
});
it('should create', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
it('should show a row with daemon info', fakeAsync(() => {
fixture.detectChanges();
tick();
expect(listDaemonsSpy).toHaveBeenCalledTimes(1);
expect(component.daemons).toEqual([daemon]);
expect(fixture.debugElement.query(By.css('cd-table')).nativeElement.textContent).toContain(
'total of 1'
);
fixture.destroy();
}));
it('should only show Gateways List tab', () => {
fixture.detectChanges();
expectTabsAndHeading(1, 'Gateways List');
});
it('should show Overall Performance tab', () => {
getPermissionsSpy.and.returnValue(permissions);
fixture.detectChanges();
expectTabsAndHeading(2, 'Overall Performance');
});
it('should show Sync Performance tab', () => {
getPermissionsSpy.and.returnValue(permissions);
getRealmsSpy.and.returnValue(of(['realm1']));
fixture.detectChanges();
expectTabsAndHeading(3, 'Sync Performance');
});
});
| 3,791 | 34.111111 | 101 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-daemon-list/rgw-daemon-list.component.ts
|
import { Component, OnInit } from '@angular/core';
import { RgwDaemon } from '~/app/ceph/rgw/models/rgw-daemon';
import { RgwDaemonService } from '~/app/shared/api/rgw-daemon.service';
import { RgwSiteService } from '~/app/shared/api/rgw-site.service';
import { ListWithDetails } from '~/app/shared/classes/list-with-details.class';
import { CdTableColumn } from '~/app/shared/models/cd-table-column';
import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context';
import { Permission } from '~/app/shared/models/permissions';
import { CephShortVersionPipe } from '~/app/shared/pipes/ceph-short-version.pipe';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
@Component({
selector: 'cd-rgw-daemon-list',
templateUrl: './rgw-daemon-list.component.html',
styleUrls: ['./rgw-daemon-list.component.scss']
})
export class RgwDaemonListComponent extends ListWithDetails implements OnInit {
columns: CdTableColumn[] = [];
daemons: RgwDaemon[] = [];
grafanaPermission: Permission;
isMultiSite: boolean;
constructor(
private rgwDaemonService: RgwDaemonService,
private authStorageService: AuthStorageService,
private cephShortVersionPipe: CephShortVersionPipe,
private rgwSiteService: RgwSiteService
) {
super();
}
ngOnInit(): void {
this.grafanaPermission = this.authStorageService.getPermissions().grafana;
this.columns = [
{
name: $localize`ID`,
prop: 'id',
flexGrow: 2
},
{
name: $localize`Hostname`,
prop: 'server_hostname',
flexGrow: 2
},
{
name: $localize`Port`,
prop: 'port',
flexGrow: 1
},
{
name: $localize`Realm`,
prop: 'realm_name',
flexGrow: 2
},
{
name: $localize`Zone Group`,
prop: 'zonegroup_name',
flexGrow: 2
},
{
name: $localize`Zone`,
prop: 'zone_name',
flexGrow: 2
},
{
name: $localize`Version`,
prop: 'version',
flexGrow: 1,
pipe: this.cephShortVersionPipe
}
];
this.rgwSiteService
.get('realms')
.subscribe((realms: string[]) => (this.isMultiSite = realms.length > 0));
}
getDaemonList(context: CdTableFetchDataContext) {
this.rgwDaemonService.list().subscribe(this.updateDaemons, () => {
context.error();
});
}
private updateDaemons = (daemons: RgwDaemon[]) => {
this.daemons = daemons;
};
}
| 2,531 | 27.772727 | 90 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-details/rgw-multisite-details.component.html
|
<div class="row">
<div class="col-sm-12 col-lg-12">
<div>
<cd-alert-panel *ngIf="!rgwModuleStatus"
type="info"
spacingClass="mb-3"
i18n>You need to enable the rgw module to access the import/export feature.
<a class="text-decoration-underline"
(click)="enableRgwModule()">
Enable RGW Module</a>
</cd-alert-panel>
<cd-table-actions class="btn-group mb-4 me-2"
[permission]="permission"
[selection]="selection"
[tableActions]="createTableActions">
</cd-table-actions>
<span *ngIf="showMigrateAction">
<cd-table-actions class="btn-group mb-4 me-2 secondary"
[permission]="permission"
[btnColor]="'light'"
[selection]="selection"
[tableActions]="migrateTableAction">
</cd-table-actions>
</span>
<cd-table-actions class="btn-group mb-4 me-2"
[permission]="permission"
[btnColor]="'light'"
[selection]="selection"
[tableActions]="importAction">
</cd-table-actions>
<cd-table-actions class="btn-group mb-4 me-2"
[permission]="permission"
[btnColor]="'light'"
[selection]="selection"
[tableActions]="exportAction">
</cd-table-actions>
</div>
<div class="card">
<div class="card-header"
i18n>Topology Viewer</div>
<div class="card-body">
<div class="row">
<div class="col-sm-6 col-lg-6 tree-container">
<i *ngIf="loadingIndicator"
[ngClass]="[icons.large, icons.spinner, icons.spin]"></i>
<tree-root #tree
[nodes]="nodes"
[options]="treeOptions"
(updateData)="onUpdateData()">
<ng-template #treeNodeTemplate
let-node>
<span *ngIf="node.data.name"
class="me-3">
<span *ngIf="(node.data.show_warning)">
<i class="text-danger"
i18n-title
[title]="node.data.warning_message"
[ngClass]="icons.danger"></i>
</span>
<i [ngClass]="node.data.icon"></i>
{{ node.data.name }}
</span>
<span class="badge badge-success me-2"
*ngIf="node.data.is_default">
default
</span>
<span class="badge badge-warning me-2"
*ngIf="node.data.is_master">
master
</span>
<span class="badge badge-warning me-2"
*ngIf="node.data.secondary_zone">
secondary-zone
</span>
<div class="btn-group align-inline-btns"
*ngIf="node.isFocused"
role="group">
<div [title]="editTitle"
i18n-title>
<button type="button"
class="btn btn-light dropdown-toggle-split ms-1"
(click)="openModal(node, true)"
[disabled]="getDisable() || node.data.secondary_zone">
<i [ngClass]="[icons.edit]"></i>
</button>
</div>
<div [title]="deleteTitle"
i18n-title>
<button type="button"
class="btn btn-light ms-1"
[disabled]="isDeleteDisabled(node) || node.data.secondary_zone"
(click)="delete(node)">
<i [ngClass]="[icons.destroy]"></i>
</button>
</div>
</div>
</ng-template>
</tree-root>
</div>
<div class="col-sm-6 col-lg-6 metadata"
*ngIf="metadata">
<legend>{{ metadataTitle }}</legend>
<cd-table-key-value cdTableDetail
[data]="metadata">
</cd-table-key-value>
</div>
</div>
</div>
</div>
</div>
</div>
| 4,566 | 39.776786 | 99 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-details/rgw-multisite-details.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { DebugElement } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { TreeModule } from '@circlon/angular-tree-component';
import { ToastrModule } from 'ngx-toastr';
import { SharedModule } from '~/app/shared/shared.module';
import { RgwMultisiteDetailsComponent } from './rgw-multisite-details.component';
import { RouterTestingModule } from '@angular/router/testing';
describe('RgwMultisiteDetailsComponent', () => {
let component: RgwMultisiteDetailsComponent;
let fixture: ComponentFixture<RgwMultisiteDetailsComponent>;
let debugElement: DebugElement;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [RgwMultisiteDetailsComponent],
imports: [
HttpClientTestingModule,
TreeModule,
SharedModule,
ToastrModule.forRoot(),
RouterTestingModule
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwMultisiteDetailsComponent);
component = fixture.componentInstance;
debugElement = fixture.debugElement;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should display right title', () => {
const span = debugElement.nativeElement.querySelector('.card-header');
expect(span.textContent).toBe('Topology Viewer');
});
});
| 1,472 | 31.733333 | 81 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-details/rgw-multisite-details.component.ts
|
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import {
TreeComponent,
ITreeOptions,
TreeModel,
TreeNode,
TREE_ACTIONS
} from '@circlon/angular-tree-component';
import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { forkJoin, Subscription, timer as observableTimer } from 'rxjs';
import { RgwRealmService } from '~/app/shared/api/rgw-realm.service';
import { RgwZoneService } from '~/app/shared/api/rgw-zone.service';
import { RgwZonegroupService } from '~/app/shared/api/rgw-zonegroup.service';
import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component';
import { ActionLabelsI18n, TimerServiceInterval } from '~/app/shared/constants/app.constants';
import { Icons } from '~/app/shared/enum/icons.enum';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdTableAction } from '~/app/shared/models/cd-table-action';
import { CdTableSelection } from '~/app/shared/models/cd-table-selection';
import { Permission } from '~/app/shared/models/permissions';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { ModalService } from '~/app/shared/services/modal.service';
import { NotificationService } from '~/app/shared/services/notification.service';
import { TimerService } from '~/app/shared/services/timer.service';
import { RgwRealm, RgwZone, RgwZonegroup } from '../models/rgw-multisite';
import { RgwMultisiteMigrateComponent } from '../rgw-multisite-migrate/rgw-multisite-migrate.component';
import { RgwMultisiteZoneDeletionFormComponent } from '../models/rgw-multisite-zone-deletion-form/rgw-multisite-zone-deletion-form.component';
import { RgwMultisiteZonegroupDeletionFormComponent } from '../models/rgw-multisite-zonegroup-deletion-form/rgw-multisite-zonegroup-deletion-form.component';
import { RgwMultisiteExportComponent } from '../rgw-multisite-export/rgw-multisite-export.component';
import { RgwMultisiteImportComponent } from '../rgw-multisite-import/rgw-multisite-import.component';
import { RgwMultisiteRealmFormComponent } from '../rgw-multisite-realm-form/rgw-multisite-realm-form.component';
import { RgwMultisiteZoneFormComponent } from '../rgw-multisite-zone-form/rgw-multisite-zone-form.component';
import { RgwMultisiteZonegroupFormComponent } from '../rgw-multisite-zonegroup-form/rgw-multisite-zonegroup-form.component';
import { RgwDaemonService } from '~/app/shared/api/rgw-daemon.service';
import { MgrModuleService } from '~/app/shared/api/mgr-module.service';
import { BlockUI, NgBlockUI } from 'ng-block-ui';
import { Router } from '@angular/router';
@Component({
selector: 'cd-rgw-multisite-details',
templateUrl: './rgw-multisite-details.component.html',
styleUrls: ['./rgw-multisite-details.component.scss']
})
export class RgwMultisiteDetailsComponent implements OnDestroy, OnInit {
private sub = new Subscription();
@ViewChild('tree') tree: TreeComponent;
messages = {
noDefaultRealm: $localize`Please create a default realm first to enable this feature`,
noMasterZone: $localize`Please create a master zone for each zonegroups to enable this feature`,
noRealmExists: $localize`No realm exists`,
disableExport: $localize`Please create master zonegroup and master zone for each of the realms`
};
@BlockUI()
blockUI: NgBlockUI;
icons = Icons;
permission: Permission;
selection = new CdTableSelection();
createTableActions: CdTableAction[];
migrateTableAction: CdTableAction[];
importAction: CdTableAction[];
exportAction: CdTableAction[];
loadingIndicator = true;
nodes: object[] = [];
treeOptions: ITreeOptions = {
useVirtualScroll: true,
nodeHeight: 22,
levelPadding: 20,
actionMapping: {
mouse: {
click: this.onNodeSelected.bind(this)
}
}
};
modalRef: NgbModalRef;
realms: RgwRealm[] = [];
zonegroups: RgwZonegroup[] = [];
zones: RgwZone[] = [];
metadata: any;
metadataTitle: string;
bsModalRef: NgbModalRef;
realmIds: string[] = [];
zoneIds: string[] = [];
defaultRealmId = '';
defaultZonegroupId = '';
defaultZoneId = '';
multisiteInfo: object[] = [];
defaultsInfo: string[] = [];
showMigrateAction: boolean = false;
editTitle: string = 'Edit';
deleteTitle: string = 'Delete';
disableExport = true;
rgwModuleStatus: boolean;
rgwModuleData: string | any[] = [];
constructor(
private modalService: ModalService,
private timerService: TimerService,
private authStorageService: AuthStorageService,
public actionLabels: ActionLabelsI18n,
public timerServiceVariable: TimerServiceInterval,
public router: Router,
public rgwRealmService: RgwRealmService,
public rgwZonegroupService: RgwZonegroupService,
public rgwZoneService: RgwZoneService,
public rgwDaemonService: RgwDaemonService,
public mgrModuleService: MgrModuleService,
private notificationService: NotificationService
) {
this.permission = this.authStorageService.getPermissions().rgw;
}
openModal(entity: any, edit = false) {
const entityName = edit ? entity.data.type : entity;
const action = edit ? 'edit' : 'create';
const initialState = {
resource: entityName,
action: action,
info: entity,
defaultsInfo: this.defaultsInfo,
multisiteInfo: this.multisiteInfo
};
if (entityName === 'realm') {
this.bsModalRef = this.modalService.show(RgwMultisiteRealmFormComponent, initialState, {
size: 'lg'
});
} else if (entityName === 'zonegroup') {
this.bsModalRef = this.modalService.show(RgwMultisiteZonegroupFormComponent, initialState, {
size: 'lg'
});
} else {
this.bsModalRef = this.modalService.show(RgwMultisiteZoneFormComponent, initialState, {
size: 'lg'
});
}
}
openMigrateModal() {
const initialState = {
multisiteInfo: this.multisiteInfo
};
this.bsModalRef = this.modalService.show(RgwMultisiteMigrateComponent, initialState, {
size: 'lg'
});
}
openImportModal() {
const initialState = {
multisiteInfo: this.multisiteInfo
};
this.bsModalRef = this.modalService.show(RgwMultisiteImportComponent, initialState, {
size: 'lg'
});
}
openExportModal() {
const initialState = {
defaultsInfo: this.defaultsInfo,
multisiteInfo: this.multisiteInfo
};
this.bsModalRef = this.modalService.show(RgwMultisiteExportComponent, initialState, {
size: 'lg'
});
}
getDisableExport() {
this.realms.forEach((realm: any) => {
this.zonegroups.forEach((zonegroup) => {
if (realm.id === zonegroup.realm_id) {
if (zonegroup.is_master && zonegroup.master_zone !== '') {
this.disableExport = false;
}
}
});
});
if (!this.rgwModuleStatus) {
return true;
}
if (this.realms.length < 1) {
return this.messages.noRealmExists;
} else if (this.disableExport) {
return this.messages.disableExport;
} else {
return false;
}
}
getDisableImport() {
if (!this.rgwModuleStatus) {
return true;
} else {
return false;
}
}
ngOnInit() {
const createRealmAction: CdTableAction = {
permission: 'create',
icon: Icons.add,
name: this.actionLabels.CREATE + ' Realm',
click: () => this.openModal('realm')
};
const createZonegroupAction: CdTableAction = {
permission: 'create',
icon: Icons.add,
name: this.actionLabels.CREATE + ' Zonegroup',
click: () => this.openModal('zonegroup'),
disable: () => this.getDisable()
};
const createZoneAction: CdTableAction = {
permission: 'create',
icon: Icons.add,
name: this.actionLabels.CREATE + ' Zone',
click: () => this.openModal('zone')
};
const migrateMultsiteAction: CdTableAction = {
permission: 'read',
icon: Icons.exchange,
name: this.actionLabels.MIGRATE,
click: () => this.openMigrateModal()
};
const importMultsiteAction: CdTableAction = {
permission: 'read',
icon: Icons.download,
name: this.actionLabels.IMPORT,
click: () => this.openImportModal(),
disable: () => this.getDisableImport()
};
const exportMultsiteAction: CdTableAction = {
permission: 'read',
icon: Icons.upload,
name: this.actionLabels.EXPORT,
click: () => this.openExportModal(),
disable: () => this.getDisableExport()
};
this.createTableActions = [createRealmAction, createZonegroupAction, createZoneAction];
this.migrateTableAction = [migrateMultsiteAction];
this.importAction = [importMultsiteAction];
this.exportAction = [exportMultsiteAction];
const observables = [
this.rgwRealmService.getAllRealmsInfo(),
this.rgwZonegroupService.getAllZonegroupsInfo(),
this.rgwZoneService.getAllZonesInfo()
];
this.sub = this.timerService
.get(() => forkJoin(observables), this.timerServiceVariable.TIMER_SERVICE_PERIOD * 2)
.subscribe(
(multisiteInfo: [object, object, object]) => {
this.multisiteInfo = multisiteInfo;
this.loadingIndicator = false;
this.nodes = this.abstractTreeData(multisiteInfo);
},
(_error) => {}
);
this.mgrModuleService.list().subscribe((moduleData: any) => {
this.rgwModuleData = moduleData.filter((module: object) => module['name'] === 'rgw');
if (this.rgwModuleData.length > 0) {
this.rgwModuleStatus = this.rgwModuleData[0].enabled;
}
});
}
/* setConfigValues() {
this.rgwDaemonService
.setMultisiteConfig(
this.defaultsInfo['defaultRealmName'],
this.defaultsInfo['defaultZonegroupName'],
this.defaultsInfo['defaultZoneName']
)
.subscribe(() => {});
}*/
ngOnDestroy() {
this.sub.unsubscribe();
}
private abstractTreeData(multisiteInfo: [object, object, object]): any[] {
let allNodes: object[] = [];
let rootNodes = {};
let firstChildNodes = {};
let allFirstChildNodes = [];
let secondChildNodes = {};
let allSecondChildNodes: {}[] = [];
this.realms = multisiteInfo[0]['realms'];
this.zonegroups = multisiteInfo[1]['zonegroups'];
this.zones = multisiteInfo[2]['zones'];
this.defaultRealmId = multisiteInfo[0]['default_realm'];
this.defaultZonegroupId = multisiteInfo[1]['default_zonegroup'];
this.defaultZoneId = multisiteInfo[2]['default_zone'];
this.defaultsInfo = this.getDefaultsEntities(
this.defaultRealmId,
this.defaultZonegroupId,
this.defaultZoneId
);
if (this.realms.length > 0) {
// get tree for realm -> zonegroup -> zone
for (const realm of this.realms) {
const result = this.rgwRealmService.getRealmTree(realm, this.defaultRealmId);
rootNodes = result['nodes'];
this.realmIds = this.realmIds.concat(result['realmIds']);
for (const zonegroup of this.zonegroups) {
if (zonegroup.realm_id === realm.id) {
firstChildNodes = this.rgwZonegroupService.getZonegroupTree(
zonegroup,
this.defaultZonegroupId,
realm
);
for (const zone of zonegroup.zones) {
const zoneResult = this.rgwZoneService.getZoneTree(
zone,
this.defaultZoneId,
this.zones,
zonegroup,
realm
);
secondChildNodes = zoneResult['nodes'];
this.zoneIds = this.zoneIds.concat(zoneResult['zoneIds']);
allSecondChildNodes.push(secondChildNodes);
secondChildNodes = {};
}
firstChildNodes['children'] = allSecondChildNodes;
allSecondChildNodes = [];
allFirstChildNodes.push(firstChildNodes);
firstChildNodes = {};
}
}
rootNodes['children'] = allFirstChildNodes;
allNodes.push(rootNodes);
firstChildNodes = {};
secondChildNodes = {};
rootNodes = {};
allFirstChildNodes = [];
allSecondChildNodes = [];
}
}
if (this.zonegroups.length > 0) {
// get tree for zonegroup -> zone (standalone zonegroups that don't match a realm eg(initial default))
for (const zonegroup of this.zonegroups) {
if (!this.realmIds.includes(zonegroup.realm_id)) {
rootNodes = this.rgwZonegroupService.getZonegroupTree(zonegroup, this.defaultZonegroupId);
for (const zone of zonegroup.zones) {
const zoneResult = this.rgwZoneService.getZoneTree(
zone,
this.defaultZoneId,
this.zones,
zonegroup
);
firstChildNodes = zoneResult['nodes'];
this.zoneIds = this.zoneIds.concat(zoneResult['zoneIds']);
allFirstChildNodes.push(firstChildNodes);
firstChildNodes = {};
}
rootNodes['children'] = allFirstChildNodes;
allNodes.push(rootNodes);
firstChildNodes = {};
rootNodes = {};
allFirstChildNodes = [];
}
}
}
if (this.zones.length > 0) {
// get tree for standalone zones(zones that do not belong to a zonegroup)
for (const zone of this.zones) {
if (this.zoneIds.length > 0 && !this.zoneIds.includes(zone.id)) {
const zoneResult = this.rgwZoneService.getZoneTree(zone, this.defaultZoneId, this.zones);
rootNodes = zoneResult['nodes'];
allNodes.push(rootNodes);
rootNodes = {};
}
}
}
if (this.realms.length < 1 && this.zonegroups.length < 1 && this.zones.length < 1) {
return [
{
name: 'No nodes!'
}
];
}
this.realmIds = [];
this.zoneIds = [];
this.getDisableMigrate();
return allNodes;
}
getDefaultsEntities(
defaultRealmId: string,
defaultZonegroupId: string,
defaultZoneId: string
): any {
const defaultRealm = this.realms.find((x: { id: string }) => x.id === defaultRealmId);
const defaultZonegroup = this.zonegroups.find(
(x: { id: string }) => x.id === defaultZonegroupId
);
const defaultZone = this.zones.find((x: { id: string }) => x.id === defaultZoneId);
const defaultRealmName = defaultRealm !== undefined ? defaultRealm.name : null;
const defaultZonegroupName = defaultZonegroup !== undefined ? defaultZonegroup.name : null;
const defaultZoneName = defaultZone !== undefined ? defaultZone.name : null;
return {
defaultRealmName: defaultRealmName,
defaultZonegroupName: defaultZonegroupName,
defaultZoneName: defaultZoneName
};
}
onNodeSelected(tree: TreeModel, node: TreeNode) {
TREE_ACTIONS.ACTIVATE(tree, node, true);
this.metadataTitle = node.data.name;
this.metadata = node.data.info;
node.data.show = true;
}
onUpdateData() {
this.tree.treeModel.expandAll();
}
getDisable() {
let isMasterZone = true;
if (this.defaultRealmId === '') {
return this.messages.noDefaultRealm;
} else {
this.zonegroups.forEach((zgp: any) => {
if (_.isEmpty(zgp.master_zone)) {
isMasterZone = false;
}
});
if (!isMasterZone) {
this.editTitle =
'Please create a master zone for each existing zonegroup to enable this feature';
return this.messages.noMasterZone;
} else {
this.editTitle = 'Edit';
return false;
}
}
}
getDisableMigrate() {
if (
this.realms.length === 0 &&
this.zonegroups.length === 1 &&
this.zonegroups[0].name === 'default' &&
this.zones.length === 1 &&
this.zones[0].name === 'default'
) {
this.showMigrateAction = true;
} else {
this.showMigrateAction = false;
}
return this.showMigrateAction;
}
isDeleteDisabled(node: TreeNode): boolean {
let disable: boolean = false;
let masterZonegroupCount: number = 0;
if (node.data.type === 'realm' && node.data.is_default && this.realms.length < 2) {
disable = true;
}
if (node.data.type === 'zonegroup') {
if (this.zonegroups.length < 2) {
this.deleteTitle = 'You can not delete the only zonegroup available';
disable = true;
} else if (node.data.is_default) {
this.deleteTitle = 'You can not delete the default zonegroup';
disable = true;
} else if (node.data.is_master) {
for (let zonegroup of this.zonegroups) {
if (zonegroup.is_master === true) {
masterZonegroupCount++;
if (masterZonegroupCount > 1) break;
}
}
if (masterZonegroupCount < 2) {
this.deleteTitle = 'You can not delete the only master zonegroup available';
disable = true;
}
}
}
if (node.data.type === 'zone') {
if (this.zones.length < 2) {
this.deleteTitle = 'You can not delete the only zone available';
disable = true;
} else if (node.data.is_default) {
this.deleteTitle = 'You can not delete the default zone';
disable = true;
} else if (node.data.is_master && node.data.zone_zonegroup.zones.length < 2) {
this.deleteTitle =
'You can not delete the master zone as there are no more zones in this zonegroup';
disable = true;
}
}
if (!disable) {
this.deleteTitle = 'Delete';
}
return disable;
}
delete(node: TreeNode) {
if (node.data.type === 'realm') {
this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, {
itemDescription: $localize`${node.data.type} ${node.data.name}`,
itemNames: [`${node.data.name}`],
submitAction: () => {
this.rgwRealmService.delete(node.data.name).subscribe(
() => {
this.modalRef.close();
this.notificationService.show(
NotificationType.success,
$localize`Realm: '${node.data.name}' deleted successfully`
);
},
() => {
this.modalRef.componentInstance.stopLoadingSpinner();
}
);
}
});
} else if (node.data.type === 'zonegroup') {
this.modalRef = this.modalService.show(RgwMultisiteZonegroupDeletionFormComponent, {
zonegroup: node.data
});
} else if (node.data.type === 'zone') {
this.modalRef = this.modalService.show(RgwMultisiteZoneDeletionFormComponent, {
zone: node.data
});
}
}
enableRgwModule() {
let $obs;
const fnWaitUntilReconnected = () => {
observableTimer(2000).subscribe(() => {
// Trigger an API request to check if the connection is
// re-established.
this.mgrModuleService.list().subscribe(
() => {
// Resume showing the notification toasties.
this.notificationService.suspendToasties(false);
// Unblock the whole UI.
this.blockUI.stop();
// Reload the data table content.
this.notificationService.show(NotificationType.success, $localize`Enabled RGW Module`);
this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
this.router.navigate(['/rgw/multisite']);
});
// Reload the data table content.
},
() => {
fnWaitUntilReconnected();
}
);
});
};
if (!this.rgwModuleStatus) {
$obs = this.mgrModuleService.enable('rgw');
}
$obs.subscribe(
() => undefined,
() => {
// Suspend showing the notification toasties.
this.notificationService.suspendToasties(true);
// Block the whole UI to prevent user interactions until
// the connection to the backend is reestablished
this.blockUI.start($localize`Reconnecting, please wait ...`);
fnWaitUntilReconnected();
}
);
}
}
| 20,218 | 33.800344 | 157 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-export/rgw-multisite-export.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">Export Multi-site Realm Token</ng-container>
<ng-container class="modal-content">
<form name="exportTokenForm"
#frm="ngForm"
[formGroup]="exportTokenForm">
<span *ngIf="loading"
class="d-flex justify-content-center">
<i [ngClass]="[icons.large3x, icons.spinner, icons.spin]"></i></span>
<div class="modal-body"
*ngIf="!loading">
<cd-alert-panel *ngIf="!tokenValid"
type="warning"
class="mx-3"
i18n>
<div *ngFor="let realminfo of realms">
<b>{{realminfo.realm}}</b> -
{{realminfo.token}}
</div>
</cd-alert-panel>
<div *ngFor="let realminfo of realms">
<div class="form-group row">
<label class="cd-col-form-label"
for="realmName"
i18n>Realm Name
</label>
<div class="cd-col-form-input">
<input id="realmName"
name="realmName"
type="text"
value="{{ realminfo.realm }}"
readonly>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label"
for="token"
i18n>Token
</label>
<div class="cd-col-form-input">
<input id="realmToken"
name="realmToken"
type="text"
value="{{ realminfo.token }}"
class="me-2 mb-4"
readonly>
<cd-copy-2-clipboard-button
source="{{ realminfo.token }}"
[byId]="false">
</cd-copy-2-clipboard-button>
</div>
<hr *ngIf="realms.length > 1">
</div>
</div>
</div>
<div class="modal-footer">
<cd-back-button class="m-2 float-end"
aria-label="Close"
(backAction)="activeModal.close()"></cd-back-button>
</div>
</form>
</ng-container>
</cd-modal>
| 2,175 | 31.969697 | 80 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-export/rgw-multisite-export.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import { SharedModule } from '~/app/shared/shared.module';
import { RgwMultisiteExportComponent } from './rgw-multisite-export.component';
describe('RgwMultisiteExportComponent', () => {
let component: RgwMultisiteExportComponent;
let fixture: ComponentFixture<RgwMultisiteExportComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
SharedModule,
ReactiveFormsModule,
RouterTestingModule,
HttpClientTestingModule,
ToastrModule.forRoot()
],
declarations: [RgwMultisiteExportComponent],
providers: [NgbActiveModal]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwMultisiteExportComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,262 | 31.384615 | 79 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-export/rgw-multisite-export.component.ts
|
import { AfterViewChecked, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { RgwRealmService } from '~/app/shared/api/rgw-realm.service';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { NotificationService } from '~/app/shared/services/notification.service';
import { RgwRealm } from '../models/rgw-multisite';
import { Icons } from '~/app/shared/enum/icons.enum';
@Component({
selector: 'cd-rgw-multisite-export',
templateUrl: './rgw-multisite-export.component.html',
styleUrls: ['./rgw-multisite-export.component.scss']
})
export class RgwMultisiteExportComponent implements OnInit, AfterViewChecked {
exportTokenForm: CdFormGroup;
realms: any;
realmList: RgwRealm[];
multisiteInfo: any;
tokenValid = false;
loading = true;
icons = Icons;
constructor(
public activeModal: NgbActiveModal,
public rgwRealmService: RgwRealmService,
public actionLabels: ActionLabelsI18n,
public notificationService: NotificationService,
private readonly changeDetectorRef: ChangeDetectorRef
) {
this.createForm();
}
createForm() {
this.exportTokenForm = new CdFormGroup({});
}
onSubmit() {
this.activeModal.close();
}
ngOnInit(): void {
this.rgwRealmService.getRealmTokens().subscribe((data: object[]) => {
this.loading = false;
this.realms = data;
var base64Matcher = new RegExp(
'^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$'
);
this.realms.forEach((realmInfo: any) => {
if (base64Matcher.test(realmInfo.token)) {
this.tokenValid = true;
} else {
this.tokenValid = false;
}
});
});
}
ngAfterViewChecked(): void {
this.changeDetectorRef.detectChanges();
}
}
| 1,936 | 29.746032 | 90 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-import/rgw-multisite-import.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">Import Multi-site Token</ng-container>
<ng-container class="modal-content">
<form name="importTokenForm"
#frm="ngForm"
[formGroup]="importTokenForm">
<div class="modal-body">
<cd-alert-panel type="info"
spacingClass="mb-3">Please create a rgw service using the secondary zone(created after submitting this form) to start the replication between zones.
</cd-alert-panel>
<div class="form-group row">
<label class="cd-col-form-label required"
for="realmToken"
i18n>Token
</label>
<div class="cd-col-form-input">
<input id="realmToken"
name="realmToken"
class="form-control"
type="text"
formControlName="realmToken">
<span class="invalid-feedback"
*ngIf="importTokenForm.showError('realmToken', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="zoneName"
i18n>Secondary Zone Name</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="Zone name..."
id="zoneName"
name="zoneName"
formControlName="zoneName">
<span class="invalid-feedback"
*ngIf="importTokenForm.showError('zoneName', frm, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="importTokenForm.showError('zoneName', frm, 'uniqueName')"
i18n>The chosen zone name is already in use.</span>
</div>
</div>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="onSubmit()"
[submitText]="actionLabels.IMPORT"
[form]="importTokenForm"></cd-form-button-panel>
</div>
</form>
</ng-container>
</cd-modal>
| 2,234 | 38.210526 | 170 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-import/rgw-multisite-import.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import { SharedModule } from '~/app/shared/shared.module';
import { RgwMultisiteImportComponent } from './rgw-multisite-import.component';
describe('RgwMultisiteImportComponent', () => {
let component: RgwMultisiteImportComponent;
let fixture: ComponentFixture<RgwMultisiteImportComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
SharedModule,
ReactiveFormsModule,
RouterTestingModule,
HttpClientTestingModule,
ToastrModule.forRoot()
],
declarations: [RgwMultisiteImportComponent],
providers: [NgbActiveModal]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwMultisiteImportComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,262 | 31.384615 | 79 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-import/rgw-multisite-import.component.ts
|
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { RgwRealmService } from '~/app/shared/api/rgw-realm.service';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { CdValidators } from '~/app/shared/forms/cd-validators';
import { NotificationService } from '~/app/shared/services/notification.service';
import { RgwZone } from '../models/rgw-multisite';
import _ from 'lodash';
@Component({
selector: 'cd-rgw-multisite-import',
templateUrl: './rgw-multisite-import.component.html',
styleUrls: ['./rgw-multisite-import.component.scss']
})
export class RgwMultisiteImportComponent implements OnInit {
readonly endpoints = /^((https?:\/\/)|(www.))(?:([a-zA-Z]+)|(\d+\.\d+.\d+.\d+)):\d{2,4}$/;
readonly ipv4Rgx = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i;
readonly ipv6Rgx = /^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$/i;
importTokenForm: CdFormGroup;
multisiteInfo: object[] = [];
zoneList: RgwZone[] = [];
zoneNames: string[];
constructor(
public activeModal: NgbActiveModal,
public rgwRealmService: RgwRealmService,
public actionLabels: ActionLabelsI18n,
public notificationService: NotificationService
) {
this.createForm();
}
ngOnInit(): void {
this.zoneList =
this.multisiteInfo[2] !== undefined && this.multisiteInfo[2].hasOwnProperty('zones')
? this.multisiteInfo[2]['zones']
: [];
this.zoneNames = this.zoneList.map((zone) => {
return zone['name'];
});
}
createForm() {
this.importTokenForm = new CdFormGroup({
realmToken: new FormControl('', {
validators: [Validators.required]
}),
zoneName: new FormControl(null, {
validators: [
Validators.required,
CdValidators.custom('uniqueName', (zoneName: string) => {
return this.zoneNames && this.zoneNames.indexOf(zoneName) !== -1;
})
]
})
});
}
onSubmit() {
const values = this.importTokenForm.value;
this.rgwRealmService.importRealmToken(values['realmToken'], values['zoneName']).subscribe(
() => {
this.notificationService.show(
NotificationType.success,
$localize`Realm token import successfull`
);
this.activeModal.close();
},
() => {
this.importTokenForm.setErrors({ cdSubmitButton: true });
}
);
}
}
| 2,684 | 33.423077 | 110 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-migrate/rgw-multisite-migrate.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">Migrate Single Site to Multi-site
<cd-helper>
<span>Migrate from a single-site deployment with a default zonegroup and zone to a multi-site system</span>
</cd-helper>
</ng-container>
<ng-container class="modal-content">
<form name="multisiteMigrateForm"
#formDir="ngForm"
[formGroup]="multisiteMigrateForm"
novalidate>
<div class="modal-body">
<div class="form-group row">
<label class="cd-col-form-label required"
for="realmName"
i18n>Realm Name</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="Realm name..."
id="realmName"
name="realmName"
formControlName="realmName">
<span class="invalid-feedback"
*ngIf="multisiteMigrateForm.showError('realmName', formDir, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="multisiteMigrateForm.showError('realmName', formDir, 'uniqueName')"
i18n>The chosen realm name is already in use.</span>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="zonegroupName"
i18n>Rename default zonegroup</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="Zonegroup name..."
id="zonegroupName"
name="zonegroupName"
formControlName="zonegroupName">
<span class="invalid-feedback"
*ngIf="multisiteMigrateForm.showError('zonegroupName', formDir, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="multisiteMigrateForm.showError('zonegroupName', formDir, 'uniqueName')"
i18n>The chosen zonegroup name is already in use.</span>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="zonegroup_endpoints"
i18n>Zonegroup Endpoints</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="e.g, http://ceph-node-00.com:80"
id="zonegroup_endpoints"
name="zonegroup_endpoints"
formControlName="zonegroup_endpoints">
<span class="invalid-feedback"
*ngIf="multisiteMigrateForm.showError('zonegroup_endpoints', formDir, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="multisiteMigrateForm.showError('zonegroup_endpoints', formDir, 'endpoint')"
i18n>Please enter a valid IP address.</span>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="zoneName"
i18n>Rename default zone</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="Zone name..."
id="zoneName"
name="zoneName"
formControlName="zoneName">
<span class="invalid-feedback"
*ngIf="multisiteMigrateForm.showError('zoneName', formDir, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="multisiteMigrateForm.showError('zoneName', formDir, 'uniqueName')"
i18n>The chosen zone name is already in use.</span>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="zone_endpoints"
i18n>Zone Endpoints</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="e.g, http://ceph-node-00.com:80"
id="zone_endpoints"
name="zone_endpoints"
formControlName="zone_endpoints">
<span class="invalid-feedback"
*ngIf="multisiteMigrateForm.showError('zone_endpoints', formDir, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="multisiteMigrateForm.showError('zone_endpoints', formDir, 'endpoint')"
i18n>Please enter a valid IP address.</span>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="access_key"
i18n>Access key</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="e.g."
id="access_key"
name="access_key"
formControlName="access_key">
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="access_key"
i18n>Secret key</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="e.g."
id="secret_key"
name="secret_key"
formControlName="secret_key">
</div>
</div>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="submit()"
[submitText]="actionLabels.MIGRATE"
[form]="multisiteMigrateForm"></cd-form-button-panel>
</div>
</form>
</ng-container>
</cd-modal>
| 6,007 | 40.434483 | 113 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-migrate/rgw-multisite-migrate.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RgwMultisiteMigrateComponent } from './rgw-multisite-migrate.component';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import { SharedModule } from '~/app/shared/shared.module';
describe('RgwMultisiteMigrateComponent', () => {
let component: RgwMultisiteMigrateComponent;
let fixture: ComponentFixture<RgwMultisiteMigrateComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
SharedModule,
ReactiveFormsModule,
RouterTestingModule,
HttpClientTestingModule,
ToastrModule.forRoot()
],
declarations: [RgwMultisiteMigrateComponent],
providers: [NgbActiveModal]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwMultisiteMigrateComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,269 | 31.564103 | 81 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-migrate/rgw-multisite-migrate.component.ts
|
import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { NgbActiveModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { RgwMultisiteService } from '~/app/shared/api/rgw-multisite.service';
import { RgwRealmService } from '~/app/shared/api/rgw-realm.service';
import { RgwZoneService } from '~/app/shared/api/rgw-zone.service';
import { RgwZonegroupService } from '~/app/shared/api/rgw-zonegroup.service';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { CdValidators } from '~/app/shared/forms/cd-validators';
import { NotificationService } from '~/app/shared/services/notification.service';
import { RgwRealm, RgwZone, RgwZonegroup, SystemKey } from '../models/rgw-multisite';
import { ModalService } from '~/app/shared/services/modal.service';
import { RgwDaemonService } from '~/app/shared/api/rgw-daemon.service';
@Component({
selector: 'cd-rgw-multisite-migrate',
templateUrl: './rgw-multisite-migrate.component.html',
styleUrls: ['./rgw-multisite-migrate.component.scss']
})
export class RgwMultisiteMigrateComponent implements OnInit {
readonly endpoints = /^((https?:\/\/)|(www.))(?:([a-zA-Z]+)|(\d+\.\d+.\d+.\d+)):\d{2,4}$/;
readonly ipv4Rgx = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i;
readonly ipv6Rgx = /^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$/i;
@Output()
submitAction = new EventEmitter();
multisiteMigrateForm: CdFormGroup;
zoneNames: string[];
realmList: RgwRealm[];
multisiteInfo: object[] = [];
realmNames: string[];
zonegroupList: RgwZonegroup[];
zonegroupNames: string[];
zoneList: RgwZone[];
realm: RgwRealm;
zonegroup: RgwZonegroup;
zone: RgwZone;
newZonegroupName: any;
newZoneName: any;
bsModalRef: NgbModalRef;
users: any;
constructor(
public activeModal: NgbActiveModal,
public actionLabels: ActionLabelsI18n,
public rgwMultisiteService: RgwMultisiteService,
public rgwZoneService: RgwZoneService,
public notificationService: NotificationService,
public rgwZonegroupService: RgwZonegroupService,
public rgwRealmService: RgwRealmService,
public rgwDaemonService: RgwDaemonService,
public modalService: ModalService
) {
this.createForm();
}
createForm() {
this.multisiteMigrateForm = new CdFormGroup({
realmName: new FormControl(null, {
validators: [
Validators.required,
CdValidators.custom('uniqueName', (realmName: string) => {
return this.realmNames && this.zoneNames.indexOf(realmName) !== -1;
})
]
}),
zonegroupName: new FormControl(null, {
validators: [
Validators.required,
CdValidators.custom('uniqueName', (zonegroupName: string) => {
return this.zonegroupNames && this.zoneNames.indexOf(zonegroupName) !== -1;
})
]
}),
zoneName: new FormControl(null, {
validators: [
Validators.required,
CdValidators.custom('uniqueName', (zoneName: string) => {
return this.zoneNames && this.zoneNames.indexOf(zoneName) !== -1;
})
]
}),
zone_endpoints: new FormControl([], {
validators: [
CdValidators.custom('endpoint', (value: string) => {
if (_.isEmpty(value)) {
return false;
} else {
if (value.includes(',')) {
value.split(',').forEach((url: string) => {
return (
!this.endpoints.test(url) && !this.ipv4Rgx.test(url) && !this.ipv6Rgx.test(url)
);
});
} else {
return (
!this.endpoints.test(value) &&
!this.ipv4Rgx.test(value) &&
!this.ipv6Rgx.test(value)
);
}
return false;
}
}),
Validators.required
]
}),
zonegroup_endpoints: new FormControl(
[],
[
CdValidators.custom('endpoint', (value: string) => {
if (_.isEmpty(value)) {
return false;
} else {
if (value.includes(',')) {
value.split(',').forEach((url: string) => {
return (
!this.endpoints.test(url) && !this.ipv4Rgx.test(url) && !this.ipv6Rgx.test(url)
);
});
} else {
return (
!this.endpoints.test(value) &&
!this.ipv4Rgx.test(value) &&
!this.ipv6Rgx.test(value)
);
}
return false;
}
}),
Validators.required
]
),
access_key: new FormControl(null),
secret_key: new FormControl(null)
});
}
ngOnInit(): void {
this.realmList =
this.multisiteInfo[0] !== undefined && this.multisiteInfo[0].hasOwnProperty('realms')
? this.multisiteInfo[0]['realms']
: [];
this.realmNames = this.realmList.map((realm) => {
return realm['name'];
});
this.zonegroupList =
this.multisiteInfo[1] !== undefined && this.multisiteInfo[1].hasOwnProperty('zonegroups')
? this.multisiteInfo[1]['zonegroups']
: [];
this.zonegroupNames = this.zonegroupList.map((zonegroup) => {
return zonegroup['name'];
});
this.zoneList =
this.multisiteInfo[2] !== undefined && this.multisiteInfo[2].hasOwnProperty('zones')
? this.multisiteInfo[2]['zones']
: [];
this.zoneNames = this.zoneList.map((zone) => {
return zone['name'];
});
}
submit() {
const values = this.multisiteMigrateForm.value;
this.realm = new RgwRealm();
this.realm.name = values['realmName'];
this.zonegroup = new RgwZonegroup();
this.zonegroup.name = values['zonegroupName'];
this.zonegroup.endpoints = values['zonegroup_endpoints'];
this.zone = new RgwZone();
this.zone.name = values['zoneName'];
this.zone.endpoints = values['zone_endpoints'];
this.zone.system_key = new SystemKey();
this.zone.system_key.access_key = values['access_key'];
this.zone.system_key.secret_key = values['secret_key'];
this.rgwMultisiteService.migrate(this.realm, this.zonegroup, this.zone).subscribe(
() => {
this.notificationService.show(
NotificationType.success,
$localize`${this.actionLabels.MIGRATE} done successfully`
);
this.notificationService.show(NotificationType.success, `Daemon restart scheduled`);
this.submitAction.emit();
this.activeModal.close();
},
() => {
this.notificationService.show(NotificationType.error, $localize`Migration failed`);
}
);
}
}
| 7,081 | 35.132653 | 110 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-realm-form/rgw-multisite-realm-form.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">{{ action | titlecase }} {{ resource | upperFirst }}</ng-container>
<ng-container class="modal-content">
<form name="multisiteRealmForm"
#formDir="ngForm"
[formGroup]="multisiteRealmForm"
novalidate>
<div class="modal-body">
<div class="form-group row">
<label class="cd-col-form-label required"
for="realmName"
i18n>Realm Name</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="Realm name..."
id="realmName"
name="realmName"
formControlName="realmName">
<span class="invalid-feedback"
*ngIf="multisiteRealmForm.showError('realmName', formDir, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="multisiteRealmForm.showError('realmName', formDir, 'uniqueName')"
i18n>The chosen realm name is already in use.</span>
<div class="custom-control custom-checkbox">
<input class="form-check-input"
id="default_realm"
name="default_realm"
formControlName="default_realm"
[attr.disabled]="action === 'edit' ? true: null"
type="checkbox">
<label class="form-check-label"
for="default_realm"
i18n>Default</label>
<cd-helper *ngIf="action === 'edit' && info.data.is_default">
<span i18n>You cannot unset the default flag.</span>
</cd-helper>
<cd-helper *ngIf="action === 'edit' && !info.data.is_default">
<span i18n>Please consult the <a href="{{ docUrl }}">documentation</a> to follow the failover mechanism</span>
</cd-helper>
<cd-helper *ngIf="defaultRealmDisabled && action === 'create'">
<span i18n>Default realm already exists.</span>
</cd-helper>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="submit()"
[form]="multisiteRealmForm"
[submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"></cd-form-button-panel>
</div>
</form>
</ng-container>
</cd-modal>
| 2,554 | 42.305085 | 124 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-realm-form/rgw-multisite-realm-form.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { of as observableOf } from 'rxjs';
import { ToastrModule } from 'ngx-toastr';
import { RgwRealmService } from '~/app/shared/api/rgw-realm.service';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { NotificationService } from '~/app/shared/services/notification.service';
import { SharedModule } from '~/app/shared/shared.module';
import { RgwMultisiteRealmFormComponent } from './rgw-multisite-realm-form.component';
describe('RgwMultisiteRealmFormComponent', () => {
let component: RgwMultisiteRealmFormComponent;
let fixture: ComponentFixture<RgwMultisiteRealmFormComponent>;
let rgwRealmService: RgwRealmService;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
SharedModule,
ReactiveFormsModule,
RouterTestingModule,
HttpClientTestingModule,
ToastrModule.forRoot()
],
providers: [NgbActiveModal],
declarations: [RgwMultisiteRealmFormComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwMultisiteRealmFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('submit form', () => {
let notificationService: NotificationService;
beforeEach(() => {
spyOn(TestBed.inject(Router), 'navigate').and.stub();
notificationService = TestBed.inject(NotificationService);
spyOn(notificationService, 'show');
rgwRealmService = TestBed.inject(RgwRealmService);
});
it('should validate name', () => {
component.action = 'create';
component.createForm();
const control = component.multisiteRealmForm.get('realmName');
expect(_.isFunction(control.validator)).toBeTruthy();
});
it('should not validate name', () => {
component.action = 'edit';
component.createForm();
const control = component.multisiteRealmForm.get('realmName');
expect(control.asyncValidator).toBeNull();
});
it('tests create success notification', () => {
spyOn(rgwRealmService, 'create').and.returnValue(observableOf([]));
component.action = 'create';
component.multisiteRealmForm.markAsDirty();
component.submit();
expect(notificationService.show).toHaveBeenCalledWith(
NotificationType.success,
"Realm: 'null' created successfully"
);
});
it('tests update success notification', () => {
spyOn(rgwRealmService, 'update').and.returnValue(observableOf([]));
component.action = 'edit';
component.info = {
data: { name: 'null' }
};
component.multisiteRealmForm.markAsDirty();
component.submit();
expect(notificationService.show).toHaveBeenCalledWith(
NotificationType.success,
"Realm: 'null' updated successfully"
);
});
});
});
| 3,337 | 33.770833 | 86 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-realm-form/rgw-multisite-realm-form.component.ts
|
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { RgwRealmService } from '~/app/shared/api/rgw-realm.service';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { CdValidators } from '~/app/shared/forms/cd-validators';
import { NotificationService } from '~/app/shared/services/notification.service';
import { RgwRealm } from '../models/rgw-multisite';
import { DocService } from '~/app/shared/services/doc.service';
@Component({
selector: 'cd-rgw-multisite-realm-form',
templateUrl: './rgw-multisite-realm-form.component.html',
styleUrls: ['./rgw-multisite-realm-form.component.scss']
})
export class RgwMultisiteRealmFormComponent implements OnInit {
action: string;
multisiteRealmForm: CdFormGroup;
info: any;
editing = false;
resource: string;
multisiteInfo: object[] = [];
realm: RgwRealm;
realmList: RgwRealm[] = [];
zonegroupList: RgwRealm[] = [];
realmNames: string[];
newRealmName: string;
isMaster: boolean;
defaultsInfo: string[];
defaultRealmDisabled = false;
docUrl: string;
constructor(
public activeModal: NgbActiveModal,
public actionLabels: ActionLabelsI18n,
public rgwRealmService: RgwRealmService,
public notificationService: NotificationService,
public docService: DocService
) {
this.action = this.editing
? this.actionLabels.EDIT + this.resource
: this.actionLabels.CREATE + this.resource;
this.createForm();
}
createForm() {
this.multisiteRealmForm = new CdFormGroup({
realmName: new FormControl(null, {
validators: [
Validators.required,
CdValidators.custom('uniqueName', (realmName: string) => {
return (
this.action === 'create' &&
this.realmNames &&
this.realmNames.indexOf(realmName) !== -1
);
})
]
}),
default_realm: new FormControl(false)
});
}
ngOnInit(): void {
this.realmList =
this.multisiteInfo[0] !== undefined && this.multisiteInfo[0].hasOwnProperty('realms')
? this.multisiteInfo[0]['realms']
: [];
this.realmNames = this.realmList.map((realm) => {
return realm['name'];
});
if (this.action === 'edit') {
this.zonegroupList =
this.multisiteInfo[1] !== undefined && this.multisiteInfo[1].hasOwnProperty('zonegroups')
? this.multisiteInfo[1]['zonegroups']
: [];
this.multisiteRealmForm.get('realmName').setValue(this.info.data.name);
this.multisiteRealmForm.get('default_realm').setValue(this.info.data.is_default);
if (this.info.data.is_default) {
this.multisiteRealmForm.get('default_realm').disable();
}
}
this.zonegroupList.forEach((zgp: any) => {
if (zgp.is_master === true && zgp.realm_id === this.info.data.id) {
this.isMaster = true;
}
});
if (this.defaultsInfo && this.defaultsInfo['defaultRealmName'] !== null) {
this.multisiteRealmForm.get('default_realm').disable();
this.defaultRealmDisabled = true;
}
this.docUrl = this.docService.urlGenerator('rgw-multisite');
}
submit() {
const values = this.multisiteRealmForm.getRawValue();
this.realm = new RgwRealm();
if (this.action === 'create') {
this.realm.name = values['realmName'];
this.rgwRealmService.create(this.realm, values['default_realm']).subscribe(
() => {
this.notificationService.show(
NotificationType.success,
$localize`Realm: '${values['realmName']}' created successfully`
);
this.activeModal.close();
},
() => {
this.multisiteRealmForm.setErrors({ cdSubmitButton: true });
}
);
} else if (this.action === 'edit') {
this.realm.name = this.info.data.name;
this.newRealmName = values['realmName'];
this.rgwRealmService.update(this.realm, values['default_realm'], this.newRealmName).subscribe(
() => {
this.notificationService.show(
NotificationType.success,
$localize`Realm: '${values['realmName']}' updated successfully`
);
this.activeModal.close();
},
() => {
this.multisiteRealmForm.setErrors({ cdSubmitButton: true });
}
);
}
}
}
| 4,600 | 33.856061 | 100 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-zone-form/rgw-multisite-zone-form.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">{{ action | titlecase }} {{ resource | upperFirst }}</ng-container>
<ng-container class="modal-content">
<form name="multisiteZoneForm"
#formDir="ngForm"
[formGroup]="multisiteZoneForm"
novalidate>
<div class="modal-body">
<div class="form-group row">
<label class="cd-col-form-label"
for="selectedZonegroup"
i18n>Select Zonegroup</label>
<div class="cd-col-form-input">
<select class="form-select"
id="selectedZonegroup"
[attr.disabled]="action === 'edit' ? true : null"
formControlName="selectedZonegroup"
name="selectedZonegroup"
(change)="onZoneGroupChange($event.target.value)">
<option *ngFor="let zonegroupName of zonegroupList"
[value]="zonegroupName.name"
[selected]="zonegroupName.name === multisiteZoneForm.getValue('selectedZonegroup')">
{{ zonegroupName.name }}
</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="zonegroupName"
i18n>Zone Name</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="Zone name..."
id="zoneName"
name="zoneName"
formControlName="zoneName">
<span class="invalid-feedback"
*ngIf="multisiteZoneForm.showError('zoneName', formDir, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="multisiteZoneForm.showError('zoneName', formDir, 'uniqueName')"
i18n>The chosen zone name is already in use.</span>
<div class="custom-control custom-checkbox">
<input class="form-check-input"
id="default_zone"
name="default_zone"
formControlName="default_zone"
[attr.disabled]="action === 'edit' ? true : null"
type="checkbox">
<label class="form-check-label"
for="default_zone"
i18n>Default</label>
<span *ngIf="disableDefault && action === 'create'">
<cd-helper i18n>Default zone can only exist in a default zonegroup.
</cd-helper>
</span>
<span *ngIf="isDefaultZone">
<cd-helper i18n>You cannot unset the default flag.
</cd-helper>
</span>
<cd-helper *ngIf="action === 'edit' && !isDefaultZone">
<span i18n>Please consult the <a href="{{ docUrl }}">documentation</a> to follow the failover mechanism</span>
</cd-helper><br>
</div>
<div class="custom-control custom-checkbox">
<input class="form-check-input"
id="master_zone"
name="master_zone"
formControlName="master_zone"
[attr.disabled]="action === 'edit' ? true : null"
type="checkbox">
<label class="form-check-label"
for="master_zone"
i18n>Master</label>
<span *ngIf="disableMaster">
<cd-helper i18n>Master zone already exists for the selected zonegroup.
</cd-helper>
</span>
<span *ngIf="isMasterZone">
<cd-helper i18n>You cannot unset the master flag.
</cd-helper>
</span>
<cd-helper *ngIf="action === 'edit' && !isMasterZone">
<span i18n>Please consult the <a href="{{ docUrl }}">documentation</a> to follow the failover mechanism</span>
</cd-helper>
</div>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="zone_endpoints"
i18n>Endpoints</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="e.g, http://ceph-node-00.com:80"
id="zone_endpoints"
name="zone_endpoints"
formControlName="zone_endpoints">
<span class="invalid-feedback"
*ngIf="multisiteZoneForm.showError('zone_endpoints', formDir, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="multisiteZoneForm.showError('zone_endpoints', formDir, 'endpoint')"
i18n>Please enter a valid IP address.</span>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="access_key"
i18n>Access key</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="DiPt4V7WWvy2njL1z6aC"
id="access_key"
name="access_key"
formControlName="access_key">
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="access_key"
i18n>Secret key</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="xSZUdYky0bTctAdCEEW8ikhfBVKsBV5LFYL82vvh"
id="secret_key"
name="secret_key"
formControlName="secret_key">
</div>
</div>
<div class="form-group row"
*ngIf="action === 'edit'">
<div *ngIf="action === 'edit'">
<legend>Placement Targets</legend>
<div class="form-group row">
<label class="cd-col-form-label"
for="placementTarget"
i18n>Placement target</label>
<div class="cd-col-form-input">
<select class="form-select"
id="placementTarget"
formControlName="placementTarget"
name="placementTarget"
(change)="getZonePlacementData($event.target.value)">
<option *ngFor="let placement of placementTargets"
[value]="placement.name"
[selected]="placement.name === multisiteZoneForm.getValue('placementTarget')">
{{ placement.name }}
</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label"
for="placementDataPool"
i18n>Data pool</label>
<div class="cd-col-form-input">
<select class="form-select"
id="placementDataPool"
formControlName="placementDataPool"
[value]="placementDataPool"
name="placementDataPool">
<option *ngFor="let pool of poolList"
[value]="pool.poolname"
[selected]="pool.poolname === multisiteZoneForm.getValue('placementDataPool')">
{{ pool.poolname }}
</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label"
for="placementIndexPool"
i18n>Index pool</label>
<div class="cd-col-form-input">
<select class="form-select"
id="placementIndexPool"
formControlName="placementIndexPool"
name="placementIndexPool">
<option *ngFor="let pool of poolList"
[value]="pool.poolname"
[selected]="pool.poolname === multisiteZoneForm.getValue('placementIndexPool')">
{{ pool.poolname }}
</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label"
for="placementDataExtraPool"
i18n>Data extra pool</label>
<div class="cd-col-form-input">
<select class="form-select"
id="placementDataExtraPool"
formControlName="placementDataExtraPool"
name="placementDataExtraPool">
<option *ngFor="let pool of poolList"
[value]="pool.poolname"
[selected]="pool.poolname === multisiteZoneForm.getValue('placementDataExtraPool')">
{{ pool.poolname }}
</option>
</select>
</div>
</div>
<div>
<legend>Storage Classes</legend>
<div class="form-group row">
<label class="cd-col-form-label"
for="storageClass"
i18n>Storage Class</label>
<div class="cd-col-form-input">
<select class="form-select"
id="storageClass"
formControlName="storageClass"
(change)="getStorageClassData($event.target.value)"
name="storageClass">
<option *ngFor="let str of storageClassList"
[value]="str.value">
{{ str.value }}
</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label"
for="storageDataPool"
i18n>Data pool</label>
<div class="cd-col-form-input">
<select class="form-select"
id="storageDataPool"
formControlName="storageDataPool"
name="storageDataPool">
<option *ngFor="let pool of poolList"
[value]="pool.poolname"
[selected]="pool.poolname === multisiteZoneForm.getValue('storageDataPool')">
{{ pool.poolname }}
</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label"
for="storageCompression"
i18n>Compression</label>
<div class="cd-col-form-input">
<select class="form-select"
id="storageCompression"
formControlName="storageCompression"
name="storageCompression">
<option *ngFor="let compression of compressionTypes"
[value]="compression">
{{ compression }}
</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="submit()"
[form]="multisiteZoneForm"
[submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"></cd-form-button-panel>
</div>
</form>
</ng-container>
</cd-modal>
| 11,731 | 41.507246 | 124 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-zone-form/rgw-multisite-zone-form.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import { SharedModule } from '~/app/shared/shared.module';
import { RgwMultisiteZoneFormComponent } from './rgw-multisite-zone-form.component';
describe('RgwMultisiteZoneFormComponent', () => {
let component: RgwMultisiteZoneFormComponent;
let fixture: ComponentFixture<RgwMultisiteZoneFormComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
SharedModule,
ReactiveFormsModule,
RouterTestingModule,
HttpClientTestingModule,
ToastrModule.forRoot()
],
providers: [NgbActiveModal],
declarations: [RgwMultisiteZoneFormComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwMultisiteZoneFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,277 | 31.769231 | 84 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-zone-form/rgw-multisite-zone-form.component.ts
|
import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { NgbActiveModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { RgwMultisiteService } from '~/app/shared/api/rgw-multisite.service';
import { RgwUserService } from '~/app/shared/api/rgw-user.service';
import { RgwZoneService } from '~/app/shared/api/rgw-zone.service';
import { RgwZonegroupService } from '~/app/shared/api/rgw-zonegroup.service';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { CdValidators } from '~/app/shared/forms/cd-validators';
import { NotificationService } from '~/app/shared/services/notification.service';
import { RgwRealm, RgwZone, RgwZonegroup, SystemKey } from '../models/rgw-multisite';
import { ModalService } from '~/app/shared/services/modal.service';
@Component({
selector: 'cd-rgw-multisite-zone-form',
templateUrl: './rgw-multisite-zone-form.component.html',
styleUrls: ['./rgw-multisite-zone-form.component.scss']
})
export class RgwMultisiteZoneFormComponent implements OnInit {
readonly endpoints = /^((https?:\/\/)|(www.))(?:([a-zA-Z]+)|(\d+\.\d+.\d+.\d+)):\d{2,4}$/;
readonly ipv4Rgx = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i;
readonly ipv6Rgx = /^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$/i;
action: string;
info: any;
multisiteZoneForm: CdFormGroup;
editing = false;
resource: string;
realm: RgwRealm;
zonegroup: RgwZonegroup;
zone: RgwZone;
defaultsInfo: string[] = [];
multisiteInfo: object[] = [];
zonegroupList: RgwZonegroup[] = [];
zoneList: RgwZone[] = [];
zoneNames: string[];
users: any;
placementTargets: any;
zoneInfo: RgwZone;
poolList: object[] = [];
storageClassList: object[] = [];
disableDefault: boolean = false;
disableMaster: boolean = false;
isMetadataSync: boolean = false;
isMasterZone: boolean;
isDefaultZone: boolean;
syncStatusTimedOut: boolean = false;
bsModalRef: NgbModalRef;
createSystemUser: boolean = false;
master_zone_of_master_zonegroup: RgwZone;
masterZoneUser: any;
access_key: any;
master_zonegroup_of_realm: RgwZonegroup;
compressionTypes = ['lz4', 'zlib', 'snappy'];
userListReady: boolean = false;
constructor(
public activeModal: NgbActiveModal,
public actionLabels: ActionLabelsI18n,
public rgwMultisiteService: RgwMultisiteService,
public rgwZoneService: RgwZoneService,
public rgwZoneGroupService: RgwZonegroupService,
public notificationService: NotificationService,
public rgwUserService: RgwUserService,
public modalService: ModalService
) {
this.action = this.editing
? this.actionLabels.EDIT + this.resource
: this.actionLabels.CREATE + this.resource;
this.createForm();
}
createForm() {
this.multisiteZoneForm = new CdFormGroup({
zoneName: new FormControl(null, {
validators: [
Validators.required,
CdValidators.custom('uniqueName', (zoneName: string) => {
return (
this.action === 'create' && this.zoneNames && this.zoneNames.indexOf(zoneName) !== -1
);
})
]
}),
default_zone: new FormControl(false),
master_zone: new FormControl(false),
selectedZonegroup: new FormControl(null),
zone_endpoints: new FormControl(null, {
validators: [
CdValidators.custom('endpoint', (value: string) => {
if (_.isEmpty(value)) {
return false;
} else {
if (value.includes(',')) {
value.split(',').forEach((url: string) => {
return (
!this.endpoints.test(url) && !this.ipv4Rgx.test(url) && !this.ipv6Rgx.test(url)
);
});
} else {
return (
!this.endpoints.test(value) &&
!this.ipv4Rgx.test(value) &&
!this.ipv6Rgx.test(value)
);
}
return false;
}
}),
Validators.required
]
}),
access_key: new FormControl(null),
secret_key: new FormControl(null),
placementTarget: new FormControl(null),
placementDataPool: new FormControl(''),
placementIndexPool: new FormControl(null),
placementDataExtraPool: new FormControl(null),
storageClass: new FormControl(null),
storageDataPool: new FormControl(null),
storageCompression: new FormControl(null)
});
}
onZoneGroupChange(zonegroupName: string) {
let zg = new RgwZonegroup();
zg.name = zonegroupName;
this.rgwZoneGroupService.get(zg).subscribe((zonegroup: RgwZonegroup) => {
if (_.isEmpty(zonegroup.master_zone)) {
this.multisiteZoneForm.get('master_zone').setValue(true);
this.multisiteZoneForm.get('master_zone').disable();
this.disableMaster = false;
} else if (!_.isEmpty(zonegroup.master_zone) && this.action === 'create') {
this.multisiteZoneForm.get('master_zone').setValue(false);
this.multisiteZoneForm.get('master_zone').disable();
this.disableMaster = true;
}
});
if (
this.multisiteZoneForm.getValue('selectedZonegroup') !==
this.defaultsInfo['defaultZonegroupName']
) {
this.disableDefault = true;
this.multisiteZoneForm.get('default_zone').disable();
}
}
ngOnInit(): void {
this.zonegroupList =
this.multisiteInfo[1] !== undefined && this.multisiteInfo[1].hasOwnProperty('zonegroups')
? this.multisiteInfo[1]['zonegroups']
: [];
this.zoneList =
this.multisiteInfo[2] !== undefined && this.multisiteInfo[2].hasOwnProperty('zones')
? this.multisiteInfo[2]['zones']
: [];
this.zoneNames = this.zoneList.map((zone) => {
return zone['name'];
});
if (this.action === 'create') {
if (this.defaultsInfo['defaultZonegroupName'] !== undefined) {
this.multisiteZoneForm
.get('selectedZonegroup')
.setValue(this.defaultsInfo['defaultZonegroupName']);
this.onZoneGroupChange(this.defaultsInfo['defaultZonegroupName']);
}
}
if (this.action === 'edit') {
this.placementTargets = this.info.parent ? this.info.parent.data.placement_targets : [];
this.rgwZoneService.getPoolNames().subscribe((pools: object[]) => {
this.poolList = pools;
});
this.multisiteZoneForm.get('zoneName').setValue(this.info.data.name);
this.multisiteZoneForm.get('selectedZonegroup').setValue(this.info.data.parent);
this.multisiteZoneForm.get('default_zone').setValue(this.info.data.is_default);
this.multisiteZoneForm.get('master_zone').setValue(this.info.data.is_master);
this.multisiteZoneForm.get('zone_endpoints').setValue(this.info.data.endpoints.toString());
this.multisiteZoneForm.get('access_key').setValue(this.info.data.access_key);
this.multisiteZoneForm.get('secret_key').setValue(this.info.data.secret_key);
this.multisiteZoneForm
.get('placementTarget')
.setValue(this.info.parent.data.default_placement);
this.getZonePlacementData(this.multisiteZoneForm.getValue('placementTarget'));
if (this.info.data.is_default) {
this.isDefaultZone = true;
this.multisiteZoneForm.get('default_zone').disable();
}
if (this.info.data.is_master) {
this.isMasterZone = true;
this.multisiteZoneForm.get('master_zone').disable();
}
const zone = new RgwZone();
zone.name = this.info.data.name;
this.onZoneGroupChange(this.info.data.parent);
}
if (
this.multisiteZoneForm.getValue('selectedZonegroup') !==
this.defaultsInfo['defaultZonegroupName']
) {
this.disableDefault = true;
this.multisiteZoneForm.get('default_zone').disable();
}
}
getZonePlacementData(placementTarget: string) {
this.zone = new RgwZone();
this.zone.name = this.info.data.name;
if (this.placementTargets) {
this.placementTargets.forEach((placement: any) => {
if (placement.name === placementTarget) {
let storageClasses = placement.storage_classes;
this.storageClassList = Object.entries(storageClasses).map(([key, value]) => ({
key,
value
}));
}
});
}
this.rgwZoneService.get(this.zone).subscribe((zoneInfo: RgwZone) => {
this.zoneInfo = zoneInfo;
if (this.zoneInfo && this.zoneInfo['placement_pools']) {
this.zoneInfo['placement_pools'].forEach((plc_pool) => {
if (plc_pool.key === placementTarget) {
let storageClasses = plc_pool.val.storage_classes;
let placementDataPool = storageClasses['STANDARD']
? storageClasses['STANDARD']['data_pool']
: '';
let placementIndexPool = plc_pool.val.index_pool;
let placementDataExtraPool = plc_pool.val.data_extra_pool;
this.poolList.push({ poolname: placementDataPool });
this.poolList.push({ poolname: placementIndexPool });
this.poolList.push({ poolname: placementDataExtraPool });
this.multisiteZoneForm.get('storageClass').setValue(this.storageClassList[0]['value']);
this.multisiteZoneForm.get('storageDataPool').setValue(placementDataPool);
this.multisiteZoneForm.get('storageCompression').setValue(this.compressionTypes[0]);
this.multisiteZoneForm.get('placementDataPool').setValue(placementDataPool);
this.multisiteZoneForm.get('placementIndexPool').setValue(placementIndexPool);
this.multisiteZoneForm.get('placementDataExtraPool').setValue(placementDataExtraPool);
}
});
}
});
}
getStorageClassData(storageClass: string) {
let storageClassSelected = this.storageClassList.find((x) => x['value'] == storageClass)[
'value'
];
this.poolList.push({ poolname: storageClassSelected.data_pool });
this.multisiteZoneForm.get('storageDataPool').setValue(storageClassSelected.data_pool);
this.multisiteZoneForm
.get('storageCompression')
.setValue(storageClassSelected.compression_type);
}
submit() {
const values = this.multisiteZoneForm.getRawValue();
if (this.action === 'create') {
this.zonegroup = new RgwZonegroup();
this.zonegroup.name = values['selectedZonegroup'];
this.zone = new RgwZone();
this.zone.name = values['zoneName'];
this.zone.endpoints = values['zone_endpoints'];
this.zone.system_key = new SystemKey();
this.zone.system_key.access_key = values['access_key'];
this.zone.system_key.secret_key = values['secret_key'];
this.rgwZoneService
.create(
this.zone,
this.zonegroup,
values['default_zone'],
values['master_zone'],
this.zone.endpoints
)
.subscribe(
() => {
this.notificationService.show(
NotificationType.success,
$localize`Zone: '${values['zoneName']}' created successfully`
);
this.activeModal.close();
},
() => {
this.multisiteZoneForm.setErrors({ cdSubmitButton: true });
}
);
} else if (this.action === 'edit') {
this.zonegroup = new RgwZonegroup();
this.zonegroup.name = values['selectedZonegroup'];
this.zone = new RgwZone();
this.zone.name = this.info.data.name;
this.zone.endpoints = values['zone_endpoints'];
this.zone.system_key = new SystemKey();
this.zone.system_key.access_key = values['access_key'];
this.zone.system_key.secret_key = values['secret_key'];
this.rgwZoneService
.update(
this.zone,
this.zonegroup,
values['zoneName'],
values['default_zone'],
values['master_zone'],
this.zone.endpoints,
values['placementTarget'],
values['placementDataPool'],
values['placementIndexPool'],
values['placementDataExtraPool'],
values['storageClass'],
values['storageDataPool'],
values['storageCompression']
)
.subscribe(
() => {
this.notificationService.show(
NotificationType.success,
$localize`Zone: '${values['zoneName']}' updated successfully`
);
this.activeModal.close();
},
() => {
this.multisiteZoneForm.setErrors({ cdSubmitButton: true });
}
);
}
}
checkUrlArray(endpoints: string) {
let endpointsArray = [];
if (endpoints.includes(',')) {
endpointsArray = endpoints.split(',');
} else {
endpointsArray.push(endpoints);
}
return endpointsArray;
}
}
| 13,110 | 37.675516 | 110 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-zonegroup-form/rgw-multisite-zonegroup-form.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">{{ action | titlecase }} {{ resource | upperFirst }}</ng-container>
<ng-container class="modal-content">
<form name="multisiteZonegroupForm"
#formDir="ngForm"
[formGroup]="multisiteZonegroupForm"
novalidate>
<div class="modal-body">
<div class="form-group row">
<label class="cd-col-form-label"
for="selectedRealm"
i18n>Select Realm</label>
<div class="cd-col-form-input">
<select class="form-select"
id="selectedRealm"
formControlName="selectedRealm"
name="selectedRealm">
<option ngValue=""
i18n>-- Select a realm --</option>
<option *ngFor="let realmName of realmList"
[value]="realmName.name"
[selected]="realmName.name === multisiteZonegroupForm.getValue('selectedRealm')">
{{ realmName.name }}
</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="zonegroupName"
i18n>Zonegroup Name</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="Zonegroup name..."
id="zonegroupName"
name="zonegroupName"
formControlName="zonegroupName">
<span class="invalid-feedback"
*ngIf="multisiteZonegroupForm.showError('zonegroupName', formDir, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="multisiteZonegroupForm.showError('zonegroupName', formDir, 'uniqueName')"
i18n>The chosen zonegroup name is already in use.</span>
<div class="custom-control custom-checkbox">
<input class="form-check-input"
id="default_zonegroup"
name="default_zonegroup"
formControlName="default_zonegroup"
[attr.disabled]="action === 'edit' ? true : null"
type="checkbox">
<label class="form-check-label"
for="default_zonegroup"
i18n>Default</label>
<span *ngIf="disableDefault && action === 'create'">
<cd-helper i18n>Zonegroup doesn't belong to the default realm.</cd-helper>
</span>
<cd-helper *ngIf="action === 'edit' && !info.data.is_default">
<span i18n>Please consult the <a href="{{ docUrl }}">documentation</a> to follow the failover mechanism</span>
</cd-helper>
<cd-helper *ngIf="action === 'edit' && info.data.is_default">
<span i18n>You cannot unset the default flag.</span>
</cd-helper><br>
<input class="form-check-input"
id="master_zonegroup"
name="master_zonegroup"
formControlName="master_zonegroup"
[attr.disabled]="action === 'edit' ? true : null"
type="checkbox">
<label class="form-check-label"
for="master_zonegroup"
i18n>Master</label>
<span *ngIf="disableMaster && action === 'create'">
<cd-helper i18n>Multiple master zonegroups can't be configured. If you want to create a new zonegroup and make it the master zonegroup, you must delete the default zonegroup.</cd-helper>
</span>
<cd-helper *ngIf="action === 'edit' && !info.data.is_master">
<span i18n>Please consult the <a href="{{ docUrl }}">documentation</a> to follow the failover mechanism</span>
</cd-helper>
<cd-helper *ngIf="action === 'edit' && info.data.is_master">
<span i18n>You cannot unset the master flag.</span>
</cd-helper>
</div>
</div>
</div>
<div class="form-group row">
<label class="cd-col-form-label required"
for="zonegroup_endpoints"
i18n>Endpoints</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="e.g, http://ceph-node-00.com:80"
id="zonegroup_endpoints"
name="zonegroup_endpoints"
formControlName="zonegroup_endpoints">
<span class="invalid-feedback"
*ngIf="multisiteZonegroupForm.showError('zonegroup_endpoints', formDir, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="multisiteZonegroupForm.showError('zonegroup_endpoints', formDir, 'endpoint')"
i18n>Please enter a valid IP address.</span>
</div>
</div>
<div class="form-group row"
*ngIf="action === 'edit'">
<label i18n
for="zones"
class="cd-col-form-label">Zones</label>
<div class="cd-col-form-input">
<cd-select-badges id="zones"
[data]="zonegroupZoneNames"
[options]="labelsOption"
[customBadges]="true">
</cd-select-badges><br>
<span class="invalid-feedback"
*ngIf="isRemoveMasterZone"
i18n>Cannot remove master zone.</span>
</div>
</div>
<div *ngIf="action === 'edit'">
<legend>Placement targets</legend>
<ng-container formArrayName="placementTargets">
<div *ngFor="let item of placementTargets.controls; let index = index; trackBy: trackByFn">
<div class="card"
[formGroup]="item">
<div class="card-header">
{{ (index + 1) | ordinal }}
<span class="float-end clickable"
name="remove_placement_target"
(click)="removePlacementTarget(index)"
ngbTooltip="Remove">×</span>
</div>
<div class="card-body">
<!-- Placement Id -->
<div class="form-group row">
<label i18n
class="cd-col-form-label required"
for="placement_id">Placement Id</label>
<div class="cd-col-form-input">
<input type="text"
class="form-control"
name="placement_id"
id="placement_id"
formControlName="placement_id"
placeholder="eg. default-placement">
<span class="invalid-feedback">
<span *ngIf="showError(index, 'placement_id', formDir, 'required')"
i18n>This field is required.</span>
</span>
</div>
</div>
<!-- Tags-->
<div class="form-group row">
<label i18n
class="cd-col-form-label"
for="tags">Tags</label>
<div class="cd-col-form-input">
<input type="text"
class="form-control"
name="tags"
id="tags"
formControlName="tags"
placeholder="comma separated tags, eg. default-placement, ssd">
</div>
</div>
<!-- Storage Class -->
<div class="form-group row">
<label i18n
class="cd-col-form-label"
for="storage_class">Storage Class</label>
<div class="cd-col-form-input">
<input type="text"
class="form-control"
name="storage_class"
id="storage_class"
formControlName="storage_class"
placeholder="eg. Standard-tier">
</div>
</div>
</div>
</div>
</div>
</ng-container>
<button type="button"
id="add-plc"
class="btn btn-light float-end my-3"
(click)="addPlacementTarget()">
<i [ngClass]="[icons.add]"></i>
<ng-container i18n>Add placement target</ng-container>
</button>
</div>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="submit()"
[form]="multisiteZonegroupForm"
[submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"></cd-form-button-panel>
</div>
</form>
</ng-container>
</cd-modal>
| 9,054 | 42.956311 | 198 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-zonegroup-form/rgw-multisite-zonegroup-form.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { ToastrModule } from 'ngx-toastr';
import { of as observableOf } from 'rxjs';
import { RgwZonegroupService } from '~/app/shared/api/rgw-zonegroup.service';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { NotificationService } from '~/app/shared/services/notification.service';
import { SharedModule } from '~/app/shared/shared.module';
import { RgwMultisiteZonegroupFormComponent } from './rgw-multisite-zonegroup-form.component';
describe('RgwMultisiteZonegroupFormComponent', () => {
let component: RgwMultisiteZonegroupFormComponent;
let fixture: ComponentFixture<RgwMultisiteZonegroupFormComponent>;
let rgwZonegroupService: RgwZonegroupService;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
SharedModule,
ReactiveFormsModule,
RouterTestingModule,
HttpClientTestingModule,
ToastrModule.forRoot()
],
providers: [NgbActiveModal],
declarations: [RgwMultisiteZonegroupFormComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwMultisiteZonegroupFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('submit form', () => {
let notificationService: NotificationService;
beforeEach(() => {
spyOn(TestBed.inject(Router), 'navigate').and.stub();
notificationService = TestBed.inject(NotificationService);
spyOn(notificationService, 'show');
rgwZonegroupService = TestBed.inject(RgwZonegroupService);
});
it('should validate name', () => {
component.action = 'create';
component.createForm();
const control = component.multisiteZonegroupForm.get('zonegroupName');
expect(_.isFunction(control.validator)).toBeTruthy();
});
it('should not validate name', () => {
component.action = 'edit';
component.createForm();
const control = component.multisiteZonegroupForm.get('zonegroupName');
expect(control.asyncValidator).toBeNull();
});
it('tests create success notification', () => {
spyOn(rgwZonegroupService, 'create').and.returnValue(observableOf([]));
component.action = 'create';
component.multisiteZonegroupForm.markAsDirty();
component.multisiteZonegroupForm._get('zonegroupName').setValue('zg-1');
component.multisiteZonegroupForm
._get('zonegroup_endpoints')
.setValue('http://192.1.1.1:8004');
component.submit();
expect(notificationService.show).toHaveBeenCalledWith(
NotificationType.success,
"Zonegroup: 'zg-1' created successfully"
);
});
it('tests update success notification', () => {
spyOn(rgwZonegroupService, 'update').and.returnValue(observableOf([]));
component.action = 'edit';
component.info = {
data: { name: 'zg-1', zones: ['z1'] }
};
component.multisiteZonegroupForm._get('zonegroupName').setValue('zg-1');
component.multisiteZonegroupForm
._get('zonegroup_endpoints')
.setValue('http://192.1.1.1:8004,http://192.12.12.12:8004');
component.multisiteZonegroupForm.markAsDirty();
component.submit();
expect(notificationService.show).toHaveBeenCalledWith(
NotificationType.success,
"Zonegroup: 'zg-1' updated successfully"
);
});
});
});
| 3,867 | 36.192308 | 94 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-multisite-zonegroup-form/rgw-multisite-zonegroup-form.component.ts
|
import { Component, OnInit } from '@angular/core';
import { FormArray, FormBuilder, FormControl, NgForm, Validators } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { RgwZonegroupService } from '~/app/shared/api/rgw-zonegroup.service';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { CdValidators } from '~/app/shared/forms/cd-validators';
import { NotificationService } from '~/app/shared/services/notification.service';
import { RgwRealm, RgwZone, RgwZonegroup } from '../models/rgw-multisite';
import { Icons } from '~/app/shared/enum/icons.enum';
import { SelectOption } from '~/app/shared/components/select/select-option.model';
@Component({
selector: 'cd-rgw-multisite-zonegroup-form',
templateUrl: './rgw-multisite-zonegroup-form.component.html',
styleUrls: ['./rgw-multisite-zonegroup-form.component.scss']
})
export class RgwMultisiteZonegroupFormComponent implements OnInit {
readonly endpoints = /^((https?:\/\/)|(www.))(?:([a-zA-Z]+)|(\d+\.\d+.\d+.\d+)):\d{2,4}$/;
readonly ipv4Rgx = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/i;
readonly ipv6Rgx = /^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$/i;
action: string;
icons = Icons;
multisiteZonegroupForm: CdFormGroup;
editing = false;
resource: string;
realm: RgwRealm;
zonegroup: RgwZonegroup;
info: any;
defaultsInfo: string[] = [];
multisiteInfo: object[] = [];
realmList: RgwRealm[] = [];
zonegroupList: RgwZonegroup[] = [];
zonegroupNames: string[];
isMaster = false;
placementTargets: FormArray;
newZonegroupName: string;
zonegroupZoneNames: string[];
labelsOption: Array<SelectOption> = [];
zoneList: RgwZone[] = [];
allZoneNames: string[];
zgZoneNames: string[];
zgZoneIds: string[];
removedZones: string[];
isRemoveMasterZone = false;
addedZones: string[];
disableDefault = false;
disableMaster = false;
constructor(
public activeModal: NgbActiveModal,
public actionLabels: ActionLabelsI18n,
public rgwZonegroupService: RgwZonegroupService,
public notificationService: NotificationService,
private formBuilder: FormBuilder
) {
this.action = this.editing
? this.actionLabels.EDIT + this.resource
: this.actionLabels.CREATE + this.resource;
this.createForm();
}
createForm() {
this.multisiteZonegroupForm = new CdFormGroup({
default_zonegroup: new FormControl(false),
zonegroupName: new FormControl(null, {
validators: [
Validators.required,
CdValidators.custom('uniqueName', (zonegroupName: string) => {
return (
this.action === 'create' &&
this.zonegroupNames &&
this.zonegroupNames.indexOf(zonegroupName) !== -1
);
})
]
}),
master_zonegroup: new FormControl(false),
selectedRealm: new FormControl(null),
zonegroup_endpoints: new FormControl(null, [
CdValidators.custom('endpoint', (value: string) => {
if (_.isEmpty(value)) {
return false;
} else {
if (value.includes(',')) {
value.split(',').forEach((url: string) => {
return (
!this.endpoints.test(url) && !this.ipv4Rgx.test(url) && !this.ipv6Rgx.test(url)
);
});
} else {
return (
!this.endpoints.test(value) &&
!this.ipv4Rgx.test(value) &&
!this.ipv6Rgx.test(value)
);
}
return false;
}
}),
Validators.required
]),
placementTargets: this.formBuilder.array([])
});
}
ngOnInit(): void {
_.forEach(this.multisiteZonegroupForm.get('placementTargets'), (placementTarget) => {
const fg = this.addPlacementTarget();
fg.patchValue(placementTarget);
});
this.placementTargets = this.multisiteZonegroupForm.get('placementTargets') as FormArray;
this.realmList =
this.multisiteInfo[0] !== undefined && this.multisiteInfo[0].hasOwnProperty('realms')
? this.multisiteInfo[0]['realms']
: [];
this.zonegroupList =
this.multisiteInfo[1] !== undefined && this.multisiteInfo[1].hasOwnProperty('zonegroups')
? this.multisiteInfo[1]['zonegroups']
: [];
this.zonegroupList.forEach((zgp: any) => {
if (zgp.is_master === true && !_.isEmpty(zgp.realm_id)) {
this.isMaster = true;
this.disableMaster = true;
}
});
if (!this.isMaster) {
this.multisiteZonegroupForm.get('master_zonegroup').setValue(true);
this.multisiteZonegroupForm.get('master_zonegroup').disable();
}
this.zoneList =
this.multisiteInfo[2] !== undefined && this.multisiteInfo[2].hasOwnProperty('zones')
? this.multisiteInfo[2]['zones']
: [];
this.zonegroupNames = this.zonegroupList.map((zonegroup) => {
return zonegroup['name'];
});
let allZonegroupZonesList = this.zonegroupList.map((zonegroup: RgwZonegroup) => {
return zonegroup['zones'];
});
const allZonegroupZonesInfo = allZonegroupZonesList.reduce(
(accumulator, value) => accumulator.concat(value),
[]
);
const allZonegroupZonesNames = allZonegroupZonesInfo.map((zone) => {
return zone['name'];
});
this.allZoneNames = this.zoneList.map((zone: RgwZone) => {
return zone['name'];
});
this.allZoneNames = _.difference(this.allZoneNames, allZonegroupZonesNames);
if (this.action === 'create' && this.defaultsInfo['defaultRealmName'] !== null) {
this.multisiteZonegroupForm
.get('selectedRealm')
.setValue(this.defaultsInfo['defaultRealmName']);
if (this.disableMaster) {
this.multisiteZonegroupForm.get('master_zonegroup').disable();
}
}
if (this.action === 'edit') {
this.multisiteZonegroupForm.get('zonegroupName').setValue(this.info.data.name);
this.multisiteZonegroupForm.get('selectedRealm').setValue(this.info.data.parent);
this.multisiteZonegroupForm.get('default_zonegroup').setValue(this.info.data.is_default);
this.multisiteZonegroupForm.get('master_zonegroup').setValue(this.info.data.is_master);
this.multisiteZonegroupForm.get('zonegroup_endpoints').setValue(this.info.data.endpoints);
if (this.info.data.is_default) {
this.multisiteZonegroupForm.get('default_zonegroup').disable();
}
if (
!this.info.data.is_default &&
this.multisiteZonegroupForm.getValue('selectedRealm') !==
this.defaultsInfo['defaultRealmName']
) {
this.multisiteZonegroupForm.get('default_zonegroup').disable();
this.disableDefault = true;
}
if (this.info.data.is_master || this.disableMaster) {
this.multisiteZonegroupForm.get('master_zonegroup').disable();
}
this.zonegroupZoneNames = this.info.data.zones.map((zone: { [x: string]: any }) => {
return zone['name'];
});
this.zgZoneNames = this.info.data.zones.map((zone: { [x: string]: any }) => {
return zone['name'];
});
this.zgZoneIds = this.info.data.zones.map((zone: { [x: string]: any }) => {
return zone['id'];
});
const uniqueZones = new Set(this.allZoneNames);
this.labelsOption = Array.from(uniqueZones).map((zone) => {
return { enabled: true, name: zone, selected: false, description: null };
});
this.info.data.placement_targets.forEach((target: object) => {
const fg = this.addPlacementTarget();
let data = {
placement_id: target['name'],
tags: target['tags'].join(','),
storage_class:
typeof target['storage_classes'] === 'string'
? target['storage_classes']
: target['storage_classes'].join(',')
};
fg.patchValue(data);
});
}
}
submit() {
const values = this.multisiteZonegroupForm.getRawValue();
if (this.action === 'create') {
this.realm = new RgwRealm();
this.realm.name = values['selectedRealm'];
this.zonegroup = new RgwZonegroup();
this.zonegroup.name = values['zonegroupName'];
this.zonegroup.endpoints = values['zonegroup_endpoints'];
this.rgwZonegroupService
.create(this.realm, this.zonegroup, values['default_zonegroup'], values['master_zonegroup'])
.subscribe(
() => {
this.notificationService.show(
NotificationType.success,
$localize`Zonegroup: '${values['zonegroupName']}' created successfully`
);
this.activeModal.close();
},
() => {
this.multisiteZonegroupForm.setErrors({ cdSubmitButton: true });
}
);
} else if (this.action === 'edit') {
this.removedZones = _.difference(this.zgZoneNames, this.zonegroupZoneNames);
const masterZoneName = this.info.data.zones.filter(
(zone: any) => zone.id === this.info.data.master_zone
);
this.isRemoveMasterZone = this.removedZones.includes(masterZoneName[0].name);
if (this.isRemoveMasterZone) {
this.multisiteZonegroupForm.setErrors({ cdSubmitButton: true });
return;
}
this.addedZones = _.difference(this.zonegroupZoneNames, this.zgZoneNames);
this.realm = new RgwRealm();
this.realm.name = values['selectedRealm'];
this.zonegroup = new RgwZonegroup();
this.zonegroup.name = this.info.data.name;
this.newZonegroupName = values['zonegroupName'];
this.zonegroup.endpoints = values['zonegroup_endpoints'];
this.zonegroup.placement_targets = values['placementTargets'];
this.rgwZonegroupService
.update(
this.realm,
this.zonegroup,
this.newZonegroupName,
values['default_zonegroup'],
values['master_zonegroup'],
this.removedZones,
this.addedZones
)
.subscribe(
() => {
this.notificationService.show(
NotificationType.success,
$localize`Zonegroup: '${values['zonegroupName']}' updated successfully`
);
this.activeModal.close();
},
() => {
this.multisiteZonegroupForm.setErrors({ cdSubmitButton: true });
}
);
}
}
checkUrlArray(endpoints: string) {
let endpointsArray = [];
if (endpoints.includes(',')) {
endpointsArray = endpoints.split(',');
} else {
endpointsArray.push(endpoints);
}
return endpointsArray;
}
addPlacementTarget() {
this.placementTargets = this.multisiteZonegroupForm.get('placementTargets') as FormArray;
const fg = new CdFormGroup({
placement_id: new FormControl('', {
validators: [Validators.required]
}),
tags: new FormControl(''),
storage_class: new FormControl([])
});
this.placementTargets.push(fg);
return fg;
}
trackByFn(index: number) {
return index;
}
removePlacementTarget(index: number) {
this.placementTargets = this.multisiteZonegroupForm.get('placementTargets') as FormArray;
this.placementTargets.removeAt(index);
}
showError(index: number, control: string, formDir: NgForm, x: string) {
return (<any>this.multisiteZonegroupForm.controls.placementTargets).controls[index].showError(
control,
formDir,
x
);
}
}
| 11,715 | 35.842767 | 110 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-system-user/rgw-system-user.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">Create System User</ng-container>
<ng-container class="modal-content">
<form name="multisiteSystemUserForm"
#formDir="ngForm"
[formGroup]="multisiteSystemUserForm"
novalidate>
<div class="modal-body">
<div class="form-group row">
<label class="cd-col-form-label required"
for="userName"
i18n>User Name</label>
<div class="cd-col-form-input">
<input class="form-control"
type="text"
placeholder="User name..."
id="userName"
name="userName"
formControlName="userName">
<span class="invalid-feedback"
*ngIf="multisiteSystemUserForm.showError('userName', formDir, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="multisiteSystemUserForm.showError('userName', formDir, 'uniqueName')"
i18n>The chosen realm name is already in use.</span>
</div>
</div>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="submit()"
[form]="multisiteSystemUserForm"></cd-form-button-panel>
</div>
</form>
</ng-container>
</cd-modal>
| 1,465 | 37.578947 | 94 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-system-user/rgw-system-user.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RgwSystemUserComponent } from './rgw-system-user.component';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { ToastrModule } from 'ngx-toastr';
import { SharedModule } from '~/app/shared/shared.module';
describe('RgwSystemUserComponent', () => {
let component: RgwSystemUserComponent;
let fixture: ComponentFixture<RgwSystemUserComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
SharedModule,
ReactiveFormsModule,
RouterTestingModule,
HttpClientTestingModule,
ToastrModule.forRoot()
],
declarations: [RgwSystemUserComponent],
providers: [NgbActiveModal]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwSystemUserComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,227 | 30.487179 | 71 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-system-user/rgw-system-user.component.ts
|
import { Component, EventEmitter, Output } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { RgwZoneService } from '~/app/shared/api/rgw-zone.service';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { NotificationService } from '~/app/shared/services/notification.service';
@Component({
selector: 'cd-rgw-system-user',
templateUrl: './rgw-system-user.component.html',
styleUrls: ['./rgw-system-user.component.scss']
})
export class RgwSystemUserComponent {
multisiteSystemUserForm: CdFormGroup;
zoneName: string;
@Output()
submitAction = new EventEmitter();
constructor(
public activeModal: NgbActiveModal,
public actionLabels: ActionLabelsI18n,
public rgwZoneService: RgwZoneService,
public notificationService: NotificationService
) {
this.createForm();
}
createForm() {
this.multisiteSystemUserForm = new CdFormGroup({
userName: new FormControl(null, {
validators: [Validators.required]
})
});
}
submit() {
const userName = this.multisiteSystemUserForm.getValue('userName');
this.rgwZoneService.createSystemUser(userName, this.zoneName).subscribe(() => {
this.submitAction.emit();
this.notificationService.show(
NotificationType.success,
$localize`User: '${this.multisiteSystemUserForm.getValue('userName')}' created successfully`
);
this.activeModal.close();
});
}
}
| 1,678 | 31.921569 | 100 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-capability-modal/rgw-user-capability-modal.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">{{ action | titlecase }} {{ resource | upperFirst }}</ng-container>
<ng-container class="modal-content">
<form #frm="ngForm"
[formGroup]="formGroup"
novalidate>
<div class="modal-body">
<!-- Type -->
<div class="form-group row">
<label class="cd-col-form-label"
[ngClass]="{'required': !editing}"
for="type"
i18n>Type</label>
<div class="cd-col-form-input">
<input id="type"
class="form-control"
type="text"
*ngIf="editing"
[readonly]="true"
formControlName="type">
<select id="type"
class="form-select"
formControlName="type"
*ngIf="!editing"
autofocus>
<option i18n
*ngIf="types !== null"
[ngValue]="null">-- Select a type --</option>
<option *ngFor="let type of types"
[value]="type">{{ type }}</option>
</select>
<span class="invalid-feedback"
*ngIf="formGroup.showError('type', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
<!-- Permission -->
<div class="form-group row">
<label class="cd-col-form-label required"
for="perm"
i18n>Permission</label>
<div class="cd-col-form-input">
<select id="perm"
class="form-select"
formControlName="perm">
<option i18n
[ngValue]="null">-- Select a permission --</option>
<option *ngFor="let perm of ['read', 'write', '*']"
[value]="perm">
{{ perm }}
</option>
</select>
<span class="invalid-feedback"
*ngIf="formGroup.showError('perm', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="onSubmit()"
[form]="formGroup"
[submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"></cd-form-button-panel>
</div>
</form>
</ng-container>
</cd-modal>
| 2,605 | 35.704225 | 121 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-capability-modal/rgw-user-capability-modal.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { RgwUserCapabilityModalComponent } from './rgw-user-capability-modal.component';
describe('RgwUserCapabilityModalComponent', () => {
let component: RgwUserCapabilityModalComponent;
let fixture: ComponentFixture<RgwUserCapabilityModalComponent>;
configureTestBed({
declarations: [RgwUserCapabilityModalComponent],
imports: [ReactiveFormsModule, SharedModule, RouterTestingModule],
providers: [NgbActiveModal]
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwUserCapabilityModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,060 | 33.225806 | 88 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-capability-modal/rgw-user-capability-modal.component.ts
|
import { Component, EventEmitter, Output } from '@angular/core';
import { Validators } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { RgwUserCapabilities } from '../models/rgw-user-capabilities';
import { RgwUserCapability } from '../models/rgw-user-capability';
@Component({
selector: 'cd-rgw-user-capability-modal',
templateUrl: './rgw-user-capability-modal.component.html',
styleUrls: ['./rgw-user-capability-modal.component.scss']
})
export class RgwUserCapabilityModalComponent {
/**
* The event that is triggered when the 'Add' or 'Update' button
* has been pressed.
*/
@Output()
submitAction = new EventEmitter();
formGroup: CdFormGroup;
editing = true;
types: string[] = [];
resource: string;
action: string;
constructor(
private formBuilder: CdFormBuilder,
public activeModal: NgbActiveModal,
public actionLabels: ActionLabelsI18n
) {
this.resource = $localize`capability`;
this.createForm();
}
createForm() {
this.formGroup = this.formBuilder.group({
type: [null, [Validators.required]],
perm: [null, [Validators.required]]
});
}
/**
* Set the 'editing' flag. If set to TRUE, the modal dialog is in 'Edit' mode,
* otherwise in 'Add' mode. According to the mode the dialog and its controls
* behave different.
* @param {boolean} viewing
*/
setEditing(editing: boolean = true) {
this.editing = editing;
this.action = this.editing ? this.actionLabels.EDIT : this.actionLabels.ADD;
}
/**
* Set the values displayed in the dialog.
*/
setValues(type: string, perm: string) {
this.formGroup.setValue({
type: type,
perm: perm
});
}
/**
* Set the current capabilities of the user.
*/
setCapabilities(capabilities: RgwUserCapability[]) {
// Parse the configured capabilities to get a list of types that
// should be displayed.
const usedTypes: string[] = [];
capabilities.forEach((capability) => {
usedTypes.push(capability.type);
});
this.types = [];
RgwUserCapabilities.getAll().forEach((type) => {
if (_.indexOf(usedTypes, type) === -1) {
this.types.push(type);
}
});
}
onSubmit() {
const capability: RgwUserCapability = this.formGroup.value;
this.submitAction.emit(capability);
this.activeModal.close();
}
}
| 2,625 | 27.236559 | 80 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-details/rgw-user-details.component.html
|
<ng-container *ngIf="selection">
<div *ngIf="user">
<div *ngIf="keys.length">
<legend i18n>Keys</legend>
<div>
<cd-table [data]="keys"
[columns]="keysColumns"
columnMode="flex"
selectionType="multi"
forceIdentifier="true"
(updateSelection)="updateKeysSelection($event)">
<div class="table-actions">
<div class="btn-group"
dropdown>
<button type="button"
class="btn btn-accent"
[disabled]="!keysSelection.hasSingleSelection"
(click)="showKeyModal()">
<i [ngClass]="[icons.show]"></i>
<ng-container i18n>Show</ng-container>
</button>
</div>
</div>
</cd-table>
</div>
</div>
<legend i18n>Details</legend>
<table class="table table-striped table-bordered">
<tbody>
<tr>
<td i18n
class="bold w-25">Tenant</td>
<td class="w-75">{{ user.tenant }}</td>
</tr>
<tr>
<td i18n
class="bold w-25">User ID</td>
<td class="w-75">{{ user.user_id }}</td>
</tr>
<tr>
<td i18n
class="bold w-25">Username</td>
<td class="w-75">{{ user.uid }}</td>
</tr>
<tr>
<td i18n
class="bold">Full name</td>
<td>{{ user.display_name }}</td>
</tr>
<tr *ngIf="user.email?.length">
<td i18n
class="bold">Email address</td>
<td>{{ user.email }}</td>
</tr>
<tr>
<td i18n
class="bold">Suspended</td>
<td>{{ user.suspended | booleanText }}</td>
</tr>
<tr>
<td i18n
class="bold">System</td>
<td>{{ user.system === 'true' | booleanText }}</td>
</tr>
<tr>
<td i18n
class="bold">Maximum buckets</td>
<td>{{ user.max_buckets | map:maxBucketsMap }}</td>
</tr>
<tr *ngIf="user.subusers && user.subusers.length">
<td i18n
class="bold">Subusers</td>
<td>
<div *ngFor="let subuser of user.subusers">
{{ subuser.id }} ({{ subuser.permissions }})
</div>
</td>
</tr>
<tr *ngIf="user.caps && user.caps.length">
<td i18n
class="bold">Capabilities</td>
<td>
<div *ngFor="let cap of user.caps">
{{ cap.type }} ({{ cap.perm }})
</div>
</td>
</tr>
<tr *ngIf="user.mfa_ids?.length">
<td i18n
class="bold">MFAs(Id)</td>
<td>{{ user.mfa_ids | join}}</td>
</tr>
</tbody>
</table>
<!-- User quota -->
<div *ngIf="user.user_quota">
<legend i18n>User quota</legend>
<table class="table table-striped table-bordered">
<tbody>
<tr>
<td i18n
class="bold w-25">Enabled</td>
<td class="w-75">{{ user.user_quota.enabled | booleanText }}</td>
</tr>
<tr>
<td i18n
class="bold">Maximum size</td>
<td *ngIf="!user.user_quota.enabled">-</td>
<td *ngIf="user.user_quota.enabled && user.user_quota.max_size <= -1"
i18n>Unlimited</td>
<td *ngIf="user.user_quota.enabled && user.user_quota.max_size > -1">
{{ user.user_quota.max_size | dimlessBinary }}
</td>
</tr>
<tr>
<td i18n
class="bold">Maximum objects</td>
<td *ngIf="!user.user_quota.enabled">-</td>
<td *ngIf="user.user_quota.enabled && user.user_quota.max_objects <= -1"
i18n>Unlimited</td>
<td *ngIf="user.user_quota.enabled && user.user_quota.max_objects > -1">
{{ user.user_quota.max_objects }}
</td>
</tr>
</tbody>
</table>
</div>
<!-- Bucket quota -->
<div *ngIf="user.bucket_quota">
<legend i18n>Bucket quota</legend>
<table class="table table-striped table-bordered">
<tbody>
<tr>
<td i18n
class="bold w-25">Enabled</td>
<td class="w-75">{{ user.bucket_quota.enabled | booleanText }}</td>
</tr>
<tr>
<td i18n
class="bold">Maximum size</td>
<td *ngIf="!user.bucket_quota.enabled">-</td>
<td *ngIf="user.bucket_quota.enabled && user.bucket_quota.max_size <= -1"
i18n>Unlimited</td>
<td *ngIf="user.bucket_quota.enabled && user.bucket_quota.max_size > -1">
{{ user.bucket_quota.max_size | dimlessBinary }}
</td>
</tr>
<tr>
<td i18n
class="bold">Maximum objects</td>
<td *ngIf="!user.bucket_quota.enabled">-</td>
<td *ngIf="user.bucket_quota.enabled && user.bucket_quota.max_objects <= -1"
i18n>Unlimited</td>
<td *ngIf="user.bucket_quota.enabled && user.bucket_quota.max_objects > -1">
{{ user.bucket_quota.max_objects }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</ng-container>
| 5,489 | 32.072289 | 88 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-details/rgw-user-details.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { RgwUserDetailsComponent } from './rgw-user-details.component';
describe('RgwUserDetailsComponent', () => {
let component: RgwUserDetailsComponent;
let fixture: ComponentFixture<RgwUserDetailsComponent>;
configureTestBed({
declarations: [RgwUserDetailsComponent],
imports: [BrowserAnimationsModule, HttpClientTestingModule, SharedModule, NgbNavModule]
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwUserDetailsComponent);
component = fixture.componentInstance;
component.selection = {};
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show correct "System" info', () => {
component.selection = { uid: '', email: '', system: 'true', keys: [], swift_keys: [] };
component.ngOnChanges();
fixture.detectChanges();
const detailsTab = fixture.debugElement.nativeElement.querySelectorAll(
'.table.table-striped.table-bordered tr td'
);
expect(detailsTab[10].textContent).toEqual('System');
expect(detailsTab[11].textContent).toEqual('Yes');
component.selection.system = 'false';
component.ngOnChanges();
fixture.detectChanges();
expect(detailsTab[11].textContent).toEqual('No');
});
it('should show mfa ids only if length > 0', () => {
component.selection = {
uid: 'dashboard',
email: '',
system: 'true',
keys: [],
swift_keys: [],
mfa_ids: ['testMFA1', 'testMFA2']
};
component.ngOnChanges();
fixture.detectChanges();
const detailsTab = fixture.debugElement.nativeElement.querySelectorAll(
'.table.table-striped.table-bordered tr td'
);
expect(detailsTab[14].textContent).toEqual('MFAs(Id)');
expect(detailsTab[15].textContent).toEqual('testMFA1, testMFA2');
});
});
| 2,227 | 30.828571 | 91 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-details/rgw-user-details.component.ts
|
import { Component, Input, OnChanges, OnInit, TemplateRef, ViewChild } from '@angular/core';
import _ from 'lodash';
import { RgwUserService } from '~/app/shared/api/rgw-user.service';
import { Icons } from '~/app/shared/enum/icons.enum';
import { CdTableColumn } from '~/app/shared/models/cd-table-column';
import { CdTableSelection } from '~/app/shared/models/cd-table-selection';
import { ModalService } from '~/app/shared/services/modal.service';
import { RgwUserS3Key } from '../models/rgw-user-s3-key';
import { RgwUserSwiftKey } from '../models/rgw-user-swift-key';
import { RgwUserS3KeyModalComponent } from '../rgw-user-s3-key-modal/rgw-user-s3-key-modal.component';
import { RgwUserSwiftKeyModalComponent } from '../rgw-user-swift-key-modal/rgw-user-swift-key-modal.component';
@Component({
selector: 'cd-rgw-user-details',
templateUrl: './rgw-user-details.component.html',
styleUrls: ['./rgw-user-details.component.scss']
})
export class RgwUserDetailsComponent implements OnChanges, OnInit {
@ViewChild('accessKeyTpl')
public accessKeyTpl: TemplateRef<any>;
@ViewChild('secretKeyTpl')
public secretKeyTpl: TemplateRef<any>;
@Input()
selection: any;
// Details tab
user: any;
maxBucketsMap: {};
// Keys tab
keys: any = [];
keysColumns: CdTableColumn[] = [];
keysSelection: CdTableSelection = new CdTableSelection();
icons = Icons;
constructor(private rgwUserService: RgwUserService, private modalService: ModalService) {}
ngOnInit() {
this.keysColumns = [
{
name: $localize`Username`,
prop: 'username',
flexGrow: 1
},
{
name: $localize`Type`,
prop: 'type',
flexGrow: 1
}
];
this.maxBucketsMap = {
'-1': $localize`Disabled`,
0: $localize`Unlimited`
};
}
ngOnChanges() {
if (this.selection) {
this.user = this.selection;
// Sort subusers and capabilities.
this.user.subusers = _.sortBy(this.user.subusers, 'id');
this.user.caps = _.sortBy(this.user.caps, 'type');
// Load the user/bucket quota of the selected user.
this.rgwUserService.getQuota(this.user.uid).subscribe((resp: object) => {
_.extend(this.user, resp);
});
// Process the keys.
this.keys = [];
if (this.user.keys) {
this.user.keys.forEach((key: RgwUserS3Key) => {
this.keys.push({
id: this.keys.length + 1, // Create an unique identifier
type: 'S3',
username: key.user,
ref: key
});
});
}
if (this.user.swift_keys) {
this.user.swift_keys.forEach((key: RgwUserSwiftKey) => {
this.keys.push({
id: this.keys.length + 1, // Create an unique identifier
type: 'Swift',
username: key.user,
ref: key
});
});
}
this.keys = _.sortBy(this.keys, 'user');
}
}
updateKeysSelection(selection: CdTableSelection) {
this.keysSelection = selection;
}
showKeyModal() {
const key = this.keysSelection.first();
const modalRef = this.modalService.show(
key.type === 'S3' ? RgwUserS3KeyModalComponent : RgwUserSwiftKeyModalComponent
);
switch (key.type) {
case 'S3':
modalRef.componentInstance.setViewing();
modalRef.componentInstance.setValues(key.ref.user, key.ref.access_key, key.ref.secret_key);
break;
case 'Swift':
modalRef.componentInstance.setValues(key.ref.user, key.ref.secret_key);
break;
}
}
}
| 3,573 | 28.53719 | 111 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-form/rgw-user-form.component.html
|
<div class="cd-col-form"
*cdFormLoading="loading">
<form #frm="ngForm"
[formGroup]="userForm"
novalidate>
<div class="card">
<div i18n="form title"
class="card-header">{{ action | titlecase }} {{ resource | upperFirst }}</div>
<div class="card-body">
<!-- User ID -->
<div class="form-group row">
<label class="cd-col-form-label"
[ngClass]="{'required': !editing}"
for="user_id"
i18n>User ID</label>
<div class="cd-col-form-input">
<input id="user_id"
class="form-control"
type="text"
formControlName="user_id"
[readonly]="editing">
<span class="invalid-feedback"
*ngIf="userForm.showError('user_id', frm, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('user_id', frm, 'pattern')"
i18n>The value is not valid.</span>
<span class="invalid-feedback"
*ngIf="!userForm.getValue('show_tenant') && userForm.showError('user_id', frm, 'notUnique')"
i18n>The chosen user ID is already in use.</span>
</div>
</div>
<!-- Show Tenant -->
<div class="form-group row">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
id="show_tenant"
type="checkbox"
(click)="updateFieldsWhenTenanted()"
formControlName="show_tenant"
[readonly]="true">
<label class="custom-control-label"
for="show_tenant"
i18n>Show Tenant</label>
</div>
</div>
</div>
<!-- Tenant -->
<div class="form-group row"
*ngIf="userForm.getValue('show_tenant')">
<label class="cd-col-form-label"
for="tenant"
i18n>Tenant</label>
<div class="cd-col-form-input">
<input id="tenant"
class="form-control"
type="text"
formControlName="tenant"
[readonly]="editing"
autofocus>
<span class="invalid-feedback"
*ngIf="userForm.showError('tenant', frm, 'pattern')"
i18n>The value is not valid.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('tenant', frm, 'notUnique')"
i18n>The chosen user ID exists in this tenant.</span>
</div>
</div>
<!-- Full name -->
<div class="form-group row">
<label class="cd-col-form-label"
[ngClass]="{'required': !editing}"
for="display_name"
i18n>Full name</label>
<div class="cd-col-form-input">
<input id="display_name"
class="form-control"
type="text"
formControlName="display_name">
<span class="invalid-feedback"
*ngIf="userForm.showError('display_name', frm, 'pattern')"
i18n>The value is not valid.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('display_name', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
<!-- Email address -->
<div class="form-group row">
<label class="cd-col-form-label"
for="email"
i18n>Email address</label>
<div class="cd-col-form-input">
<input id="email"
class="form-control"
type="text"
formControlName="email">
<span class="invalid-feedback"
*ngIf="userForm.showError('email', frm, 'email')"
i18n>This is not a valid email address.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('email', frm, 'notUnique')"
i18n>The chosen email address is already in use.</span>
</div>
</div>
<!-- Max. buckets -->
<div class="form-group row">
<label class="cd-col-form-label"
for="max_buckets_mode"
i18n>Max. buckets</label>
<div class="cd-col-form-input">
<select class="form-select"
formControlName="max_buckets_mode"
name="max_buckets_mode"
id="max_buckets_mode"
(change)="onMaxBucketsModeChange($event.target.value)">
<option i18n
value="-1">Disabled</option>
<option i18n
value="0">Unlimited</option>
<option i18n
value="1">Custom</option>
</select>
</div>
</div>
<div *ngIf="1 == userForm.get('max_buckets_mode').value"
class="form-group row">
<label class="cd-col-form-label"></label>
<div class="cd-col-form-input">
<input id="max_buckets"
class="form-control"
type="number"
formControlName="max_buckets"
min="1">
<span class="invalid-feedback"
*ngIf="userForm.showError('max_buckets', frm, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('max_buckets', frm, 'min')"
i18n>The entered value must be >= 1.</span>
</div>
</div>
<!-- Suspended -->
<div class="form-group row">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
id="suspended"
type="checkbox"
formControlName="suspended">
<label class="custom-control-label"
for="suspended"
i18n>Suspended</label>
<cd-helper i18n>Suspending the user disables the user and subuser.</cd-helper>
</div>
</div>
</div>
<!-- S3 key -->
<fieldset *ngIf="!editing">
<legend i18n>S3 key</legend>
<!-- Auto-generate key -->
<div class="form-group row">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
id="generate_key"
type="checkbox"
formControlName="generate_key">
<label class="custom-control-label"
for="generate_key"
i18n>Auto-generate key</label>
</div>
</div>
</div>
<!-- Access key -->
<div class="form-group row"
*ngIf="!editing && !userForm.getValue('generate_key')">
<label class="cd-col-form-label required"
for="access_key"
i18n>Access key</label>
<div class="cd-col-form-input">
<div class="input-group">
<input id="access_key"
class="form-control"
type="password"
formControlName="access_key">
<button type="button"
class="btn btn-light"
cdPasswordButton="access_key">
</button>
<cd-copy-2-clipboard-button source="access_key">
</cd-copy-2-clipboard-button>
</div>
<span class="invalid-feedback"
*ngIf="userForm.showError('access_key', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
<!-- Secret key -->
<div class="form-group row"
*ngIf="!editing && !userForm.getValue('generate_key')">
<label class="cd-col-form-label required"
for="secret_key"
i18n>Secret key</label>
<div class="cd-col-form-input">
<div class="input-group">
<input id="secret_key"
class="form-control"
type="password"
formControlName="secret_key">
<button type="button"
class="btn btn-light"
cdPasswordButton="secret_key">
</button>
<cd-copy-2-clipboard-button source="secret_key">
</cd-copy-2-clipboard-button>
</div>
<span class="invalid-feedback"
*ngIf="userForm.showError('secret_key', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</fieldset>
<!-- Subusers -->
<fieldset *ngIf="editing">
<legend i18n>Subusers</legend>
<div class="row">
<div class="cd-col-form-offset">
<span *ngIf="subusers.length === 0"
class="no-border">
<span class="form-text text-muted"
i18n>There are no subusers.</span>
</span>
<span *ngFor="let subuser of subusers; let i=index;">
<div class="input-group">
<span class="input-group-text">
<i class="{{ icons.user }}"></i>
</span>
<input type="text"
class="cd-form-control"
value="{{ subuser.id }}"
readonly>
<span class="input-group-text">
<i class="{{ icons.share }}"></i>
</span>
<input type="text"
class="cd-form-control"
value="{{ ('full-control' === subuser.permissions) ? 'full' : subuser.permissions }}"
readonly>
<button type="button"
class="btn btn-light tc_showSubuserButton"
i18n-ngbTooltip
ngbTooltip="Edit"
(click)="showSubuserModal(i)">
<i [ngClass]="[icons.edit]"></i>
</button>
<button type="button"
class="btn btn-light tc_deleteSubuserButton"
i18n-ngbTooltip
ngbTooltip="Delete"
(click)="deleteSubuser(i)">
<i [ngClass]="[icons.destroy]"></i>
</button>
</div>
<span class="form-text text-muted"></span>
</span>
<div class="row my-2">
<div class="col-12">
<button type="button"
class="btn btn-light float-end tc_addSubuserButton"
(click)="showSubuserModal()">
<i [ngClass]="[icons.add]"></i>
<ng-container i18n>{{ actionLabels.CREATE | titlecase }}
{{ subuserLabel | upperFirst }}</ng-container>
</button>
</div>
</div>
<span class="help-block"></span>
</div>
</div>
</fieldset>
<!-- Keys -->
<fieldset *ngIf="editing">
<legend i18n>Keys</legend>
<!-- S3 keys -->
<div class="form-group row">
<label class="cd-col-form-label"
i18n>S3</label>
<div class="cd-col-form-input">
<span *ngIf="s3Keys.length === 0"
class="no-border">
<span class="form-text text-muted"
i18n>There are no keys.</span>
</span>
<span *ngFor="let key of s3Keys; let i=index;">
<div class="input-group">
<div class="input-group-text">
<i class="{{ icons.key }}"></i>
</div>
<input type="text"
class="cd-form-control"
value="{{ key.user }}"
readonly>
<button type="button"
class="btn btn-light tc_showS3KeyButton"
i18n-ngbTooltip
ngbTooltip="Show"
(click)="showS3KeyModal(i)">
<i [ngClass]="[icons.show]"></i>
</button>
<button type="button"
class="btn btn-light tc_deleteS3KeyButton"
i18n-ngbTooltip
ngbTooltip="Delete"
(click)="deleteS3Key(i)">
<i [ngClass]="[icons.destroy]"></i>
</button>
</div>
<span class="form-text text-muted"></span>
</span>
<div class="row my-2">
<div class="col-12">
<button type="button"
class="btn btn-light float-end tc_addS3KeyButton"
(click)="showS3KeyModal()">
<i [ngClass]="[icons.add]"></i>
<ng-container i18n>{{ actionLabels.CREATE | titlecase }}
{{ s3keyLabel | upperFirst }}</ng-container>
</button>
</div>
</div>
<span class="help-block"></span>
</div>
<hr>
</div>
<!-- Swift keys -->
<div class="form-group row">
<label class="cd-col-form-label"
i18n>Swift</label>
<div class="cd-col-form-input">
<span *ngIf="swiftKeys.length === 0"
class="no-border">
<span class="form-text text-muted"
i18n>There are no keys.</span>
</span>
<span *ngFor="let key of swiftKeys; let i=index;">
<div class="input-group">
<span class="input-group-text">
<i class="{{ icons.key }}"></i>
</span>
<input type="text"
class="cd-form-control"
value="{{ key.user }}"
readonly>
<button type="button"
class="btn btn-light tc_showSwiftKeyButton"
i18n-ngbTooltip
ngbTooltip="Show"
(click)="showSwiftKeyModal(i)">
<i [ngClass]="[icons.show]"></i>
</button>
</div>
<span class="form-text text-muted"></span>
</span>
</div>
</div>
</fieldset>
<!-- Capabilities -->
<fieldset *ngIf="editing">
<legend i18n>Capabilities</legend>
<div class="form-group row">
<div class="cd-col-form-offset">
<span *ngIf="capabilities.length === 0"
class="no-border">
<span class="form-text text-muted"
i18n>There are no capabilities.</span>
</span>
<span *ngFor="let cap of capabilities; let i=index;">
<div class="input-group">
<div class="input-group-text">
<i class="{{ icons.share }}"></i>
</div>
<input type="text"
class="cd-form-control"
value="{{ cap.type }}:{{ cap.perm }}"
readonly>
<button type="button"
class="btn btn-light tc_editCapButton"
i18n-ngbTooltip
ngbTooltip="Edit"
(click)="showCapabilityModal(i)">
<i [ngClass]="[icons.edit]"></i>
</button>
<button type="button"
class="btn btn-light tc_deleteCapButton"
i18n-ngbTooltip
ngbTooltip="Delete"
(click)="deleteCapability(i)">
<i [ngClass]="[icons.destroy]"></i>
</button>
</div>
<span class="form-text text-muted"></span>
</span>
<div class="row my-2">
<div class="col-12">
<button type="button"
class="btn btn-light float-end tc_addCapButton"
[disabled]="capabilities | pipeFunction:hasAllCapabilities"
i18n-ngbTooltip
ngbTooltip="All capabilities are already added."
[disableTooltip]="!(capabilities | pipeFunction:hasAllCapabilities)"
triggers="pointerenter:pointerleave"
(click)="showCapabilityModal()">
<i [ngClass]="[icons.add]"></i>
<ng-container i18n>{{ actionLabels.ADD | titlecase }}
{{ capabilityLabel | upperFirst }}</ng-container>
</button>
</div>
</div>
<span class="help-block"></span>
</div>
</div>
</fieldset>
<!-- User quota -->
<fieldset>
<legend i18n>User quota</legend>
<!-- Enabled -->
<div class="form-group row">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
id="user_quota_enabled"
type="checkbox"
formControlName="user_quota_enabled">
<label class="custom-control-label"
for="user_quota_enabled"
i18n>Enabled</label>
</div>
</div>
</div>
<!-- Unlimited size -->
<div class="form-group row"
*ngIf="userForm.controls.user_quota_enabled.value">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
id="user_quota_max_size_unlimited"
type="checkbox"
formControlName="user_quota_max_size_unlimited">
<label class="custom-control-label"
for="user_quota_max_size_unlimited"
i18n>Unlimited size</label>
</div>
</div>
</div>
<!-- Maximum size -->
<div class="form-group row"
*ngIf="userForm.controls.user_quota_enabled.value && !userForm.getValue('user_quota_max_size_unlimited')">
<label class="cd-col-form-label required"
for="user_quota_max_size"
i18n>Max. size</label>
<div class="cd-col-form-input">
<input id="user_quota_max_size"
class="form-control"
type="text"
formControlName="user_quota_max_size"
cdDimlessBinary>
<span class="invalid-feedback"
*ngIf="userForm.showError('user_quota_max_size', frm, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('user_quota_max_size', frm, 'quotaMaxSize')"
i18n>The value is not valid.</span>
</div>
</div>
<!-- Unlimited objects -->
<div class="form-group row"
*ngIf="userForm.controls.user_quota_enabled.value">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
id="user_quota_max_objects_unlimited"
type="checkbox"
formControlName="user_quota_max_objects_unlimited">
<label class="custom-control-label"
for="user_quota_max_objects_unlimited"
i18n>Unlimited objects</label>
</div>
</div>
</div>
<!-- Maximum objects -->
<div class="form-group row"
*ngIf="userForm.controls.user_quota_enabled.value && !userForm.getValue('user_quota_max_objects_unlimited')">
<label class="cd-col-form-label required"
for="user_quota_max_objects"
i18n>Max. objects</label>
<div class="cd-col-form-input">
<input id="user_quota_max_objects"
class="form-control"
type="number"
formControlName="user_quota_max_objects"
min="0">
<span class="invalid-feedback"
*ngIf="userForm.showError('user_quota_max_objects', frm, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('user_quota_max_objects', frm, 'min')"
i18n>The entered value must be >= 0.</span>
</div>
</div>
</fieldset>
<!-- Bucket quota -->
<fieldset>
<legend i18n>Bucket quota</legend>
<!-- Enabled -->
<div class="form-group row">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
id="bucket_quota_enabled"
type="checkbox"
formControlName="bucket_quota_enabled">
<label class="custom-control-label"
for="bucket_quota_enabled"
i18n>Enabled</label>
</div>
</div>
</div>
<!-- Unlimited size -->
<div class="form-group row"
*ngIf="userForm.controls.bucket_quota_enabled.value">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
id="bucket_quota_max_size_unlimited"
type="checkbox"
formControlName="bucket_quota_max_size_unlimited">
<label class="custom-control-label"
for="bucket_quota_max_size_unlimited"
i18n>Unlimited size</label>
</div>
</div>
</div>
<!-- Maximum size -->
<div class="form-group row"
*ngIf="userForm.controls.bucket_quota_enabled.value && !userForm.getValue('bucket_quota_max_size_unlimited')">
<label class="cd-col-form-label required"
for="bucket_quota_max_size"
i18n>Max. size</label>
<div class="cd-col-form-input">
<input id="bucket_quota_max_size"
class="form-control"
type="text"
formControlName="bucket_quota_max_size"
cdDimlessBinary>
<span class="invalid-feedback"
*ngIf="userForm.showError('bucket_quota_max_size', frm, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('bucket_quota_max_size', frm, 'quotaMaxSize')"
i18n>The value is not valid.</span>
</div>
</div>
<!-- Unlimited objects -->
<div class="form-group row"
*ngIf="userForm.controls.bucket_quota_enabled.value">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
id="bucket_quota_max_objects_unlimited"
type="checkbox"
formControlName="bucket_quota_max_objects_unlimited">
<label class="custom-control-label"
for="bucket_quota_max_objects_unlimited"
i18n>Unlimited objects</label>
</div>
</div>
</div>
<!-- Maximum objects -->
<div class="form-group row"
*ngIf="userForm.controls.bucket_quota_enabled.value && !userForm.getValue('bucket_quota_max_objects_unlimited')">
<label class="cd-col-form-label required"
for="bucket_quota_max_objects"
i18n>Max. objects</label>
<div class="cd-col-form-input">
<input id="bucket_quota_max_objects"
class="form-control"
type="number"
formControlName="bucket_quota_max_objects"
min="0">
<span class="invalid-feedback"
*ngIf="userForm.showError('bucket_quota_max_objects', frm, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('bucket_quota_max_objects', frm, 'min')"
i18n>The entered value must be >= 0.</span>
</div>
</div>
</fieldset>
</div>
<div class="card-footer">
<cd-form-button-panel (submitActionEvent)="onSubmit()"
[form]="userForm"
[submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"
wrappingClass="text-right"></cd-form-button-panel>
</div>
</div>
</form>
</div>
| 26,814 | 40.190476 | 128 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-form/rgw-user-form.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import { NgxPipeFunctionModule } from 'ngx-pipe-function';
import { ToastrModule } from 'ngx-toastr';
import { of as observableOf, throwError } from 'rxjs';
import { RgwUserService } from '~/app/shared/api/rgw-user.service';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { NotificationService } from '~/app/shared/services/notification.service';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed, FormHelper } from '~/testing/unit-test-helper';
import { RgwUserCapabilities } from '../models/rgw-user-capabilities';
import { RgwUserCapability } from '../models/rgw-user-capability';
import { RgwUserS3Key } from '../models/rgw-user-s3-key';
import { RgwUserFormComponent } from './rgw-user-form.component';
describe('RgwUserFormComponent', () => {
let component: RgwUserFormComponent;
let fixture: ComponentFixture<RgwUserFormComponent>;
let rgwUserService: RgwUserService;
let formHelper: FormHelper;
configureTestBed({
declarations: [RgwUserFormComponent],
imports: [
HttpClientTestingModule,
ReactiveFormsModule,
RouterTestingModule,
SharedModule,
ToastrModule.forRoot(),
NgbTooltipModule,
NgxPipeFunctionModule
]
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwUserFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
rgwUserService = TestBed.inject(RgwUserService);
formHelper = new FormHelper(component.userForm);
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('s3 key management', () => {
beforeEach(() => {
spyOn(rgwUserService, 'addS3Key').and.stub();
});
it('should not update key', () => {
component.setS3Key(new RgwUserS3Key(), 3);
expect(component.s3Keys.length).toBe(0);
expect(rgwUserService.addS3Key).not.toHaveBeenCalled();
});
it('should set user defined key', () => {
const key = new RgwUserS3Key();
key.user = 'test1:subuser2';
key.access_key = 'my-access-key';
key.secret_key = 'my-secret-key';
component.setS3Key(key);
expect(component.s3Keys.length).toBe(1);
expect(component.s3Keys[0].user).toBe('test1:subuser2');
expect(rgwUserService.addS3Key).toHaveBeenCalledWith('test1', {
subuser: 'subuser2',
generate_key: 'false',
access_key: 'my-access-key',
secret_key: 'my-secret-key'
});
});
it('should set params for auto-generating key', () => {
const key = new RgwUserS3Key();
key.user = 'test1:subuser2';
key.generate_key = true;
key.access_key = 'my-access-key';
key.secret_key = 'my-secret-key';
component.setS3Key(key);
expect(component.s3Keys.length).toBe(1);
expect(component.s3Keys[0].user).toBe('test1:subuser2');
expect(rgwUserService.addS3Key).toHaveBeenCalledWith('test1', {
subuser: 'subuser2',
generate_key: 'true'
});
});
it('should set key w/o subuser', () => {
const key = new RgwUserS3Key();
key.user = 'test1';
component.setS3Key(key);
expect(component.s3Keys.length).toBe(1);
expect(component.s3Keys[0].user).toBe('test1');
expect(rgwUserService.addS3Key).toHaveBeenCalledWith('test1', {
subuser: '',
generate_key: 'false',
access_key: undefined,
secret_key: undefined
});
});
});
describe('quotaMaxSizeValidator', () => {
it('should validate max size (1)', () => {
const resp = component.quotaMaxSizeValidator(new FormControl(''));
expect(resp).toBe(null);
});
it('should validate max size (2)', () => {
const resp = component.quotaMaxSizeValidator(new FormControl('xxxx'));
expect(resp.quotaMaxSize).toBeTruthy();
});
it('should validate max size (3)', () => {
const resp = component.quotaMaxSizeValidator(new FormControl('1023'));
expect(resp.quotaMaxSize).toBeTruthy();
});
it('should validate max size (4)', () => {
const resp = component.quotaMaxSizeValidator(new FormControl('1024'));
expect(resp).toBe(null);
});
it('should validate max size (5)', () => {
const resp = component.quotaMaxSizeValidator(new FormControl('1M'));
expect(resp).toBe(null);
});
it('should validate max size (6)', () => {
const resp = component.quotaMaxSizeValidator(new FormControl('1024 gib'));
expect(resp).toBe(null);
});
it('should validate max size (7)', () => {
const resp = component.quotaMaxSizeValidator(new FormControl('10 X'));
expect(resp.quotaMaxSize).toBeTruthy();
});
it('should validate max size (8)', () => {
const resp = component.quotaMaxSizeValidator(new FormControl('1.085 GiB'));
expect(resp).toBe(null);
});
it('should validate max size (9)', () => {
const resp = component.quotaMaxSizeValidator(new FormControl('1,085 GiB'));
expect(resp.quotaMaxSize).toBeTruthy();
});
});
describe('username validation', () => {
it('should validate that username is required', () => {
formHelper.expectErrorChange('user_id', '', 'required', true);
});
it('should validate that username is valid', fakeAsync(() => {
spyOn(rgwUserService, 'get').and.returnValue(throwError('foo'));
formHelper.setValue('user_id', 'ab', true);
tick();
formHelper.expectValid('user_id');
}));
it('should validate that username is invalid', fakeAsync(() => {
spyOn(rgwUserService, 'get').and.returnValue(observableOf({}));
formHelper.setValue('user_id', 'abc', true);
tick();
formHelper.expectError('user_id', 'notUnique');
}));
});
describe('max buckets', () => {
it('disable creation (create)', () => {
spyOn(rgwUserService, 'create');
formHelper.setValue('max_buckets_mode', -1, true);
component.onSubmit();
expect(rgwUserService.create).toHaveBeenCalledWith({
access_key: '',
display_name: null,
email: '',
generate_key: true,
max_buckets: -1,
secret_key: '',
suspended: false,
uid: null
});
});
it('disable creation (edit)', () => {
spyOn(rgwUserService, 'update');
component.editing = true;
formHelper.setValue('max_buckets_mode', -1, true);
component.onSubmit();
expect(rgwUserService.update).toHaveBeenCalledWith(null, {
display_name: null,
email: null,
max_buckets: -1,
suspended: false
});
});
it('unlimited buckets (create)', () => {
spyOn(rgwUserService, 'create');
formHelper.setValue('max_buckets_mode', 0, true);
component.onSubmit();
expect(rgwUserService.create).toHaveBeenCalledWith({
access_key: '',
display_name: null,
email: '',
generate_key: true,
max_buckets: 0,
secret_key: '',
suspended: false,
uid: null
});
});
it('unlimited buckets (edit)', () => {
spyOn(rgwUserService, 'update');
component.editing = true;
formHelper.setValue('max_buckets_mode', 0, true);
component.onSubmit();
expect(rgwUserService.update).toHaveBeenCalledWith(null, {
display_name: null,
email: null,
max_buckets: 0,
suspended: false
});
});
it('custom (create)', () => {
spyOn(rgwUserService, 'create');
formHelper.setValue('max_buckets_mode', 1, true);
formHelper.setValue('max_buckets', 100, true);
component.onSubmit();
expect(rgwUserService.create).toHaveBeenCalledWith({
access_key: '',
display_name: null,
email: '',
generate_key: true,
max_buckets: 100,
secret_key: '',
suspended: false,
uid: null
});
});
it('custom (edit)', () => {
spyOn(rgwUserService, 'update');
component.editing = true;
formHelper.setValue('max_buckets_mode', 1, true);
formHelper.setValue('max_buckets', 100, true);
component.onSubmit();
expect(rgwUserService.update).toHaveBeenCalledWith(null, {
display_name: null,
email: null,
max_buckets: 100,
suspended: false
});
});
});
describe('submit form', () => {
let notificationService: NotificationService;
beforeEach(() => {
spyOn(TestBed.inject(Router), 'navigate').and.stub();
notificationService = TestBed.inject(NotificationService);
spyOn(notificationService, 'show');
});
it('should be able to clear the mail field on update', () => {
spyOn(rgwUserService, 'update');
component.editing = true;
formHelper.setValue('email', '', true);
component.onSubmit();
expect(rgwUserService.update).toHaveBeenCalledWith(null, {
display_name: null,
email: '',
max_buckets: 1000,
suspended: false
});
});
it('tests create success notification', () => {
spyOn(rgwUserService, 'create').and.returnValue(observableOf([]));
component.editing = false;
formHelper.setValue('suspended', true, true);
component.onSubmit();
expect(notificationService.show).toHaveBeenCalledWith(
NotificationType.success,
`Created Object Gateway user 'null'`
);
});
it('tests update success notification', () => {
spyOn(rgwUserService, 'update').and.returnValue(observableOf([]));
component.editing = true;
formHelper.setValue('suspended', true, true);
component.onSubmit();
expect(notificationService.show).toHaveBeenCalledWith(
NotificationType.success,
`Updated Object Gateway user 'null'`
);
});
});
describe('RgwUserCapabilities', () => {
it('capability button disabled when all capabilities are added', () => {
component.editing = true;
for (const capabilityType of RgwUserCapabilities.getAll()) {
const capability = new RgwUserCapability();
capability.type = capabilityType;
capability.perm = 'read';
component.setCapability(capability);
}
fixture.detectChanges();
expect(component.hasAllCapabilities(component.capabilities)).toBeTruthy();
const capabilityButton = fixture.debugElement.nativeElement.querySelector('.tc_addCapButton');
expect(capabilityButton.disabled).toBeTruthy();
});
it('capability button not disabled when not all capabilities are added', () => {
component.editing = true;
fixture.detectChanges();
const capabilityButton = fixture.debugElement.nativeElement.querySelector('.tc_addCapButton');
expect(capabilityButton.disabled).toBeFalsy();
});
});
});
| 11,227 | 32.023529 | 100 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-form/rgw-user-form.component.ts
|
import { Component, OnInit } from '@angular/core';
import { AbstractControl, ValidationErrors, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import _ from 'lodash';
import { concat as observableConcat, forkJoin as observableForkJoin, Observable } from 'rxjs';
import { RgwUserService } from '~/app/shared/api/rgw-user.service';
import { ActionLabelsI18n, URLVerbs } from '~/app/shared/constants/app.constants';
import { Icons } from '~/app/shared/enum/icons.enum';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdForm } from '~/app/shared/forms/cd-form';
import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { CdValidators, isEmptyInputValue } from '~/app/shared/forms/cd-validators';
import { FormatterService } from '~/app/shared/services/formatter.service';
import { ModalService } from '~/app/shared/services/modal.service';
import { NotificationService } from '~/app/shared/services/notification.service';
import { RgwUserCapabilities } from '../models/rgw-user-capabilities';
import { RgwUserCapability } from '../models/rgw-user-capability';
import { RgwUserS3Key } from '../models/rgw-user-s3-key';
import { RgwUserSubuser } from '../models/rgw-user-subuser';
import { RgwUserSwiftKey } from '../models/rgw-user-swift-key';
import { RgwUserCapabilityModalComponent } from '../rgw-user-capability-modal/rgw-user-capability-modal.component';
import { RgwUserS3KeyModalComponent } from '../rgw-user-s3-key-modal/rgw-user-s3-key-modal.component';
import { RgwUserSubuserModalComponent } from '../rgw-user-subuser-modal/rgw-user-subuser-modal.component';
import { RgwUserSwiftKeyModalComponent } from '../rgw-user-swift-key-modal/rgw-user-swift-key-modal.component';
@Component({
selector: 'cd-rgw-user-form',
templateUrl: './rgw-user-form.component.html',
styleUrls: ['./rgw-user-form.component.scss']
})
export class RgwUserFormComponent extends CdForm implements OnInit {
userForm: CdFormGroup;
editing = false;
submitObservables: Observable<Object>[] = [];
icons = Icons;
subusers: RgwUserSubuser[] = [];
s3Keys: RgwUserS3Key[] = [];
swiftKeys: RgwUserSwiftKey[] = [];
capabilities: RgwUserCapability[] = [];
action: string;
resource: string;
subuserLabel: string;
s3keyLabel: string;
capabilityLabel: string;
usernameExists: boolean;
showTenant = false;
previousTenant: string = null;
constructor(
private formBuilder: CdFormBuilder,
private route: ActivatedRoute,
private router: Router,
private rgwUserService: RgwUserService,
private modalService: ModalService,
private notificationService: NotificationService,
public actionLabels: ActionLabelsI18n
) {
super();
this.resource = $localize`user`;
this.subuserLabel = $localize`subuser`;
this.s3keyLabel = $localize`S3 Key`;
this.capabilityLabel = $localize`capability`;
this.editing = this.router.url.startsWith(`/rgw/user/${URLVerbs.EDIT}`);
this.action = this.editing ? this.actionLabels.EDIT : this.actionLabels.CREATE;
this.createForm();
}
createForm() {
this.userForm = this.formBuilder.group({
// General
user_id: [
null,
[Validators.required, Validators.pattern(/^[a-zA-Z0-9!@#%^&*()_-]+$/)],
this.editing
? []
: [
CdValidators.unique(this.rgwUserService.exists, this.rgwUserService, () =>
this.userForm.getValue('tenant')
)
]
],
show_tenant: [this.editing],
tenant: [
null,
[Validators.pattern(/^[a-zA-Z0-9!@#%^&*()_-]+$/)],
this.editing
? []
: [
CdValidators.unique(
this.rgwUserService.exists,
this.rgwUserService,
() => this.userForm.getValue('user_id'),
true
)
]
],
display_name: [null, [Validators.required, Validators.pattern(/^[a-zA-Z0-9!@#%^&*()_ -]+$/)]],
email: [
null,
[CdValidators.email],
[CdValidators.unique(this.rgwUserService.emailExists, this.rgwUserService)]
],
max_buckets_mode: [1],
max_buckets: [
1000,
[CdValidators.requiredIf({ max_buckets_mode: '1' }), CdValidators.number(false)]
],
suspended: [false],
// S3 key
generate_key: [true],
access_key: [null, [CdValidators.requiredIf({ generate_key: false })]],
secret_key: [null, [CdValidators.requiredIf({ generate_key: false })]],
// User quota
user_quota_enabled: [false],
user_quota_max_size_unlimited: [true],
user_quota_max_size: [
null,
[
CdValidators.composeIf(
{
user_quota_enabled: true,
user_quota_max_size_unlimited: false
},
[Validators.required, this.quotaMaxSizeValidator]
)
]
],
user_quota_max_objects_unlimited: [true],
user_quota_max_objects: [
null,
[
CdValidators.requiredIf({
user_quota_enabled: true,
user_quota_max_objects_unlimited: false
})
]
],
// Bucket quota
bucket_quota_enabled: [false],
bucket_quota_max_size_unlimited: [true],
bucket_quota_max_size: [
null,
[
CdValidators.composeIf(
{
bucket_quota_enabled: true,
bucket_quota_max_size_unlimited: false
},
[Validators.required, this.quotaMaxSizeValidator]
)
]
],
bucket_quota_max_objects_unlimited: [true],
bucket_quota_max_objects: [
null,
[
CdValidators.requiredIf({
bucket_quota_enabled: true,
bucket_quota_max_objects_unlimited: false
})
]
]
});
}
ngOnInit() {
// Process route parameters.
this.route.params.subscribe((params: { uid: string }) => {
if (!params.hasOwnProperty('uid')) {
this.loadingReady();
return;
}
const uid = decodeURIComponent(params.uid);
// Load the user and quota information.
const observables = [];
observables.push(this.rgwUserService.get(uid));
observables.push(this.rgwUserService.getQuota(uid));
observableForkJoin(observables).subscribe(
(resp: any[]) => {
// Get the default values.
const defaults = _.clone(this.userForm.value);
// Extract the values displayed in the form.
let value = _.pick(resp[0], _.keys(this.userForm.value));
// Map the max. buckets values.
switch (value['max_buckets']) {
case -1:
value['max_buckets_mode'] = -1;
value['max_buckets'] = '';
break;
case 0:
value['max_buckets_mode'] = 0;
value['max_buckets'] = '';
break;
default:
value['max_buckets_mode'] = 1;
break;
}
// Map the quota values.
['user', 'bucket'].forEach((type) => {
const quota = resp[1][type + '_quota'];
value[type + '_quota_enabled'] = quota.enabled;
if (quota.max_size < 0) {
value[type + '_quota_max_size_unlimited'] = true;
value[type + '_quota_max_size'] = null;
} else {
value[type + '_quota_max_size_unlimited'] = false;
value[type + '_quota_max_size'] = `${quota.max_size} B`;
}
if (quota.max_objects < 0) {
value[type + '_quota_max_objects_unlimited'] = true;
value[type + '_quota_max_objects'] = null;
} else {
value[type + '_quota_max_objects_unlimited'] = false;
value[type + '_quota_max_objects'] = quota.max_objects;
}
});
// Merge with default values.
value = _.merge(defaults, value);
// Update the form.
this.userForm.setValue(value);
// Get the sub users.
this.subusers = resp[0].subusers;
// Get the keys.
this.s3Keys = resp[0].keys;
this.swiftKeys = resp[0].swift_keys;
// Process the capabilities.
const mapPerm = { 'read, write': '*' };
resp[0].caps.forEach((cap: any) => {
if (cap.perm in mapPerm) {
cap.perm = mapPerm[cap.perm];
}
});
this.capabilities = resp[0].caps;
this.loadingReady();
},
() => {
this.loadingError();
}
);
});
}
goToListView() {
this.router.navigate(['/rgw/user']);
}
onSubmit() {
let notificationTitle: string;
// Exit immediately if the form isn't dirty.
if (this.userForm.pristine) {
this.goToListView();
return;
}
const uid = this.getUID();
if (this.editing) {
// Edit
if (this._isGeneralDirty()) {
const args = this._getUpdateArgs();
this.submitObservables.push(this.rgwUserService.update(uid, args));
}
notificationTitle = $localize`Updated Object Gateway user '${uid}'`;
} else {
// Add
const args = this._getCreateArgs();
this.submitObservables.push(this.rgwUserService.create(args));
notificationTitle = $localize`Created Object Gateway user '${uid}'`;
}
// Check if user quota has been modified.
if (this._isUserQuotaDirty()) {
const userQuotaArgs = this._getUserQuotaArgs();
this.submitObservables.push(this.rgwUserService.updateQuota(uid, userQuotaArgs));
}
// Check if bucket quota has been modified.
if (this._isBucketQuotaDirty()) {
const bucketQuotaArgs = this._getBucketQuotaArgs();
this.submitObservables.push(this.rgwUserService.updateQuota(uid, bucketQuotaArgs));
}
// Finally execute all observables one by one in serial.
observableConcat(...this.submitObservables).subscribe({
error: () => {
// Reset the 'Submit' button.
this.userForm.setErrors({ cdSubmitButton: true });
},
complete: () => {
this.notificationService.show(NotificationType.success, notificationTitle);
this.goToListView();
}
});
}
updateFieldsWhenTenanted() {
this.showTenant = this.userForm.getValue('show_tenant');
if (!this.showTenant) {
this.userForm.get('user_id').markAsUntouched();
this.userForm.get('tenant').patchValue(this.previousTenant);
} else {
this.userForm.get('user_id').markAsTouched();
this.previousTenant = this.userForm.get('tenant').value;
this.userForm.get('tenant').patchValue(null);
}
}
getUID(): string {
let uid = this.userForm.getValue('user_id');
const tenant = this.userForm?.getValue('tenant');
if (tenant && tenant.length > 0) {
uid = `${this.userForm.getValue('tenant')}$${uid}`;
}
return uid;
}
/**
* Validate the quota maximum size, e.g. 1096, 1K, 30M or 1.9MiB.
*/
quotaMaxSizeValidator(control: AbstractControl): ValidationErrors | null {
if (isEmptyInputValue(control.value)) {
return null;
}
const m = RegExp('^(\\d+(\\.\\d+)?)\\s*(B|K(B|iB)?|M(B|iB)?|G(B|iB)?|T(B|iB)?)?$', 'i').exec(
control.value
);
if (m === null) {
return { quotaMaxSize: true };
}
const bytes = new FormatterService().toBytes(control.value);
return bytes < 1024 ? { quotaMaxSize: true } : null;
}
/**
* Add/Update a subuser.
*/
setSubuser(subuser: RgwUserSubuser, index?: number) {
const mapPermissions: Record<string, string> = {
'full-control': 'full',
'read-write': 'readwrite'
};
const uid = this.getUID();
const args = {
subuser: subuser.id,
access:
subuser.permissions in mapPermissions
? mapPermissions[subuser.permissions]
: subuser.permissions,
key_type: 'swift',
secret_key: subuser.secret_key,
generate_secret: subuser.generate_secret ? 'true' : 'false'
};
this.submitObservables.push(this.rgwUserService.createSubuser(uid, args));
if (_.isNumber(index)) {
// Modify
// Create an observable to modify the subuser when the form is submitted.
this.subusers[index] = subuser;
} else {
// Add
// Create an observable to add the subuser when the form is submitted.
this.subusers.push(subuser);
// Add a Swift key. If the secret key is auto-generated, then visualize
// this to the user by displaying a notification instead of the key.
this.swiftKeys.push({
user: subuser.id,
secret_key: subuser.generate_secret ? 'Apply your changes first...' : subuser.secret_key
});
}
// Mark the form as dirty to be able to submit it.
this.userForm.markAsDirty();
}
/**
* Delete a subuser.
* @param {number} index The subuser to delete.
*/
deleteSubuser(index: number) {
const subuser = this.subusers[index];
// Create an observable to delete the subuser when the form is submitted.
this.submitObservables.push(this.rgwUserService.deleteSubuser(this.getUID(), subuser.id));
// Remove the associated S3 keys.
this.s3Keys = this.s3Keys.filter((key) => {
return key.user !== subuser.id;
});
// Remove the associated Swift keys.
this.swiftKeys = this.swiftKeys.filter((key) => {
return key.user !== subuser.id;
});
// Remove the subuser to update the UI.
this.subusers.splice(index, 1);
// Mark the form as dirty to be able to submit it.
this.userForm.markAsDirty();
}
/**
* Add/Update a capability.
*/
setCapability(cap: RgwUserCapability, index?: number) {
const uid = this.getUID();
if (_.isNumber(index)) {
// Modify
const oldCap = this.capabilities[index];
// Note, the RadosGW Admin OPS API does not support the modification of
// user capabilities. Because of that it is necessary to delete it and
// then to re-add the capability with its new value/permission.
this.submitObservables.push(
this.rgwUserService.deleteCapability(uid, oldCap.type, oldCap.perm)
);
this.submitObservables.push(this.rgwUserService.addCapability(uid, cap.type, cap.perm));
this.capabilities[index] = cap;
} else {
// Add
// Create an observable to add the capability when the form is submitted.
this.submitObservables.push(this.rgwUserService.addCapability(uid, cap.type, cap.perm));
this.capabilities = [...this.capabilities, cap]; // Notify Angular CD
}
// Mark the form as dirty to be able to submit it.
this.userForm.markAsDirty();
}
/**
* Delete the given capability:
* - Delete it from the local array to update the UI
* - Create an observable that will be executed on form submit
* @param {number} index The capability to delete.
*/
deleteCapability(index: number) {
const cap = this.capabilities[index];
// Create an observable to delete the capability when the form is submitted.
this.submitObservables.push(
this.rgwUserService.deleteCapability(this.getUID(), cap.type, cap.perm)
);
// Remove the capability to update the UI.
this.capabilities.splice(index, 1);
this.capabilities = [...this.capabilities]; // Notify Angular CD
// Mark the form as dirty to be able to submit it.
this.userForm.markAsDirty();
}
hasAllCapabilities(capabilities: RgwUserCapability[]) {
return !_.difference(RgwUserCapabilities.getAll(), _.map(capabilities, 'type')).length;
}
/**
* Add/Update a S3 key.
*/
setS3Key(key: RgwUserS3Key, index?: number) {
if (_.isNumber(index)) {
// Modify
// Nothing to do here at the moment.
} else {
// Add
// Split the key's user name into its user and subuser parts.
const userMatches = key.user.match(/([^:]+)(:(.+))?/);
// Create an observable to add the S3 key when the form is submitted.
const uid = userMatches[1];
const args = {
subuser: userMatches[2] ? userMatches[3] : '',
generate_key: key.generate_key ? 'true' : 'false'
};
if (args['generate_key'] === 'false') {
if (!_.isNil(key.access_key)) {
args['access_key'] = key.access_key;
}
if (!_.isNil(key.secret_key)) {
args['secret_key'] = key.secret_key;
}
}
this.submitObservables.push(this.rgwUserService.addS3Key(uid, args));
// If the access and the secret key are auto-generated, then visualize
// this to the user by displaying a notification instead of the key.
this.s3Keys.push({
user: key.user,
access_key: key.generate_key ? 'Apply your changes first...' : key.access_key,
secret_key: key.generate_key ? 'Apply your changes first...' : key.secret_key
});
}
// Mark the form as dirty to be able to submit it.
this.userForm.markAsDirty();
}
/**
* Delete a S3 key.
* @param {number} index The S3 key to delete.
*/
deleteS3Key(index: number) {
const key = this.s3Keys[index];
// Create an observable to delete the S3 key when the form is submitted.
this.submitObservables.push(this.rgwUserService.deleteS3Key(this.getUID(), key.access_key));
// Remove the S3 key to update the UI.
this.s3Keys.splice(index, 1);
// Mark the form as dirty to be able to submit it.
this.userForm.markAsDirty();
}
/**
* Show the specified subuser in a modal dialog.
* @param {number | undefined} index The subuser to show.
*/
showSubuserModal(index?: number) {
const uid = this.getUID();
const modalRef = this.modalService.show(RgwUserSubuserModalComponent);
if (_.isNumber(index)) {
// Edit
const subuser = this.subusers[index];
modalRef.componentInstance.setEditing();
modalRef.componentInstance.setValues(uid, subuser.id, subuser.permissions);
} else {
// Add
modalRef.componentInstance.setEditing(false);
modalRef.componentInstance.setValues(uid);
modalRef.componentInstance.setSubusers(this.subusers);
}
modalRef.componentInstance.submitAction.subscribe((subuser: RgwUserSubuser) => {
this.setSubuser(subuser, index);
});
}
/**
* Show the specified S3 key in a modal dialog.
* @param {number | undefined} index The S3 key to show.
*/
showS3KeyModal(index?: number) {
const modalRef = this.modalService.show(RgwUserS3KeyModalComponent);
if (_.isNumber(index)) {
// View
const key = this.s3Keys[index];
modalRef.componentInstance.setViewing();
modalRef.componentInstance.setValues(key.user, key.access_key, key.secret_key);
} else {
// Add
const candidates = this._getS3KeyUserCandidates();
modalRef.componentInstance.setViewing(false);
modalRef.componentInstance.setUserCandidates(candidates);
modalRef.componentInstance.submitAction.subscribe((key: RgwUserS3Key) => {
this.setS3Key(key);
});
}
}
/**
* Show the specified Swift key in a modal dialog.
* @param {number} index The Swift key to show.
*/
showSwiftKeyModal(index: number) {
const modalRef = this.modalService.show(RgwUserSwiftKeyModalComponent);
const key = this.swiftKeys[index];
modalRef.componentInstance.setValues(key.user, key.secret_key);
}
/**
* Show the specified capability in a modal dialog.
* @param {number | undefined} index The S3 key to show.
*/
showCapabilityModal(index?: number) {
const modalRef = this.modalService.show(RgwUserCapabilityModalComponent);
if (_.isNumber(index)) {
// Edit
const cap = this.capabilities[index];
modalRef.componentInstance.setEditing();
modalRef.componentInstance.setValues(cap.type, cap.perm);
} else {
// Add
modalRef.componentInstance.setEditing(false);
modalRef.componentInstance.setCapabilities(this.capabilities);
}
modalRef.componentInstance.submitAction.subscribe((cap: RgwUserCapability) => {
this.setCapability(cap, index);
});
}
/**
* Check if the general user settings (display name, email, ...) have been modified.
* @return {Boolean} Returns TRUE if the general user settings have been modified.
*/
private _isGeneralDirty(): boolean {
return ['display_name', 'email', 'max_buckets_mode', 'max_buckets', 'suspended'].some(
(path) => {
return this.userForm.get(path).dirty;
}
);
}
/**
* Check if the user quota has been modified.
* @return {Boolean} Returns TRUE if the user quota has been modified.
*/
private _isUserQuotaDirty(): boolean {
return [
'user_quota_enabled',
'user_quota_max_size_unlimited',
'user_quota_max_size',
'user_quota_max_objects_unlimited',
'user_quota_max_objects'
].some((path) => {
return this.userForm.get(path).dirty;
});
}
/**
* Check if the bucket quota has been modified.
* @return {Boolean} Returns TRUE if the bucket quota has been modified.
*/
private _isBucketQuotaDirty(): boolean {
return [
'bucket_quota_enabled',
'bucket_quota_max_size_unlimited',
'bucket_quota_max_size',
'bucket_quota_max_objects_unlimited',
'bucket_quota_max_objects'
].some((path) => {
return this.userForm.get(path).dirty;
});
}
/**
* Helper function to get the arguments of the API request when a new
* user is created.
*/
private _getCreateArgs() {
const result = {
uid: this.getUID(),
display_name: this.userForm.getValue('display_name'),
suspended: this.userForm.getValue('suspended'),
email: '',
max_buckets: this.userForm.getValue('max_buckets'),
generate_key: this.userForm.getValue('generate_key'),
access_key: '',
secret_key: ''
};
const email = this.userForm.getValue('email');
if (_.isString(email) && email.length > 0) {
_.merge(result, { email: email });
}
const generateKey = this.userForm.getValue('generate_key');
if (!generateKey) {
_.merge(result, {
generate_key: false,
access_key: this.userForm.getValue('access_key'),
secret_key: this.userForm.getValue('secret_key')
});
}
const maxBucketsMode = parseInt(this.userForm.getValue('max_buckets_mode'), 10);
if (_.includes([-1, 0], maxBucketsMode)) {
// -1 => Disable bucket creation.
// 0 => Unlimited bucket creation.
_.merge(result, { max_buckets: maxBucketsMode });
}
return result;
}
/**
* Helper function to get the arguments for the API request when the user
* configuration has been modified.
*/
private _getUpdateArgs() {
const result: Record<string, any> = {};
const keys = ['display_name', 'email', 'max_buckets', 'suspended'];
for (const key of keys) {
result[key] = this.userForm.getValue(key);
}
const maxBucketsMode = parseInt(this.userForm.getValue('max_buckets_mode'), 10);
if (_.includes([-1, 0], maxBucketsMode)) {
// -1 => Disable bucket creation.
// 0 => Unlimited bucket creation.
result['max_buckets'] = maxBucketsMode;
}
return result;
}
/**
* Helper function to get the arguments for the API request when the user
* quota configuration has been modified.
*/
private _getUserQuotaArgs(): Record<string, any> {
const result = {
quota_type: 'user',
enabled: this.userForm.getValue('user_quota_enabled'),
max_size_kb: -1,
max_objects: -1
};
if (!this.userForm.getValue('user_quota_max_size_unlimited')) {
// Convert the given value to bytes.
const bytes = new FormatterService().toBytes(this.userForm.getValue('user_quota_max_size'));
// Finally convert the value to KiB.
result['max_size_kb'] = (bytes / 1024).toFixed(0) as any;
}
if (!this.userForm.getValue('user_quota_max_objects_unlimited')) {
result['max_objects'] = this.userForm.getValue('user_quota_max_objects');
}
return result;
}
/**
* Helper function to get the arguments for the API request when the bucket
* quota configuration has been modified.
*/
private _getBucketQuotaArgs(): Record<string, any> {
const result = {
quota_type: 'bucket',
enabled: this.userForm.getValue('bucket_quota_enabled'),
max_size_kb: -1,
max_objects: -1
};
if (!this.userForm.getValue('bucket_quota_max_size_unlimited')) {
// Convert the given value to bytes.
const bytes = new FormatterService().toBytes(this.userForm.getValue('bucket_quota_max_size'));
// Finally convert the value to KiB.
result['max_size_kb'] = (bytes / 1024).toFixed(0) as any;
}
if (!this.userForm.getValue('bucket_quota_max_objects_unlimited')) {
result['max_objects'] = this.userForm.getValue('bucket_quota_max_objects');
}
return result;
}
/**
* Helper method to get the user candidates for S3 keys.
* @returns {Array} Returns a list of user identifiers.
*/
private _getS3KeyUserCandidates() {
let result = [];
// Add the current user id.
const uid = this.getUID();
if (_.isString(uid) && !_.isEmpty(uid)) {
result.push(uid);
}
// Append the subusers.
this.subusers.forEach((subUser) => {
result.push(subUser.id);
});
// Note that it's possible to create multiple S3 key pairs for a user,
// thus we append already configured users, too.
this.s3Keys.forEach((key) => {
result.push(key.user);
});
result = _.uniq(result);
return result;
}
onMaxBucketsModeChange(mode: string) {
if (mode === '1') {
// If 'Custom' mode is selected, then ensure that the form field
// 'Max. buckets' contains a valid value. Set it to default if
// necessary.
if (!this.userForm.get('max_buckets').valid) {
this.userForm.patchValue({
max_buckets: 1000
});
}
}
}
}
| 26,255 | 33.68428 | 115 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-list/rgw-user-list.component.html
|
<cd-rgw-user-tabs></cd-rgw-user-tabs>
<cd-table #table
[autoReload]="false"
[data]="users"
[columns]="columns"
columnMode="flex"
selectionType="multiClick"
[hasDetails]="true"
(setExpandedRow)="setExpandedRow($event)"
(updateSelection)="updateSelection($event)"
identifier="uid"
(fetchData)="getUserList($event)"
[status]="tableStatus">
<cd-table-actions class="table-actions"
[permission]="permission"
[selection]="selection"
[tableActions]="tableActions">
</cd-table-actions>
<cd-rgw-user-details cdTableDetail
[selection]="expandedRow">
</cd-rgw-user-details>
</cd-table>
<ng-template #userSizeTpl
let-row="row">
<cd-usage-bar *ngIf="row.user_quota.max_size > 0 && row.user_quota.enabled; else noSizeQuota"
[total]="row.user_quota.max_size"
[used]="row.stats.size_actual">
</cd-usage-bar>
<ng-template #noSizeQuota
i18n>No Limit</ng-template>
</ng-template>
<ng-template #userObjectTpl
let-row="row">
<cd-usage-bar *ngIf="row.user_quota.max_objects > 0 && row.user_quota.enabled; else noObjectQuota"
[total]="row.user_quota.max_objects"
[used]="row.stats.num_objects"
[isBinary]="false">
</cd-usage-bar>
<ng-template #noObjectQuota
i18n>No Limit</ng-template>
</ng-template>
| 1,532 | 31.617021 | 100 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-list/rgw-user-list.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { RgwUserService } from '~/app/shared/api/rgw-user.service';
import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed, PermissionHelper } from '~/testing/unit-test-helper';
import { RgwUserListComponent } from './rgw-user-list.component';
describe('RgwUserListComponent', () => {
let component: RgwUserListComponent;
let fixture: ComponentFixture<RgwUserListComponent>;
let rgwUserService: RgwUserService;
let rgwUserServiceListSpy: jasmine.Spy;
configureTestBed({
declarations: [RgwUserListComponent],
imports: [BrowserAnimationsModule, RouterTestingModule, HttpClientTestingModule, SharedModule],
schemas: [NO_ERRORS_SCHEMA]
});
beforeEach(() => {
rgwUserService = TestBed.inject(RgwUserService);
rgwUserServiceListSpy = spyOn(rgwUserService, 'list');
rgwUserServiceListSpy.and.returnValue(of([]));
fixture = TestBed.createComponent(RgwUserListComponent);
component = fixture.componentInstance;
spyOn(component, 'setTableRefreshTimeout').and.stub();
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
expect(rgwUserServiceListSpy).toHaveBeenCalledTimes(1);
});
it('should test all TableActions combinations', () => {
const permissionHelper: PermissionHelper = new PermissionHelper(component.permission);
const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions(
component.tableActions
);
expect(tableActions).toEqual({
'create,update,delete': {
actions: ['Create', 'Edit', 'Delete'],
primary: { multiple: 'Delete', executing: 'Edit', single: 'Edit', no: 'Create' }
},
'create,update': {
actions: ['Create', 'Edit'],
primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' }
},
'create,delete': {
actions: ['Create', 'Delete'],
primary: { multiple: 'Delete', executing: 'Create', single: 'Create', no: 'Create' }
},
create: {
actions: ['Create'],
primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' }
},
'update,delete': {
actions: ['Edit', 'Delete'],
primary: { multiple: 'Delete', executing: 'Edit', single: 'Edit', no: 'Edit' }
},
update: {
actions: ['Edit'],
primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' }
},
delete: {
actions: ['Delete'],
primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' }
},
'no-permissions': {
actions: [],
primary: { multiple: '', executing: '', single: '', no: '' }
}
});
});
it('should test if rgw-user data is tranformed correctly', () => {
rgwUserServiceListSpy.and.returnValue(
of([
{
user_id: 'testid',
stats: {
size_actual: 6,
num_objects: 6
},
user_quota: {
max_size: 20,
max_objects: 10,
enabled: true
}
}
])
);
component.getUserList(null);
expect(rgwUserServiceListSpy).toHaveBeenCalledTimes(2);
expect(component.users).toEqual([
{
user_id: 'testid',
stats: {
size_actual: 6,
num_objects: 6
},
user_quota: {
max_size: 20,
max_objects: 10,
enabled: true
}
}
]);
});
it('should usage bars only if quota enabled', () => {
rgwUserServiceListSpy.and.returnValue(
of([
{
user_id: 'testid',
stats: {
size_actual: 6,
num_objects: 6
},
user_quota: {
max_size: 1024,
max_objects: 10,
enabled: true
}
}
])
);
component.getUserList(null);
expect(rgwUserServiceListSpy).toHaveBeenCalledTimes(2);
fixture.detectChanges();
const usageBars = fixture.debugElement.nativeElement.querySelectorAll('cd-usage-bar');
expect(usageBars.length).toBe(2);
});
it('should not show any usage bars if quota disabled', () => {
rgwUserServiceListSpy.and.returnValue(
of([
{
user_id: 'testid',
stats: {
size_actual: 6,
num_objects: 6
},
user_quota: {
max_size: 1024,
max_objects: 10,
enabled: false
}
}
])
);
component.getUserList(null);
expect(rgwUserServiceListSpy).toHaveBeenCalledTimes(2);
fixture.detectChanges();
const usageBars = fixture.debugElement.nativeElement.querySelectorAll('cd-usage-bar');
expect(usageBars.length).toBe(0);
});
});
| 5,276 | 30.598802 | 101 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-list/rgw-user-list.component.ts
|
import { Component, NgZone, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { forkJoin as observableForkJoin, Observable, Subscriber } from 'rxjs';
import { RgwUserService } from '~/app/shared/api/rgw-user.service';
import { ListWithDetails } from '~/app/shared/classes/list-with-details.class';
import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { TableComponent } from '~/app/shared/datatable/table/table.component';
import { CellTemplate } from '~/app/shared/enum/cell-template.enum';
import { Icons } from '~/app/shared/enum/icons.enum';
import { CdTableAction } from '~/app/shared/models/cd-table-action';
import { CdTableColumn } from '~/app/shared/models/cd-table-column';
import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context';
import { CdTableSelection } from '~/app/shared/models/cd-table-selection';
import { Permission } from '~/app/shared/models/permissions';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { ModalService } from '~/app/shared/services/modal.service';
import { URLBuilderService } from '~/app/shared/services/url-builder.service';
const BASE_URL = 'rgw/user';
@Component({
selector: 'cd-rgw-user-list',
templateUrl: './rgw-user-list.component.html',
styleUrls: ['./rgw-user-list.component.scss'],
providers: [{ provide: URLBuilderService, useValue: new URLBuilderService(BASE_URL) }]
})
export class RgwUserListComponent extends ListWithDetails implements OnInit {
@ViewChild(TableComponent, { static: true })
table: TableComponent;
@ViewChild('userSizeTpl', { static: true })
userSizeTpl: TemplateRef<any>;
@ViewChild('userObjectTpl', { static: true })
userObjectTpl: TemplateRef<any>;
permission: Permission;
tableActions: CdTableAction[];
columns: CdTableColumn[] = [];
users: object[] = [];
selection: CdTableSelection = new CdTableSelection();
staleTimeout: number;
constructor(
private authStorageService: AuthStorageService,
private rgwUserService: RgwUserService,
private modalService: ModalService,
private urlBuilder: URLBuilderService,
public actionLabels: ActionLabelsI18n,
protected ngZone: NgZone
) {
super(ngZone);
}
ngOnInit() {
this.permission = this.authStorageService.getPermissions().rgw;
this.columns = [
{
name: $localize`Username`,
prop: 'uid',
flexGrow: 1
},
{
name: $localize`Tenant`,
prop: 'tenant',
flexGrow: 1
},
{
name: $localize`Full name`,
prop: 'display_name',
flexGrow: 1
},
{
name: $localize`Email address`,
prop: 'email',
flexGrow: 1
},
{
name: $localize`Suspended`,
prop: 'suspended',
flexGrow: 1,
cellClass: 'text-center',
cellTransformation: CellTemplate.checkIcon
},
{
name: $localize`Max. buckets`,
prop: 'max_buckets',
flexGrow: 1,
cellTransformation: CellTemplate.map,
customTemplateConfig: {
'-1': $localize`Disabled`,
0: $localize`Unlimited`
}
},
{
name: $localize`Capacity Limit %`,
prop: 'size_usage',
cellTemplate: this.userSizeTpl,
flexGrow: 0.8
},
{
name: $localize`Object Limit %`,
prop: 'object_usage',
cellTemplate: this.userObjectTpl,
flexGrow: 0.8
}
];
const getUserUri = () =>
this.selection.first() && `${encodeURIComponent(this.selection.first().uid)}`;
const addAction: CdTableAction = {
permission: 'create',
icon: Icons.add,
routerLink: () => this.urlBuilder.getCreate(),
name: this.actionLabels.CREATE,
canBePrimary: (selection: CdTableSelection) => !selection.hasSelection
};
const editAction: CdTableAction = {
permission: 'update',
icon: Icons.edit,
routerLink: () => this.urlBuilder.getEdit(getUserUri()),
name: this.actionLabels.EDIT
};
const deleteAction: CdTableAction = {
permission: 'delete',
icon: Icons.destroy,
click: () => this.deleteAction(),
disable: () => !this.selection.hasSelection,
name: this.actionLabels.DELETE,
canBePrimary: (selection: CdTableSelection) => selection.hasMultiSelection
};
this.tableActions = [addAction, editAction, deleteAction];
this.setTableRefreshTimeout();
}
getUserList(context: CdTableFetchDataContext) {
this.setTableRefreshTimeout();
this.rgwUserService.list().subscribe(
(resp: object[]) => {
this.users = resp;
},
() => {
context.error();
}
);
}
updateSelection(selection: CdTableSelection) {
this.selection = selection;
}
deleteAction() {
this.modalService.show(CriticalConfirmationModalComponent, {
itemDescription: this.selection.hasSingleSelection ? $localize`user` : $localize`users`,
itemNames: this.selection.selected.map((user: any) => user['uid']),
submitActionObservable: (): Observable<any> => {
return new Observable((observer: Subscriber<any>) => {
// Delete all selected data table rows.
observableForkJoin(
this.selection.selected.map((user: any) => {
return this.rgwUserService.delete(user.uid);
})
).subscribe({
error: (error) => {
// Forward the error to the observer.
observer.error(error);
// Reload the data table content because some deletions might
// have been executed successfully in the meanwhile.
this.table.refreshBtn();
},
complete: () => {
// Notify the observer that we are done.
observer.complete();
// Reload the data table content.
this.table.refreshBtn();
}
});
});
}
});
}
}
| 6,171 | 33.099448 | 143 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-s3-key-modal/rgw-user-s3-key-modal.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">{{ action | titlecase }} {{ resource | upperFirst }}</ng-container>
<ng-container class="modal-content">
<form #frm="ngForm"
[formGroup]="formGroup"
novalidate>
<div class="modal-body">
<!-- Username -->
<div class="form-group row">
<label class="cd-col-form-label"
[ngClass]="{'required': !viewing}"
for="user"
i18n>Username</label>
<div class="cd-col-form-input">
<input id="user"
class="form-control"
type="text"
*ngIf="viewing"
[readonly]="true"
formControlName="user">
<select id="user"
class="form-control"
formControlName="user"
*ngIf="!viewing"
autofocus>
<option i18n
*ngIf="userCandidates !== null"
[ngValue]="null">-- Select a username --</option>
<option *ngFor="let userCandidate of userCandidates"
[value]="userCandidate">{{ userCandidate }}</option>
</select>
<span class="invalid-feedback"
*ngIf="formGroup.showError('user', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
<!-- Auto-generate key -->
<div class="form-group row"
*ngIf="!viewing">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
id="generate_key"
type="checkbox"
formControlName="generate_key">
<label class="custom-control-label"
for="generate_key"
i18n>Auto-generate key</label>
</div>
</div>
</div>
<!-- Access key -->
<div class="form-group row"
*ngIf="!formGroup.getValue('generate_key')">
<label class="cd-col-form-label"
[ngClass]="{'required': !viewing}"
for="access_key"
i18n>Access key</label>
<div class="cd-col-form-input">
<div class="input-group">
<input id="access_key"
class="form-control"
type="password"
[readonly]="viewing"
formControlName="access_key">
<button type="button"
class="btn btn-light"
cdPasswordButton="access_key">
</button>
<cd-copy-2-clipboard-button source="access_key">
</cd-copy-2-clipboard-button>
</div>
<span class="invalid-feedback"
*ngIf="formGroup.showError('access_key', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
<!-- Secret key -->
<div class="form-group row"
*ngIf="!formGroup.getValue('generate_key')">
<label class="cd-col-form-label"
[ngClass]="{'required': !viewing}"
for="secret_key"
i18n>Secret key</label>
<div class="cd-col-form-input">
<div class="input-group">
<input id="secret_key"
class="form-control"
type="password"
[readonly]="viewing"
formControlName="secret_key">
<button type="button"
class="btn btn-light"
cdPasswordButton="secret_key">
</button>
<cd-copy-2-clipboard-button source="secret_key">
</cd-copy-2-clipboard-button>
</div>
<span class="invalid-feedback"
*ngIf="formGroup.showError('secret_key', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="onSubmit()"
[form]="formGroup"
[submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"
[showSubmit]="!viewing"></cd-form-button-panel>
</div>
</form>
</ng-container>
</cd-modal>
| 4,615 | 36.836066 | 103 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-s3-key-modal/rgw-user-s3-key-modal.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { RgwUserS3KeyModalComponent } from './rgw-user-s3-key-modal.component';
describe('RgwUserS3KeyModalComponent', () => {
let component: RgwUserS3KeyModalComponent;
let fixture: ComponentFixture<RgwUserS3KeyModalComponent>;
configureTestBed({
declarations: [RgwUserS3KeyModalComponent],
imports: [ReactiveFormsModule, SharedModule, RouterTestingModule],
providers: [NgbActiveModal]
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwUserS3KeyModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,026 | 32.129032 | 79 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-s3-key-modal/rgw-user-s3-key-modal.component.ts
|
import { Component, EventEmitter, Output } from '@angular/core';
import { Validators } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { CdValidators } from '~/app/shared/forms/cd-validators';
import { RgwUserS3Key } from '../models/rgw-user-s3-key';
@Component({
selector: 'cd-rgw-user-s3-key-modal',
templateUrl: './rgw-user-s3-key-modal.component.html',
styleUrls: ['./rgw-user-s3-key-modal.component.scss']
})
export class RgwUserS3KeyModalComponent {
/**
* The event that is triggered when the 'Add' button as been pressed.
*/
@Output()
submitAction = new EventEmitter();
formGroup: CdFormGroup;
viewing = true;
userCandidates: string[] = [];
resource: string;
action: string;
constructor(
private formBuilder: CdFormBuilder,
public activeModal: NgbActiveModal,
public actionLabels: ActionLabelsI18n
) {
this.resource = $localize`S3 Key`;
this.createForm();
}
createForm() {
this.formGroup = this.formBuilder.group({
user: [null, [Validators.required]],
generate_key: [true],
access_key: [null, [CdValidators.requiredIf({ generate_key: false })]],
secret_key: [null, [CdValidators.requiredIf({ generate_key: false })]]
});
}
/**
* Set the 'viewing' flag. If set to TRUE, the modal dialog is in 'View' mode,
* otherwise in 'Add' mode. According to the mode the dialog and its controls
* behave different.
* @param {boolean} viewing
*/
setViewing(viewing: boolean = true) {
this.viewing = viewing;
this.action = this.viewing ? this.actionLabels.SHOW : this.actionLabels.CREATE;
}
/**
* Set the values displayed in the dialog.
*/
setValues(user: string, access_key: string, secret_key: string) {
this.formGroup.setValue({
user: user,
generate_key: _.isEmpty(access_key),
access_key: access_key,
secret_key: secret_key
});
}
/**
* Set the user candidates displayed in the 'Username' dropdown box.
*/
setUserCandidates(candidates: string[]) {
this.userCandidates = candidates;
}
onSubmit() {
const key: RgwUserS3Key = this.formGroup.value;
this.submitAction.emit(key);
this.activeModal.close();
}
}
| 2,476 | 28.141176 | 83 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-subuser-modal/rgw-user-subuser-modal.component.html
|
<cd-modal [modalRef]="bsModalRef">
<ng-container i18n="form title"
class="modal-title">{{ action | titlecase }} {{ resource | upperFirst }}</ng-container>
<ng-container class="modal-content">
<form #frm="ngForm"
[formGroup]="formGroup"
novalidate>
<div class="modal-body">
<!-- Username -->
<div class="form-group row">
<label class="cd-col-form-label"
for="uid"
i18n>Username</label>
<div class="cd-col-form-input">
<input id="uid"
class="form-control"
type="text"
formControlName="uid"
[readonly]="true">
</div>
</div>
<!-- Subuser -->
<div class="form-group row">
<label class="cd-col-form-label"
[ngClass]="{'required': !editing}"
for="subuid"
i18n>Subuser</label>
<div class="cd-col-form-input">
<input id="subuid"
class="form-control"
type="text"
formControlName="subuid"
[readonly]="editing"
autofocus>
<span class="invalid-feedback"
*ngIf="formGroup.showError('subuid', frm, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="formGroup.showError('subuid', frm, 'subuserIdExists')"
i18n>The chosen subuser ID is already in use.</span>
</div>
</div>
<!-- Permission -->
<div class="form-group row">
<label class="cd-col-form-label required"
for="perm"
i18n>Permission</label>
<div class="cd-col-form-input">
<select id="perm"
class="form-select"
formControlName="perm">
<option i18n
[ngValue]="null">-- Select a permission --</option>
<option *ngFor="let perm of ['read', 'write']"
[value]="perm">
{{ perm }}
</option>
<option i18n
value="read-write">read, write</option>
<option i18n
value="full-control">full</option>
</select>
<span class="invalid-feedback"
*ngIf="formGroup.showError('perm', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
<!-- Swift key -->
<fieldset *ngIf="!editing">
<legend i18n>Swift key</legend>
<!-- Auto-generate key -->
<div class="form-group row">
<div class="cd-col-form-offset">
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
id="generate_secret"
type="checkbox"
formControlName="generate_secret">
<label class="custom-control-label"
for="generate_secret"
i18n>Auto-generate secret</label>
</div>
</div>
</div>
<!-- Secret key -->
<div class="form-group row"
*ngIf="!editing && !formGroup.getValue('generate_secret')">
<label class="cd-col-form-label required"
for="secret_key"
i18n>Secret key</label>
<div class="cd-col-form-input">
<div class="input-group">
<input id="secret_key"
class="form-control"
type="password"
formControlName="secret_key">
<button type="button"
class="btn btn-light"
cdPasswordButton="secret_key">
</button>
<cd-copy-2-clipboard-button source="secret_key">
</cd-copy-2-clipboard-button>
</div>
<span class="invalid-feedback"
*ngIf="formGroup.showError('secret_key', frm, 'required')"
i18n>This field is required.</span>
</div>
</div>
</fieldset>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="onSubmit()"
[form]="formGroup"
[submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"></cd-form-button-panel>
</div>
</form>
</ng-container>
</cd-modal>
| 4,714 | 36.125984 | 121 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-subuser-modal/rgw-user-subuser-modal.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { RgwUserSubuserModalComponent } from './rgw-user-subuser-modal.component';
describe('RgwUserSubuserModalComponent', () => {
let component: RgwUserSubuserModalComponent;
let fixture: ComponentFixture<RgwUserSubuserModalComponent>;
configureTestBed({
declarations: [RgwUserSubuserModalComponent],
imports: [ReactiveFormsModule, SharedModule, RouterTestingModule],
providers: [NgbActiveModal]
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwUserSubuserModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('subuserValidator', () => {
beforeEach(() => {
component.editing = false;
component.subusers = [
{ id: 'Edith', permissions: 'full-control' },
{ id: 'Edith:images', permissions: 'read-write' }
];
});
it('should validate subuser (1/5)', () => {
component.editing = true;
const validatorFn = component.subuserValidator();
const resp = validatorFn(new FormControl());
expect(resp).toBe(null);
});
it('should validate subuser (2/5)', () => {
const validatorFn = component.subuserValidator();
const resp = validatorFn(new FormControl(''));
expect(resp).toBe(null);
});
it('should validate subuser (3/5)', () => {
const validatorFn = component.subuserValidator();
const resp = validatorFn(new FormControl('Melissa'));
expect(resp).toBe(null);
});
it('should validate subuser (4/5)', () => {
const validatorFn = component.subuserValidator();
const resp = validatorFn(new FormControl('Edith'));
expect(resp.subuserIdExists).toBeTruthy();
});
it('should validate subuser (5/5)', () => {
const validatorFn = component.subuserValidator();
const resp = validatorFn(new FormControl('images'));
expect(resp.subuserIdExists).toBeTruthy();
});
});
});
| 2,381 | 32.083333 | 82 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-subuser-modal/rgw-user-subuser-modal.component.ts
|
import { Component, EventEmitter, Output } from '@angular/core';
import { AbstractControl, ValidationErrors, ValidatorFn, Validators } from '@angular/forms';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { CdValidators, isEmptyInputValue } from '~/app/shared/forms/cd-validators';
import { RgwUserSubuser } from '../models/rgw-user-subuser';
@Component({
selector: 'cd-rgw-user-subuser-modal',
templateUrl: './rgw-user-subuser-modal.component.html',
styleUrls: ['./rgw-user-subuser-modal.component.scss']
})
export class RgwUserSubuserModalComponent {
/**
* The event that is triggered when the 'Add' or 'Update' button
* has been pressed.
*/
@Output()
submitAction = new EventEmitter();
formGroup: CdFormGroup;
editing = true;
subusers: RgwUserSubuser[] = [];
resource: string;
action: string;
constructor(
private formBuilder: CdFormBuilder,
public bsModalRef: NgbActiveModal,
private actionLabels: ActionLabelsI18n
) {
this.resource = $localize`Subuser`;
this.createForm();
}
createForm() {
this.formGroup = this.formBuilder.group({
uid: [null],
subuid: [null, [Validators.required, this.subuserValidator()]],
perm: [null, [Validators.required]],
// Swift key
generate_secret: [true],
secret_key: [null, [CdValidators.requiredIf({ generate_secret: false })]]
});
}
/**
* Validates whether the subuser already exists.
*/
subuserValidator(): ValidatorFn {
const self = this;
return (control: AbstractControl): ValidationErrors | null => {
if (self.editing) {
return null;
}
if (isEmptyInputValue(control.value)) {
return null;
}
const found = self.subusers.some((subuser) => {
return _.isEqual(self.getSubuserName(subuser.id), control.value);
});
return found ? { subuserIdExists: true } : null;
};
}
/**
* Get the subuser name.
* Examples:
* 'johndoe' => 'johndoe'
* 'janedoe:xyz' => 'xyz'
* @param {string} value The value to process.
* @returns {string} Returns the user ID.
*/
private getSubuserName(value: string) {
if (_.isEmpty(value)) {
return value;
}
const matches = value.match(/([^:]+)(:(.+))?/);
return _.isUndefined(matches[3]) ? matches[1] : matches[3];
}
/**
* Set the 'editing' flag. If set to TRUE, the modal dialog is in 'Edit' mode,
* otherwise in 'Add' mode. According to the mode the dialog and its controls
* behave different.
* @param {boolean} viewing
*/
setEditing(editing: boolean = true) {
this.editing = editing;
this.action = this.editing ? this.actionLabels.EDIT : this.actionLabels.CREATE;
}
/**
* Set the values displayed in the dialog.
*/
setValues(uid: string, subuser: string = '', permissions: string = '') {
this.formGroup.setValue({
uid: uid,
subuid: this.getSubuserName(subuser),
perm: permissions,
generate_secret: true,
secret_key: null
});
}
/**
* Set the current capabilities of the user.
*/
setSubusers(subusers: RgwUserSubuser[]) {
this.subusers = subusers;
}
onSubmit() {
// Get the values from the form and create an object that is sent
// by the triggered submit action event.
const values = this.formGroup.value;
const subuser = new RgwUserSubuser();
subuser.id = `${values.uid}:${values.subuid}`;
subuser.permissions = values.perm;
subuser.generate_secret = values.generate_secret;
subuser.secret_key = values.secret_key;
this.submitAction.emit(subuser);
this.bsModalRef.close();
}
}
| 3,886 | 28.671756 | 92 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-swift-key-modal/rgw-user-swift-key-modal.component.html
|
<cd-modal [modalRef]="activeModal">
<ng-container i18n="form title"
class="modal-title">{{ action | titlecase }} {{ resource | upperFirst }}</ng-container>
<ng-container class="modal-content">
<div class="modal-body">
<form novalidate>
<!-- Username -->
<div class="form-group row">
<label class="cd-col-form-label"
for="user"
i18n>Username</label>
<div class="cd-col-form-input">
<input id="user"
name="user"
class="form-control"
type="text"
[readonly]="true"
[(ngModel)]="user">
</div>
</div>
<!-- Secret key -->
<div class="form-group row">
<label class="cd-col-form-label"
for="secret_key"
i18n>Secret key</label>
<div class="cd-col-form-input">
<div class="input-group">
<input id="secret_key"
name="secret_key"
class="form-control"
type="password"
[(ngModel)]="secret_key"
[readonly]="true">
<button type="button"
class="btn btn-light"
cdPasswordButton="secret_key">
</button>
<cd-copy-2-clipboard-button source="secret_key">
</cd-copy-2-clipboard-button>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<cd-back-button (backAction)="activeModal.close()"></cd-back-button>
</div>
</ng-container>
</cd-modal>
| 1,714 | 31.358491 | 103 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-swift-key-modal/rgw-user-swift-key-modal.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { RgwUserSwiftKeyModalComponent } from './rgw-user-swift-key-modal.component';
describe('RgwUserSwiftKeyModalComponent', () => {
let component: RgwUserSwiftKeyModalComponent;
let fixture: ComponentFixture<RgwUserSwiftKeyModalComponent>;
configureTestBed({
declarations: [RgwUserSwiftKeyModalComponent],
imports: [ToastrModule.forRoot(), FormsModule, SharedModule, RouterTestingModule],
providers: [NgbActiveModal]
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwUserSwiftKeyModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,098 | 33.34375 | 86 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-swift-key-modal/rgw-user-swift-key-modal.component.ts
|
import { Component } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
@Component({
selector: 'cd-rgw-user-swift-key-modal',
templateUrl: './rgw-user-swift-key-modal.component.html',
styleUrls: ['./rgw-user-swift-key-modal.component.scss']
})
export class RgwUserSwiftKeyModalComponent {
user: string;
secret_key: string;
resource: string;
action: string;
constructor(public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n) {
this.resource = $localize`Swift Key`;
this.action = this.actionLabels.SHOW;
}
/**
* Set the values displayed in the dialog.
*/
setValues(user: string, secret_key: string) {
this.user = user;
this.secret_key = secret_key;
}
}
| 827 | 25.709677 | 90 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-tabs/rgw-user-tabs.component.html
|
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link"
routerLink="/rgw/user"
routerLinkActive="active"
ariaCurrentWhenActive="page"
[routerLinkActiveOptions]="{exact: true}"
i18n>Users</a>
</li>
<li class="nav-item">
<a class="nav-link"
routerLink="/rgw/roles"
routerLinkActive="active"
ariaCurrentWhenActive="page"
[routerLinkActiveOptions]="{exact: true}"
i18n>Roles</a>
</li>
</ul>
| 485 | 24.578947 | 48 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-tabs/rgw-user-tabs.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RgwUserTabsComponent } from './rgw-user-tabs.component';
describe('RgwUserTabsComponent', () => {
let component: RgwUserTabsComponent;
let fixture: ComponentFixture<RgwUserTabsComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [RgwUserTabsComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(RgwUserTabsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 656 | 25.28 | 66 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/rgw/rgw-user-tabs/rgw-user-tabs.component.ts
|
import { Component } from '@angular/core';
@Component({
selector: 'cd-rgw-user-tabs',
templateUrl: './rgw-user-tabs.component.html',
styleUrls: ['./rgw-user-tabs.component.scss']
})
export class RgwUserTabsComponent {}
| 226 | 24.222222 | 48 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/ceph-shared.module.ts
|
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap';
import { NgxPipeFunctionModule } from 'ngx-pipe-function';
import { DataTableModule } from '~/app/shared/datatable/datatable.module';
import { SharedModule } from '~/app/shared/shared.module';
import { DeviceListComponent } from './device-list/device-list.component';
import { SmartListComponent } from './smart-list/smart-list.component';
@NgModule({
imports: [CommonModule, DataTableModule, SharedModule, NgbNavModule, NgxPipeFunctionModule],
exports: [DeviceListComponent, SmartListComponent],
declarations: [DeviceListComponent, SmartListComponent]
})
export class CephSharedModule {}
| 747 | 40.555556 | 94 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/pg-category.model.ts
|
export class PgCategory {
static readonly CATEGORY_CLEAN = 'clean';
static readonly CATEGORY_WORKING = 'working';
static readonly CATEGORY_WARNING = 'warning';
static readonly CATEGORY_UNKNOWN = 'unknown';
static readonly VALID_CATEGORIES = [
PgCategory.CATEGORY_CLEAN,
PgCategory.CATEGORY_WORKING,
PgCategory.CATEGORY_WARNING,
PgCategory.CATEGORY_UNKNOWN
];
states: string[];
constructor(public type: string) {
if (!this.isValidType()) {
throw new Error('Wrong placement group category type');
}
this.setTypeStates();
}
private isValidType() {
return PgCategory.VALID_CATEGORIES.includes(this.type);
}
private setTypeStates() {
switch (this.type) {
case PgCategory.CATEGORY_CLEAN:
this.states = ['active', 'clean'];
break;
case PgCategory.CATEGORY_WORKING:
this.states = [
'activating',
'backfill_wait',
'backfilling',
'creating',
'deep',
'degraded',
'forced_backfill',
'forced_recovery',
'peering',
'peered',
'recovering',
'recovery_wait',
'repair',
'scrubbing',
'snaptrim',
'snaptrim_wait'
];
break;
case PgCategory.CATEGORY_WARNING:
this.states = [
'backfill_toofull',
'backfill_unfound',
'down',
'incomplete',
'inconsistent',
'recovery_toofull',
'recovery_unfound',
'remapped',
'snaptrim_error',
'stale',
'undersized'
];
break;
default:
this.states = [];
}
}
}
| 1,709 | 22.75 | 61 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/pg-category.service.spec.ts
|
import { TestBed } from '@angular/core/testing';
import { configureTestBed } from '~/testing/unit-test-helper';
import { PgCategory } from './pg-category.model';
import { PgCategoryService } from './pg-category.service';
describe('PgCategoryService', () => {
let service: PgCategoryService;
configureTestBed({
providers: [PgCategoryService]
});
beforeEach(() => {
service = TestBed.inject(PgCategoryService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('returns all category types', () => {
const categoryTypes = service.getAllTypes();
expect(categoryTypes).toEqual(PgCategory.VALID_CATEGORIES);
});
describe('getTypeByStates', () => {
const testMethod = (value: string, expected: string) =>
expect(service.getTypeByStates(value)).toEqual(expected);
it(PgCategory.CATEGORY_CLEAN, () => {
testMethod('clean', PgCategory.CATEGORY_CLEAN);
});
it(PgCategory.CATEGORY_WORKING, () => {
testMethod('clean+scrubbing', PgCategory.CATEGORY_WORKING);
testMethod('active+clean+snaptrim_wait', PgCategory.CATEGORY_WORKING);
testMethod(
' 8 active+clean+scrubbing+deep, 255 active+clean ',
PgCategory.CATEGORY_WORKING
);
});
it(PgCategory.CATEGORY_WARNING, () => {
testMethod('clean+scrubbing+down', PgCategory.CATEGORY_WARNING);
testMethod('clean+scrubbing+down+nonMappedState', PgCategory.CATEGORY_WARNING);
});
it(PgCategory.CATEGORY_UNKNOWN, () => {
testMethod('clean+scrubbing+nonMappedState', PgCategory.CATEGORY_UNKNOWN);
testMethod('nonMappedState', PgCategory.CATEGORY_UNKNOWN);
testMethod('', PgCategory.CATEGORY_UNKNOWN);
});
});
});
| 1,734 | 29.438596 | 85 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/pg-category.service.ts
|
import { Injectable } from '@angular/core';
import _ from 'lodash';
import { CephSharedModule } from './ceph-shared.module';
import { PgCategory } from './pg-category.model';
@Injectable({
providedIn: CephSharedModule
})
export class PgCategoryService {
private categories: object;
constructor() {
this.categories = this.createCategories();
}
getAllTypes() {
return PgCategory.VALID_CATEGORIES;
}
getTypeByStates(pgStatesText: string): string {
const pgStates = this.getPgStatesFromText(pgStatesText);
if (pgStates.length === 0) {
return PgCategory.CATEGORY_UNKNOWN;
}
const intersections = _.zipObject(
PgCategory.VALID_CATEGORIES,
PgCategory.VALID_CATEGORIES.map(
(category) => _.intersection(this.categories[category].states, pgStates).length
)
);
if (intersections[PgCategory.CATEGORY_WARNING] > 0) {
return PgCategory.CATEGORY_WARNING;
}
const pgWorkingStates = intersections[PgCategory.CATEGORY_WORKING];
if (pgStates.length > intersections[PgCategory.CATEGORY_CLEAN] + pgWorkingStates) {
return PgCategory.CATEGORY_UNKNOWN;
}
return pgWorkingStates ? PgCategory.CATEGORY_WORKING : PgCategory.CATEGORY_CLEAN;
}
private createCategories() {
return _.zipObject(
PgCategory.VALID_CATEGORIES,
PgCategory.VALID_CATEGORIES.map((category) => new PgCategory(category))
);
}
private getPgStatesFromText(pgStatesText: string) {
const pgStates = pgStatesText
.replace(/[^a-z_]+/g, ' ')
.trim()
.split(' ');
return _.uniq(pgStates);
}
}
| 1,611 | 24.1875 | 87 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/device-list/device-list.component.html
|
<cd-table *ngIf="hostname || osdId !== null"
[data]="devices"
[columns]="columns"></cd-table>
<cd-alert-panel type="warning"
*ngIf="hostname === '' && osdId === null"
i18n>Neither hostname nor OSD ID given</cd-alert-panel>
<ng-template #deviceLocation
let-value="value">
<ng-container *ngFor="let location of value">
<cd-label *ngIf="location.host === hostname"
[value]="location.dev"></cd-label>
</ng-container>
</ng-template>
<ng-template #daemonName
let-value="value">
<ng-container [ngTemplateOutlet]="osdId !== null ? osdIdDaemon : readableDaemons"
[ngTemplateOutletContext]="{daemons: value}">
</ng-container>
</ng-template>
<ng-template #osdIdDaemon
let-daemons="daemons">
<ng-container *ngFor="let daemon of daemons">
<cd-label *ngIf="daemon.includes(osdId)"
[value]="daemon"></cd-label>
</ng-container>
</ng-template>
<ng-template #readableDaemons
let-daemons="daemons">
<ng-container *ngFor="let daemon of daemons">
<cd-label class="me-1"
[value]="daemon"></cd-label>
</ng-container>
</ng-template>
<ng-template #lifeExpectancy
let-value="value">
<span *ngIf="!value.life_expectancy_enabled"
i18n>{{ "" | notAvailable }}</span>
<span *ngIf="value.min && !value.max">> {{value.min | i18nPlural: translationMapping}}</span>
<span *ngIf="value.max && !value.min">< {{value.max | i18nPlural: translationMapping}}</span>
<span *ngIf="value.max && value.min">{{value.min}} to {{value.max | i18nPlural: translationMapping}}</span>
</ng-template>
<ng-template #lifeExpectancyTimestamp
let-value="value">
{{value}}
</ng-template>
| 1,779 | 31.962963 | 109 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/device-list/device-list.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { DeviceListComponent } from './device-list.component';
describe('DeviceListComponent', () => {
let component: DeviceListComponent;
let fixture: ComponentFixture<DeviceListComponent>;
configureTestBed({
declarations: [DeviceListComponent],
imports: [SharedModule, HttpClientTestingModule]
});
beforeEach(() => {
fixture = TestBed.createComponent(DeviceListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 817 | 29.296296 | 71 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/device-list/device-list.component.ts
|
import { DatePipe } from '@angular/common';
import { Component, Input, OnChanges, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { HostService } from '~/app/shared/api/host.service';
import { OsdService } from '~/app/shared/api/osd.service';
import { CellTemplate } from '~/app/shared/enum/cell-template.enum';
import { CdTableColumn } from '~/app/shared/models/cd-table-column';
import { CdDevice } from '~/app/shared/models/devices';
@Component({
selector: 'cd-device-list',
templateUrl: './device-list.component.html',
styleUrls: ['./device-list.component.scss']
})
export class DeviceListComponent implements OnChanges, OnInit {
@Input()
hostname = '';
@Input()
osdId: number = null;
@Input()
osdList = false;
@ViewChild('deviceLocation', { static: true })
locationTemplate: TemplateRef<any>;
@ViewChild('daemonName', { static: true })
daemonNameTemplate: TemplateRef<any>;
@ViewChild('lifeExpectancy', { static: true })
lifeExpectancyTemplate: TemplateRef<any>;
@ViewChild('lifeExpectancyTimestamp', { static: true })
lifeExpectancyTimestampTemplate: TemplateRef<any>;
devices: CdDevice[] = null;
columns: CdTableColumn[] = [];
translationMapping = {
'=1': '# week',
other: '# weeks'
};
constructor(
private hostService: HostService,
private datePipe: DatePipe,
private osdService: OsdService
) {}
ngOnInit() {
this.columns = [
{ prop: 'devid', name: $localize`Device ID`, minWidth: 200 },
{
prop: 'state',
name: $localize`State of Health`,
flexGrow: 1,
cellTransformation: CellTemplate.badge,
customTemplateConfig: {
map: {
good: { value: $localize`Good`, class: 'badge-success' },
warning: { value: $localize`Warning`, class: 'badge-warning' },
bad: { value: $localize`Bad`, class: 'badge-danger' },
stale: { value: $localize`Stale`, class: 'badge-info' },
unknown: { value: $localize`Unknown`, class: 'badge-dark' }
}
}
},
{
prop: 'life_expectancy_weeks',
name: $localize`Life Expectancy`,
cellTemplate: this.lifeExpectancyTemplate
},
{
prop: 'life_expectancy_stamp',
name: $localize`Prediction Creation Date`,
cellTemplate: this.lifeExpectancyTimestampTemplate,
pipe: this.datePipe,
isHidden: true
},
{ prop: 'location', name: $localize`Device Name`, cellTemplate: this.locationTemplate },
{ prop: 'daemons', name: $localize`Daemons`, cellTemplate: this.daemonNameTemplate }
];
}
ngOnChanges() {
const updateDevicesFn = (devices: CdDevice[]) => (this.devices = devices);
if (this.osdList && this.osdId !== null) {
this.osdService.getDevices(this.osdId).subscribe(updateDevicesFn);
} else if (this.hostname) {
this.hostService.getDevices(this.hostname).subscribe(updateDevicesFn);
}
}
}
| 2,974 | 32.055556 | 94 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/feedback/feedback.component.html
|
<cd-modal [modalRef]="activeModal">
<div class="modal-title"
i18n>Report an issue</div>
<div class="modal-content">
<form name="feedbackForm"
[formGroup]="feedbackForm"
#formDir="ngForm">
<div class="modal-body">
<cd-alert-panel *ngIf="!isFeedbackEnabled"
type="error"
i18n>Feedback module is not enabled. Please enable it from <a (click)="redirect()">Cluster-> Manager Modules.</a>
</cd-alert-panel>
<!-- api_key -->
<div class="form-group row mt-3"
*ngIf="!isAPIKeySet">
<label class="cd-col-form-label required"
for="api_key"
i18n>Ceph Tracker API Key</label>
<div class="cd-col-form-input">
<input id="api_key"
type="password"
formControlName="api_key"
class="form-control"
placeholder="Add Ceph tracker API key">
<span class="invalid-feedback"
*ngIf="feedbackForm.showError('api_key', formDir, 'required')"
i18n>Ceph Tracker API key is required.</span>
<span class="invalid-feedback"
*ngIf="feedbackForm.showError('api_key', formDir, 'invalidApiKey')"
i18n>Ceph Tracker API key is invalid.</span>
</div>
</div>
<!-- project -->
<div class="form-group row">
<label class="cd-col-form-label required"
for="project"
i18n>Project name</label>
<div class="cd-col-form-input">
<select class="form-control"
id="project"
formControlName="project">
<option ngValue=""
i18n>-- Select a project --</option>
<option *ngFor="let projectName of project"
[value]="projectName">{{ projectName }}</option>
</select>
<span class="invalid-feedback"
*ngIf="feedbackForm.showError('project', formDir, 'required')"
i18n>Project name is required.</span>
</div>
</div>
<!-- tracker -->
<div class="form-group row">
<label class="cd-col-form-label required"
for="tracker"
i18n>Tracker</label>
<div class="cd-col-form-input">
<select class="form-control"
id="tracker"
formControlName="tracker">
<option ngValue=""
i18n>-- Select a tracker --</option>
<option *ngFor="let trackerName of tracker"
[value]="trackerName">{{ trackerName }}</option>
</select>
<span class="invalid-feedback"
*ngIf="feedbackForm.showError('tracker', formDir, 'required')"
i18n>Tracker name is required.</span>
</div>
</div>
<!-- subject -->
<div class="form-group row">
<label class="cd-col-form-label required"
for="subject"
i18n>Subject</label>
<div class="cd-col-form-input">
<input id="subject"
type="text"
formControlName="subject"
class="form-control"
placeholder="Add issue title">
<span class="invalid-feedback"
*ngIf="feedbackForm.showError('subject', formDir, 'required')"
i18n>Subject is required.</span>
</div>
</div>
<!-- description -->
<div class="form-group row">
<label class="cd-col-form-label required"
for="description"
i18n>Description</label>
<div class="cd-col-form-input">
<textarea id="description"
type="text"
formControlName="description"
class="form-control"
placeholder="Add issue description">
</textarea>
<span class="invalid-feedback"
*ngIf="feedbackForm.showError('description', formDir, 'required')"
i18n>Description is required.</span>
</div>
</div>
</div>
<div class="modal-footer">
<cd-form-button-panel (submitActionEvent)="onSubmit()"
[form]="feedbackForm"
[submitText]="actionLabels.SUBMIT"
wrappingClass="text-right">
</cd-form-button-panel>
</div>
</form>
</div>
</cd-modal>
| 4,717 | 37.991736 | 137 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/feedback/feedback.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ToastrModule } from 'ngx-toastr';
import { throwError } from 'rxjs';
import { FeedbackService } from '~/app/shared/api/feedback.service';
import { ComponentsModule } from '~/app/shared/components/components.module';
import { configureTestBed, FormHelper } from '~/testing/unit-test-helper';
import { FeedbackComponent } from './feedback.component';
describe('FeedbackComponent', () => {
let component: FeedbackComponent;
let fixture: ComponentFixture<FeedbackComponent>;
let feedbackService: FeedbackService;
let formHelper: FormHelper;
configureTestBed({
imports: [
ComponentsModule,
HttpClientTestingModule,
RouterTestingModule,
ReactiveFormsModule,
ToastrModule.forRoot()
],
declarations: [FeedbackComponent],
providers: [NgbActiveModal]
});
beforeEach(() => {
fixture = TestBed.createComponent(FeedbackComponent);
component = fixture.componentInstance;
feedbackService = TestBed.inject(FeedbackService);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should open the form in a modal', () => {
const nativeEl = fixture.debugElement.nativeElement;
expect(nativeEl.querySelector('cd-modal')).not.toBe(null);
});
it('should redirect to mgr-modules if feedback module is not enabled', () => {
spyOn(feedbackService, 'isKeyExist').and.returnValue(throwError({ status: 400 }));
component.ngOnInit();
expect(component.isFeedbackEnabled).toEqual(false);
expect(component.feedbackForm.disabled).toBeTruthy();
});
it('should test invalid api-key', () => {
component.ngOnInit();
formHelper = new FormHelper(component.feedbackForm);
spyOn(feedbackService, 'createIssue').and.returnValue(throwError({ status: 400 }));
formHelper.setValue('api_key', 'invalidkey');
formHelper.setValue('project', 'dashboard');
formHelper.setValue('tracker', 'bug');
formHelper.setValue('subject', 'foo');
formHelper.setValue('description', 'foo');
component.onSubmit();
formHelper.expectError('api_key', 'invalidApiKey');
});
});
| 2,454 | 32.175676 | 87 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/feedback/feedback.component.ts
|
import { Component, OnDestroy, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NgbActiveModal, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { Subscription } from 'rxjs';
import { FeedbackService } from '~/app/shared/api/feedback.service';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { NotificationType } from '~/app/shared/enum/notification-type.enum';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { NotificationService } from '~/app/shared/services/notification.service';
@Component({
selector: 'cd-feedback',
templateUrl: './feedback.component.html',
styleUrls: ['./feedback.component.scss']
})
export class FeedbackComponent implements OnInit, OnDestroy {
title = 'Feedback';
project: any = [
'dashboard',
'block',
'objects',
'file_system',
'ceph_manager',
'orchestrator',
'ceph_volume',
'core_ceph'
];
tracker: string[] = ['bug', 'feature'];
api_key: string;
keySub: Subscription;
feedbackForm: CdFormGroup;
isAPIKeySet = false;
isFeedbackEnabled = true;
constructor(
private feedbackService: FeedbackService,
public activeModal: NgbActiveModal,
public actionLabels: ActionLabelsI18n,
public secondaryModal: NgbModal,
private notificationService: NotificationService,
private router: Router
) {}
ngOnInit() {
this.createForm();
this.keySub = this.feedbackService.isKeyExist().subscribe({
next: (data: boolean) => {
this.isAPIKeySet = data;
if (this.isAPIKeySet) {
this.feedbackForm.get('api_key').clearValidators();
}
},
error: () => {
this.isFeedbackEnabled = false;
this.feedbackForm.disable();
}
});
}
private createForm() {
this.feedbackForm = new CdFormGroup({
project: new FormControl('', Validators.required),
tracker: new FormControl('', Validators.required),
subject: new FormControl('', Validators.required),
description: new FormControl('', Validators.required),
api_key: new FormControl('', Validators.required)
});
}
ngOnDestroy() {
this.keySub.unsubscribe();
}
onSubmit() {
this.feedbackService
.createIssue(
this.feedbackForm.controls['project'].value,
this.feedbackForm.controls['tracker'].value,
this.feedbackForm.controls['subject'].value,
this.feedbackForm.controls['description'].value,
this.feedbackForm.controls['api_key'].value
)
.subscribe({
next: (result) => {
this.notificationService.show(
NotificationType.success,
$localize`Issue successfully created on Ceph Issue tracker`,
`Go to the tracker: <a href="https://tracker.ceph.com/issues/${result['message']['issue']['id']}" target="_blank"> ${result['message']['issue']['id']} </a>`
);
},
error: () => {
this.feedbackForm.get('api_key').setErrors({ invalidApiKey: true });
this.feedbackForm.setErrors({ cdSubmitButton: true });
},
complete: () => {
this.activeModal.close();
}
});
}
redirect() {
this.activeModal.close();
this.router.navigate(['/mgr-modules']);
}
}
| 3,362 | 29.572727 | 168 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/smart-list/smart-list.component.html
|
<ng-container *ngIf="!loading; else isLoading">
<cd-alert-panel *ngIf="error"
type="error"
i18n>Failed to retrieve SMART data.</cd-alert-panel>
<cd-alert-panel *ngIf="incompatible"
type="warning"
i18n>The data received has the JSON format version 2.x and is currently incompatible with the
dashboard.</cd-alert-panel>
<ng-container *ngIf="!error && !incompatible">
<cd-alert-panel *ngIf="data | pipeFunction:isEmpty"
type="info"
i18n>No SMART data available.</cd-alert-panel>
<ng-container *ngIf="!(data | pipeFunction:isEmpty)">
<nav ngbNav
#nav="ngbNav"
class="nav-tabs">
<ng-container ngbNavItem
*ngFor="let device of data | keyvalue">
<a ngbNavLink>{{ device.value.device }} ({{ device.value.identifier }})</a>
<ng-template ngbNavContent>
<ng-container *ngIf="device.value.error; else noError">
<cd-alert-panel id="alert-error"
type="warning">{{ device.value.userMessage }}</cd-alert-panel>
</ng-container>
<ng-template #noError>
<cd-alert-panel *ngIf="device.value.info?.smart_status | pipeFunction:isEmpty; else hasSmartStatus"
id="alert-self-test-unknown"
size="slim"
type="warning"
i18n-title
title="SMART overall-health self-assessment test result"
i18n>unknown</cd-alert-panel>
<ng-template #hasSmartStatus>
<!-- HDD/NVMe self test -->
<ng-container *ngIf="device.value.info.smart_status.passed; else selfTestFailed">
<cd-alert-panel id="alert-self-test-passed"
size="slim"
type="info"
i18n-title
title="SMART overall-health self-assessment test result"
i18n>passed</cd-alert-panel>
</ng-container>
<ng-template #selfTestFailed>
<cd-alert-panel id="alert-self-test-failed"
size="slim"
type="warning"
i18n-title
title="SMART overall-health self-assessment test result"
i18n>failed</cd-alert-panel>
</ng-template>
</ng-template>
</ng-template>
<ng-container *ngIf="!(device.value.info | pipeFunction:isEmpty) || !(device.value.smart | pipeFunction:isEmpty)">
<nav ngbNav
#innerNav="ngbNav"
class="nav-tabs">
<li [ngbNavItem]="1">
<a ngbNavLink
i18n>Device Information</a>
<ng-template ngbNavContent>
<cd-table-key-value *ngIf="!(device.value.info | pipeFunction:isEmpty)"
[renderObjects]="true"
[data]="device.value.info"></cd-table-key-value>
<cd-alert-panel *ngIf="device.value.info | pipeFunction:isEmpty"
id="alert-device-info-unavailable"
type="info"
i18n>No device information available for this device.</cd-alert-panel>
</ng-template>
</li>
<li [ngbNavItem]="2">
<a ngbNavLink
i18n>SMART</a>
<ng-template ngbNavContent>
<cd-table *ngIf="device.value.smart?.attributes"
[data]="device.value.smart.attributes.table"
updateSelectionOnRefresh="never"
[columns]="smartDataColumns"></cd-table>
<cd-table-key-value *ngIf="device.value.smart?.scsi_error_counter_log"
[renderObjects]="true"
[data]="device.value.smart"
updateSelectionOnRefresh="never"></cd-table-key-value>
<cd-table-key-value *ngIf="device.value.smart?.nvmeData"
[renderObjects]="true"
[data]="device.value.smart.nvmeData"
updateSelectionOnRefresh="never"></cd-table-key-value>
<cd-alert-panel *ngIf="!device.value.smart?.attributes && !device.value.smart?.nvmeData && !device.value.smart?.scsi_error_counter_log"
id="alert-device-smart-data-unavailable"
type="info"
i18n>No SMART data available for this device.</cd-alert-panel>
</ng-template>
</li>
</nav>
<div [ngbNavOutlet]="innerNav"></div>
</ng-container>
</ng-template>
</ng-container>
</nav>
<div [ngbNavOutlet]="nav"></div>
</ng-container>
</ng-container>
</ng-container>
<ng-template #isLoading>
<cd-loading-panel i18n>SMART data is loading.</cd-loading-panel>
</ng-template>
| 5,596 | 49.423423 | 155 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/smart-list/smart-list.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { SimpleChange, SimpleChanges } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { NgxPipeFunctionModule } from 'ngx-pipe-function';
import { of } from 'rxjs';
import { OsdService } from '~/app/shared/api/osd.service';
import {
AtaSmartDataV1,
IscsiSmartDataV1,
NvmeSmartDataV1,
SmartDataResult
} from '~/app/shared/models/smart';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { SmartListComponent } from './smart-list.component';
describe('OsdSmartListComponent', () => {
let component: SmartListComponent;
let fixture: ComponentFixture<SmartListComponent>;
let osdService: OsdService;
const SMART_DATA_ATA_VERSION_1_0: AtaSmartDataV1 = require('./fixtures/smart_data_version_1_0_ata_response.json');
const SMART_DATA_NVME_VERSION_1_0: NvmeSmartDataV1 = require('./fixtures/smart_data_version_1_0_nvme_response.json');
const SMART_DATA_SCSI_VERSION_1_0: IscsiSmartDataV1 = require('./fixtures/smart_data_version_1_0_scsi_response.json');
/**
* Sets attributes for _all_ returned devices according to the given path. The syntax is the same
* as used in lodash.set().
*
* @example
* patchData('json_format_version', [2, 0]) // sets the value of `json_format_version` to [2, 0]
* // for all devices
*
* patchData('json_format_version[0]', 2) // same result
*
* @param path The path to the attribute
* @param newValue The new value
*/
const patchData = (path: string, newValue: any): any => {
return _.reduce(
_.cloneDeep(SMART_DATA_ATA_VERSION_1_0),
(result: object, dataObj, deviceId) => {
result[deviceId] = _.set<any>(dataObj, path, newValue);
return result;
},
{}
);
};
/**
* Initializes the component after it spied upon the `getSmartData()` method
* of `OsdService`. Determines which data is returned.
*/
const initializeComponentWithData = (
dataType: 'hdd_v1' | 'nvme_v1' | 'hdd_v1_scsi',
patch: { [path: string]: any } = null,
simpleChanges?: SimpleChanges
) => {
let data: AtaSmartDataV1 | NvmeSmartDataV1 | IscsiSmartDataV1;
switch (dataType) {
case 'hdd_v1':
data = SMART_DATA_ATA_VERSION_1_0;
break;
case 'nvme_v1':
data = SMART_DATA_NVME_VERSION_1_0;
break;
case 'hdd_v1_scsi':
data = SMART_DATA_SCSI_VERSION_1_0;
break;
}
if (_.isObject(patch)) {
_.each(patch, (replacement, path) => {
data = patchData(path, replacement);
});
}
spyOn(osdService, 'getSmartData').and.callFake(() => of(data));
component.ngOnInit();
const changes: SimpleChanges = simpleChanges || {
osdId: new SimpleChange(null, 0, true)
};
component.ngOnChanges(changes);
};
/**
* Verify an alert panel and its attributes.
*
* @param selector The CSS selector for the alert panel.
* @param panelTitle The title should be displayed.
* @param panelType Alert level of panel. Can be in `warning` or `info`.
* @param panelSize Pass `slim` for slim alert panel.
*/
const verifyAlertPanel = (
selector: string,
panelTitle: string,
panelType: 'warning' | 'info',
panelSize?: 'slim'
) => {
const alertPanel = fixture.debugElement.query(By.css(selector));
expect(component.incompatible).toBe(false);
expect(component.loading).toBe(false);
expect(alertPanel.attributes.type).toBe(panelType);
if (panelSize === 'slim') {
expect(alertPanel.attributes.title).toBe(panelTitle);
expect(alertPanel.attributes.size).toBe(panelSize);
} else {
const panelText = alertPanel.query(By.css('.alert-panel-text'));
expect(panelText.nativeElement.textContent).toBe(panelTitle);
}
};
configureTestBed({
declarations: [SmartListComponent],
imports: [
BrowserAnimationsModule,
SharedModule,
HttpClientTestingModule,
NgbNavModule,
NgxPipeFunctionModule
]
});
beforeEach(() => {
fixture = TestBed.createComponent(SmartListComponent);
component = fixture.componentInstance;
fixture.detectChanges();
osdService = TestBed.inject(OsdService);
});
it('should create', () => {
expect(component).toBeTruthy();
});
describe('tests ATA version 1.x', () => {
beforeEach(() => initializeComponentWithData('hdd_v1'));
it('should return with proper keys', () => {
_.each(component.data, (smartData, _deviceId) => {
expect(_.keys(smartData)).toEqual(['info', 'smart', 'device', 'identifier']);
});
});
it('should not contain excluded keys in `info`', () => {
const excludes = [
'ata_smart_attributes',
'ata_smart_selective_self_test_log',
'ata_smart_data'
];
_.each(component.data, (smartData: SmartDataResult, _deviceId) => {
_.each(excludes, (exclude) => expect(smartData.info[exclude]).toBeUndefined());
});
});
});
describe('tests NVMe version 1.x', () => {
beforeEach(() => initializeComponentWithData('nvme_v1'));
it('should return with proper keys', () => {
_.each(component.data, (smartData, _deviceId) => {
expect(_.keys(smartData)).toEqual(['info', 'smart', 'device', 'identifier']);
});
});
it('should not contain excluded keys in `info`', () => {
const excludes = ['nvme_smart_health_information_log'];
_.each(component.data, (smartData: SmartDataResult, _deviceId) => {
_.each(excludes, (exclude) => expect(smartData.info[exclude]).toBeUndefined());
});
});
});
describe('tests SCSI version 1.x', () => {
beforeEach(() => initializeComponentWithData('hdd_v1_scsi'));
it('should return with proper keys', () => {
_.each(component.data, (smartData, _deviceId) => {
expect(_.keys(smartData)).toEqual(['info', 'smart', 'device', 'identifier']);
});
});
it('should not contain excluded keys in `info`', () => {
const excludes = ['scsi_error_counter_log', 'scsi_grown_defect_list'];
_.each(component.data, (smartData: SmartDataResult, _deviceId) => {
_.each(excludes, (exclude) => expect(smartData.info[exclude]).toBeUndefined());
});
});
});
it('should not work for version 2.x', () => {
initializeComponentWithData('nvme_v1', { json_format_version: [2, 0] });
expect(component.data).toEqual({});
expect(component.incompatible).toBeTruthy();
});
it('should display info panel for passed self test', () => {
initializeComponentWithData('hdd_v1');
fixture.detectChanges();
verifyAlertPanel(
'cd-alert-panel#alert-self-test-passed',
'SMART overall-health self-assessment test result',
'info',
'slim'
);
});
it('should display warning panel for failed self test', () => {
initializeComponentWithData('hdd_v1', { 'smart_status.passed': false });
fixture.detectChanges();
verifyAlertPanel(
'cd-alert-panel#alert-self-test-failed',
'SMART overall-health self-assessment test result',
'warning',
'slim'
);
});
it('should display warning panel for unknown self test', () => {
initializeComponentWithData('hdd_v1', { smart_status: undefined });
fixture.detectChanges();
verifyAlertPanel(
'cd-alert-panel#alert-self-test-unknown',
'SMART overall-health self-assessment test result',
'warning',
'slim'
);
});
it('should display info panel for empty device info', () => {
initializeComponentWithData('hdd_v1');
const deviceId: string = _.keys(component.data)[0];
component.data[deviceId]['info'] = {};
fixture.detectChanges();
component.nav.select(1);
fixture.detectChanges();
verifyAlertPanel(
'cd-alert-panel#alert-device-info-unavailable',
'No device information available for this device.',
'info'
);
});
it('should display info panel for empty SMART data', () => {
initializeComponentWithData('hdd_v1');
const deviceId: string = _.keys(component.data)[0];
component.data[deviceId]['smart'] = {};
fixture.detectChanges();
component.nav.select(2);
fixture.detectChanges();
verifyAlertPanel(
'cd-alert-panel#alert-device-smart-data-unavailable',
'No SMART data available for this device.',
'info'
);
});
});
| 8,773 | 32.109434 | 120 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/shared/smart-list/smart-list.component.ts
|
import { Component, Input, OnChanges, OnInit, SimpleChanges, ViewChild } from '@angular/core';
import { NgbNav } from '@ng-bootstrap/ng-bootstrap';
import _ from 'lodash';
import { HostService } from '~/app/shared/api/host.service';
import { OsdService } from '~/app/shared/api/osd.service';
import { CdTableColumn } from '~/app/shared/models/cd-table-column';
import {
AtaSmartDataV1,
IscsiSmartDataV1,
NvmeSmartDataV1,
SmartDataResult,
SmartError,
SmartErrorResult
} from '~/app/shared/models/smart';
@Component({
selector: 'cd-smart-list',
templateUrl: './smart-list.component.html',
styleUrls: ['./smart-list.component.scss']
})
export class SmartListComponent implements OnInit, OnChanges {
@ViewChild('innerNav')
nav: NgbNav;
@Input()
osdId: number = null;
@Input()
hostname: string = null;
loading = false;
incompatible = false;
error = false;
data: { [deviceId: string]: SmartDataResult | SmartErrorResult } = {};
smartDataColumns: CdTableColumn[];
scsiSmartDataColumns: CdTableColumn[];
isEmpty = _.isEmpty;
constructor(private osdService: OsdService, private hostService: HostService) {}
isSmartError(data: any): data is SmartError {
return _.get(data, 'error') !== undefined;
}
isNvmeSmartData(data: any): data is NvmeSmartDataV1 {
return _.get(data, 'device.protocol', '').toLowerCase() === 'nvme';
}
isAtaSmartData(data: any): data is AtaSmartDataV1 {
return _.get(data, 'device.protocol', '').toLowerCase() === 'ata';
}
isIscsiSmartData(data: any): data is IscsiSmartDataV1 {
return _.get(data, 'device.protocol', '').toLowerCase() === 'scsi';
}
private fetchData(data: any) {
const result: { [deviceId: string]: SmartDataResult | SmartErrorResult } = {};
_.each(data, (smartData, deviceId) => {
if (this.isSmartError(smartData)) {
let userMessage = '';
if (smartData.smartctl_error_code === -22) {
userMessage = $localize`Smartctl has received an unknown argument \
(error code ${smartData.smartctl_error_code}). \
You may be using an incompatible version of smartmontools. Version >= 7.0 of \
smartmontools is required to successfully retrieve data.`;
} else {
userMessage = $localize`An error with error code ${smartData.smartctl_error_code} occurred.`;
}
const _result: SmartErrorResult = {
error: smartData.error,
smartctl_error_code: smartData.smartctl_error_code,
smartctl_output: smartData.smartctl_output,
userMessage: userMessage,
device: smartData.dev,
identifier: smartData.nvme_vendor
};
result[deviceId] = _result;
return;
}
// Prepare S.M.A.R.T data
if (smartData.json_format_version[0] === 1) {
// Version 1.x
if (this.isAtaSmartData(smartData)) {
result[deviceId] = this.extractAtaData(smartData);
} else if (this.isIscsiSmartData(smartData)) {
result[deviceId] = this.extractIscsiData(smartData);
} else if (this.isNvmeSmartData(smartData)) {
result[deviceId] = this.extractNvmeData(smartData);
}
return;
} else {
this.incompatible = true;
}
});
this.data = result;
this.loading = false;
}
private extractNvmeData(smartData: NvmeSmartDataV1): SmartDataResult {
const info = _.omitBy(smartData, (_value: string, key: string) =>
['nvme_smart_health_information_log'].includes(key)
);
return {
info: info,
smart: {
nvmeData: smartData.nvme_smart_health_information_log
},
device: smartData.device.name,
identifier: smartData.serial_number
};
}
private extractIscsiData(smartData: IscsiSmartDataV1): SmartDataResult {
const info = _.omitBy(smartData, (_value: string, key: string) =>
['scsi_error_counter_log', 'scsi_grown_defect_list'].includes(key)
);
return {
info: info,
smart: {
scsi_error_counter_log: smartData.scsi_error_counter_log,
scsi_grown_defect_list: smartData.scsi_grown_defect_list
},
device: info.device.name,
identifier: info.serial_number
};
}
private extractAtaData(smartData: AtaSmartDataV1): SmartDataResult {
const info = _.omitBy(smartData, (_value: string, key: string) =>
['ata_smart_attributes', 'ata_smart_selective_self_test_log', 'ata_smart_data'].includes(key)
);
return {
info: info,
smart: {
attributes: smartData.ata_smart_attributes,
data: smartData.ata_smart_data
},
device: info.device.name,
identifier: info.serial_number
};
}
private updateData() {
this.loading = true;
if (this.osdId !== null) {
this.osdService.getSmartData(this.osdId).subscribe({
next: this.fetchData.bind(this),
error: (error) => {
error.preventDefault();
this.error = error;
this.loading = false;
}
});
} else if (this.hostname !== null) {
this.hostService.getSmartData(this.hostname).subscribe({
next: this.fetchData.bind(this),
error: (error) => {
error.preventDefault();
this.error = error;
this.loading = false;
}
});
}
}
ngOnInit() {
this.smartDataColumns = [
{ prop: 'id', name: $localize`ID` },
{ prop: 'name', name: $localize`Name` },
{ prop: 'raw.value', name: $localize`Raw` },
{ prop: 'thresh', name: $localize`Threshold` },
{ prop: 'value', name: $localize`Value` },
{ prop: 'when_failed', name: $localize`When Failed` },
{ prop: 'worst', name: $localize`Worst` }
];
this.scsiSmartDataColumns = [
{
prop: 'correction_algorithm_invocations',
name: $localize`Correction Algorithm Invocations`
},
{
prop: 'errors_corrected_by_eccdelayed',
name: $localize`Errors Corrected by ECC (Delayed)`
},
{ prop: 'errors_corrected_by_eccfast', name: $localize`Errors Corrected by ECC (Fast)` },
{
prop: 'errors_corrected_by_rereads_rewrites',
name: $localize`Errors Corrected by Rereads/Rewrites`
},
{ prop: 'gigabytes_processed', name: $localize`Gigabyes Processed` },
{ prop: 'total_errors_corrected', name: $localize`Total Errors Corrected` },
{ prop: 'total_uncorrected_errors', name: $localize`Total Errors Uncorrected` }
];
}
ngOnChanges(changes: SimpleChanges): void {
this.data = {}; // Clear previous data
if (changes.osdId) {
this.osdId = changes.osdId.currentValue;
} else if (changes.hostname) {
this.hostname = changes.hostname.currentValue;
}
this.updateData();
}
}
| 6,773 | 30.802817 | 103 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/core.module.ts
|
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap';
import { BlockUIModule } from 'ng-block-ui';
import { ContextComponent } from '~/app/core/context/context.component';
import { SharedModule } from '~/app/shared/shared.module';
import { ErrorComponent } from './error/error.component';
import { BlankLayoutComponent } from './layouts/blank-layout/blank-layout.component';
import { LoginLayoutComponent } from './layouts/login-layout/login-layout.component';
import { WorkbenchLayoutComponent } from './layouts/workbench-layout/workbench-layout.component';
import { NavigationModule } from './navigation/navigation.module';
@NgModule({
imports: [
BlockUIModule.forRoot(),
CommonModule,
NavigationModule,
NgbDropdownModule,
RouterModule,
SharedModule
],
exports: [NavigationModule],
declarations: [
ContextComponent,
WorkbenchLayoutComponent,
BlankLayoutComponent,
LoginLayoutComponent,
ErrorComponent
]
})
export class CoreModule {}
| 1,140 | 31.6 | 97 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/auth.module.ts
|
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RouterModule, Routes } from '@angular/router';
import { NgbNavModule, NgbPopoverModule } from '@ng-bootstrap/ng-bootstrap';
import { NgxPipeFunctionModule } from 'ngx-pipe-function';
import { ActionLabels, URLVerbs } from '~/app/shared/constants/app.constants';
import { SharedModule } from '~/app/shared/shared.module';
import { LoginPasswordFormComponent } from './login-password-form/login-password-form.component';
import { LoginComponent } from './login/login.component';
import { RoleDetailsComponent } from './role-details/role-details.component';
import { RoleFormComponent } from './role-form/role-form.component';
import { RoleListComponent } from './role-list/role-list.component';
import { UserFormComponent } from './user-form/user-form.component';
import { UserListComponent } from './user-list/user-list.component';
import { UserPasswordFormComponent } from './user-password-form/user-password-form.component';
import { UserTabsComponent } from './user-tabs/user-tabs.component';
@NgModule({
imports: [
CommonModule,
FormsModule,
ReactiveFormsModule,
SharedModule,
NgbNavModule,
NgbPopoverModule,
NgxPipeFunctionModule,
RouterModule
],
declarations: [
LoginComponent,
LoginPasswordFormComponent,
RoleDetailsComponent,
RoleFormComponent,
RoleListComponent,
UserTabsComponent,
UserListComponent,
UserFormComponent,
UserPasswordFormComponent
]
})
export class AuthModule {}
const routes: Routes = [
{ path: '', redirectTo: 'users', pathMatch: 'full' },
{
path: 'users',
data: { breadcrumbs: 'Users' },
children: [
{ path: '', component: UserListComponent },
{
path: URLVerbs.CREATE,
component: UserFormComponent,
data: { breadcrumbs: ActionLabels.CREATE }
},
{
path: `${URLVerbs.EDIT}/:username`,
component: UserFormComponent,
data: { breadcrumbs: ActionLabels.EDIT }
}
]
},
{
path: 'roles',
data: { breadcrumbs: 'Roles' },
children: [
{ path: '', component: RoleListComponent },
{
path: URLVerbs.CREATE,
component: RoleFormComponent,
data: { breadcrumbs: ActionLabels.CREATE }
},
{
path: `${URLVerbs.EDIT}/:name`,
component: RoleFormComponent,
data: { breadcrumbs: ActionLabels.EDIT }
}
]
}
];
@NgModule({
imports: [AuthModule, RouterModule.forChild(routes)]
})
export class RoutedAuthModule {}
| 2,655 | 29.181818 | 97 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/login-password-form/login-password-form.component.html
|
<div>
<h2 i18n>Please set a new password.</h2>
<h4 i18n>You will be redirected to the login page afterwards.</h4>
<form #frm="ngForm"
[formGroup]="userForm"
novalidate>
<!-- Old password -->
<div class="form-group has-feedback">
<div class="input-group">
<input class="form-control"
type="password"
placeholder="Old password..."
id="oldpassword"
formControlName="oldpassword"
autocomplete="new-password"
autofocus>
<button class="btn btn-outline-light btn-password"
cdPasswordButton="oldpassword">
</button>
</div>
<span class="invalid-feedback"
*ngIf="userForm.showError('oldpassword', frm, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('oldpassword', frm, 'notmatch')"
i18n>The old and new passwords must be different.</span>
</div>
<!-- New password -->
<div class="form-group has-feedback">
<div class="input-group">
<input class="form-control"
type="password"
placeholder="New password..."
id="newpassword"
autocomplete="new-password"
formControlName="newpassword">
<button type="button"
class="btn btn-outline-light btn-password"
cdPasswordButton="newpassword">
</button>
</div>
<div class="password-strength-level">
<div class="{{ passwordStrengthLevelClass }}"
data-toggle="tooltip"
title="{{ passwordValuation }}">
</div>
</div>
<span class="invalid-feedback"
*ngIf="userForm.showError('newpassword', frm, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('newpassword', frm, 'notmatch')"
i18n>The old and new passwords must be different.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('newpassword', frm, 'passwordPolicy')">
{{ passwordValuation }}
</span>
</div>
<!-- Confirm new password -->
<div class="form-group has-feedback">
<div class="input-group">
<input class="form-control"
type="password"
autocomplete="new-password"
placeholder="Confirm new password..."
id="confirmnewpassword"
formControlName="confirmnewpassword">
<button class="btn btn-outline-light btn-password"
cdPasswordButton="confirmnewpassword">
</button>
</div>
<span class="invalid-feedback"
*ngIf="userForm.showError('confirmnewpassword', frm, 'required')"
i18n>This field is required.</span>
<span class="invalid-feedback"
*ngIf="userForm.showError('confirmnewpassword', frm, 'match')"
i18n>Password confirmation doesn't match the new password.</span>
</div>
<cd-form-button-panel (submitActionEvent)="onSubmit()"
(backActionEvent)="onCancel()"
[form]="userForm"
[disabled]="userForm.invalid"
[submitText]="(action | titlecase) + ' ' + (resource | upperFirst)"
wrappingClass="text-right"></cd-form-button-panel>
</form>
</div>
| 3,523 | 38.155556 | 93 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/login-password-form/login-password-form.component.spec.ts
|
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ReactiveFormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { ToastrModule } from 'ngx-toastr';
import { AuthService } from '~/app/shared/api/auth.service';
import { ComponentsModule } from '~/app/shared/components/components.module';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed, FormHelper } from '~/testing/unit-test-helper';
import { LoginPasswordFormComponent } from './login-password-form.component';
describe('LoginPasswordFormComponent', () => {
let component: LoginPasswordFormComponent;
let fixture: ComponentFixture<LoginPasswordFormComponent>;
let form: CdFormGroup;
let formHelper: FormHelper;
let httpTesting: HttpTestingController;
let router: Router;
let authStorageService: AuthStorageService;
let authService: AuthService;
configureTestBed({
imports: [
HttpClientTestingModule,
RouterTestingModule,
ReactiveFormsModule,
ComponentsModule,
ToastrModule.forRoot(),
SharedModule
],
declarations: [LoginPasswordFormComponent]
});
beforeEach(() => {
fixture = TestBed.createComponent(LoginPasswordFormComponent);
component = fixture.componentInstance;
httpTesting = TestBed.inject(HttpTestingController);
router = TestBed.inject(Router);
authStorageService = TestBed.inject(AuthStorageService);
authService = TestBed.inject(AuthService);
spyOn(router, 'navigate');
fixture.detectChanges();
form = component.userForm;
formHelper = new FormHelper(form);
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should submit', () => {
spyOn(component, 'onPasswordChange').and.callThrough();
spyOn(authService, 'logout');
spyOn(authStorageService, 'getUsername').and.returnValue('test1');
formHelper.setMultipleValues({
oldpassword: 'foo',
newpassword: 'bar'
});
formHelper.setValue('confirmnewpassword', 'bar', true);
component.onSubmit();
const request = httpTesting.expectOne('api/user/test1/change_password');
request.flush({});
expect(component.onPasswordChange).toHaveBeenCalled();
expect(authService.logout).toHaveBeenCalled();
});
it('should cancel', () => {
spyOn(authService, 'logout');
component.onCancel();
expect(authService.logout).toHaveBeenCalled();
});
});
| 2,755 | 34.333333 | 94 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/login-password-form/login-password-form.component.ts
|
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '~/app/shared/api/auth.service';
import { UserService } from '~/app/shared/api/user.service';
import { ActionLabelsI18n } from '~/app/shared/constants/app.constants';
import { CdFormBuilder } from '~/app/shared/forms/cd-form-builder';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { NotificationService } from '~/app/shared/services/notification.service';
import { PasswordPolicyService } from '~/app/shared/services/password-policy.service';
import { UserPasswordFormComponent } from '../user-password-form/user-password-form.component';
@Component({
selector: 'cd-login-password-form',
templateUrl: './login-password-form.component.html',
styleUrls: ['./login-password-form.component.scss']
})
export class LoginPasswordFormComponent extends UserPasswordFormComponent {
constructor(
public actionLabels: ActionLabelsI18n,
public notificationService: NotificationService,
public userService: UserService,
public authStorageService: AuthStorageService,
public formBuilder: CdFormBuilder,
public router: Router,
public passwordPolicyService: PasswordPolicyService,
public authService: AuthService
) {
super(
actionLabels,
notificationService,
userService,
authStorageService,
formBuilder,
router,
passwordPolicyService
);
}
onPasswordChange() {
// Logout here because changing the password will change the
// session token which will finally lead to a 401 when calling
// the REST API the next time. The API HTTP interceptor will
// then also redirect to the login page immediately.
this.authService.logout();
}
onCancel() {
this.authService.logout();
}
}
| 1,840 | 34.403846 | 95 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/login/login.component.html
|
<div class="container"
*ngIf="isLoginActive">
<h1 class="sr-only">Ceph login</h1>
<form name="loginForm"
(ngSubmit)="login()"
#loginForm="ngForm"
novalidate>
<!-- Username -->
<div class="form-group has-feedback d-flex flex-column py-3">
<label class="placeholder ps-3"
for="username"
i18n>Username</label>
<input id="username"
name="username"
[(ngModel)]="model.username"
#username="ngModel"
type="text"
[attr.aria-invalid]="username.invalid"
aria-labelledby="username"
class="form-control ps-3"
required
autofocus>
<div class="invalid-feedback ps-3"
*ngIf="(loginForm.submitted || username.dirty) && username.invalid"
i18n>Username is required</div>
</div>
<!-- Password -->
<div class="form-group has-feedback"
id="password-div">
<div class="input-group d-flex flex-nowrap">
<div class="d-flex flex-column flex-grow-1 py-3">
<label class="placeholder ps-3"
for="password"
i18n>Password</label>
<input id="password"
name="password"
[(ngModel)]="model.password"
#password="ngModel"
type="password"
[attr.aria-invalid]="password.invalid"
aria-labelledby="password"
class="form-control ps-3"
required>
<div class="invalid-feedback ps-3"
*ngIf="(loginForm.submitted || password.dirty) && password.invalid"
i18n>Password is required</div>
</div>
<span class="form-group-append">
<button type="button"
class="btn btn-outline-light btn-password h-100 px-4"
cdPasswordButton="password"
aria-label="toggle-password">
</button>
</span>
</div>
</div>
<input type="submit"
class="btn btn-accent px-5 py-2"
[disabled]="loginForm.invalid"
value="Log in"
i18n-value>
</form>
</div>
| 2,219 | 32.134328 | 82 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/login/login.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { AuthService } from '~/app/shared/api/auth.service';
import { configureTestBed } from '~/testing/unit-test-helper';
import { AuthModule } from '../auth.module';
import { LoginComponent } from './login.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let routerNavigateSpy: jasmine.Spy;
let authServiceLoginSpy: jasmine.Spy;
configureTestBed({
imports: [RouterTestingModule, HttpClientTestingModule, AuthModule]
});
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
routerNavigateSpy = spyOn(TestBed.inject(Router), 'navigate');
routerNavigateSpy.and.returnValue(true);
authServiceLoginSpy = spyOn(TestBed.inject(AuthService), 'login');
authServiceLoginSpy.and.returnValue(of(null));
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should ensure no modal dialogs are opened', () => {
component['modalService']['modalsCount'] = 2;
component.ngOnInit();
expect(component['modalService'].hasOpenModals()).toBeFalsy();
});
it('should not show create cluster wizard if cluster creation was successful', () => {
component.postInstalled = true;
component.login();
expect(routerNavigateSpy).toHaveBeenCalledTimes(1);
expect(routerNavigateSpy).toHaveBeenCalledWith(['/']);
});
it('should show create cluster wizard if cluster creation was failed', () => {
component.postInstalled = false;
component.login();
expect(routerNavigateSpy).toHaveBeenCalledTimes(1);
expect(routerNavigateSpy).toHaveBeenCalledWith(['/expand-cluster']);
});
});
| 2,013 | 33.135593 | 88 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/login/login.component.ts
|
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import _ from 'lodash';
import { AuthService } from '~/app/shared/api/auth.service';
import { Credentials } from '~/app/shared/models/credentials';
import { AuthStorageService } from '~/app/shared/services/auth-storage.service';
import { ModalService } from '~/app/shared/services/modal.service';
@Component({
selector: 'cd-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
model = new Credentials();
isLoginActive = false;
returnUrl: string;
postInstalled = false;
constructor(
private authService: AuthService,
private authStorageService: AuthStorageService,
private modalService: ModalService,
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
if (this.authStorageService.isLoggedIn()) {
this.router.navigate(['']);
} else {
// Make sure all open modal dialogs are closed. This might be
// necessary when the logged in user is redirected to the login
// page after a 401.
this.modalService.dismissAll();
let token: string = null;
if (window.location.hash.indexOf('access_token=') !== -1) {
token = window.location.hash.split('access_token=')[1];
const uri = window.location.toString();
window.history.replaceState({}, document.title, uri.split('?')[0]);
}
this.authService.check(token).subscribe((login: any) => {
if (login.login_url) {
this.postInstalled = login.cluster_status === 'POST_INSTALLED';
if (login.login_url === '#/login') {
this.isLoginActive = true;
} else {
window.location.replace(login.login_url);
}
} else {
this.authStorageService.set(
login.username,
login.permissions,
login.sso,
login.pwdExpirationDate
);
this.router.navigate(['']);
}
});
}
}
login() {
this.authService.login(this.model).subscribe(() => {
const urlPath = this.postInstalled ? '/' : '/expand-cluster';
let url = _.get(this.route.snapshot.queryParams, 'returnUrl', urlPath);
if (!this.postInstalled && this.route.snapshot.queryParams['returnUrl'] === '/dashboard') {
url = '/expand-cluster';
}
this.router.navigate([url]);
});
}
}
| 2,501 | 31.493506 | 97 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/role-details/role-details.component.html
|
<ng-container *ngIf="selection">
<cd-table [data]="scopes_permissions"
[columns]="columns"
columnMode="flex"
[toolHeader]="false"
[autoReload]="false"
[autoSave]="false"
[footer]="false"
[limit]="0">
</cd-table>
</ng-container>
| 316 | 25.416667 | 39 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/core/auth/role-details/role-details.component.spec.ts
|
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap';
import { SharedModule } from '~/app/shared/shared.module';
import { configureTestBed } from '~/testing/unit-test-helper';
import { RoleDetailsComponent } from './role-details.component';
describe('RoleDetailsComponent', () => {
let component: RoleDetailsComponent;
let fixture: ComponentFixture<RoleDetailsComponent>;
configureTestBed({
imports: [SharedModule, RouterTestingModule, HttpClientTestingModule, NgbNavModule],
declarations: [RoleDetailsComponent]
});
beforeEach(() => {
fixture = TestBed.createComponent(RoleDetailsComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should create scopes permissions [1/2]', () => {
component.scopes = ['log', 'rgw'];
component.selection = {
description: 'RGW Manager',
name: 'rgw-manager',
scopes_permissions: {
rgw: ['read', 'create', 'update', 'delete']
},
system: true
};
expect(component.scopes_permissions.length).toBe(0);
component.ngOnChanges();
expect(component.scopes_permissions).toEqual([
{ scope: 'log', read: false, create: false, update: false, delete: false },
{ scope: 'rgw', read: true, create: true, update: true, delete: true }
]);
});
it('should create scopes permissions [2/2]', () => {
component.scopes = ['cephfs', 'log', 'rgw'];
component.selection = {
description: 'Test',
name: 'test',
scopes_permissions: {
log: ['read', 'update'],
rgw: ['read', 'create', 'update']
},
system: false
};
expect(component.scopes_permissions.length).toBe(0);
component.ngOnChanges();
expect(component.scopes_permissions).toEqual([
{ scope: 'cephfs', read: false, create: false, update: false, delete: false },
{ scope: 'log', read: true, create: false, update: true, delete: false },
{ scope: 'rgw', read: true, create: true, update: true, delete: false }
]);
});
});
| 2,304 | 32.897059 | 88 |
ts
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.