Search is not available for this dataset
repo
stringlengths 2
152
⌀ | file
stringlengths 15
239
| code
stringlengths 0
58.4M
| file_length
int64 0
58.4M
| avg_line_length
float64 0
1.81M
| max_line_length
int64 0
12.7M
| extension_type
stringclasses 364
values |
---|---|---|---|---|---|---|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/ng-bootstrap-form-validation/cd-form-control.directive.spec.ts
|
/**
* MIT License
*
* Copyright (c) 2017 Kevin Kipp
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
* Based on https://github.com/third774/ng-bootstrap-form-validation
*/
import { NgForm } from '@angular/forms';
import { CdFormControlDirective } from './cd-form-control.directive';
describe('CdFormControlDirective', () => {
it('should create an instance', () => {
const directive = new CdFormControlDirective(new NgForm([], []));
expect(directive).toBeTruthy();
});
});
| 1,524 | 39.131579 | 81 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/ng-bootstrap-form-validation/cd-form-control.directive.ts
|
/**
* MIT License
*
* Copyright (c) 2017 Kevin Kipp
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
* Based on https://github.com/third774/ng-bootstrap-form-validation
*/
import { Directive, Host, HostBinding, Input, Optional, SkipSelf } from '@angular/core';
import { ControlContainer, FormControl } from '@angular/forms';
export function controlPath(name: string, parent: ControlContainer): string[] {
// tslint:disable-next-line:no-non-null-assertion
return [...parent.path!, name];
}
@Directive({
// eslint-disable-next-line
selector: '.form-control,.form-check-input,.custom-control-input'
})
export class CdFormControlDirective {
@Input()
formControlName: string;
@Input()
formControl: string;
@HostBinding('class.is-valid')
get validClass() {
if (!this.control) {
return false;
}
return this.control.valid && (this.control.touched || this.control.dirty);
}
@HostBinding('class.is-invalid')
get invalidClass() {
if (!this.control) {
return false;
}
return this.control.invalid && this.control.touched && this.control.dirty;
}
get path() {
return controlPath(this.formControlName, this.parent);
}
get control(): FormControl {
return this.formDirective && this.formDirective.getControl(this);
}
get formDirective(): any {
return this.parent ? this.parent.formDirective : null;
}
constructor(
// this value might be null, but we union type it as such until
// this issue is resolved: https://github.com/angular/angular/issues/25544
@Optional()
@Host()
@SkipSelf()
private parent: ControlContainer
) {}
}
| 2,670 | 31.180723 | 88 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/ng-bootstrap-form-validation/cd-form-group.directive.spec.ts
|
/**
* MIT License
*
* Copyright (c) 2017 Kevin Kipp
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
* Based on https://github.com/third774/ng-bootstrap-form-validation
*/
import { ElementRef } from '@angular/core';
import { CdFormGroupDirective } from './cd-form-group.directive';
describe('CdFormGroupDirective', () => {
it('should create an instance', () => {
const directive = new CdFormGroupDirective(new ElementRef(null));
expect(directive).toBeTruthy();
});
});
| 1,521 | 39.052632 | 81 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/ng-bootstrap-form-validation/cd-form-group.directive.ts
|
/**
* MIT License
*
* Copyright (c) 2017 Kevin Kipp
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
* Based on https://github.com/third774/ng-bootstrap-form-validation
*/
import {
ContentChildren,
Directive,
ElementRef,
HostBinding,
Input,
QueryList
} from '@angular/core';
import { FormControlName } from '@angular/forms';
@Directive({
// eslint-disable-next-line
selector: '.form-group'
})
export class CdFormGroupDirective {
@ContentChildren(FormControlName)
formControlNames: QueryList<FormControlName>;
@Input()
validationDisabled = false;
@HostBinding('class.has-error')
get hasErrors() {
return (
this.formControlNames.some((c) => !c.valid && c.dirty && c.touched) &&
!this.validationDisabled
);
}
@HostBinding('class.has-success')
get hasSuccess() {
return (
!this.formControlNames.some((c) => !c.valid) &&
this.formControlNames.some((c) => c.dirty && c.touched) &&
!this.validationDisabled
);
}
constructor(private elRef: ElementRef) {}
get label() {
const label = this.elRef.nativeElement.querySelector('label');
return label && label.textContent ? label.textContent.trim() : 'This field';
}
get isDirtyAndTouched() {
return this.formControlNames.some((c) => c.dirty && c.touched);
}
}
| 2,346 | 29.480519 | 81 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/ng-bootstrap-form-validation/cd-form-validation.directive.spec.ts
|
/**
* MIT License
*
* Copyright (c) 2017 Kevin Kipp
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
* Based on https://github.com/third774/ng-bootstrap-form-validation
*/
import { CdFormValidationDirective } from './cd-form-validation.directive';
describe('CdFormValidationDirective', () => {
it('should create an instance', () => {
const directive = new CdFormValidationDirective();
expect(directive).toBeTruthy();
});
});
| 1,476 | 40.027778 | 81 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/directives/ng-bootstrap-form-validation/cd-form-validation.directive.ts
|
/**
* MIT License
*
* Copyright (c) 2017 Kevin Kipp
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
* Based on https://github.com/third774/ng-bootstrap-form-validation
*/
import { Directive, EventEmitter, HostListener, Input, Output } from '@angular/core';
import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms';
@Directive({
// eslint-disable-next-line
selector: '[formGroup]'
})
export class CdFormValidationDirective {
@Input()
formGroup: FormGroup;
@Output()
validSubmit = new EventEmitter<any>();
@HostListener('submit')
onSubmit() {
this.markAsTouchedAndDirty(this.formGroup);
if (this.formGroup.valid) {
this.validSubmit.emit(this.formGroup.value);
}
}
markAsTouchedAndDirty(control: AbstractControl) {
if (control instanceof FormGroup) {
Object.keys(control.controls).forEach((key) =>
this.markAsTouchedAndDirty(control.controls[key])
);
} else if (control instanceof FormArray) {
control.controls.forEach((c) => this.markAsTouchedAndDirty(c));
} else if (control instanceof FormControl && control.enabled) {
control.markAsDirty();
control.markAsTouched();
control.updateValueAndValidity();
}
}
}
| 2,276 | 35.142857 | 85 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/enum/cell-template.enum.ts
|
export enum CellTemplate {
bold = 'bold',
sparkline = 'sparkline',
perSecond = 'perSecond',
checkIcon = 'checkIcon',
routerLink = 'routerLink',
// Display the cell with an executing state. The state can be set to the `cdExecuting`
// attribute of table rows.
// It supports an optional custom configuration:
// {
// ...
// cellTransformation: CellTemplate.executing,
// customTemplateConfig: {
// valueClass?: string; // Cell value classes.
// executingClass?: string; // Executing state classes.
// }
executing = 'executing',
classAdding = 'classAdding',
// Display the cell value as a badge. The template
// supports an optional custom configuration:
// {
// ...
// cellTransformation: CellTemplate.badge,
// customTemplateConfig: {
// class?: string; // Additional class name.
// prefix?: any; // Prefix of the value to be displayed.
// // 'map' and 'prefix' exclude each other.
// map?: {
// [key: any]: { value: any, class?: string }
// }
// }
// }
badge = 'badge',
// Maps the value using the given dictionary.
// {
// ...
// cellTransformation: CellTemplate.map,
// customTemplateConfig: {
// [key: any]: any
// }
// }
map = 'map',
// Truncates string if it's longer than the given maximum
// string length.
// {
// ...
// cellTransformation: CellTemplate.truncate,
// customTemplateConfig: {
// length?: number; // Defaults to 30.
// omission?: string; // Defaults to empty string.
// }
// }
truncate = 'truncate',
/*
This templace replaces a time, datetime or timestamp with a user-friendly "X {seconds,minutes,hours,days,...} ago",
but the tooltip still displays the absolute timestamp
*/
timeAgo = 'timeAgo'
}
| 1,839 | 29.666667 | 117 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/enum/components.enum.ts
|
export enum Components {
auth = 'Login',
cephfs = 'CephFS',
rbd = 'RBD',
pool = 'Pool',
osd = 'OSD',
role = 'Role',
user = 'User'
}
| 146 | 13.7 | 24 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/enum/dashboard-promqls.enum.ts
|
export enum Promqls {
USEDCAPACITY = 'ceph_cluster_total_used_bytes',
IPS = 'sum(rate(ceph_osd_op_w_in_bytes[$interval]))',
OPS = 'sum(rate(ceph_osd_op_r_out_bytes[$interval]))',
READLATENCY = 'avg_over_time(ceph_osd_apply_latency_ms[$interval])',
WRITELATENCY = 'avg_over_time(ceph_osd_commit_latency_ms[$interval])',
READCLIENTTHROUGHPUT = 'sum(rate(ceph_pool_rd_bytes[$interval]))',
WRITECLIENTTHROUGHPUT = 'sum(rate(ceph_pool_wr_bytes[$interval]))',
RECOVERYBYTES = 'sum(rate(ceph_osd_recovery_bytes[$interval]))'
}
| 536 | 47.818182 | 72 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/enum/health-color.enum.ts
|
export enum HealthColor {
HEALTH_ERR = 'health-color-error',
HEALTH_WARN = 'health-color-warning',
HEALTH_OK = 'health-color-healthy'
}
| 142 | 22.833333 | 39 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/enum/health-icon.enum.ts
|
export enum HealthIcon {
HEALTH_ERR = 'fa fa-exclamation-circle',
HEALTH_WARN = 'fa fa-exclamation-triangle',
HEALTH_OK = 'fa fa-check-circle'
}
| 151 | 24.333333 | 45 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/enum/health-label.enum.ts
|
export enum HealthLabel {
HEALTH_ERR = 'error',
HEALTH_WARN = 'warning',
HEALTH_OK = 'ok'
}
| 98 | 15.5 | 26 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/enum/icons.enum.ts
|
export enum Icons {
/* Icons for Symbol */
add = 'fa fa-plus', // Create, Add
addCircle = 'fa fa-plus-circle', // Plus with Circle
minusCircle = 'fa fa-minus-circle', // Minus with Circle
edit = 'fa fa-pencil', // Edit, Edit Mode, Rename
destroy = 'fa fa-times', // Destroy, Remove, Delete
destroyCircle = 'fa fa-times-circle', // Destroy, Remove, Delete
exchange = 'fa fa-exchange', // Edit-Peer
copy = 'fa fa-copy', // Copy
clipboard = 'fa fa-clipboard', // Clipboard
flatten = 'fa fa-chain-broken', // Flatten, Link broken, Mark Lost
trash = 'fa fa-trash-o', // Move to trash
lock = 'fa fa-lock', // Protect
unlock = 'fa fa-unlock', // Unprotect
clone = 'fa fa-clone', // clone
undo = 'fa fa-undo', // Rollback, Restore
search = 'fa fa-search', // Search
start = 'fa fa-play', // Enable
stop = 'fa fa-stop', // Disable
analyse = 'fa fa-stethoscope', // Scrub
deepCheck = 'fa fa-cog', // Deep Scrub, Setting, Configuration
reweight = 'fa fa-balance-scale', // Reweight
up = 'fa fa-arrow-up', // Up
left = 'fa fa-arrow-left', // Mark out
right = 'fa fa-arrow-right', // Mark in
down = 'fa fa-arrow-down', // Mark Down
erase = 'fa fa-eraser', // Purge color: bd.$white;
user = 'fa fa-user', // User, Initiators
users = 'fa fa-users', // Users, Groups
share = 'fa fa-share-alt', // share
key = 'fa fa-key-modern', // S3 Keys, Swift Keys, Authentication
warning = 'fa fa-exclamation-triangle', // Notification warning
info = 'fa fa-info', // Notification information
infoCircle = 'fa fa-info-circle', // Info on landing page
questionCircle = 'fa fa-question-circle-o',
danger = 'fa fa-exclamation-circle',
success = 'fa fa-check-circle',
check = 'fa fa-check', // Notification check
show = 'fa fa-eye', // Show
paragraph = 'fa fa-paragraph', // Silence Matcher - Attribute name
terminal = 'fa fa-terminal', // Silence Matcher - Value
magic = 'fa fa-magic', // Silence Matcher - Regex checkbox
hourglass = 'fa fa-hourglass-o', // Task
filledHourglass = 'fa fa-hourglass', // Task
table = 'fa fa-table', // Table,
spinner = 'fa fa-spinner', // spinner, Load
refresh = 'fa fa-refresh', // Refresh
bullseye = 'fa fa-bullseye', // Target
disk = 'fa fa-hdd-o', // Hard disk, disks
server = 'fa fa-server', // Server, Portal
filter = 'fa fa-filter', // Filter
lineChart = 'fa fa-line-chart', // Line chart
signOut = 'fa fa-sign-out', // Sign Out
health = 'fa fa-heartbeat', // Health
circle = 'fa fa-circle', // Circle
bell = 'fa fa-bell', // Notification
mute = 'fa fa-bell-slash', // Mute or silence
tag = 'fa fa-tag', // Tag, Badge
leftArrow = 'fa fa-angle-left', // Left facing angle
rightArrow = 'fa fa-angle-right', // Right facing angle
leftArrowDouble = 'fa fa-angle-double-left', // Left facing Double angle
rightArrowDouble = 'fa fa-angle-double-right', // Left facing Double angle
flag = 'fa fa-flag', // OSD configuration
clearFilters = 'fa fa-window-close', // Clear filters, solid x
download = 'fa fa-download', // Download
upload = 'fa fa-upload', // Upload
close = 'fa fa-times', // Close
json = 'fa fa-file-code-o', // JSON file
text = 'fa fa-file-text', // Text file
wrench = 'fa fa-wrench', // Configuration Error
enter = 'fa fa-sign-in', // Enter
exit = 'fa fa-sign-out', // Exit
restart = 'fa fa-history', // Restart
deploy = 'fa fa-cube', // Deploy, Redeploy
cubes = 'fa fa-cubes',
/* Icons for special effect */
large = 'fa fa-lg', // icon becomes 33% larger
large2x = 'fa fa-2x', // icon becomes 50% larger
large3x = 'fa fa-3x', // icon becomes 3 times larger
stack = 'fa fa-stack', // To stack multiple icons
stack1x = 'fa fa-stack-1x', // To stack regularly sized icon
stack2x = 'fa fa-stack-2x', // To stack regularly sized icon
pulse = 'fa fa-pulse', // To have spinner rotate with 8 steps
spin = 'fa fa-spin', // To get any icon to rotate
inverse = 'fa fa-inverse' // To get an alternative icon color
}
| 3,997 | 43.422222 | 76 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/enum/notification-type.enum.ts
|
export enum NotificationType {
error,
info,
success
}
| 60 | 9.166667 | 30 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/enum/unix_errno.enum.ts
|
// http://www.virtsync.com/c-error-codes-include-errno
export enum UnixErrno {
EEXIST = 17 // File exists
}
| 110 | 21.2 | 54 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/enum/view-cache-status.enum.ts
|
export enum ViewCacheStatus {
ValueOk = 0,
ValueStale = 1,
ValueNone = 2,
ValueException = 3
}
| 103 | 13.857143 | 29 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-form-builder.spec.ts
|
import { Validators } from '@angular/forms';
import { CdFormBuilder } from './cd-form-builder';
import { CdFormGroup } from './cd-form-group';
describe('cd-form-builder', () => {
let service: CdFormBuilder;
beforeEach(() => {
service = new CdFormBuilder();
});
it('should be created', () => {
expect(service).toBeTruthy();
});
it('should create a nested CdFormGroup', () => {
const form = service.group({
nested: service.group({
a: [null],
b: ['sth'],
c: [2, [Validators.min(3)]]
}),
d: [{ e: 3 }],
f: [true]
});
expect(form.constructor).toBe(CdFormGroup);
expect(form instanceof CdFormGroup).toBeTruthy();
expect(form.getValue('b')).toBe('sth');
expect(form.getValue('d')).toEqual({ e: 3 });
expect(form.get('c').valid).toBeFalsy();
});
});
| 845 | 23.882353 | 53 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-form-builder.ts
|
import { Injectable } from '@angular/core';
import { AbstractControlOptions, FormBuilder } from '@angular/forms';
import { CdFormGroup } from './cd-form-group';
/**
* CdFormBuilder extends FormBuilder to create an CdFormGroup based form.
*/
@Injectable({
providedIn: 'root'
})
export class CdFormBuilder extends FormBuilder {
group(
controlsConfig: { [key: string]: any },
extra: AbstractControlOptions | null = null
): CdFormGroup {
const form = super.group(controlsConfig, extra);
return new CdFormGroup(form.controls, form.validator, form.asyncValidator);
}
}
| 591 | 27.190476 | 79 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-form-group.spec.ts
|
import { AbstractControl, FormControl, FormGroup, NgForm } from '@angular/forms';
import { CdFormGroup } from './cd-form-group';
describe('CdFormGroup', () => {
let form: CdFormGroup;
const createTestForm = (controlName: string, value: any): FormGroup =>
new FormGroup({
[controlName]: new FormControl(value)
});
describe('test get and getValue in nested forms', () => {
let formA: FormGroup;
let formB: FormGroup;
let formC: FormGroup;
beforeEach(() => {
formA = createTestForm('a', 'a');
formB = createTestForm('b', 'b');
formC = createTestForm('c', 'c');
form = new CdFormGroup({
formA: formA,
formB: formB,
formC: formC
});
});
it('should find controls out of every form', () => {
expect(form.get('a')).toBe(formA.get('a'));
expect(form.get('b')).toBe(formB.get('b'));
expect(form.get('c')).toBe(formC.get('c'));
});
it('should throw an error if element could be found', () => {
expect(() => form.get('d')).toThrowError(`Control 'd' could not be found!`);
expect(() => form.get('sth')).toThrowError(`Control 'sth' could not be found!`);
});
});
describe('CdFormGroup tests', () => {
let x: CdFormGroup, nested: CdFormGroup, a: FormControl, c: FormGroup;
beforeEach(() => {
a = new FormControl('a');
x = new CdFormGroup({
a: a
});
nested = new CdFormGroup({
lev1: new CdFormGroup({
lev2: new FormControl('lev2')
})
});
c = createTestForm('c', 'c');
form = new CdFormGroup({
nested: nested,
cdform: x,
b: new FormControl('b'),
formC: c
});
});
it('should return single value from "a" control in not nested form "x"', () => {
expect(x.get('a')).toBe(a);
expect(x.getValue('a')).toBe('a');
});
it('should return control "a" out of form "x" in nested form', () => {
expect(form.get('a')).toBe(a);
expect(form.getValue('a')).toBe('a');
});
it('should return value "b" that is not nested in nested form', () => {
expect(form.getValue('b')).toBe('b');
});
it('return value "c" out of normal form group "c" in nested form', () => {
expect(form.getValue('c')).toBe('c');
});
it('should return "lev2" value', () => {
expect(form.getValue('lev2')).toBe('lev2');
});
it('should nested throw an error if control could not be found', () => {
expect(() => form.get('d')).toThrowError(`Control 'd' could not be found!`);
expect(() => form.getValue('sth')).toThrowError(`Control 'sth' could not be found!`);
});
});
describe('test different values for getValue', () => {
beforeEach(() => {
form = new CdFormGroup({
form_undefined: createTestForm('undefined', undefined),
form_null: createTestForm('null', null),
form_emptyObject: createTestForm('emptyObject', {}),
form_filledObject: createTestForm('filledObject', { notEmpty: 1 }),
form_number0: createTestForm('number0', 0),
form_number1: createTestForm('number1', 1),
form_emptyString: createTestForm('emptyString', ''),
form_someString1: createTestForm('someString1', 's'),
form_someString2: createTestForm('someString2', 'sth'),
form_floating: createTestForm('floating', 0.1),
form_false: createTestForm('false', false),
form_true: createTestForm('true', true)
});
});
it('returns objects', () => {
expect(form.getValue('null')).toBe(null);
expect(form.getValue('emptyObject')).toEqual({});
expect(form.getValue('filledObject')).toEqual({ notEmpty: 1 });
});
it('returns set numbers', () => {
expect(form.getValue('number0')).toBe(0);
expect(form.getValue('number1')).toBe(1);
expect(form.getValue('floating')).toBe(0.1);
});
it('returns strings', () => {
expect(form.getValue('emptyString')).toBe('');
expect(form.getValue('someString1')).toBe('s');
expect(form.getValue('someString2')).toBe('sth');
});
it('returns booleans', () => {
expect(form.getValue('true')).toBe(true);
expect(form.getValue('false')).toBe(false);
});
it('returns null if control was set as undefined', () => {
expect(form.getValue('undefined')).toBe(null);
});
it('returns a falsy value for null, undefined, false and 0', () => {
expect(form.getValue('false')).toBeFalsy();
expect(form.getValue('null')).toBeFalsy();
expect(form.getValue('number0')).toBeFalsy();
});
});
describe('should test showError', () => {
let formDir: NgForm;
let test: AbstractControl;
beforeEach(() => {
formDir = new NgForm([], []);
form = new CdFormGroup({
test_form: createTestForm('test', '')
});
test = form.get('test');
test.setErrors({ someError: 'failed' });
});
it('should not show an error if not dirty and not submitted', () => {
expect(form.showError('test', formDir)).toBe(false);
});
it('should show an error if dirty', () => {
test.markAsDirty();
expect(form.showError('test', formDir)).toBe(true);
});
it('should show an error if submitted', () => {
expect(form.showError('test', <NgForm>{ submitted: true })).toBe(true);
});
it('should not show an error if no error exits', () => {
test.setErrors(null);
expect(form.showError('test', <NgForm>{ submitted: true })).toBe(false);
test.markAsDirty();
expect(form.showError('test', formDir)).toBe(false);
});
it('should not show error if the given error is not there', () => {
expect(form.showError('test', <NgForm>{ submitted: true }, 'someOtherError')).toBe(false);
});
it('should show error if the given error is there', () => {
expect(form.showError('test', <NgForm>{ submitted: true }, 'someError')).toBe(true);
});
});
});
| 6,011 | 31.497297 | 96 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-form-group.ts
|
import {
AbstractControl,
AbstractControlOptions,
AsyncValidatorFn,
FormGroup,
NgForm,
ValidatorFn
} from '@angular/forms';
/**
* CdFormGroup extends FormGroup with a few new methods that will help form development.
*/
export class CdFormGroup extends FormGroup {
constructor(
public controls: { [key: string]: AbstractControl },
validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null,
asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null
) {
super(controls, validatorOrOpts, asyncValidator);
}
/**
* Get a control out of any control even if its nested in other CdFormGroups or a FormGroup
*/
get(controlName: string): AbstractControl {
const control = this._get(controlName);
if (!control) {
throw new Error(`Control '${controlName}' could not be found!`);
}
return control;
}
_get(controlName: string): AbstractControl {
return (
super.get(controlName) ||
Object.values(this.controls)
.filter((c) => c.get)
.map((form) => {
if (form instanceof CdFormGroup) {
return form._get(controlName);
}
return form.get(controlName);
})
.find((c) => Boolean(c))
);
}
/**
* Get the value of a control
*/
getValue(controlName: string): any {
return this.get(controlName).value;
}
/**
* Sets a control without triggering a value changes event
*
* Very useful if a function is called through a value changes event but the value
* should be changed within the call.
*/
silentSet(controlName: string, value: any) {
this.get(controlName).setValue(value, { emitEvent: false });
}
/**
* Indicates errors of the control in templates
*/
showError(controlName: string, form: NgForm, errorName?: string): boolean {
const control = this.get(controlName);
return (
(form.submitted || control.dirty) &&
(errorName ? control.hasError(errorName) : control.invalid)
);
}
}
| 2,027 | 25.684211 | 93 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-form.spec.ts
|
import { CdForm, LoadingStatus } from './cd-form';
describe('CdForm', () => {
let form: CdForm;
beforeEach(() => {
form = new CdForm();
});
describe('loading', () => {
it('should start in loading state', () => {
expect(form.loading).toBe(LoadingStatus.Loading);
});
it('should change to ready when calling loadingReady', () => {
form.loadingReady();
expect(form.loading).toBe(LoadingStatus.Ready);
});
it('should change to error state calling loadingError', () => {
form.loadingError();
expect(form.loading).toBe(LoadingStatus.Error);
});
it('should change to loading state calling loadingStart', () => {
form.loadingError();
expect(form.loading).toBe(LoadingStatus.Error);
form.loadingStart();
expect(form.loading).toBe(LoadingStatus.Loading);
});
});
});
| 863 | 25.181818 | 69 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-form.ts
|
export enum LoadingStatus {
Loading,
Ready,
Error,
None
}
export class CdForm {
loading = LoadingStatus.Loading;
loadingStart() {
this.loading = LoadingStatus.Loading;
}
loadingReady() {
this.loading = LoadingStatus.Ready;
}
loadingError() {
this.loading = LoadingStatus.Error;
}
loadingNone() {
this.loading = LoadingStatus.None;
}
}
| 382 | 13.185185 | 41 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-validators.spec.ts
|
import { fakeAsync, tick } from '@angular/core/testing';
import { FormControl, Validators } from '@angular/forms';
import _ from 'lodash';
import { of as observableOf } from 'rxjs';
import { RgwBucketService } from '~/app/shared/api/rgw-bucket.service';
import { CdFormGroup } from '~/app/shared/forms/cd-form-group';
import { CdValidators } from '~/app/shared/forms/cd-validators';
import { FormHelper } from '~/testing/unit-test-helper';
let mockBucketExists = observableOf(true);
jest.mock('~/app/shared/api/rgw-bucket.service', () => {
return {
RgwBucketService: jest.fn().mockImplementation(() => {
return {
exists: () => mockBucketExists
};
})
};
});
describe('CdValidators', () => {
let formHelper: FormHelper;
let form: CdFormGroup;
const expectValid = (value: any) => formHelper.expectValidChange('x', value);
const expectPatternError = (value: any) => formHelper.expectErrorChange('x', value, 'pattern');
const updateValidity = (controlName: string) => form.get(controlName).updateValueAndValidity();
beforeEach(() => {
form = new CdFormGroup({
x: new FormControl()
});
formHelper = new FormHelper(form);
});
describe('email', () => {
beforeEach(() => {
form.get('x').setValidators(CdValidators.email);
});
it('should not error on an empty email address', () => {
expectValid('');
});
it('should not error on valid email address', () => {
expectValid('[email protected]');
});
it('should error on invalid email address', () => {
formHelper.expectErrorChange('x', 'xyz', 'email');
});
});
describe('ip validator', () => {
describe('IPv4', () => {
beforeEach(() => {
form.get('x').setValidators(CdValidators.ip(4));
});
it('should not error on empty addresses', () => {
expectValid('');
});
it('should accept valid address', () => {
expectValid('19.117.23.141');
});
it('should error containing whitespace', () => {
expectPatternError('155.144.133.122 ');
expectPatternError('155. 144.133 .122');
expectPatternError(' 155.144.133.122');
});
it('should error containing invalid char', () => {
expectPatternError('155.144.eee.122 ');
expectPatternError('155.1?.133 .1&2');
});
it('should error containing blocks higher than 255', () => {
expectPatternError('155.270.133.122');
expectPatternError('155.144.133.290');
});
});
describe('IPv4', () => {
beforeEach(() => {
form.get('x').setValidators(CdValidators.ip(6));
});
it('should not error on empty IPv6 addresses', () => {
expectValid('');
});
it('should accept valid IPv6 address', () => {
expectValid('c4dc:1475:cb0b:24ed:3c80:468b:70cd:1a95');
});
it('should error on IPv6 address containing too many blocks', () => {
formHelper.expectErrorChange(
'x',
'c4dc:14753:cb0b:24ed:3c80:468b:70cd:1a95:a3f3',
'pattern'
);
});
it('should error on IPv6 address containing more than 4 digits per block', () => {
expectPatternError('c4dc:14753:cb0b:24ed:3c80:468b:70cd:1a95');
});
it('should error on IPv6 address containing whitespace', () => {
expectPatternError('c4dc:14753:cb0b:24ed:3c80:468b:70cd:1a95 ');
expectPatternError('c4dc:14753 :cb0b:24ed:3c80 :468b:70cd :1a95');
expectPatternError(' c4dc:14753:cb0b:24ed:3c80:468b:70cd:1a95');
});
it('should error on IPv6 address containing invalid char', () => {
expectPatternError('c4dx:14753:cb0b:24ed:3c80:468b:70cd:1a95');
expectPatternError('c4da:14753:cb0b:24ed:3$80:468b:70cd:1a95');
});
});
it('should accept valid IPv4/6 addresses if not protocol version is given', () => {
const x = form.get('x');
x.setValidators(CdValidators.ip());
expectValid('19.117.23.141');
expectValid('c4dc:1475:cb0b:24ed:3c80:468b:70cd:1a95');
});
});
describe('uuid validator', () => {
const expectUuidError = (value: string) =>
formHelper.expectErrorChange('x', value, 'invalidUuid', true);
beforeEach(() => {
form.get('x').setValidators(CdValidators.uuid());
});
it('should accept empty value', () => {
expectValid('');
});
it('should accept valid version 1 uuid', () => {
expectValid('171af0b2-c305-11e8-a355-529269fb1459');
});
it('should accept valid version 4 uuid', () => {
expectValid('e33bbcb6-fcc3-40b1-ae81-3f81706a35d5');
});
it('should error on uuid containing too many blocks', () => {
expectUuidError('e33bbcb6-fcc3-40b1-ae81-3f81706a35d5-23d3');
});
it('should error on uuid containing too many chars in block', () => {
expectUuidError('aae33bbcb6-fcc3-40b1-ae81-3f81706a35d5');
});
it('should error on uuid containing invalid char', () => {
expectUuidError('x33bbcb6-fcc3-40b1-ae81-3f81706a35d5');
expectUuidError('$33bbcb6-fcc3-40b1-ae81-3f81706a35d5');
});
});
describe('number validator', () => {
beforeEach(() => {
form.get('x').setValidators(CdValidators.number());
});
it('should accept empty value', () => {
expectValid('');
});
it('should accept numbers', () => {
expectValid(42);
expectValid(-42);
expectValid('42');
});
it('should error on decimal numbers', () => {
expectPatternError(42.3);
expectPatternError(-42.3);
expectPatternError('42.3');
});
it('should error on chars', () => {
expectPatternError('char');
expectPatternError('42char');
});
it('should error on whitespaces', () => {
expectPatternError('42 ');
expectPatternError('4 2');
});
});
describe('number validator (without negative values)', () => {
beforeEach(() => {
form.get('x').setValidators(CdValidators.number(false));
});
it('should accept positive numbers', () => {
expectValid(42);
expectValid('42');
});
it('should error on negative numbers', () => {
expectPatternError(-42);
expectPatternError('-42');
});
});
describe('decimal number validator', () => {
beforeEach(() => {
form.get('x').setValidators(CdValidators.decimalNumber());
});
it('should accept empty value', () => {
expectValid('');
});
it('should accept numbers and decimal numbers', () => {
expectValid(42);
expectValid(-42);
expectValid(42.3);
expectValid(-42.3);
expectValid('42');
expectValid('42.3');
});
it('should error on chars', () => {
expectPatternError('42e');
expectPatternError('e42.3');
});
it('should error on whitespaces', () => {
expectPatternError('42.3 ');
expectPatternError('42 .3');
});
});
describe('decimal number validator (without negative values)', () => {
beforeEach(() => {
form.get('x').setValidators(CdValidators.decimalNumber(false));
});
it('should accept positive numbers and decimals', () => {
expectValid(42);
expectValid(42.3);
expectValid('42');
expectValid('42.3');
});
it('should error on negative numbers and decimals', () => {
expectPatternError(-42);
expectPatternError('-42');
expectPatternError(-42.3);
expectPatternError('-42.3');
});
});
describe('requiredIf', () => {
beforeEach(() => {
form = new CdFormGroup({
a: new FormControl(''),
b: new FormControl('xyz'),
x: new FormControl(true),
y: new FormControl('abc'),
z: new FormControl('')
});
formHelper = new FormHelper(form);
});
it('should not error because all conditions are fulfilled', () => {
formHelper.setValue('z', 'zyx');
const validatorFn = CdValidators.requiredIf({
x: true,
y: 'abc'
});
expect(validatorFn(form.get('z'))).toBeNull();
});
it('should not error because of unmet prerequisites', () => {
// Define prereqs that do not match the current values of the form fields.
const validatorFn = CdValidators.requiredIf({
x: false,
y: 'xyz'
});
// The validator must succeed because the prereqs do not match, so the
// validation of the 'z' control will be skipped.
expect(validatorFn(form.get('z'))).toBeNull();
});
it('should error because of an empty value', () => {
// Define prereqs that force the validator to validate the value of
// the 'z' control.
const validatorFn = CdValidators.requiredIf({
x: true,
y: 'abc'
});
// The validator must fail because the value of control 'z' is empty.
expect(validatorFn(form.get('z'))).toEqual({ required: true });
});
it('should not error because of unsuccessful condition', () => {
formHelper.setValue('z', 'zyx');
// Define prereqs that force the validator to validate the value of
// the 'z' control.
const validatorFn = CdValidators.requiredIf(
{
x: true,
z: 'zyx'
},
() => false
);
expect(validatorFn(form.get('z'))).toBeNull();
});
it('should error because of successful condition', () => {
const conditionFn = (value: string) => {
return value === 'abc';
};
// Define prereqs that force the validator to validate the value of
// the 'y' control.
const validatorFn = CdValidators.requiredIf(
{
x: true,
z: ''
},
conditionFn
);
expect(validatorFn(form.get('y'))).toEqual({ required: true });
});
it('should process extended prerequisites (1)', () => {
const validatorFn = CdValidators.requiredIf({
y: { op: '!empty' }
});
expect(validatorFn(form.get('z'))).toEqual({ required: true });
});
it('should process extended prerequisites (2)', () => {
const validatorFn = CdValidators.requiredIf({
y: { op: '!empty' }
});
expect(validatorFn(form.get('b'))).toBeNull();
});
it('should process extended prerequisites (3)', () => {
const validatorFn = CdValidators.requiredIf({
y: { op: 'minLength', arg1: 2 }
});
expect(validatorFn(form.get('z'))).toEqual({ required: true });
});
it('should process extended prerequisites (4)', () => {
const validatorFn = CdValidators.requiredIf({
z: { op: 'empty' }
});
expect(validatorFn(form.get('a'))).toEqual({ required: true });
});
it('should process extended prerequisites (5)', () => {
const validatorFn = CdValidators.requiredIf({
z: { op: 'empty' }
});
expect(validatorFn(form.get('y'))).toBeNull();
});
it('should process extended prerequisites (6)', () => {
const validatorFn = CdValidators.requiredIf({
y: { op: 'empty' }
});
expect(validatorFn(form.get('z'))).toBeNull();
});
it('should process extended prerequisites (7)', () => {
const validatorFn = CdValidators.requiredIf({
y: { op: 'minLength', arg1: 4 }
});
expect(validatorFn(form.get('z'))).toBeNull();
});
it('should process extended prerequisites (8)', () => {
const validatorFn = CdValidators.requiredIf({
x: { op: 'equal', arg1: true }
});
expect(validatorFn(form.get('z'))).toEqual({ required: true });
});
it('should process extended prerequisites (9)', () => {
const validatorFn = CdValidators.requiredIf({
b: { op: '!equal', arg1: 'abc' }
});
expect(validatorFn(form.get('z'))).toEqual({ required: true });
});
});
describe('custom validation', () => {
beforeEach(() => {
form = new CdFormGroup({
x: new FormControl(
3,
CdValidators.custom('odd', (x: number) => x % 2 === 1)
),
y: new FormControl(
5,
CdValidators.custom('not-dividable-by-x', (y: number) => {
const x = (form && form.get('x').value) || 1;
return y % x !== 0;
})
)
});
formHelper = new FormHelper(form);
});
it('should test error and valid condition for odd x', () => {
formHelper.expectError('x', 'odd');
expectValid(4);
});
it('should test error and valid condition for y if its dividable by x', () => {
updateValidity('y');
formHelper.expectError('y', 'not-dividable-by-x');
formHelper.expectValidChange('y', 6);
});
});
describe('validate if condition', () => {
beforeEach(() => {
form = new CdFormGroup({
x: new FormControl(3),
y: new FormControl(5)
});
CdValidators.validateIf(form.get('x'), () => ((form && form.get('y').value) || 0) > 10, [
CdValidators.custom('min', (x: number) => x < 7),
CdValidators.custom('max', (x: number) => x > 12)
]);
formHelper = new FormHelper(form);
});
it('should test min error', () => {
formHelper.setValue('y', 11);
updateValidity('x');
formHelper.expectError('x', 'min');
});
it('should test max error', () => {
formHelper.setValue('y', 11);
formHelper.setValue('x', 13);
formHelper.expectError('x', 'max');
});
it('should test valid number with validation', () => {
formHelper.setValue('y', 11);
formHelper.setValue('x', 12);
formHelper.expectValid('x');
});
it('should validate automatically if dependency controls are defined', () => {
CdValidators.validateIf(
form.get('x'),
() => ((form && form.getValue('y')) || 0) > 10,
[Validators.min(7), Validators.max(12)],
undefined,
[form.get('y')]
);
formHelper.expectValid('x');
formHelper.setValue('y', 13);
formHelper.expectError('x', 'min');
});
it('should always validate the permanentValidators', () => {
CdValidators.validateIf(
form.get('x'),
() => ((form && form.getValue('y')) || 0) > 10,
[Validators.min(7), Validators.max(12)],
[Validators.required],
[form.get('y')]
);
formHelper.expectValid('x');
formHelper.setValue('x', '');
formHelper.expectError('x', 'required');
});
});
describe('match', () => {
let y: FormControl;
beforeEach(() => {
y = new FormControl('aaa');
form = new CdFormGroup({
x: new FormControl('aaa'),
y: y
});
formHelper = new FormHelper(form);
});
it('should error when values are different', () => {
formHelper.setValue('y', 'aab');
CdValidators.match('x', 'y')(form);
formHelper.expectValid('x');
formHelper.expectError('y', 'match');
});
it('should not error when values are equal', () => {
CdValidators.match('x', 'y')(form);
formHelper.expectValid('x');
formHelper.expectValid('y');
});
it('should unset error when values are equal', () => {
y.setErrors({ match: true });
CdValidators.match('x', 'y')(form);
formHelper.expectValid('x');
formHelper.expectValid('y');
});
it('should keep other existing errors', () => {
y.setErrors({ match: true, notUnique: true });
CdValidators.match('x', 'y')(form);
formHelper.expectValid('x');
formHelper.expectError('y', 'notUnique');
});
});
describe('unique', () => {
beforeEach(() => {
form = new CdFormGroup({
x: new FormControl(
'',
null,
CdValidators.unique((value) => {
return observableOf('xyz' === value);
})
)
});
formHelper = new FormHelper(form);
});
it('should not error because of empty input', () => {
expectValid('');
});
it('should not error because of not existing input', fakeAsync(() => {
formHelper.setValue('x', 'abc', true);
tick(500);
formHelper.expectValid('x');
}));
it('should error because of already existing input', fakeAsync(() => {
formHelper.setValue('x', 'xyz', true);
tick(500);
formHelper.expectError('x', 'notUnique');
}));
});
describe('composeIf', () => {
beforeEach(() => {
form = new CdFormGroup({
x: new FormControl(true),
y: new FormControl('abc'),
z: new FormControl('')
});
formHelper = new FormHelper(form);
});
it('should not error because all conditions are fulfilled', () => {
formHelper.setValue('z', 'zyx');
const validatorFn = CdValidators.composeIf(
{
x: true,
y: 'abc'
},
[Validators.required]
);
expect(validatorFn(form.get('z'))).toBeNull();
});
it('should not error because of unmet prerequisites', () => {
// Define prereqs that do not match the current values of the form fields.
const validatorFn = CdValidators.composeIf(
{
x: false,
y: 'xyz'
},
[Validators.required]
);
// The validator must succeed because the prereqs do not match, so the
// validation of the 'z' control will be skipped.
expect(validatorFn(form.get('z'))).toBeNull();
});
it('should error because of an empty value', () => {
// Define prereqs that force the validator to validate the value of
// the 'z' control.
const validatorFn = CdValidators.composeIf(
{
x: true,
y: 'abc'
},
[Validators.required]
);
// The validator must fail because the value of control 'z' is empty.
expect(validatorFn(form.get('z'))).toEqual({ required: true });
});
});
describe('dimmlessBinary validators', () => {
const i18nMock = (a: string, b: { value: string }) => a.replace('{{value}}', b.value);
beforeEach(() => {
form = new CdFormGroup({
x: new FormControl('2 KiB', [CdValidators.binaryMin(1024), CdValidators.binaryMax(3072)])
});
formHelper = new FormHelper(form);
});
it('should not raise exception an exception for valid change', () => {
formHelper.expectValidChange('x', '2.5 KiB');
});
it('should not raise minimum error', () => {
formHelper.expectErrorChange('x', '0.5 KiB', 'binaryMin');
expect(form.get('x').getError('binaryMin')(i18nMock)).toBe(
'Size has to be at least 1 KiB or more'
);
});
it('should not raise maximum error', () => {
formHelper.expectErrorChange('x', '4 KiB', 'binaryMax');
expect(form.get('x').getError('binaryMax')(i18nMock)).toBe(
'Size has to be at most 3 KiB or less'
);
});
});
describe('passwordPolicy', () => {
let valid: boolean;
let callbackCalled: boolean;
const fakeUserService = {
validatePassword: () => {
return observableOf({ valid: valid, credits: 17, valuation: 'foo' });
}
};
beforeEach(() => {
callbackCalled = false;
form = new CdFormGroup({
x: new FormControl(
'',
null,
CdValidators.passwordPolicy(
fakeUserService,
() => 'admin',
() => {
callbackCalled = true;
}
)
)
});
formHelper = new FormHelper(form);
});
it('should not error because of empty input', () => {
expectValid('');
expect(callbackCalled).toBeTruthy();
});
it('should not error because password matches the policy', fakeAsync(() => {
valid = true;
formHelper.setValue('x', 'abc', true);
tick(500);
formHelper.expectValid('x');
}));
it('should error because password does not match the policy', fakeAsync(() => {
valid = false;
formHelper.setValue('x', 'xyz', true);
tick(500);
formHelper.expectError('x', 'passwordPolicy');
}));
it('should call the callback function', fakeAsync(() => {
formHelper.setValue('x', 'xyz', true);
tick(500);
expect(callbackCalled).toBeTruthy();
}));
describe('sslCert validator', () => {
beforeEach(() => {
form.get('x').setValidators(CdValidators.sslCert());
});
it('should not error because of empty input', () => {
expectValid('');
});
it('should accept SSL certificate', () => {
expectValid(
'-----BEGIN CERTIFICATE-----\n' +
'MIIC1TCCAb2gAwIBAgIJAM33ZCMvOLVdMA0GCSqGSIb3DQEBBQUAMBoxGDAWBgNV\n' +
'...\n' +
'3Ztorm2A5tFB\n' +
'-----END CERTIFICATE-----\n' +
'\n'
);
});
it('should error on invalid SSL certificate (1)', () => {
expectPatternError(
'MIIC1TCCAb2gAwIBAgIJAM33ZCMvOLVdMA0GCSqGSIb3DQEBBQUAMBoxGDAWBgNV\n' +
'...\n' +
'3Ztorm2A5tFB\n' +
'-----END CERTIFICATE-----\n' +
'\n'
);
});
it('should error on invalid SSL certificate (2)', () => {
expectPatternError(
'-----BEGIN CERTIFICATE-----\n' +
'MIIC1TCCAb2gAwIBAgIJAM33ZCMvOLVdMA0GCSqGSIb3DQEBBQUAMBoxGDAWBgNV\n'
);
});
});
describe('sslPrivKey validator', () => {
beforeEach(() => {
form.get('x').setValidators(CdValidators.sslPrivKey());
});
it('should not error because of empty input', () => {
expectValid('');
});
it('should accept SSL private key', () => {
expectValid(
'-----BEGIN RSA PRIVATE KEY-----\n' +
'MIIEpQIBAAKCAQEA5VwkMK63D7AoGJVbVpgiV3XlEC1rwwOEpHPZW9F3ZW1fYS1O\n' +
'...\n' +
'SA4Jbana77S7adg919vNBCLWPAeoN44lI2+B1Ub5DxSnOpBf+zKiScU=\n' +
'-----END RSA PRIVATE KEY-----\n' +
'\n'
);
});
it('should error on invalid SSL private key (1)', () => {
expectPatternError(
'MIIEpQIBAAKCAQEA5VwkMK63D7AoGJVbVpgiV3XlEC1rwwOEpHPZW9F3ZW1fYS1O\n' +
'...\n' +
'SA4Jbana77S7adg919vNBCLWPAeoN44lI2+B1Ub5DxSnOpBf+zKiScU=\n' +
'-----END RSA PRIVATE KEY-----\n' +
'\n'
);
});
it('should error on invalid SSL private key (2)', () => {
expectPatternError(
'-----BEGIN RSA PRIVATE KEY-----\n' +
'MIIEpQIBAAKCAQEA5VwkMK63D7AoGJVbVpgiV3XlEC1rwwOEpHPZW9F3ZW1fYS1O\n' +
'...\n' +
'SA4Jbana77S7adg919vNBCLWPAeoN44lI2+B1Ub5DxSnOpBf+zKiScU=\n'
);
});
});
});
describe('bucket', () => {
const testValidator = (name: string, valid: boolean, expectedError?: string) => {
formHelper.setValue('x', name, true);
tick();
if (valid) {
formHelper.expectValid('x');
} else {
formHelper.expectError('x', expectedError);
}
};
describe('bucketName', () => {
beforeEach(() => {
form = new CdFormGroup({
x: new FormControl('', null, CdValidators.bucketName())
});
formHelper = new FormHelper(form);
});
it('bucket name cannot be empty', fakeAsync(() => {
testValidator('', false, 'required');
}));
it('bucket names cannot be formatted as IP address', fakeAsync(() => {
const testIPs = ['1.1.1.01', '001.1.1.01', '127.0.0.1'];
for (const ip of testIPs) {
testValidator(ip, false, 'ipAddress');
}
}));
it('bucket name must be >= 3 characters long (1/2)', fakeAsync(() => {
testValidator('ab', false, 'shouldBeInRange');
}));
it('bucket name must be >= 3 characters long (2/2)', fakeAsync(() => {
testValidator('abc', true);
}));
it('bucket name must be <= than 63 characters long (1/2)', fakeAsync(() => {
testValidator(_.repeat('a', 64), false, 'shouldBeInRange');
}));
it('bucket name must be <= than 63 characters long (2/2)', fakeAsync(() => {
testValidator(_.repeat('a', 63), true);
}));
it('bucket names must not contain uppercase characters or underscores (1/2)', fakeAsync(() => {
testValidator('iAmInvalid', false, 'bucketNameInvalid');
}));
it('bucket names can only contain lowercase letters, numbers, periods and hyphens', fakeAsync(() => {
testValidator('bk@2', false, 'bucketNameInvalid');
}));
it('bucket names must not contain uppercase characters or underscores (2/2)', fakeAsync(() => {
testValidator('i_am_invalid', false, 'bucketNameInvalid');
}));
it('bucket names must start and end with letters or numbers', fakeAsync(() => {
testValidator('abcd-', false, 'lowerCaseOrNumber');
}));
it('bucket labels cannot be empty', fakeAsync(() => {
testValidator('bk.', false, 'onlyLowerCaseAndNumbers');
}));
it('bucket names with invalid labels (1/3)', fakeAsync(() => {
testValidator('abc.1def.Ghi2', false, 'bucketNameInvalid');
}));
it('bucket names with invalid labels (2/3)', fakeAsync(() => {
testValidator('abc.1_xy', false, 'bucketNameInvalid');
}));
it('bucket names with invalid labels (3/3)', fakeAsync(() => {
testValidator('abc.*def', false, 'bucketNameInvalid');
}));
it('bucket names must be a series of one or more labels and can contain lowercase letters, numbers, and hyphens (1/3)', fakeAsync(() => {
testValidator('xyz.abc', true);
}));
it('bucket names must be a series of one or more labels and can contain lowercase letters, numbers, and hyphens (2/3)', fakeAsync(() => {
testValidator('abc.1-def', true);
}));
it('bucket names must be a series of one or more labels and can contain lowercase letters, numbers, and hyphens (3/3)', fakeAsync(() => {
testValidator('abc.ghi2', true);
}));
it('bucket names must be unique', fakeAsync(() => {
testValidator('bucket-name-is-unique', true);
}));
it('bucket names must not contain spaces', fakeAsync(() => {
testValidator('bucket name with spaces', false, 'bucketNameInvalid');
}));
});
describe('bucketExistence', () => {
const rgwBucketService = new RgwBucketService(undefined, undefined);
beforeEach(() => {
form = new CdFormGroup({
x: new FormControl('', null, CdValidators.bucketExistence(false, rgwBucketService))
});
formHelper = new FormHelper(form);
});
it('bucket name cannot be empty', fakeAsync(() => {
testValidator('', false, 'required');
}));
it('bucket name should not exist but it does', fakeAsync(() => {
testValidator('testName', false, 'bucketNameNotAllowed');
}));
it('bucket name should not exist and it does not', fakeAsync(() => {
mockBucketExists = observableOf(false);
testValidator('testName', true);
}));
it('bucket name should exist but it does not', fakeAsync(() => {
form.get('x').setAsyncValidators(CdValidators.bucketExistence(true, rgwBucketService));
mockBucketExists = observableOf(false);
testValidator('testName', false, 'bucketNameNotAllowed');
}));
it('bucket name should exist and it does', fakeAsync(() => {
form.get('x').setAsyncValidators(CdValidators.bucketExistence(true, rgwBucketService));
mockBucketExists = observableOf(true);
testValidator('testName', true);
}));
});
});
});
| 27,741 | 29.586549 | 143 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/cd-validators.ts
|
import {
AbstractControl,
AsyncValidatorFn,
ValidationErrors,
ValidatorFn,
Validators
} from '@angular/forms';
import _ from 'lodash';
import { Observable, of as observableOf, timer as observableTimer } from 'rxjs';
import { map, switchMapTo, take } from 'rxjs/operators';
import { RgwBucketService } from '~/app/shared/api/rgw-bucket.service';
import { DimlessBinaryPipe } from '~/app/shared/pipes/dimless-binary.pipe';
import { FormatterService } from '~/app/shared/services/formatter.service';
export function isEmptyInputValue(value: any): boolean {
return value == null || value.length === 0;
}
export type existsServiceFn = (value: any) => Observable<boolean>;
export class CdValidators {
/**
* Validator that performs email validation. In contrast to the Angular
* email validator an empty email will not be handled as invalid.
*/
static email(control: AbstractControl): ValidationErrors | null {
// Exit immediately if value is empty.
if (isEmptyInputValue(control.value)) {
return null;
}
return Validators.email(control);
}
/**
* Validator function in order to validate IP addresses.
* @param {number} version determines the protocol version. It needs to be set to 4 for IPv4 and
* to 6 for IPv6 validation. For any other number (it's also the default case) it will return a
* function to validate the input string against IPv4 OR IPv6.
* @returns {ValidatorFn} A validator function that returns an error map containing `pattern`
* if the validation check fails, otherwise `null`.
*/
static ip(version: number = 0): ValidatorFn {
// prettier-ignore
const 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;
const ipv6Rgx = /^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$/i;
if (version === 4) {
return Validators.pattern(ipv4Rgx);
} else if (version === 6) {
return Validators.pattern(ipv6Rgx);
} else {
return Validators.pattern(new RegExp(ipv4Rgx.source + '|' + ipv6Rgx.source));
}
}
/**
* Validator function in order to validate numbers.
* @returns {ValidatorFn} A validator function that returns an error map containing `pattern`
* if the validation check fails, otherwise `null`.
*/
static number(allowsNegative: boolean = true): ValidatorFn {
if (allowsNegative) {
return Validators.pattern(/^-?[0-9]+$/i);
} else {
return Validators.pattern(/^[0-9]+$/i);
}
}
/**
* Validator function in order to validate decimal numbers.
* @returns {ValidatorFn} A validator function that returns an error map containing `pattern`
* if the validation check fails, otherwise `null`.
*/
static decimalNumber(allowsNegative: boolean = true): ValidatorFn {
if (allowsNegative) {
return Validators.pattern(/^-?[0-9]+(.[0-9]+)?$/i);
} else {
return Validators.pattern(/^[0-9]+(.[0-9]+)?$/i);
}
}
/**
* Validator that performs SSL certificate validation.
* @returns {ValidatorFn} A validator function that returns an error map containing `pattern`
* if the validation check fails, otherwise `null`.
*/
static sslCert(): ValidatorFn {
return Validators.pattern(
/^-----BEGIN CERTIFICATE-----(\n|\r|\f)((.+)?((\n|\r|\f).+)*)(\n|\r|\f)-----END CERTIFICATE-----[\n\r\f]*$/
);
}
/**
* Validator that performs SSL private key validation.
* @returns {ValidatorFn} A validator function that returns an error map containing `pattern`
* if the validation check fails, otherwise `null`.
*/
static sslPrivKey(): ValidatorFn {
return Validators.pattern(
/^-----BEGIN RSA PRIVATE KEY-----(\n|\r|\f)((.+)?((\n|\r|\f).+)*)(\n|\r|\f)-----END RSA PRIVATE KEY-----[\n\r\f]*$/
);
}
/**
* Validator that performs SSL certificate validation of pem format.
* @returns {ValidatorFn} A validator function that returns an error map containing `pattern`
* if the validation check fails, otherwise `null`.
*/
static pemCert(): ValidatorFn {
return Validators.pattern(/^-----BEGIN .+-----$.+^-----END .+-----$/ms);
}
/**
* Validator that requires controls to fulfill the specified condition if
* the specified prerequisites matches. If the prerequisites are fulfilled,
* then the given function is executed and if it succeeds, the 'required'
* validation error will be returned, otherwise null.
* @param {Object} prerequisites An object containing the prerequisites.
* To do additional checks rather than checking for equality you can
* use the extended prerequisite syntax:
* 'field_name': { 'op': '<OPERATOR>', arg1: '<OPERATOR_ARGUMENT>' }
* The following operators are supported:
* * empty
* * !empty
* * equal
* * !equal
* * minLength
* ### Example
* ```typescript
* {
* 'generate_key': true,
* 'username': 'Max Mustermann'
* }
* ```
* ### Example - Extended prerequisites
* ```typescript
* {
* 'generate_key': { 'op': 'equal', 'arg1': true },
* 'username': { 'op': 'minLength', 'arg1': 5 }
* }
* ```
* Only if all prerequisites are fulfilled, then the validation of the
* control will be triggered.
* @param {Function | undefined} condition The function to be executed when all
* prerequisites are fulfilled. If not set, then the {@link isEmptyInputValue}
* function will be used by default. The control's value is used as function
* argument. The function must return true to set the validation error.
* @return {ValidatorFn} Returns the validator function.
*/
static requiredIf(prerequisites: object, condition?: Function | undefined): ValidatorFn {
let isWatched = false;
return (control: AbstractControl): ValidationErrors | null => {
if (!isWatched && control.parent) {
Object.keys(prerequisites).forEach((key) => {
control.parent.get(key).valueChanges.subscribe(() => {
control.updateValueAndValidity({ emitEvent: false });
});
});
isWatched = true;
}
// Check if all prerequisites met.
if (
!Object.keys(prerequisites).every((key) => {
if (!control.parent) {
return false;
}
const value = control.parent.get(key).value;
const prerequisite = prerequisites[key];
if (_.isObjectLike(prerequisite)) {
let result = false;
switch (prerequisite['op']) {
case 'empty':
result = _.isEmpty(value);
break;
case '!empty':
result = !_.isEmpty(value);
break;
case 'equal':
result = value === prerequisite['arg1'];
break;
case '!equal':
result = value !== prerequisite['arg1'];
break;
case 'minLength':
if (_.isString(value)) {
result = value.length >= prerequisite['arg1'];
}
break;
}
return result;
}
return value === prerequisite;
})
) {
return null;
}
const success = _.isFunction(condition)
? condition.call(condition, control.value)
: isEmptyInputValue(control.value);
return success ? { required: true } : null;
};
}
/**
* Compose multiple validators into a single function that returns the union of
* the individual error maps for the provided control when the given prerequisites
* are fulfilled.
*
* @param {Object} prerequisites An object containing the prerequisites as
* key/value pairs.
* ### Example
* ```typescript
* {
* 'generate_key': true,
* 'username': 'Max Mustermann'
* }
* ```
* @param {ValidatorFn[]} validators List of validators that should be taken
* into action when the prerequisites are met.
* @return {ValidatorFn} Returns the validator function.
*/
static composeIf(prerequisites: object, validators: ValidatorFn[]): ValidatorFn {
let isWatched = false;
return (control: AbstractControl): ValidationErrors | null => {
if (!isWatched && control.parent) {
Object.keys(prerequisites).forEach((key) => {
control.parent.get(key).valueChanges.subscribe(() => {
control.updateValueAndValidity({ emitEvent: false });
});
});
isWatched = true;
}
// Check if all prerequisites are met.
if (
!Object.keys(prerequisites).every((key) => {
return control.parent && control.parent.get(key).value === prerequisites[key];
})
) {
return null;
}
return Validators.compose(validators)(control);
};
}
/**
* Custom validation by passing a name for the error and a function as error condition.
*
* @param {string} error
* @param {Function} condition - a truthy return value will trigger the error
* @returns {ValidatorFn}
*/
static custom(error: string, condition: Function): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
const value = condition.call(this, control.value);
if (value) {
return { [error]: value };
}
return null;
};
}
/**
* Validate form control if condition is true with validators.
*
* @param {AbstractControl} formControl
* @param {Function} condition
* @param {ValidatorFn[]} conditionalValidators List of validators that should only be tested
* when the condition is met
* @param {ValidatorFn[]} permanentValidators List of validators that should always be tested
* @param {AbstractControl[]} watchControls List of controls that the condition depend on.
* Every time one of this controls value is updated, the validation will be triggered
*/
static validateIf(
formControl: AbstractControl,
condition: Function,
conditionalValidators: ValidatorFn[],
permanentValidators: ValidatorFn[] = [],
watchControls: AbstractControl[] = []
) {
conditionalValidators = conditionalValidators.concat(permanentValidators);
formControl.setValidators((control: AbstractControl): {
[key: string]: any;
} => {
const value = condition.call(this);
if (value) {
return Validators.compose(conditionalValidators)(control);
}
if (permanentValidators.length > 0) {
return Validators.compose(permanentValidators)(control);
}
return null;
});
watchControls.forEach((control: AbstractControl) => {
control.valueChanges.subscribe(() => {
formControl.updateValueAndValidity({ emitEvent: false });
});
});
}
/**
* Validator that requires that both specified controls have the same value.
* Error will be added to the `path2` control.
* @param {string} path1 A dot-delimited string that define the path to the control.
* @param {string} path2 A dot-delimited string that define the path to the control.
* @return {ValidatorFn} Returns a validator function that always returns `null`.
* If the validation fails an error map with the `match` property will be set
* on the `path2` control.
*/
static match(path1: string, path2: string): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
const ctrl1 = control.get(path1);
const ctrl2 = control.get(path2);
if (!ctrl1 || !ctrl2) {
return null;
}
if (ctrl1.value !== ctrl2.value) {
ctrl2.setErrors({ match: true });
} else {
const hasError = ctrl2.hasError('match');
if (hasError) {
// Remove the 'match' error. If no more errors exists, then set
// the error value to 'null', otherwise the field is still marked
// as invalid.
const errors = ctrl2.errors;
_.unset(errors, 'match');
ctrl2.setErrors(_.isEmpty(_.keys(errors)) ? null : errors);
}
}
return null;
};
}
/**
* Asynchronous validator that requires the control's value to be unique.
* The validation is only executed after the specified delay. Every
* keystroke during this delay will restart the timer.
* @param serviceFn {existsServiceFn} The service function that is
* called to check whether the given value exists. It must return
* boolean 'true' if the given value exists, otherwise 'false'.
* @param serviceFnThis {any} The object to be used as the 'this' object
* when calling the serviceFn function. Defaults to null.
* @param {number|Date} dueTime The delay time to wait before the
* serviceFn call is executed. This is useful to prevent calls on
* every keystroke. Defaults to 500.
* @return {AsyncValidatorFn} Returns an asynchronous validator function
* that returns an error map with the `notUnique` property if the
* validation check succeeds, otherwise `null`.
*/
static unique(
serviceFn: existsServiceFn,
serviceFnThis: any = null,
usernameFn?: Function,
uidField = false
): AsyncValidatorFn {
let uName: string;
return (control: AbstractControl): Observable<ValidationErrors | null> => {
// Exit immediately if user has not interacted with the control yet
// or the control value is empty.
if (control.pristine || isEmptyInputValue(control.value)) {
return observableOf(null);
}
uName = control.value;
if (_.isFunction(usernameFn) && usernameFn() !== null && usernameFn() !== '') {
if (uidField) {
uName = `${control.value}$${usernameFn()}`;
} else {
uName = `${usernameFn()}$${control.value}`;
}
}
return observableTimer().pipe(
switchMapTo(serviceFn.call(serviceFnThis, uName)),
map((resp: boolean) => {
if (!resp) {
return null;
} else {
return { notUnique: true };
}
}),
take(1)
);
};
}
/**
* Validator function for UUIDs.
* @param required - Defines if it is mandatory to fill in the UUID
* @return Validator function that returns an error object containing `invalidUuid` if the
* validation failed, `null` otherwise.
*/
static uuid(required = false): ValidatorFn {
const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return (control: AbstractControl): { [key: string]: any } | null => {
if (control.pristine && control.untouched) {
return null;
} else if (!required && !control.value) {
return null;
} else if (uuidRe.test(control.value)) {
return null;
}
return { invalidUuid: 'This is not a valid UUID' };
};
}
/**
* A simple minimum validator vor cd-binary inputs.
*
* To use the validation message pass I18n into the function as it cannot
* be called in a static one.
*/
static binaryMin(bytes: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: () => string } | null => {
const formatterService = new FormatterService();
const currentBytes = new FormatterService().toBytes(control.value);
if (bytes <= currentBytes) {
return null;
}
const value = new DimlessBinaryPipe(formatterService).transform(bytes);
return {
binaryMin: () => $localize`Size has to be at least ${value} or more`
};
};
}
/**
* A simple maximum validator vor cd-binary inputs.
*
* To use the validation message pass I18n into the function as it cannot
* be called in a static one.
*/
static binaryMax(bytes: number): ValidatorFn {
return (control: AbstractControl): { [key: string]: () => string } | null => {
const formatterService = new FormatterService();
const currentBytes = formatterService.toBytes(control.value);
if (bytes >= currentBytes) {
return null;
}
const value = new DimlessBinaryPipe(formatterService).transform(bytes);
return {
binaryMax: () => $localize`Size has to be at most ${value} or less`
};
};
}
/**
* Asynchronous validator that checks if the password meets the password
* policy.
* @param userServiceThis The object to be used as the 'this' object
* when calling the 'validatePassword' method of the 'UserService'.
* @param usernameFn Function to get the username that should be
* taken into account.
* @param callback Callback function that is called after the validation
* has been done.
* @return {AsyncValidatorFn} Returns an asynchronous validator function
* that returns an error map with the `passwordPolicy` property if the
* validation check fails, otherwise `null`.
*/
static passwordPolicy(
userServiceThis: any,
usernameFn?: Function,
callback?: (valid: boolean, credits?: number, valuation?: string) => void
): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
if (control.pristine || control.value === '') {
if (_.isFunction(callback)) {
callback(true, 0);
}
return observableOf(null);
}
let username;
if (_.isFunction(usernameFn)) {
username = usernameFn();
}
return observableTimer(500).pipe(
switchMapTo(_.invoke(userServiceThis, 'validatePassword', control.value, username)),
map((resp: { valid: boolean; credits: number; valuation: string }) => {
if (_.isFunction(callback)) {
callback(resp.valid, resp.credits, resp.valuation);
}
if (resp.valid) {
return null;
} else {
return { passwordPolicy: true };
}
}),
take(1)
);
};
}
/**
* Validate the bucket name. In general, bucket names should follow domain
* name constraints:
* - Bucket names must be unique.
* - Bucket names cannot be formatted as IP address.
* - Bucket names can be between 3 and 63 characters long.
* - Bucket names must not contain uppercase characters or underscores.
* - Bucket names must start with a lowercase letter or number.
* - Bucket names must be a series of one or more labels. Adjacent
* labels are separated by a single period (.). Bucket names can
* contain lowercase letters, numbers, and hyphens. Each label must
* start and end with a lowercase letter or a number.
*/
static bucketName(): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
if (control.pristine || !control.value) {
return observableOf({ required: true });
}
const constraints = [];
let errorName: string;
// - Bucket names cannot be formatted as IP address.
constraints.push(() => {
const 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;
const ipv6Rgx = /^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}$/i;
const name = control.value;
let notIP = true;
if (ipv4Rgx.test(name) || ipv6Rgx.test(name)) {
errorName = 'ipAddress';
notIP = false;
}
return notIP;
});
// - Bucket names can be between 3 and 63 characters long.
constraints.push((name: string) => {
if (!_.inRange(name.length, 3, 64)) {
errorName = 'shouldBeInRange';
return false;
}
// Bucket names can only contain lowercase letters, numbers, periods and hyphens.
if (!/^[0-9a-z.-]+$/.test(control.value)) {
errorName = 'bucketNameInvalid';
return false;
}
return true;
});
// - Bucket names must not contain uppercase characters or underscores.
// - Bucket names must start with a lowercase letter or number.
// - Bucket names must be a series of one or more labels. Adjacent
// labels are separated by a single period (.). Bucket names can
// contain lowercase letters, numbers, and hyphens. Each label must
// start and end with a lowercase letter or a number.
constraints.push((name: string) => {
const labels = _.split(name, '.');
return _.every(labels, (label) => {
// Bucket names must not contain uppercase characters or underscores.
if (label !== _.toLower(label) || label.includes('_')) {
errorName = 'containsUpperCase';
return false;
}
// Bucket labels can contain lowercase letters, numbers, and hyphens.
if (!/^[0-9a-z-]+$/.test(label)) {
errorName = 'onlyLowerCaseAndNumbers';
return false;
}
// Each label must start and end with a lowercase letter or a number.
return _.every([0, label.length - 1], (index) => {
errorName = 'lowerCaseOrNumber';
return /[a-z]/.test(label[index]) || _.isInteger(_.parseInt(label[index]));
});
});
});
if (!_.every(constraints, (func: Function) => func(control.value))) {
return observableOf(
(() => {
switch (errorName) {
case 'onlyLowerCaseAndNumbers':
return { onlyLowerCaseAndNumbers: true };
case 'shouldBeInRange':
return { shouldBeInRange: true };
case 'ipAddress':
return { ipAddress: true };
case 'containsUpperCase':
return { containsUpperCase: true };
case 'lowerCaseOrNumber':
return { lowerCaseOrNumber: true };
default:
return { bucketNameInvalid: true };
}
})()
);
}
return observableOf(null);
};
}
static bucketExistence(
requiredExistenceResult: boolean,
rgwBucketService: RgwBucketService
): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
if (control.pristine || !control.value) {
return observableOf({ required: true });
}
return rgwBucketService
.exists(control.value)
.pipe(
map((existenceResult: boolean) =>
existenceResult === requiredExistenceResult ? null : { bucketNameNotAllowed: true }
)
);
};
}
}
| 22,558 | 35.800979 | 121 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/crud-form.component.html
|
<div class="cd-col-form">
<div class="card pb-0"
*ngIf="formUISchema$ | async as formUISchema">
<div i18n="form title"
class="card-header">{{ formUISchema.title }}</div>
<form *ngIf="formUISchema.uiSchema"
[formGroup]="form"
(ngSubmit)="submit(model, formUISchema.taskInfo)">
<div class="card-body position-relative">
<formly-form [form]="form"
[fields]="formUISchema.controlSchema"
[model]="model"
[options]="{formState: formUISchema.uiSchema}"></formly-form>
</div>
<div class="card-footer">
<cd-form-button-panel (submitActionEvent)="submit(model, formUISchema.taskInfo)"
[form]="formDir"
[submitText]="formUISchema.title"
[disabled]="!form.valid"
wrappingClass="text-right"></cd-form-button-panel>
</div>
</form>
</div>
</div>
| 1,007 | 37.769231 | 88 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/crud-form.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ToastrModule, ToastrService } from 'ngx-toastr';
import { configureTestBed } from '~/testing/unit-test-helper';
import { CdDatePipe } from '~/app/shared/pipes/cd-date.pipe';
import { CrudFormComponent } from './crud-form.component';
import { RouterTestingModule } from '@angular/router/testing';
describe('CrudFormComponent', () => {
let component: CrudFormComponent;
let fixture: ComponentFixture<CrudFormComponent>;
const toastFakeService = {
error: () => true,
info: () => true,
success: () => true
};
configureTestBed({
imports: [ToastrModule.forRoot(), RouterTestingModule, HttpClientTestingModule],
providers: [
{ provide: ToastrService, useValue: toastFakeService },
{ provide: CdDatePipe, useValue: { transform: (d: any) => d } }
]
});
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [CrudFormComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(CrudFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,323 | 29.790698 | 84 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/crud-form.component.ts
|
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { DataGatewayService } from '~/app/shared/services/data-gateway.service';
import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service';
import { FinishedTask } from '~/app/shared/models/finished-task';
import { Location } from '@angular/common';
import { FormGroup } from '@angular/forms';
import { mergeMap } from 'rxjs/operators';
import { CrudTaskInfo, JsonFormUISchema } from './crud-form.model';
import { Observable } from 'rxjs';
import _ from 'lodash';
import { CdTableSelection } from '../../models/cd-table-selection';
@Component({
selector: 'cd-crud-form',
templateUrl: './crud-form.component.html',
styleUrls: ['./crud-form.component.scss']
})
export class CrudFormComponent implements OnInit {
model: any = {};
resource: string;
task: { message: string; id: string } = { message: '', id: '' };
form = new FormGroup({});
formUISchema$: Observable<JsonFormUISchema>;
methodType: string;
urlFormName: string;
key: string = '';
selected: CdTableSelection;
constructor(
private dataGatewayService: DataGatewayService,
private activatedRoute: ActivatedRoute,
private taskWrapper: TaskWrapperService,
private location: Location,
private router: Router
) {}
ngOnInit(): void {
this.activatedRoute.queryParamMap.subscribe((paramMap) => {
this.formUISchema$ = this.activatedRoute.data.pipe(
mergeMap((data: any) => {
this.resource = data.resource || this.resource;
const url = '/' + this.activatedRoute.snapshot.url.join('/');
const key = paramMap.get('key') || '';
return this.dataGatewayService.form(`ui-${this.resource}`, url, key);
})
);
this.formUISchema$.subscribe((data: any) => {
this.methodType = data.methodType;
this.model = data.model;
});
this.urlFormName = this.router.url.split('/').pop();
// remove optional arguments
const paramIndex = this.urlFormName.indexOf('?');
if (paramIndex > 0) {
this.urlFormName = this.urlFormName.substring(0, paramIndex);
}
});
}
async readFileAsText(file: File): Promise<string> {
let fileReader = new FileReader();
let text: string = '';
await new Promise((resolve) => {
fileReader.onload = (_) => {
text = fileReader.result.toString();
resolve(true);
};
fileReader.readAsText(file);
});
return text;
}
async preSubmit(data: { [name: string]: any }) {
for (const [key, value] of Object.entries(data)) {
if (value instanceof FileList) {
let file = value[0];
let text = await this.readFileAsText(file);
data[key] = text;
}
}
}
async submit(data: { [name: string]: any }, taskInfo: CrudTaskInfo) {
if (data) {
let taskMetadata = {};
_.forEach(taskInfo.metadataFields, (field) => {
taskMetadata[field] = data[field];
});
taskMetadata['__message'] = taskInfo.message;
await this.preSubmit(data);
this.taskWrapper
.wrapTaskAroundCall({
task: new FinishedTask(`crud-component/${this.urlFormName}`, taskMetadata),
call: this.dataGatewayService.submit(this.resource, data, this.methodType)
})
.subscribe({
complete: () => {
this.location.back();
}
});
}
}
}
| 3,480 | 32.152381 | 85 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/crud-form.model.ts
|
import { FormlyFieldConfig } from '@ngx-formly/core';
export interface CrudTaskInfo {
metadataFields: string[];
message: string;
}
export interface JsonFormUISchema {
title: string;
controlSchema: FormlyFieldConfig[];
uiSchema: any;
taskInfo: CrudTaskInfo;
methodType: string;
model: any;
}
| 309 | 18.375 | 53 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/helpers.ts
|
import { ValidatorFn } from '@angular/forms';
import { FormlyFieldConfig } from '@ngx-formly/core';
import { forEach } from 'lodash';
import { formlyAsyncFileValidator } from './validators/file-validator';
import { formlyAsyncJsonValidator } from './validators/json-validator';
import { formlyRgwRoleNameValidator, formlyRgwRolePath } from './validators/rgw-role-validator';
export function getFieldState(field: FormlyFieldConfig, uiSchema: any[] = undefined) {
const formState: any[] = uiSchema || field.options?.formState;
if (formState) {
return formState.find((element) => element.key == field.key);
}
return {};
}
export function setupValidators(field: FormlyFieldConfig, uiSchema: any[]) {
const fieldState = getFieldState(field, uiSchema);
let validators: ValidatorFn[] = [];
forEach(fieldState.validators, (validatorStr) => {
switch (validatorStr) {
case 'json': {
validators.push(formlyAsyncJsonValidator);
break;
}
case 'rgwRoleName': {
validators.push(formlyRgwRoleNameValidator);
break;
}
case 'rgwRolePath': {
validators.push(formlyRgwRolePath);
break;
}
case 'file': {
validators.push(formlyAsyncFileValidator);
break;
}
}
});
field.asyncValidators = { validation: validators };
}
| 1,339 | 31.682927 | 96 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-array-type/formly-array-type.component.html
|
<div class="mb-3">
<legend *ngIf="props.label"
class="cd-header mt-1"
i18n>{{ props.label }}</legend>
<p *ngIf="props.description"
i18n>{{ props.description }}</p>
<div *ngFor="let field of field.fieldGroup; let i = index"
class="d-flex">
<formly-field class="col"
[field]="field"></formly-field>
<div class="action-btn">
<button class="btn btn-light ms-1"
type="button"
(click)="addWrapper()">
<i [ngClass]="icons.add"></i>
</button>
<button class="btn btn-light ms-1"
type="button"
(click)="remove(i)"
*ngIf="field.props.removable !== false">
<i [ngClass]="icons.trash"></i>
</button>
</div>
</div>
<div *ngIf="field.fieldGroup.length === 0"
class="text-right">
<button class="btn btn-light"
type="button"
(click)="addWrapper()"
i18n>
<i [ngClass]="icons.add"></i>
Add {{ props.label }}
</button>
</div>
<span class="invalid-feedback"
role="alert"
*ngIf="showError && formControl.errors">
<formly-validation-message [field]="field"></formly-validation-message>
</span>
</div>
| 1,251 | 28.116279 | 75 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-array-type/formly-array-type.component.spec.ts
|
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig, FormlyModule } from '@ngx-formly/core';
import { FormlyArrayTypeComponent } from './formly-array-type.component';
@Component({
template: ` <form [formGroup]="form">
<formly-form [model]="{}" [fields]="fields" [options]="{}" [form]="form"></formly-form>
</form>`
})
class MockFormComponent {
form = new FormGroup({});
fields: FormlyFieldConfig[] = [
{
wrappers: ['input'],
defaultValue: {}
}
];
}
describe('FormlyArrayTypeComponent', () => {
let component: MockFormComponent;
let fixture: ComponentFixture<MockFormComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [FormlyArrayTypeComponent],
imports: [
FormlyModule.forRoot({
types: [{ name: 'array', component: FormlyArrayTypeComponent }]
})
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MockFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,276 | 26.170213 | 91 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-array-type/formly-array-type.component.ts
|
/** Copyright 2021 Formly. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at https://github.com/ngx-formly/ngx-formly/blob/main/LICENSE */
import { Component, OnInit } from '@angular/core';
import { FieldArrayType } from '@ngx-formly/core';
import { forEach } from 'lodash';
import { Icons } from '~/app/shared/enum/icons.enum';
@Component({
selector: 'cd-formly-array-type',
templateUrl: './formly-array-type.component.html',
styleUrls: ['./formly-array-type.component.scss']
})
export class FormlyArrayTypeComponent extends FieldArrayType implements OnInit {
icons = Icons;
ngOnInit(): void {
this.propagateTemplateOptions();
}
addWrapper() {
this.add();
this.propagateTemplateOptions();
}
propagateTemplateOptions() {
forEach(this.field.fieldGroup, (field) => {
if (field.type == 'object') {
field.props.templateOptions = this.props.templateOptions.objectTemplateOptions;
}
});
}
}
| 1,031 | 28.485714 | 101 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-file-type/formly-file-type-accessor.ts
|
import { Directive } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';
@Directive({
// eslint-disable-next-line
selector: 'input[type=file]',
// eslint-disable-next-line
host: {
'(change)': 'onChange($event.target.files)',
'(input)': 'onChange($event.target.files)',
'(blur)': 'onTouched()'
},
providers: [
{ provide: NG_VALUE_ACCESSOR, useExisting: FormlyFileValueAccessorDirective, multi: true }
]
})
// https://github.com/angular/angular/issues/7341
export class FormlyFileValueAccessorDirective implements ControlValueAccessor {
value: any;
onChange = (_: any) => {};
onTouched = () => {};
writeValue(_value: any) {}
registerOnChange(fn: any) {
this.onChange = fn;
}
registerOnTouched(fn: any) {
this.onTouched = fn;
}
}
| 826 | 26.566667 | 94 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-file-type/formly-file-type.component.html
|
<input type="file"
[formControl]="formControl"
[formlyAttributes]="field"
/>
| 98 | 18.8 | 34 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-file-type/formly-file-type.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormControl } from '@angular/forms';
import { FormlyModule } from '@ngx-formly/core';
import { FormlyFileTypeComponent } from './formly-file-type.component';
describe('FormlyFileTypeComponent', () => {
let component: FormlyFileTypeComponent;
let fixture: ComponentFixture<FormlyFileTypeComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [FormlyModule.forRoot()],
declarations: [FormlyFileTypeComponent]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(FormlyFileTypeComponent);
component = fixture.componentInstance;
const formControl = new FormControl();
const field = {
key: 'file',
type: 'file',
templateOptions: {},
get formControl() {
return formControl;
}
};
component.field = field;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,043 | 24.463415 | 71 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-file-type/formly-file-type.component.ts
|
import { Component } from '@angular/core';
import { FieldType } from '@ngx-formly/core';
@Component({
selector: 'cd-formly-file-type',
templateUrl: './formly-file-type.component.html',
styleUrls: ['./formly-file-type.component.scss']
})
export class FormlyFileTypeComponent extends FieldType {}
| 302 | 29.3 | 57 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-input-type/formly-input-type.component.html
|
<input [formControl]="formControl"
[formlyAttributes]="field"
class="form-control col-form-input"/>
| 114 | 27.75 | 44 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-input-type/formly-input-type.component.spec.ts
|
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig, FormlyModule } from '@ngx-formly/core';
import { FormlyInputTypeComponent } from './formly-input-type.component';
@Component({
template: ` <form [formGroup]="form">
<formly-form [model]="{}" [fields]="fields" [options]="{}" [form]="form"></formly-form>
</form>`
})
class MockFormComponent {
form = new FormGroup({});
fields: FormlyFieldConfig[] = [
{
wrappers: ['input'],
defaultValue: {}
}
];
}
describe('FormlyInputTypeComponent', () => {
let component: MockFormComponent;
let fixture: ComponentFixture<MockFormComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [FormlyInputTypeComponent],
imports: [
FormlyModule.forRoot({
types: [{ name: 'input', component: FormlyInputTypeComponent }]
})
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MockFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,277 | 25.625 | 91 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-input-type/formly-input-type.component.ts
|
import { Component } from '@angular/core';
import { FieldType, FieldTypeConfig } from '@ngx-formly/core';
@Component({
selector: 'cd-formly-input-type',
templateUrl: './formly-input-type.component.html',
styleUrls: ['./formly-input-type.component.scss']
})
export class FormlyInputTypeComponent extends FieldType<FieldTypeConfig> {}
| 340 | 33.1 | 75 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-input-wrapper/formly-input-wrapper.component.html
|
<ng-template #labelTemplate>
<div class="d-flex align-items-center">
<label *ngIf="props.label && props.hideLabel !== true"
[attr.for]="id"
class="form-label">
{{ props.label }}
<span *ngIf="props.required && props.hideRequiredMarker !== true"
aria-hidden="true">*</span>
<cd-helper *ngIf="helper">
<span [innerHTML]="helper"></span>
</cd-helper>
</label>
</div>
</ng-template>
<div class="mb-3"
[class.form-floating]="props.labelPosition === 'floating'"
[class.has-error]="showError">
<ng-container *ngIf="props.labelPosition !== 'floating'">
<ng-container [ngTemplateOutlet]="labelTemplate"></ng-container>
</ng-container>
<ng-container #fieldComponent></ng-container>
<ng-container *ngIf="props.labelPosition === 'floating'">
<ng-container [ngTemplateOutlet]="labelTemplate"></ng-container>
</ng-container>
<div *ngIf="showError"
class="invalid-feedback"
[style.display]="'block'">
<formly-validation-message [field]="field"></formly-validation-message>
</div>
<small *ngIf="props.description"
class="form-text text-muted">{{ props.description }}</small>
</div>
| 1,209 | 30.842105 | 75 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-input-wrapper/formly-input-wrapper.component.spec.ts
|
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig, FormlyModule } from '@ngx-formly/core';
import { FormlyInputWrapperComponent } from './formly-input-wrapper.component';
@Component({
template: ` <form [formGroup]="form">
<formly-form [model]="{}" [fields]="fields" [options]="{}" [form]="form"></formly-form>
</form>`
})
class MockFormComponent {
form = new FormGroup({});
fields: FormlyFieldConfig[] = [
{
wrappers: ['input'],
defaultValue: {}
}
];
}
describe('FormlyInputWrapperComponent', () => {
let component: MockFormComponent;
let fixture: ComponentFixture<MockFormComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [FormlyInputWrapperComponent],
imports: [
FormlyModule.forRoot({
types: [{ name: 'input', component: FormlyInputWrapperComponent }]
})
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MockFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,292 | 25.9375 | 91 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-input-wrapper/formly-input-wrapper.component.ts
|
import { Component } from '@angular/core';
import { FieldWrapper } from '@ngx-formly/core';
import { getFieldState } from '../helpers';
@Component({
selector: 'cd-formly-input-wrapper',
templateUrl: './formly-input-wrapper.component.html',
styleUrls: ['./formly-input-wrapper.component.scss']
})
export class FormlyInputWrapperComponent extends FieldWrapper {
get helper(): string {
const fieldState = getFieldState(this.field);
return fieldState?.help || '';
}
}
| 483 | 29.25 | 63 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-object-type/formly-object-type.component.html
|
<div class="mb-3">
<legend *ngIf="props.label"
class="cd-col-form-label"
i18n>{{ props.label }}</legend>
<p *ngIf="props.description"
i18n>{{ props.description }}</p>
<div class="alert alert-danger"
role="alert"
*ngIf="showError && formControl.errors">
<formly-validation-message [field]="field"></formly-validation-message>
</div>
<div [ngClass]="inputClass">
<formly-field *ngFor="let f of field.fieldGroup"
[field]="f"
class="flex-grow-1"></formly-field>
</div>
</div>
| 567 | 30.555556 | 75 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-object-type/formly-object-type.component.spec.ts
|
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormlyObjectTypeComponent } from './formly-object-type.component';
import { FormlyFieldConfig, FormlyModule } from '@ngx-formly/core';
import { Component } from '@angular/core';
import { FormGroup } from '@angular/forms';
@Component({
template: ` <form [formGroup]="form">
<formly-form [model]="{}" [fields]="fields" [options]="{}" [form]="form"></formly-form>
</form>`
})
class MockFormComponent {
form = new FormGroup({});
fields: FormlyFieldConfig[] = [
{
wrappers: ['object'],
defaultValue: {}
}
];
}
describe('FormlyObjectTypeComponent', () => {
let fixture: ComponentFixture<MockFormComponent>;
let mockComponent: MockFormComponent;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [FormlyObjectTypeComponent],
imports: [
FormlyModule.forRoot({
types: [{ name: 'object', component: FormlyObjectTypeComponent }]
})
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MockFormComponent);
mockComponent = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(mockComponent).toBeTruthy();
});
});
| 1,296 | 26.020833 | 91 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-object-type/formly-object-type.component.ts
|
/** Copyright 2021 Formly. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at https://github.com/ngx-formly/ngx-formly/blob/main/LICENSE */
import { Component } from '@angular/core';
import { FieldType } from '@ngx-formly/core';
@Component({
selector: 'cd-formly-object-type',
templateUrl: './formly-object-type.component.html',
styleUrls: ['./formly-object-type.component.scss']
})
export class FormlyObjectTypeComponent extends FieldType {
get inputClass(): string {
const layoutType = this.props.templateOptions?.layoutType;
const defaultFlexClasses = 'd-flex justify-content-center align-content-stretch gap-3';
if (layoutType == 'row') {
return defaultFlexClasses + ' flex-row';
}
return defaultFlexClasses + ' flex-column';
}
}
| 852 | 36.086957 | 101 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-textarea-type/formly-textarea-type.component.html
|
<textarea #textArea
[formControl]="formControl"
[cols]="props.cols"
[rows]="props.rows"
class="form-control"
[class.is-invalid]="showError"
[formlyAttributes]="field"
(change)="onChange()">
</textarea>
| 272 | 26.3 | 40 |
html
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-textarea-type/formly-textarea-type.component.spec.ts
|
import { Component } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { FormGroup } from '@angular/forms';
import { FormlyFieldConfig, FormlyModule } from '@ngx-formly/core';
import { FormlyTextareaTypeComponent } from './formly-textarea-type.component';
@Component({
template: ` <form [formGroup]="form">
<formly-form [model]="{}" [fields]="fields" [options]="{}" [form]="form"></formly-form>
</form>`
})
class MockFormComponent {
options = {};
form = new FormGroup({});
fields: FormlyFieldConfig[] = [
{
wrappers: ['input'],
defaultValue: {}
}
];
}
describe('FormlyTextareaTypeComponent', () => {
let component: MockFormComponent;
let fixture: ComponentFixture<MockFormComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [FormlyTextareaTypeComponent],
imports: [
FormlyModule.forRoot({
types: [{ name: 'input', component: FormlyTextareaTypeComponent }]
})
]
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MockFormComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
| 1,307 | 26.25 | 91 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/formly-textarea-type/formly-textarea-type.component.ts
|
import { Component, ViewChild, ElementRef } from '@angular/core';
import { FieldType, FieldTypeConfig } from '@ngx-formly/core';
@Component({
selector: 'cd-formly-textarea-type',
templateUrl: './formly-textarea-type.component.html',
styleUrls: ['./formly-textarea-type.component.scss']
})
export class FormlyTextareaTypeComponent extends FieldType<FieldTypeConfig> {
@ViewChild('textArea')
public textArea: ElementRef<any>;
onChange() {
const value = this.textArea.nativeElement.value;
try {
const formatted = JSON.stringify(JSON.parse(value), null, 2);
this.textArea.nativeElement.value = formatted;
this.textArea.nativeElement.style.height = 'auto';
const lineNumber = formatted.split('\n').length;
const pixelPerLine = 25;
const pixels = lineNumber * pixelPerLine;
this.textArea.nativeElement.style.height = pixels + 'px';
} catch (e) {}
}
}
| 915 | 34.230769 | 77 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/validators/file-validator.ts
|
import { AbstractControl } from '@angular/forms';
export function formlyAsyncFileValidator(control: AbstractControl): Promise<any> {
return new Promise((resolve, _reject) => {
if (control.value instanceof FileList) {
control.value;
let file = control.value[0];
if (file.size > 4096) {
resolve({ file_size: true });
}
resolve(null);
}
resolve({ not_a_file: true });
});
}
| 426 | 25.6875 | 82 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/validators/json-validator.ts
|
import { AbstractControl } from '@angular/forms';
export function formlyAsyncJsonValidator(control: AbstractControl): Promise<any> {
return new Promise((resolve, _reject) => {
try {
JSON.parse(control.value);
resolve(null);
} catch (e) {
resolve({ json: true });
}
});
}
| 306 | 22.615385 | 82 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/forms/crud-form/validators/rgw-role-validator.ts
|
import { AbstractControl } from '@angular/forms';
export function formlyRgwRolePath(control: AbstractControl): Promise<any> {
return new Promise((resolve, _reject) => {
if (control.value.match('^((\u002F)|(\u002F[\u0021-\u007E]+\u002F))$')) {
resolve(null);
}
resolve({ rgwRolePath: true });
});
}
export function formlyRgwRoleNameValidator(control: AbstractControl): Promise<any> {
return new Promise((resolve, _reject) => {
if (control.value.match('^[0-9a-zA-Z_+=,.@-]+$')) {
resolve(null);
}
resolve({ rgwRoleName: true });
});
}
| 579 | 28 | 84 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/helpers/helpers.module.ts
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
@NgModule({
declarations: [],
imports: [CommonModule]
})
export class HelpersModule {}
| 182 | 19.333333 | 47 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/helpers/prometheus-list-helper.ts
|
import { Directive, OnInit } from '@angular/core';
import { PrometheusService } from '~/app/shared/api/prometheus.service';
import { ListWithDetails } from '~/app/shared/classes/list-with-details.class';
@Directive()
// tslint:disable-next-line: directive-class-suffix
export class PrometheusListHelper extends ListWithDetails implements OnInit {
public isPrometheusConfigured = false;
public isAlertmanagerConfigured = false;
constructor(protected prometheusService: PrometheusService) {
super();
}
ngOnInit() {
this.prometheusService.ifAlertmanagerConfigured(() => {
this.isAlertmanagerConfigured = true;
});
this.prometheusService.ifPrometheusConfigured(() => {
this.isPrometheusConfigured = true;
});
}
}
| 757 | 29.32 | 79 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/alertmanager-silence.ts
|
import { PrometheusRule } from './prometheus-alerts';
export class AlertmanagerSilenceMatcher {
name: string;
value: any;
isRegex: boolean;
}
export class AlertmanagerSilenceMatcherMatch {
status: string;
cssClass: string;
}
export class AlertmanagerSilence {
id?: string;
matchers: AlertmanagerSilenceMatcher[];
startsAt: string; // DateStr
endsAt: string; // DateStr
updatedAt?: string; // DateStr
createdBy: string;
comment: string;
status?: {
state: 'expired' | 'active' | 'pending';
};
silencedAlerts?: PrometheusRule[];
}
| 565 | 19.962963 | 53 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/breadcrumbs.ts
|
/*
The MIT License
Copyright (c) 2017 (null) McNull https://github.com/McNull
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { ActivatedRouteSnapshot, Resolve, UrlSegment } from '@angular/router';
import { Observable, of } from 'rxjs';
export class BreadcrumbsResolver implements Resolve<IBreadcrumb[]> {
public resolve(
route: ActivatedRouteSnapshot
): Observable<IBreadcrumb[]> | Promise<IBreadcrumb[]> | IBreadcrumb[] {
const data = route.routeConfig.data;
const path = data.path === null ? null : this.getFullPath(route);
const text =
typeof data.breadcrumbs === 'string'
? data.breadcrumbs
: data.breadcrumbs.text || data.text || path;
const crumbs: IBreadcrumb[] = [{ text: text, path: path }];
return of(crumbs);
}
public getFullPath(route: ActivatedRouteSnapshot): string {
const relativePath = (segments: UrlSegment[]) =>
segments.reduce((a, v) => (a += '/' + v.path), '');
const fullPath = (routes: ActivatedRouteSnapshot[]) =>
routes.reduce((a, v) => (a += relativePath(v.url)), '');
return fullPath(route.pathFromRoot);
}
}
export interface IBreadcrumb {
text: string;
path: string;
}
| 2,179 | 35.333333 | 78 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-details.ts
|
export interface DashboardDetails {
fsid?: string;
orchestrator?: string;
cephVersion?: string;
}
| 104 | 16.5 | 35 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-form-modal-field-config.ts
|
import { ValidatorFn } from '@angular/forms';
export class CdFormModalFieldConfig {
// --- Generic field properties ---
name: string;
// 'binary' will use cdDimlessBinary directive on input element
// 'select' will use select element
type: 'number' | 'text' | 'binary' | 'select' | 'select-badges';
label?: string;
required?: boolean;
value?: any;
errors?: { [errorName: string]: string };
validators: ValidatorFn[];
// --- Specific field properties ---
typeConfig?: {
[prop: string]: any;
// 'select':
// ---------
// placeholder?: string;
// options?: Array<{
// text: string;
// value: any;
// }>;
//
// 'select-badges':
// ----------------
// customBadges: boolean;
// options: Array<SelectOption>;
// messages: SelectMessages;
};
}
| 825 | 24.030303 | 66 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-notification.spec.ts
|
import { NotificationType } from '../enum/notification-type.enum';
import { CdNotification, CdNotificationConfig } from './cd-notification';
describe('cd-notification classes', () => {
const expectObject = (something: object, expected: object) => {
Object.keys(expected).forEach((key) => expect(something[key]).toBe(expected[key]));
};
// As these Models have a view methods they need to be tested
describe('CdNotificationConfig', () => {
it('should create a new config without any parameters', () => {
expectObject(new CdNotificationConfig(), {
application: 'Ceph',
applicationClass: 'ceph-icon',
message: undefined,
options: undefined,
title: undefined,
type: 1
});
});
it('should create a new config with parameters', () => {
expectObject(
new CdNotificationConfig(
NotificationType.error,
'Some Alert',
'Something failed',
undefined,
'Prometheus'
),
{
application: 'Prometheus',
applicationClass: 'prometheus-icon',
message: 'Something failed',
options: undefined,
title: 'Some Alert',
type: 0
}
);
});
});
describe('CdNotification', () => {
beforeEach(() => {
const baseTime = new Date('2022-02-22');
spyOn(global, 'Date').and.returnValue(baseTime);
});
it('should create a new config without any parameters', () => {
expectObject(new CdNotification(), {
application: 'Ceph',
applicationClass: 'ceph-icon',
iconClass: 'fa fa-info',
message: undefined,
options: undefined,
textClass: 'text-info',
timestamp: '2022-02-22T00:00:00.000Z',
title: undefined,
type: 1
});
});
it('should create a new config with parameters', () => {
expectObject(
new CdNotification(
new CdNotificationConfig(
NotificationType.error,
'Some Alert',
'Something failed',
undefined,
'Prometheus'
)
),
{
application: 'Prometheus',
applicationClass: 'prometheus-icon',
iconClass: 'fa fa-exclamation-triangle',
message: 'Something failed',
options: undefined,
textClass: 'text-danger',
timestamp: '2022-02-22T00:00:00.000Z',
title: 'Some Alert',
type: 0
}
);
});
it('should expect the right success classes', () => {
expectObject(new CdNotification(new CdNotificationConfig(NotificationType.success)), {
iconClass: 'fa fa-check',
textClass: 'text-success'
});
});
});
});
| 2,771 | 27.875 | 92 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-notification.ts
|
import { IndividualConfig } from 'ngx-toastr';
import { Icons } from '../enum/icons.enum';
import { NotificationType } from '../enum/notification-type.enum';
export class CdNotificationConfig {
applicationClass: string;
isFinishedTask = false;
private classes = {
Ceph: 'ceph-icon',
Prometheus: 'prometheus-icon'
};
constructor(
public type: NotificationType = NotificationType.info,
public title?: string,
public message?: string, // Use this for additional information only
public options?: any | IndividualConfig,
public application: string = 'Ceph'
) {
this.applicationClass = this.classes[this.application];
}
}
export class CdNotification extends CdNotificationConfig {
timestamp: string;
textClass: string;
iconClass: string;
duration: number;
borderClass: string;
alertSilenced = false;
silenceId?: string;
private textClasses = ['text-danger', 'text-info', 'text-success'];
private iconClasses = [Icons.warning, Icons.info, Icons.check];
private borderClasses = ['border-danger', 'border-info', 'border-success'];
constructor(private config: CdNotificationConfig = new CdNotificationConfig()) {
super(config.type, config.title, config.message, config.options, config.application);
delete this.config;
/* string representation of the Date object so it can be directly compared
with the timestamps parsed from localStorage */
this.timestamp = new Date().toJSON();
this.iconClass = this.iconClasses[this.type];
this.textClass = this.textClasses[this.type];
this.borderClass = this.borderClasses[this.type];
this.isFinishedTask = config.isFinishedTask;
}
}
| 1,675 | 31.862745 | 89 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-pwd-expiration-settings.ts
|
export class CdPwdExpirationSettings {
pwdExpirationSpan = 0;
pwdExpirationWarning1: number;
pwdExpirationWarning2: number;
constructor(settings: { [key: string]: any }) {
this.pwdExpirationSpan = settings.user_pwd_expiration_span;
this.pwdExpirationWarning1 = settings.user_pwd_expiration_warning_1;
this.pwdExpirationWarning2 = settings.user_pwd_expiration_warning_2;
}
}
| 397 | 32.166667 | 72 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-pwd-policy-settings.ts
|
export class CdPwdPolicySettings {
pwdPolicyEnabled: boolean;
pwdPolicyMinLength: number;
pwdPolicyCheckLengthEnabled: boolean;
pwdPolicyCheckOldpwdEnabled: boolean;
pwdPolicyCheckUsernameEnabled: boolean;
pwdPolicyCheckExclusionListEnabled: boolean;
pwdPolicyCheckRepetitiveCharsEnabled: boolean;
pwdPolicyCheckSequentialCharsEnabled: boolean;
pwdPolicyCheckComplexityEnabled: boolean;
constructor(settings: { [key: string]: any }) {
this.pwdPolicyEnabled = settings.pwd_policy_enabled;
this.pwdPolicyMinLength = settings.pwd_policy_min_length;
this.pwdPolicyCheckLengthEnabled = settings.pwd_policy_check_length_enabled;
this.pwdPolicyCheckOldpwdEnabled = settings.pwd_policy_check_oldpwd_enabled;
this.pwdPolicyCheckUsernameEnabled = settings.pwd_policy_check_username_enabled;
this.pwdPolicyCheckExclusionListEnabled = settings.pwd_policy_check_exclusion_list_enabled;
this.pwdPolicyCheckRepetitiveCharsEnabled = settings.pwd_policy_check_repetitive_chars_enabled;
this.pwdPolicyCheckSequentialCharsEnabled = settings.pwd_policy_check_sequential_chars_enabled;
this.pwdPolicyCheckComplexityEnabled = settings.pwd_policy_check_complexity_enabled;
}
}
| 1,213 | 49.583333 | 99 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-table-action.ts
|
import { CdTableSelection } from './cd-table-selection';
export class CdTableAction {
// It's possible to assign a string
// or a function that returns the link if it has to be dynamic
// or none if it's not needed
routerLink?: string | Function;
preserveFragment? = false;
// This is the function that will be triggered on a click event if defined
click?: Function;
permission: 'create' | 'update' | 'delete' | 'read';
// The name of the action
name: string;
// The font awesome icon that will be used
icon: string;
/**
* You can define the condition to disable the action.
* By default all 'update' and 'delete' actions will only be enabled
* if one selection is made and no task is running on the selected item.`
*
* In some cases you might want to give the user a hint why a button is
* disabled. This is achieved by returning a string.
* */
disable?: (_: CdTableSelection) => boolean | string;
/**
* Defines if the button can become 'primary' (displayed as button and not
* 'hidden' in the menu). Only one button can be primary at a time. By
* default all 'create' actions can be the action button if no or multiple
* items are selected. Also, all 'update' and 'delete' actions can be the
* action button by default, provided only one item is selected.
*/
canBePrimary?: (_: CdTableSelection) => boolean;
// In some rare cases you want to hide a action that can be used by the user for example
// if one action can lock the item and another action unlocks it
visible?: (_: CdTableSelection) => boolean;
}
| 1,596 | 34.488889 | 90 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-table-column-filter.ts
|
import { CdTableColumn } from './cd-table-column';
export interface CdTableColumnFilter {
column: CdTableColumn;
options: { raw: string; formatted: string }[]; // possible options of a filter
value?: { raw: string; formatted: string }; // selected option
}
| 264 | 32.125 | 80 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-table-column-filters-change.ts
|
import { TableColumnProp } from '@swimlane/ngx-datatable';
export interface CdTableColumnFiltersChange {
/**
* Applied filters.
*/
filters: {
name: string;
prop: TableColumnProp;
value: { raw: string; formatted: string };
}[];
/**
* Filtered data.
*/
data: any[];
/**
* Filtered out data.
*/
dataOut: any[];
}
| 357 | 14.565217 | 58 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-table-column.ts
|
import { TableColumn, TableColumnProp } from '@swimlane/ngx-datatable';
import { CellTemplate } from '../enum/cell-template.enum';
export interface CdTableColumn extends TableColumn {
cellTransformation?: CellTemplate;
isHidden?: boolean;
prop: TableColumnProp; // Enforces properties to get sortable columns
customTemplateConfig?: any; // Custom configuration used by cell templates.
/**
* Add a filter for the column if true.
*
* By default, options for the filter are deduced from values of the column.
*/
filterable?: boolean;
/**
* Use these options for filter rather than deducing from values of the column.
*
* If there is a pipe function associated with the column, pipe function is applied
* to the options before displaying them.
*/
filterOptions?: any[];
/**
* Default applied option, should be value in filterOptions.
*/
filterInitValue?: any;
/**
* Specify a custom function for filtering.
*
* By default, the filter compares if values are string-equal with options. Specify
* a customize function if that's not desired. Return true to include a row.
*/
filterPredicate?: (row: any, value: any) => boolean;
}
| 1,200 | 29.794872 | 85 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-table-fetch-data-context.ts
|
import { HttpParams } from '@angular/common/http';
import { PageInfo } from './cd-table-paging';
export class CdTableFetchDataContext {
errorConfig = {
resetData: true, // Force data table to show no data
displayError: true // Show an error panel above the data table
};
/**
* The function that should be called from within the error handler
* of the 'fetchData' function to display the error panel and to
* reset the data table to the correct state.
*/
error: Function;
pageInfo: PageInfo = new PageInfo();
search = '';
sort = '+name';
constructor(error: () => void) {
this.error = error;
}
toParams(): HttpParams {
if (Number.isNaN(this.pageInfo.offset)) {
this.pageInfo.offset = 0;
}
if (this.pageInfo.limit === null) {
this.pageInfo.limit = 0;
}
if (!this.search) {
this.search = '';
}
if (!this.sort || this.sort.length < 2) {
this.sort = '+name';
}
return new HttpParams({
fromObject: {
offset: String(this.pageInfo.offset * this.pageInfo.limit),
limit: String(this.pageInfo.limit),
search: this.search,
sort: this.sort
}
});
}
}
| 1,199 | 22.076923 | 69 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-table-paging.ts
|
export const PAGE_LIMIT = 10;
export class PageInfo {
// Total number of rows in a table
count: number;
// Current page (current row = offset x limit or pageSize)
offset = 0;
// Max. number of rows fetched from the server
limit: number = PAGE_LIMIT;
/*
pageSize and limit can be decoupled if hybrid server-side and client-side
are used. A use-case would be to reduce the amount of queries: that is,
the pageSize (client-side paging) might be 10, but the back-end queries
could have a limit of 100. That would avoid triggering requests
*/
pageSize: number = PAGE_LIMIT;
}
| 601 | 27.666667 | 75 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-table-selection.ts
|
export class CdTableSelection {
private _selected: any[] = [];
hasMultiSelection: boolean;
hasSingleSelection: boolean;
hasSelection: boolean;
constructor(rows?: any[]) {
if (rows) {
this._selected = rows;
}
this.update();
}
/**
* Recalculate the variables based on the current number
* of selected rows.
*/
private update() {
this.hasSelection = this._selected.length > 0;
this.hasSingleSelection = this._selected.length === 1;
this.hasMultiSelection = this._selected.length > 1;
}
set selected(selection: any[]) {
this._selected = selection;
this.update();
}
get selected() {
return this._selected;
}
add(row: any) {
this._selected.push(row);
this.update();
}
/**
* Get the first selected row.
* @return {any | null}
*/
first() {
return this.hasSelection ? this._selected[0] : null;
}
}
| 903 | 18.652174 | 58 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cd-user-config.ts
|
import { SortPropDir } from '@swimlane/ngx-datatable';
import { CdTableColumn } from './cd-table-column';
export interface CdUserConfig {
limit?: number;
offset?: number;
search?: string;
sorts?: SortPropDir[];
columns?: CdTableColumn[];
}
| 252 | 20.083333 | 54 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/cephfs-directory-models.ts
|
import { TreeStatus } from '@swimlane/ngx-datatable';
export class CephfsSnapshot {
name: string;
path: string;
created: string;
}
export class CephfsQuotas {
max_bytes?: number;
max_files?: number;
}
export class CephfsDir {
name: string;
path: string;
quotas: CephfsQuotas;
snapshots: CephfsSnapshot[];
parent: string;
treeStatus?: TreeStatus; // Needed for table tree view
}
| 403 | 17.363636 | 56 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/chart-tooltip.ts
|
import { ElementRef } from '@angular/core';
export class ChartTooltip {
tooltipEl: any;
chartEl: any;
getStyleLeft: Function;
getStyleTop: Function;
customColors: Record<string, any> = {
backgroundColor: undefined,
borderColor: undefined
};
checkOffset = false;
/**
* Creates an instance of ChartTooltip.
* @param {ElementRef} chartCanvas Canvas Element
* @param {ElementRef} chartTooltip Tooltip Element
* @param {Function} getStyleLeft Function that calculates the value of Left
* @param {Function} getStyleTop Function that calculates the value of Top
* @memberof ChartTooltip
*/
constructor(
chartCanvas: ElementRef,
chartTooltip: ElementRef,
getStyleLeft: Function,
getStyleTop: Function
) {
this.chartEl = chartCanvas.nativeElement;
this.getStyleLeft = getStyleLeft;
this.getStyleTop = getStyleTop;
this.tooltipEl = chartTooltip.nativeElement;
}
/**
* Implementation of a ChartJS custom tooltip function.
*
* @param {any} tooltip
* @memberof ChartTooltip
*/
customTooltips(tooltip: any) {
// Hide if no tooltip
if (tooltip.opacity === 0) {
this.tooltipEl.style.opacity = 0;
return;
}
// Set caret Position
this.tooltipEl.classList.remove('above', 'below', 'no-transform');
if (tooltip.yAlign) {
this.tooltipEl.classList.add(tooltip.yAlign);
} else {
this.tooltipEl.classList.add('no-transform');
}
// Set Text
if (tooltip.body) {
const titleLines = tooltip.title || [];
const bodyLines = tooltip.body.map((bodyItem: any) => {
return bodyItem.lines;
});
let innerHtml = '<thead>';
titleLines.forEach((title: string) => {
innerHtml += '<tr><th>' + this.getTitle(title) + '</th></tr>';
});
innerHtml += '</thead><tbody>';
bodyLines.forEach((body: string, i: number) => {
const colors = tooltip.labelColors[i];
let style = 'background:' + (this.customColors.backgroundColor || colors.backgroundColor);
style += '; border-color:' + (this.customColors.borderColor || colors.borderColor);
style += '; border-width: 2px';
const span = '<span class="chartjs-tooltip-key" style="' + style + '"></span>';
innerHtml += '<tr><td nowrap>' + span + this.getBody(body) + '</td></tr>';
});
innerHtml += '</tbody>';
const tableRoot = this.tooltipEl.querySelector('table');
tableRoot.innerHTML = innerHtml;
}
const positionY = this.chartEl.offsetTop;
const positionX = this.chartEl.offsetLeft;
// Display, position, and set styles for font
if (this.checkOffset) {
const halfWidth = tooltip.width / 2;
this.tooltipEl.classList.remove('transform-left');
this.tooltipEl.classList.remove('transform-right');
if (tooltip.caretX - halfWidth < 0) {
this.tooltipEl.classList.add('transform-left');
} else if (tooltip.caretX + halfWidth > this.chartEl.width) {
this.tooltipEl.classList.add('transform-right');
}
}
this.tooltipEl.style.left = this.getStyleLeft(tooltip, positionX);
this.tooltipEl.style.top = this.getStyleTop(tooltip, positionY);
this.tooltipEl.style.opacity = 1;
this.tooltipEl.style.fontFamily = tooltip._fontFamily;
this.tooltipEl.style.fontSize = tooltip.fontSize;
this.tooltipEl.style.fontStyle = tooltip._fontStyle;
this.tooltipEl.style.padding = tooltip.yPadding + 'px ' + tooltip.xPadding + 'px';
}
getBody(body: string) {
return body;
}
getTitle(title: string) {
return title;
}
}
| 3,623 | 30.241379 | 98 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/configuration.ts
|
export enum RbdConfigurationSourceField {
global = 0,
pool = 1,
image = 2
}
export enum RbdConfigurationType {
bps,
iops,
milliseconds
}
/**
* This configuration can also be set on a pool level.
*/
export interface RbdConfigurationEntry {
name: string;
source: RbdConfigurationSourceField;
value: any;
type?: RbdConfigurationType; // Non-external field.
description?: string; // Non-external field.
displayName?: string; // Non-external field. Nice name for the UI which is added in the UI.
}
/**
* This object contains additional information injected into the elements retrieved by the service.
*/
export interface RbdConfigurationExtraField {
name: string;
displayName: string;
description: string;
type: RbdConfigurationType;
readOnly?: boolean;
}
/**
* Represents a set of data to be used for editing or creating configuration options
*/
export interface RbdConfigurationSection {
heading: string;
class: string;
options: RbdConfigurationExtraField[];
}
| 1,008 | 21.931818 | 99 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/credentials.ts
|
export class Credentials {
username: string;
password: string;
}
| 69 | 13 | 26 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/crud-table-metadata.ts
|
import { CdTableColumn } from '~/app/shared/models/cd-table-column';
import { CdTableAction } from './cd-table-action';
class Table {
columns: CdTableColumn[];
columnMode: string;
toolHeader: boolean;
selectionType: string;
}
export class CrudMetadata {
table: Table;
permissions: string[];
actions: CdTableAction[];
forms: any;
columnKey: string;
}
| 370 | 19.611111 | 68 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/crush-node.ts
|
export class CrushNode {
id: number;
name: string;
type: string;
type_id: number;
// For nodes with leafs (Buckets)
children?: number[]; // Holds node id's of children
// For non root nodes
pool_weights?: object;
// For leafs (Devices)
device_class?: string;
crush_weight?: number;
exists?: number;
primary_affinity?: number;
reweight?: number;
status?: string;
}
| 394 | 20.944444 | 53 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/crush-rule.ts
|
import { CrushStep } from './crush-step';
export class CrushRule {
usable_size?: number;
rule_id: number;
type: number;
rule_name: string;
steps: CrushStep[];
}
export class CrushRuleConfig {
root: string; // The name of the node under which data should be placed.
name: string;
failure_domain: string; // The type of CRUSH nodes across which we should separate replicas.
device_class?: string; // The device class data should be placed on.
}
| 463 | 26.294118 | 94 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/crush-step.ts
|
export class CrushStep {
op: string;
item_name?: string;
item?: number;
type?: string;
num?: number;
}
| 113 | 13.25 | 24 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/daemon.interface.ts
|
export interface Daemon {
nodename: string;
container_id: string;
container_image_id: string;
container_image_name: string;
daemon_id: string;
daemon_type: string;
version: string;
status: number;
status_desc: string;
last_refresh: Date;
}
| 260 | 19.076923 | 31 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/devices.ts
|
/**
* Fields returned by the back-end.
*/
export interface CephDevice {
devid: string;
location: { host: string; dev: string }[];
daemons: string[];
life_expectancy_min?: string;
life_expectancy_max?: string;
life_expectancy_stamp?: string;
life_expectancy_enabled?: boolean;
}
/**
* Fields added by the front-end. Fields may be empty if no expectancy is provided for the
* CephDevice interface.
*/
export interface CdDevice extends CephDevice {
life_expectancy_weeks?: {
max: number;
min: number;
};
state?: 'good' | 'warning' | 'bad' | 'stale' | 'unknown';
readableDaemons?: string; // Human readable daemons (which can wrap lines inside the table cell)
}
| 694 | 25.730769 | 98 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/erasure-code-profile.ts
|
export class ErasureCodeProfile {
name: string;
plugin: string;
k?: number;
m?: number;
c?: number;
l?: number;
d?: number;
packetsize?: number;
technique?: string;
scalar_mds?: 'jerasure' | 'isa' | 'shec';
'crush-root'?: string;
'crush-locality'?: string;
'crush-failure-domain'?: string;
'crush-device-class'?: string;
'directory'?: string;
}
| 375 | 19.888889 | 43 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/executing-task.ts
|
import { Task } from './task';
export class ExecutingTask extends Task {
begin_time: number;
progress: number;
}
| 118 | 16 | 41 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/finished-task.ts
|
import { Task } from './task';
import { TaskException } from './task-exception';
export class FinishedTask extends Task {
begin_time: string;
end_time: string;
exception: TaskException;
latency: number;
progress: number;
ret_value: any;
success: boolean;
duration: number;
errorMessage: string;
}
| 317 | 18.875 | 49 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/flag.ts
|
export class Flag {
code: 'noout' | 'noin' | 'nodown' | 'noup';
name: string;
description: string;
value: boolean;
clusterWide: boolean;
indeterminate: boolean;
}
| 175 | 18.555556 | 45 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/image-spec.ts
|
export class ImageSpec {
static fromString(imageSpec: string) {
const imageSpecSplited = imageSpec.split('/');
const poolName = imageSpecSplited[0];
const namespace = imageSpecSplited.length >= 3 ? imageSpecSplited[1] : null;
const imageName = imageSpecSplited.length >= 3 ? imageSpecSplited[2] : imageSpecSplited[1];
return new this(poolName, namespace, imageName);
}
constructor(public poolName: string, public namespace: string, public imageName: string) {}
private getNameSpace() {
return this.namespace ? `${this.namespace}/` : '';
}
toString() {
return `${this.poolName}/${this.getNameSpace()}${this.imageName}`;
}
toStringEncoded() {
return encodeURIComponent(`${this.poolName}/${this.getNameSpace()}${this.imageName}`);
}
}
| 788 | 29.346154 | 95 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/inventory-device-type.model.ts
|
import { InventoryDevice } from '~/app/ceph/cluster/inventory/inventory-devices/inventory-device.model';
export interface InventoryDeviceType {
type: string;
capacity: number;
devices: InventoryDevice[];
canSelect: boolean;
totalDevices: number;
}
| 259 | 25 | 104 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/login-response.ts
|
export class LoginResponse {
username: string;
permissions: object;
pwdExpirationDate: number;
sso: boolean;
pwdUpdateRequired: boolean;
}
| 149 | 17.75 | 29 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/mirroring-summary.ts
|
export interface MirroringSummary {
content_data?: any;
site_name?: any;
status?: any;
}
| 95 | 15 | 35 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/orchestrator.enum.ts
|
export enum OrchestratorFeature {
HOST_LIST = 'get_hosts',
HOST_ADD = 'add_host',
HOST_REMOVE = 'remove_host',
HOST_LABEL_ADD = 'add_host_label',
HOST_LABEL_REMOVE = 'remove_host_label',
HOST_MAINTENANCE_ENTER = 'enter_host_maintenance',
HOST_MAINTENANCE_EXIT = 'exit_host_maintenance',
HOST_FACTS = 'get_facts',
HOST_DRAIN = 'drain_host',
SERVICE_LIST = 'describe_service',
SERVICE_CREATE = 'apply',
SERVICE_EDIT = 'apply',
SERVICE_DELETE = 'remove_service',
SERVICE_RELOAD = 'service_action',
DAEMON_LIST = 'list_daemons',
OSD_GET_REMOVE_STATUS = 'remove_osds_status',
OSD_CREATE = 'apply_drivegroups',
OSD_DELETE = 'remove_osds',
DEVICE_LIST = 'get_inventory',
DEVICE_BLINK_LIGHT = 'blink_device_light'
}
| 751 | 27.923077 | 52 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/orchestrator.interface.ts
|
export interface OrchestratorStatus {
available: boolean;
message: string;
features: {
[feature: string]: {
available: boolean;
};
};
}
| 158 | 14.9 | 37 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/osd-deployment-options.ts
|
export enum OsdDeploymentOptions {
COST_CAPACITY = 'cost_capacity',
THROUGHPUT = 'throughput_optimized',
IOPS = 'iops_optimized'
}
export interface DeploymentOption {
name: OsdDeploymentOptions;
title: string;
desc: string;
capacity: number;
available: boolean;
hdd_used: number;
used: number;
nvme_used: number;
ssd_used: number;
}
export interface DeploymentOptions {
options: {
[key in OsdDeploymentOptions]: DeploymentOption;
};
recommended_option: OsdDeploymentOptions;
}
| 513 | 19.56 | 52 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/osd-settings.ts
|
export class OsdSettings {
nearfull_ratio: number;
full_ratio: number;
}
| 77 | 14.6 | 26 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/permission.spec.ts
|
import { Permissions } from './permissions';
describe('cd-notification classes', () => {
it('should show empty permissions', () => {
expect(new Permissions({})).toEqual({
cephfs: { create: false, delete: false, read: false, update: false },
configOpt: { create: false, delete: false, read: false, update: false },
grafana: { create: false, delete: false, read: false, update: false },
hosts: { create: false, delete: false, read: false, update: false },
iscsi: { create: false, delete: false, read: false, update: false },
log: { create: false, delete: false, read: false, update: false },
manager: { create: false, delete: false, read: false, update: false },
monitor: { create: false, delete: false, read: false, update: false },
nfs: { create: false, delete: false, read: false, update: false },
osd: { create: false, delete: false, read: false, update: false },
pool: { create: false, delete: false, read: false, update: false },
prometheus: { create: false, delete: false, read: false, update: false },
rbdImage: { create: false, delete: false, read: false, update: false },
rbdMirroring: { create: false, delete: false, read: false, update: false },
rgw: { create: false, delete: false, read: false, update: false },
user: { create: false, delete: false, read: false, update: false }
});
});
it('should show full permissions', () => {
const fullyGranted = {
cephfs: ['create', 'read', 'update', 'delete'],
'config-opt': ['create', 'read', 'update', 'delete'],
grafana: ['create', 'read', 'update', 'delete'],
hosts: ['create', 'read', 'update', 'delete'],
iscsi: ['create', 'read', 'update', 'delete'],
log: ['create', 'read', 'update', 'delete'],
manager: ['create', 'read', 'update', 'delete'],
monitor: ['create', 'read', 'update', 'delete'],
osd: ['create', 'read', 'update', 'delete'],
pool: ['create', 'read', 'update', 'delete'],
prometheus: ['create', 'read', 'update', 'delete'],
'rbd-image': ['create', 'read', 'update', 'delete'],
'rbd-mirroring': ['create', 'read', 'update', 'delete'],
rgw: ['create', 'read', 'update', 'delete'],
user: ['create', 'read', 'update', 'delete']
};
expect(new Permissions(fullyGranted)).toEqual({
cephfs: { create: true, delete: true, read: true, update: true },
configOpt: { create: true, delete: true, read: true, update: true },
grafana: { create: true, delete: true, read: true, update: true },
hosts: { create: true, delete: true, read: true, update: true },
iscsi: { create: true, delete: true, read: true, update: true },
log: { create: true, delete: true, read: true, update: true },
manager: { create: true, delete: true, read: true, update: true },
monitor: { create: true, delete: true, read: true, update: true },
nfs: { create: false, delete: false, read: false, update: false },
osd: { create: true, delete: true, read: true, update: true },
pool: { create: true, delete: true, read: true, update: true },
prometheus: { create: true, delete: true, read: true, update: true },
rbdImage: { create: true, delete: true, read: true, update: true },
rbdMirroring: { create: true, delete: true, read: true, update: true },
rgw: { create: true, delete: true, read: true, update: true },
user: { create: true, delete: true, read: true, update: true }
});
});
});
| 3,533 | 55.095238 | 81 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/permissions.ts
|
export class Permission {
read: boolean;
create: boolean;
update: boolean;
delete: boolean;
constructor(serverPermission: Array<string> = []) {
['read', 'create', 'update', 'delete'].forEach(
(permission) => (this[permission] = serverPermission.includes(permission))
);
}
}
export class Permissions {
hosts: Permission;
configOpt: Permission;
pool: Permission;
osd: Permission;
monitor: Permission;
rbdImage: Permission;
iscsi: Permission;
rbdMirroring: Permission;
rgw: Permission;
cephfs: Permission;
manager: Permission;
log: Permission;
user: Permission;
grafana: Permission;
prometheus: Permission;
nfs: Permission;
constructor(serverPermissions: any) {
this.hosts = new Permission(serverPermissions['hosts']);
this.configOpt = new Permission(serverPermissions['config-opt']);
this.pool = new Permission(serverPermissions['pool']);
this.osd = new Permission(serverPermissions['osd']);
this.monitor = new Permission(serverPermissions['monitor']);
this.rbdImage = new Permission(serverPermissions['rbd-image']);
this.iscsi = new Permission(serverPermissions['iscsi']);
this.rbdMirroring = new Permission(serverPermissions['rbd-mirroring']);
this.rgw = new Permission(serverPermissions['rgw']);
this.cephfs = new Permission(serverPermissions['cephfs']);
this.manager = new Permission(serverPermissions['manager']);
this.log = new Permission(serverPermissions['log']);
this.user = new Permission(serverPermissions['user']);
this.grafana = new Permission(serverPermissions['grafana']);
this.prometheus = new Permission(serverPermissions['prometheus']);
this.nfs = new Permission(serverPermissions['nfs-ganesha']);
}
}
| 1,747 | 33.27451 | 80 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/pool-form-info.ts
|
import { CrushNode } from './crush-node';
import { CrushRule } from './crush-rule';
import { ErasureCodeProfile } from './erasure-code-profile';
export class PoolFormInfo {
pool_names: string[];
osd_count: number;
is_all_bluestore: boolean;
bluestore_compression_algorithm: string;
compression_algorithms: string[];
compression_modes: string[];
crush_rules_replicated: CrushRule[];
crush_rules_erasure: CrushRule[];
pg_autoscale_default_mode: string;
pg_autoscale_modes: string[];
erasure_code_profiles: ErasureCodeProfile[];
used_rules: { [rule_name: string]: string[] };
used_profiles: { [profile_name: string]: string[] };
nodes: CrushNode[];
}
| 677 | 31.285714 | 60 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/prometheus-alerts.ts
|
export class PrometheusAlertLabels {
alertname: string;
instance: string;
job: string;
severity: string;
}
class Annotations {
description: string;
summary: string;
}
class CommonAlertmanagerAlert {
labels: PrometheusAlertLabels;
annotations: Annotations;
startsAt: string; // Date string
endsAt: string; // Date string
generatorURL: string;
}
class PrometheusAlert {
labels: PrometheusAlertLabels;
annotations: Annotations;
state: 'pending' | 'firing';
activeAt: string; // Date string
value: number;
}
export interface PrometheusRuleGroup {
name: string;
file: string;
rules: PrometheusRule[];
}
export class PrometheusRule {
name: string; // => PrometheusAlertLabels.alertname
query: string;
duration: 10;
labels: {
severity: string; // => PrometheusAlertLabels.severity
};
annotations: Annotations;
alerts: PrometheusAlert[]; // Shows only active alerts
health: string;
type: string;
group?: string; // Added field for flattened list
}
export class AlertmanagerAlert extends CommonAlertmanagerAlert {
status: {
state: 'unprocessed' | 'active' | 'suppressed';
silencedBy: null | string[];
inhibitedBy: null | string[];
};
receivers: string[];
fingerprint: string;
}
export class AlertmanagerNotificationAlert extends CommonAlertmanagerAlert {
status: 'firing' | 'resolved';
}
export class AlertmanagerNotification {
status: 'firing' | 'resolved';
groupLabels: object;
commonAnnotations: object;
groupKey: string;
notified: string;
id: string;
alerts: AlertmanagerNotificationAlert[];
version: string;
receiver: string;
externalURL: string;
commonLabels: {
severity: string;
};
}
export class PrometheusCustomAlert {
status: 'resolved' | 'unprocessed' | 'active' | 'suppressed';
name: string;
url: string;
description: string;
fingerprint?: string | boolean;
}
| 1,894 | 21.034884 | 76 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/service.interface.ts
|
export interface CephServiceStatus {
container_image_id: string;
container_image_name: string;
size: number;
running: number;
last_refresh: Date;
created: Date;
}
// This will become handy when creating arbitrary services
export interface CephServiceSpec {
service_name: string;
service_type: string;
service_id: string;
unmanaged: boolean;
status: CephServiceStatus;
spec: CephServiceAdditionalSpec;
placement: CephServicePlacement;
}
export interface CephServiceAdditionalSpec {
backend_service: string;
api_user: string;
api_password: string;
api_port: number;
api_secure: boolean;
rgw_frontend_port: number;
trusted_ip_list: string[];
virtual_ip: string;
frontend_port: number;
monitor_port: number;
virtual_interface_networks: string[];
pool: string;
rgw_frontend_ssl_certificate: string;
ssl: boolean;
ssl_cert: string;
ssl_key: string;
port: number;
initial_admin_password: string;
rgw_realm: string;
rgw_zonegroup: string;
rgw_zone: string;
}
export interface CephServicePlacement {
count: number;
placement: string;
hosts: string[];
label: string;
}
| 1,138 | 21.333333 | 58 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/smart.ts
|
export interface SmartAttribute {
flags: {
auto_keep: boolean;
error_rate: boolean;
event_count: boolean;
performance: boolean;
prefailure: boolean;
string: string;
updated_online: boolean;
value: number;
};
id: number;
name: string;
raw: { string: string; value: number };
thresh: number;
value: number;
when_failed: string;
worst: number;
}
/**
* The error structure returned from the back-end if SMART data couldn't be
* retrieved.
*/
export interface SmartError {
dev: string;
error: string;
nvme_smart_health_information_add_log_error: string;
nvme_smart_health_information_add_log_error_code: number;
nvme_vendor: string;
smartctl_error_code: number;
smartctl_output: string;
}
/**
* Common smartctl output structure.
*/
interface SmartCtlOutput {
argv: string[];
build_info: string;
exit_status: number;
output: string[];
platform_info: string;
svn_revision: string;
version: number[];
}
/**
* Common smartctl device structure.
*/
interface SmartCtlDevice {
info_name: string;
name: string;
protocol: string;
type: string;
}
/**
* smartctl data structure shared among HDD/NVMe.
*/
interface SmartCtlBaseDataV1 {
device: SmartCtlDevice;
firmware_version: string;
json_format_version: number[];
local_time: { asctime: string; time_t: number };
logical_block_size: number;
model_name: string;
nvme_smart_health_information_add_log_error: string;
nvme_smart_health_information_add_log_error_code: number;
nvme_vendor: string;
power_cycle_count: number;
power_on_time: { hours: number };
serial_number: string;
smart_status: { passed: boolean; nvme?: { value: number } };
smartctl: SmartCtlOutput;
temperature: { current: number };
user_capacity: { blocks: number; bytes: number };
}
export interface RVWAttributes {
correction_algorithm_invocations: number;
errors_corrected_by_eccdelayed: number;
errors_corrected_by_eccfast: number;
errors_corrected_by_rereads_rewrites: number;
gigabytes_processed: number;
total_errors_corrected: number;
total_uncorrected_errors: number;
}
/**
* Result structure of `smartctl` applied on an SCSI. Returned by the back-end.
*/
export interface IscsiSmartDataV1 extends SmartCtlBaseDataV1 {
scsi_error_counter_log: {
read: RVWAttributes[];
};
scsi_grown_defect_list: number;
}
/**
* Result structure of `smartctl` applied on an HDD. Returned by the back-end.
*/
export interface AtaSmartDataV1 extends SmartCtlBaseDataV1 {
ata_sct_capabilities: {
data_table_supported: boolean;
error_recovery_control_supported: boolean;
feature_control_supported: boolean;
value: number;
};
ata_smart_attributes: {
revision: number;
table: SmartAttribute[];
};
ata_smart_data: {
capabilities: {
attribute_autosave_enabled: boolean;
conveyance_self_test_supported: boolean;
error_logging_supported: boolean;
exec_offline_immediate_supported: boolean;
gp_logging_supported: boolean;
offline_is_aborted_upon_new_cmd: boolean;
offline_surface_scan_supported: boolean;
selective_self_test_supported: boolean;
self_tests_supported: boolean;
values: number[];
};
offline_data_collection: {
completion_seconds: number;
status: { string: string; value: number };
};
self_test: {
polling_minutes: { conveyance: number; extended: number; short: number };
status: { passed: boolean; string: string; value: number };
};
};
ata_smart_error_log: { summary: { count: number; revision: number } };
ata_smart_selective_self_test_log: {
flags: { remainder_scan_enabled: boolean; value: number };
power_up_scan_resume_minutes: number;
revision: number;
table: {
lba_max: number;
lba_min: number;
status: { string: string; value: number };
}[];
};
ata_smart_self_test_log: { standard: { count: number; revision: number } };
ata_version: { major_value: number; minor_value: number; string: string };
in_smartctl_database: boolean;
interface_speed: {
current: {
bits_per_unit: number;
sata_value: number;
string: string;
units_per_second: number;
};
max: {
bits_per_unit: number;
sata_value: number;
string: string;
units_per_second: number;
};
};
model_family: string;
physical_block_size: number;
rotation_rate: number;
sata_version: { string: string; value: number };
smart_status: { passed: boolean };
smartctl: SmartCtlOutput;
wwn: { id: number; naa: number; oui: number };
}
/**
* Result structure of `smartctl` returned by Ceph and then back-end applied on
* an NVMe.
*/
export interface NvmeSmartDataV1 extends SmartCtlBaseDataV1 {
nvme_controller_id: number;
nvme_ieee_oui_identifier: number;
nvme_namespaces: {
capacity: { blocks: number; bytes: number };
eui64: { ext_id: number; oui: number };
formatted_lba_size: number;
id: number;
size: { blocks: number; bytes: number };
utilization: { blocks: number; bytes: number };
}[];
nvme_number_of_namespaces: number;
nvme_pci_vendor: { id: number; subsystem_id: number };
nvme_smart_health_information_log: {
available_spare: number;
available_spare_threshold: number;
controller_busy_time: number;
critical_comp_time: number;
critical_warning: number;
data_units_read: number;
data_units_written: number;
host_reads: number;
host_writes: number;
media_errors: number;
num_err_log_entries: number;
percentage_used: number;
power_cycles: number;
power_on_hours: number;
temperature: number;
temperature_sensors: number[];
unsafe_shutdowns: number;
warning_temp_time: number;
};
nvme_total_capacity: number;
nvme_unallocated_capacity: number;
}
/**
* The shared fields each result has after it has been processed by the front-end.
*/
interface SmartBasicResult {
device: string;
identifier: string;
}
/**
* The SMART data response structure of the back-end. Per device it will either
* contain the structure for a HDD, NVMe or an error.
*/
export interface SmartDataResponseV1 {
[deviceId: string]: AtaSmartDataV1 | NvmeSmartDataV1 | SmartError;
}
/**
* The SMART data result after it has been processed by the front-end.
*/
export interface SmartDataResult extends SmartBasicResult {
info: { [key: string]: any };
smart: {
attributes?: any;
data?: any;
nvmeData?: any;
scsi_error_counter_log?: any;
scsi_grown_defect_list?: any;
};
}
/**
* The SMART error result after is has been processed by the front-end. If SMART
* data couldn't be retrieved, this is the structure which is returned.
*/
export interface SmartErrorResult extends SmartBasicResult {
error: string;
smartctl_error_code: number;
smartctl_output: string;
userMessage: string;
}
| 6,914 | 26.224409 | 82 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/summary.model.ts
|
import { ExecutingTask } from './executing-task';
import { FinishedTask } from './finished-task';
export class Summary {
executing_tasks?: ExecutingTask[];
filesystems?: any[];
finished_tasks?: FinishedTask[];
have_mon_connection?: boolean;
health_status?: string;
mgr_host?: string;
mgr_id?: string;
rbd_mirroring?: any;
rbd_pools?: any[];
version?: string;
}
| 382 | 22.9375 | 49 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/task-exception.ts
|
import { Task } from './task';
export class TaskException {
status: number;
code: number;
component: string;
detail: string;
task: Task;
}
| 150 | 14.1 | 30 |
ts
|
null |
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/shared/models/task.ts
|
export class Task {
constructor(name?: string, metadata?: object) {
this.name = name;
this.metadata = metadata;
}
name: string;
metadata: object;
description: string;
}
| 188 | 16.181818 | 49 |
ts
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.