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/cypress/e2e/rgw/daemons.e2e-spec.ts
import { DaemonsPageHelper } from './daemons.po'; describe('RGW daemons page', () => { const daemons = new DaemonsPageHelper(); beforeEach(() => { cy.login(); daemons.navigateTo(); }); describe('breadcrumb and tab tests', () => { it('should open and show breadcrumb', () => { daemons.expectBreadcrumbText('Gateways'); }); it('should show two tabs', () => { daemons.getTabsCount().should('eq', 2); }); it('should show daemons list tab at first', () => { daemons.getTabText(0).should('eq', 'Gateways List'); }); it('should show overall performance as a second tab', () => { daemons.getTabText(1).should('eq', 'Overall Performance'); }); }); describe('details and performance counters table tests', () => { it('should check that details/performance tables are visible when daemon is selected', () => { daemons.checkTables(); }); }); });
933
25.685714
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/rgw/daemons.po.ts
import { PageHelper } from '../page-helper.po'; export class DaemonsPageHelper extends PageHelper { pages = { index: { url: '#/rgw/daemon', id: 'cd-rgw-daemon-list' } }; getTableCell() { return cy .get('.tab-content') .its(1) .find('cd-table') .should('have.length', 1) // Only 1 table should be renderer .find('datatable-body-cell'); } checkTables() { // click on a daemon so details table appears cy.get('.datatable-body-cell-label').first().click(); // check details table is visible // check at least one field is present this.getTableCell().should('be.visible').should('contain.text', 'ceph_version'); // click on performance counters tab and check table is loaded cy.contains('.nav-link', 'Performance Counters').click(); // check at least one field is present this.getTableCell().should('be.visible').should('contain.text', 'objecter.op_r'); // click on performance details tab cy.contains('.nav-link', 'Performance Details').click(); } }
1,047
28.942857
85
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/rgw/roles.e2e-spec.ts
import { RolesPageHelper } from './roles.po'; describe('RGW roles page', () => { const roles = new RolesPageHelper(); beforeEach(() => { cy.login(); roles.navigateTo(); }); describe('Create, Edit & Delete rgw roles', () => { it('should create rgw roles', () => { roles.navigateTo('create'); roles.create('testRole', '/', '{}'); roles.navigateTo(); roles.checkExist('testRole', true); }); }); });
449
21.5
53
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/rgw/roles.po.ts
import { PageHelper } from '../page-helper.po'; const pages = { index: { url: '#/rgw/roles', id: 'cd-crud-table' }, create: { url: '#/rgw/roles/create', id: 'cd-crud-form' } }; export class RolesPageHelper extends PageHelper { pages = pages; columnIndex = { roleName: 2, path: 3, arn: 4 }; @PageHelper.restrictTo(pages.create.url) create(name: string, path: string, policyDocument: string) { cy.get('#formly_3_string_role_name_0').type(name); cy.get('#formly_3_textarea_role_assume_policy_doc_2').type(policyDocument); cy.get('#formly_3_string_role_path_1').type(path); cy.get("[aria-label='Create Role']").should('exist').click(); cy.get('cd-crud-table').should('exist'); } @PageHelper.restrictTo(pages.index.url) checkExist(name: string, exist: boolean) { this.getTableCell(this.columnIndex.roleName, name).should(($elements) => { const roleName = $elements.map((_, el) => el.textContent).get(); if (exist) { expect(roleName).to.include(name); } else { expect(roleName).to.not.include(name); } }); } }
1,111
28.263158
79
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/rgw/users.e2e-spec.ts
import { UsersPageHelper } from './users.po'; describe('RGW users page', () => { const users = new UsersPageHelper(); const tenant = 'e2e_000tenant'; const user_id = 'e2e_000user_create_edit_delete'; const user_name = tenant + '$' + user_id; beforeEach(() => { cy.login(); users.navigateTo(); }); describe('breadcrumb tests', () => { it('should open and show breadcrumb', () => { users.expectBreadcrumbText('Users'); }); }); describe('create, edit & delete user tests', () => { it('should create user', () => { users.navigateTo('create'); users.create(tenant, user_id, 'Some Name', '[email protected]', '1200'); users.getFirstTableCell(user_id).should('exist'); }); it('should edit users full name, email and max buckets', () => { users.edit(user_name, 'Another Identity', '[email protected]', '1969'); }); it('should delete user', () => { users.delete(user_name); }); }); describe('Invalid input tests', () => { it('should put invalid input into user creation form and check fields are marked invalid', () => { users.invalidCreate(); }); it('should put invalid input into user edit form and check fields are marked invalid', () => { users.invalidEdit(); }); }); });
1,310
27.5
102
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/rgw/users.po.ts
import { PageHelper } from '../page-helper.po'; const pages = { index: { url: '#/rgw/user', id: 'cd-rgw-user-list' }, create: { url: '#/rgw/user/create', id: 'cd-rgw-user-form' } }; export class UsersPageHelper extends PageHelper { pages = pages; @PageHelper.restrictTo(pages.create.url) create(tenant: string, user_id: string, fullname: string, email: string, maxbuckets: string) { // Enter in user_id cy.get('#user_id').type(user_id); // Show Tenanat cy.get('#show_tenant').click({ force: true }); // Enter in tenant cy.get('#tenant').type(tenant); // Enter in full name cy.get('#display_name').click().type(fullname); // Enter in email cy.get('#email').click().type(email); // Enter max buckets this.selectOption('max_buckets_mode', 'Custom'); cy.get('#max_buckets').should('exist').should('have.value', '1000'); cy.get('#max_buckets').click().clear().type(maxbuckets); // Click the create button and wait for user to be made cy.contains('button', 'Create User').click(); this.getFirstTableCell(tenant + '$' + user_id).should('exist'); } @PageHelper.restrictTo(pages.index.url) edit(name: string, new_fullname: string, new_email: string, new_maxbuckets: string) { this.navigateEdit(name); // Change the full name field cy.get('#display_name').click().clear().type(new_fullname); // Change the email field cy.get('#email').click().clear().type(new_email); // Change the max buckets field this.selectOption('max_buckets_mode', 'Custom'); cy.get('#max_buckets').click().clear().type(new_maxbuckets); cy.contains('button', 'Edit User').click(); // Click the user and check its details table for updated content this.getExpandCollapseElement(name).click(); cy.get('.datatable-row-detail') .should('contain.text', new_fullname) .and('contain.text', new_email) .and('contain.text', new_maxbuckets); } invalidCreate() { const tenant = '000invalid_tenant'; const uname = '000invalid_create_user'; // creating this user in order to check that you can't give two users the same name this.navigateTo('create'); this.create(tenant, uname, 'xxx', 'xxx@xxx', '1'); this.navigateTo('create'); // Username cy.get('#user_id') // No username had been entered. Field should be invalid .should('have.class', 'ng-invalid') // Try to give user already taken name. Should make field invalid. .type(uname); cy.get('#show_tenant').click({ force: true }); cy.get('#tenant').type(tenant).should('have.class', 'ng-invalid'); cy.contains('#tenant + .invalid-feedback', 'The chosen user ID exists in this tenant.'); // check that username field is marked invalid if username has been cleared off cy.get('#user_id').clear().blur().should('have.class', 'ng-invalid'); cy.contains('#user_id + .invalid-feedback', 'This field is required.'); // Full name cy.get('#display_name') // No display name has been given so field should be invalid .should('have.class', 'ng-invalid') // display name field should also be marked invalid if given input then emptied .type('a') .clear() .blur() .should('have.class', 'ng-invalid'); cy.contains('#display_name + .invalid-feedback', 'This field is required.'); // put invalid email to make field invalid cy.get('#email').type('a').blur().should('have.class', 'ng-invalid'); cy.contains('#email + .invalid-feedback', 'This is not a valid email address.'); // put negative max buckets to make field invalid this.expectSelectOption('max_buckets_mode', 'Custom'); cy.get('#max_buckets').clear().type('-5').blur().should('have.class', 'ng-invalid'); cy.contains('#max_buckets + .invalid-feedback', 'The entered value must be >= 1.'); this.navigateTo(); this.delete(tenant + '$' + uname); } invalidEdit() { const tenant = '000invalid_tenant'; const uname = '000invalid_edit_user'; // creating this user to edit for the test this.navigateTo('create'); this.create(tenant, uname, 'xxx', 'xxx@xxx', '50'); const name = tenant + '$' + uname; this.navigateEdit(name); // put invalid email to make field invalid cy.get('#email') .clear() .type('a') .blur() .should('not.have.class', 'ng-pending') .should('have.class', 'ng-invalid'); cy.contains('#email + .invalid-feedback', 'This is not a valid email address.'); // empty the display name field making it invalid cy.get('#display_name').clear().blur().should('have.class', 'ng-invalid'); cy.contains('#display_name + .invalid-feedback', 'This field is required.'); // put negative max buckets to make field invalid this.selectOption('max_buckets_mode', 'Disabled'); cy.get('#max_buckets').should('not.exist'); this.selectOption('max_buckets_mode', 'Custom'); cy.get('#max_buckets').should('exist').should('have.value', '50'); cy.get('#max_buckets').clear().type('-5').blur().should('have.class', 'ng-invalid'); cy.contains('#max_buckets + .invalid-feedback', 'The entered value must be >= 1.'); this.navigateTo(); this.delete(tenant + '$' + uname); } }
5,271
36.657143
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/api-docs.e2e-spec.ts
import { ApiDocsPageHelper } from '../ui/api-docs.po'; describe('Api Docs Page', () => { const apiDocs = new ApiDocsPageHelper(); beforeEach(() => { cy.login(); apiDocs.navigateTo(); }); it('should show the API Docs description', () => { cy.get('.renderedMarkdown').first().contains('This is the official Ceph REST API'); }); });
355
22.733333
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/api-docs.po.ts
import { PageHelper } from '../page-helper.po'; export class ApiDocsPageHelper extends PageHelper { pages = { index: { url: '#/api-docs', id: 'cd-api-docs' } }; }
166
26.833333
62
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/dashboard-v3.e2e-spec.ts
import { ManagerModulesPageHelper } from '../cluster/mgr-modules.po'; import { DashboardV3PageHelper } from './dashboard-v3.po'; describe('Dashboard-v3 Main Page', () => { const dashboard = new DashboardV3PageHelper(); const mgrmodules = new ManagerModulesPageHelper(); before(() => { cy.login(); mgrmodules.navigateTo(); mgrmodules.navigateEdit('dashboard'); cy.get('#FEATURE_TOGGLE_DASHBOARD').check(); cy.contains('button', 'Update').click(); }); beforeEach(() => { cy.login(); dashboard.navigateTo(); }); describe('Check that all hyperlinks on inventory card lead to the correct page and fields exist', () => { it('should ensure that all linked pages in the inventory card lead to correct page', () => { const expectationMap = { Host: 'Hosts', Monitor: 'Monitors', OSDs: 'OSDs', Pool: 'Pools', 'Object Gateway': 'Gateways' }; for (const [linkText, breadcrumbText] of Object.entries(expectationMap)) { cy.location('hash').should('eq', '#/dashboard'); dashboard.clickInventoryCardLink(linkText); dashboard.expectBreadcrumbText(breadcrumbText); dashboard.navigateBack(); } }); it('should verify that cards exist on dashboard in proper order', () => { // Ensures that cards are all displayed on the dashboard tab while being in the proper // order, checks for card title and position via indexing into a list of all cards. const order = ['Details', 'Status', 'Capacity', 'Inventory', 'Cluster utilization']; for (let i = 0; i < order.length; i++) { dashboard.card(i).should('contain.text', order[i]); } }); }); });
1,716
33.34
107
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/dashboard-v3.po.ts
import { PageHelper } from '../page-helper.po'; export class DashboardV3PageHelper extends PageHelper { pages = { index: { url: '#/dashboard', id: 'cd-dashboard-v3' } }; cardTitle(index: number) { return cy.get('.card-title').its(index).text(); } clickInventoryCardLink(link: string) { console.log(link); cy.get(`cd-card[cardTitle="Inventory"]`).contains('a', link).click(); } card(indexOrTitle: number) { cy.get('cd-card').as('cards'); return cy.get('@cards').its(indexOrTitle); } }
523
23.952381
73
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/dashboard.e2e-spec.ts
import { IscsiPageHelper } from '../block/iscsi.po'; import { HostsPageHelper } from '../cluster/hosts.po'; import { ManagerModulesPageHelper } from '../cluster/mgr-modules.po'; import { MonitorsPageHelper } from '../cluster/monitors.po'; import { OSDsPageHelper } from '../cluster/osds.po'; import { PageHelper } from '../page-helper.po'; import { PoolPageHelper } from '../pools/pools.po'; import { DaemonsPageHelper } from '../rgw/daemons.po'; import { DashboardPageHelper } from './dashboard.po'; describe('Dashboard Main Page', () => { const dashboard = new DashboardPageHelper(); const daemons = new DaemonsPageHelper(); const hosts = new HostsPageHelper(); const osds = new OSDsPageHelper(); const pools = new PoolPageHelper(); const monitors = new MonitorsPageHelper(); const iscsi = new IscsiPageHelper(); const mgrmodules = new ManagerModulesPageHelper(); before(() => { cy.login(); mgrmodules.navigateTo(); mgrmodules.navigateEdit('dashboard'); cy.get('#FEATURE_TOGGLE_DASHBOARD').uncheck(); cy.contains('button', 'Update').click(); }); beforeEach(() => { cy.login(); dashboard.navigateTo(); }); describe('Check that all hyperlinks on info cards lead to the correct page and fields exist', () => { it('should ensure that all linked info cards lead to correct page', () => { const expectationMap = { Monitors: 'Monitors', OSDs: 'OSDs', Hosts: 'Hosts', 'Object Gateways': 'Gateways', 'iSCSI Gateways': 'Overview', Pools: 'Pools' }; for (const [linkText, breadcrumbText] of Object.entries(expectationMap)) { cy.location('hash').should('eq', '#/dashboard'); dashboard.clickInfoCardLink(linkText); dashboard.expectBreadcrumbText(breadcrumbText); dashboard.navigateBack(); } }); it('should verify that info cards exist on dashboard in proper order', () => { // Ensures that info cards are all displayed on the dashboard tab while being in the proper // order, checks for card title and position via indexing into a list of all info cards. const order = [ 'Cluster Status', 'Hosts', 'Monitors', 'OSDs', 'Managers', 'Object Gateways', 'Metadata Servers', 'iSCSI Gateways', 'Raw Capacity', 'Objects', 'PG Status', 'Pools', 'PGs per OSD', 'Client Read/Write', 'Client Throughput', 'Recovery Throughput', 'Scrubbing' ]; for (let i = 0; i < order.length; i++) { dashboard.infoCard(i).should('contain.text', order[i]); } }); it('should verify that info card group titles are present and in the right order', () => { cy.location('hash').should('eq', '#/dashboard'); dashboard.infoGroupTitle(0).should('eq', 'Status'); dashboard.infoGroupTitle(1).should('eq', 'Capacity'); dashboard.infoGroupTitle(2).should('eq', 'Performance'); }); }); it('Should check that dashboard cards have correct information', () => { interface TestSpec { cardName: string; regexMatcher?: RegExp; pageObject: PageHelper; } const testSpecs: TestSpec[] = [ { cardName: 'Object Gateways', regexMatcher: /(\d+)\s+total/, pageObject: daemons }, { cardName: 'Monitors', regexMatcher: /(\d+)\s+\(quorum/, pageObject: monitors }, { cardName: 'Hosts', regexMatcher: /(\d+)\s+total/, pageObject: hosts }, { cardName: 'OSDs', regexMatcher: /(\d+)\s+total/, pageObject: osds }, { cardName: 'Pools', pageObject: pools }, { cardName: 'iSCSI Gateways', regexMatcher: /(\d+)\s+total/, pageObject: iscsi } ]; for (let i = 0; i < testSpecs.length; i++) { const spec = testSpecs[i]; dashboard.navigateTo(); dashboard.infoCardBodyText(spec.cardName).then((infoCardBodyText: string) => { let dashCount = 0; if (spec.regexMatcher) { const match = infoCardBodyText.match(new RegExp(spec.regexMatcher)); expect(match).to.length.gt( 1, `Regex ${spec.regexMatcher} did not find a match for card with name ` + `${spec.cardName}` ); dashCount = Number(match[1]); } else { dashCount = Number(infoCardBodyText); } spec.pageObject.navigateTo(); spec.pageObject.getTableCount('total').then((tableCount) => { expect(tableCount).to.eq( dashCount, `Text of card "${spec.cardName}" and regex "${spec.regexMatcher}" resulted in ${dashCount} ` + `but did not match table count ${tableCount}` ); }); }); } }); after(() => { cy.login(); mgrmodules.navigateTo(); mgrmodules.navigateEdit('dashboard'); cy.get('#FEATURE_TOGGLE_DASHBOARD').click(); cy.contains('button', 'Update').click(); }); });
4,959
33.929577
106
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/dashboard.po.ts
import { PageHelper } from '../page-helper.po'; export class DashboardPageHelper extends PageHelper { pages = { index: { url: '#/dashboard', id: 'cd-dashboard' } }; infoGroupTitle(index: number) { return cy.get('.info-group-title').its(index).text(); } clickInfoCardLink(cardName: string) { cy.get(`cd-info-card[cardtitle="${cardName}"]`).contains('a', cardName).click(); } infoCard(indexOrTitle: number | string) { cy.get('cd-info-card').as('infoCards'); if (typeof indexOrTitle === 'number') { return cy.get('@infoCards').its(indexOrTitle); } else { return cy.contains('cd-info-card a', indexOrTitle).parent().parent().parent().parent(); } } infoCardBodyText(infoCard: string) { return this.infoCard(infoCard).find('.card-text').text(); } infoCardBody(infoCard: string) { return this.infoCard(infoCard).find('.card-text'); } }
902
27.21875
93
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/language.e2e-spec.ts
import { LanguagePageHelper } from './language.po'; describe('Shared pages', () => { const language = new LanguagePageHelper(); beforeEach(() => { cy.login(); language.navigateTo(); }); it('should check default language', () => { language.getLanguageBtn().should('contain.text', 'English'); }); it('should check all available languages', () => { language.getLanguageBtn().click(); language.getAllLanguages().should('have.length', 1).should('contain.text', 'English'); }); });
514
24.75
90
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/language.po.ts
import { PageHelper } from '../page-helper.po'; export class LanguagePageHelper extends PageHelper { pages = { index: { url: '#/dashboard', id: 'cd-dashboard' } }; getLanguageBtn() { return cy.get('cd-language-selector a').first(); } getAllLanguages() { return cy.get('cd-language-selector button'); } }
331
19.75
53
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/login.e2e-spec.ts
import { LoginPageHelper } from './login.po'; describe('Login page', () => { const login = new LoginPageHelper(); it('should login and navigate to dashboard page', () => { login.navigateTo(); login.doLogin(); }); it('should logout when clicking the button', () => { login.navigateTo(); login.doLogin(); login.doLogout(); }); it('should have no accessibility violations', () => { login.navigateTo(); cy.injectAxe(); cy.checkA11y(); }); });
490
19.458333
59
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/login.po.ts
import { PageHelper } from '../page-helper.po'; export class LoginPageHelper extends PageHelper { pages = { index: { url: '#/login', id: 'cd-login' }, dashboard: { url: '#/dashboard', id: 'cd-dashboard' } }; doLogin() { cy.get('[name=username]').type('admin'); cy.get('#password').type('admin'); cy.get('[type=submit]').click(); cy.get('cd-dashboard').should('exist'); } doLogout() { cy.get('cd-identity a').click(); cy.contains('cd-identity span', 'Sign out').click(); cy.get('cd-login').should('exist'); cy.location('hash').should('eq', '#/login'); } }
610
25.565217
57
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/navigation.e2e-spec.ts
import { NavigationPageHelper } from './navigation.po'; describe('Shared pages', () => { const shared = new NavigationPageHelper(); beforeEach(() => { cy.login(); shared.navigateTo(); }); it('should display the vertical menu by default', () => { shared.getVerticalMenu().should('not.have.class', 'active'); }); it('should hide the vertical menu', () => { shared.getMenuToggler().click(); shared.getVerticalMenu().should('have.class', 'active'); }); it('should navigate to the correct page', () => { shared.checkNavigations(shared.navigations); }); });
599
24
64
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/navigation.po.ts
import { PageHelper } from '../page-helper.po'; export class NavigationPageHelper extends PageHelper { pages = { index: { url: '#/dashboard', id: 'cd-dashboard' } }; navigations = [ { menu: 'NFS', component: 'cd-error' }, { menu: 'Object Gateway', submenus: [ { menu: 'Gateways', component: 'cd-rgw-daemon-list' }, { menu: 'Users', component: 'cd-rgw-user-list' }, { menu: 'Buckets', component: 'cd-rgw-bucket-list' } ] }, { menu: 'Dashboard', component: 'cd-dashboard' }, { menu: 'Cluster', submenus: [ { menu: 'Hosts', component: 'cd-hosts' }, { menu: 'Physical Disks', component: 'cd-error' }, { menu: 'Monitors', component: 'cd-monitor' }, { menu: 'Services', component: 'cd-error' }, { menu: 'OSDs', component: 'cd-osd-list' }, { menu: 'Configuration', component: 'cd-configuration' }, { menu: 'CRUSH map', component: 'cd-crushmap' }, { menu: 'Manager Modules', component: 'cd-mgr-module-list' }, { menu: 'Ceph Users', component: 'cd-crud-table' }, { menu: 'Logs', component: 'cd-logs' }, { menu: 'Alerts', component: 'cd-prometheus-tabs' } ] }, { menu: 'Pools', component: 'cd-pool-list' }, { menu: 'Block', submenus: [ { menu: 'Images', component: 'cd-error' }, { menu: 'Mirroring', component: 'cd-mirroring' }, { menu: 'iSCSI', component: 'cd-iscsi' } ] }, { menu: 'File Systems', component: 'cd-cephfs-list' } ]; getVerticalMenu() { return cy.get('nav[id=sidebar]'); } getMenuToggler() { return cy.get('[aria-label="toggle sidebar visibility"]'); } checkNavigations(navs: any) { // The nfs-ganesha, RGW, and block/rbd status requests are mocked to ensure that this method runs in time cy.intercept('/ui-api/nfs-ganesha/status', { fixture: 'nfs-ganesha-status.json' }); cy.intercept('/ui-api/rgw/status', { fixture: 'rgw-status.json' }); cy.intercept('/ui-api/block/rbd/status', { fixture: 'block-rbd-status.json' }); navs.forEach((nav: any) => { cy.contains('.simplebar-content li.nav-item a', nav.menu).click(); if (nav.submenus) { this.checkNavSubMenu(nav.menu, nav.submenus); } else { cy.get(nav.component).should('exist'); } }); } checkNavSubMenu(menu: any, submenu: any) { submenu.forEach((nav: any) => { cy.contains('.simplebar-content li.nav-item', menu).within(() => { cy.contains(`ul.list-unstyled li a`, nav.menu).click(); }); }); } }
2,619
32.164557
109
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/notification.e2e-spec.ts
import { PoolPageHelper } from '../pools/pools.po'; import { NotificationSidebarPageHelper } from './notification.po'; describe('Notification page', () => { const notification = new NotificationSidebarPageHelper(); const pools = new PoolPageHelper(); const poolName = 'e2e_notification_pool'; before(() => { cy.login(); pools.navigateTo('create'); pools.create(poolName, 8); pools.edit_pool_pg(poolName, 4, false); }); after(() => { cy.login(); pools.navigateTo(); pools.delete(poolName); }); beforeEach(() => { cy.login(); pools.navigateTo(); }); it('should open notification sidebar', () => { notification.getSidebar().should('not.be.visible'); notification.open(); notification.getSidebar().should('be.visible'); }); it('should display a running task', () => { notification.getToast().should('not.exist'); // Check that running task is shown. notification.open(); notification.getTasks().contains(poolName).should('exist'); // Delete pool after task is complete (otherwise we get an error). notification.getTasks().contains(poolName, { timeout: 300000 }).should('not.exist'); }); it('should have notifications', () => { notification.open(); notification.getNotifications().should('have.length.gt', 0); }); it('should clear notifications', () => { notification.getToast().should('not.exist'); notification.open(); notification.getNotifications().should('have.length.gt', 0); notification.getClearNotficationsBtn().should('be.visible'); notification.clearNotifications(); }); });
1,625
27.526316
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/notification.po.ts
import { PageHelper } from '../page-helper.po'; export class NotificationSidebarPageHelper extends PageHelper { getNotificatinoIcon() { return cy.get('cd-notifications a'); } getSidebar() { return cy.get('cd-notifications-sidebar'); } getTasks() { return this.getSidebar().find('.card.tc_task'); } getNotifications() { return this.getSidebar().find('.card.tc_notification'); } getClearNotficationsBtn() { return this.getSidebar().find('button.btn-block'); } getCloseBtn() { return this.getSidebar().find('button.close'); } open() { this.getNotificatinoIcon().click(); this.getSidebar().should('be.visible'); } clearNotifications() { // It can happen that although notifications are cleared, by the time we check the notifications // amount, another notification can appear, so we check it more than once (if needed). this.getClearNotficationsBtn().click(); this.getNotifications() .should('have.length.gte', 0) .then(($elems) => { if ($elems.length > 0) { this.clearNotifications(); } }); } }
1,125
23.478261
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/role-mgmt.e2e-spec.ts
import { RoleMgmtPageHelper } from './role-mgmt.po'; describe('Role Management page', () => { const roleMgmt = new RoleMgmtPageHelper(); const role_name = 'e2e_role_mgmt_role'; beforeEach(() => { cy.login(); roleMgmt.navigateTo(); }); describe('breadcrumb tests', () => { it('should check breadcrumb on roles tab on user management page', () => { roleMgmt.expectBreadcrumbText('Roles'); }); it('should check breadcrumb on role creation page', () => { roleMgmt.navigateTo('create'); roleMgmt.expectBreadcrumbText('Create'); }); }); describe('role create, edit & delete test', () => { it('should create a role', () => { roleMgmt.create(role_name, 'An interesting description'); }); it('should edit a role', () => { roleMgmt.edit(role_name, 'A far more interesting description'); }); it('should delete a role', () => { roleMgmt.delete(role_name); }); }); });
963
25.054054
78
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/role-mgmt.po.ts
import { PageHelper } from '../page-helper.po'; export class RoleMgmtPageHelper extends PageHelper { pages = { index: { url: '#/user-management/roles', id: 'cd-role-list' }, create: { url: '#/user-management/roles/create', id: 'cd-role-form' } }; create(name: string, description: string) { this.navigateTo('create'); // Waits for data to load cy.contains('grafana'); // fill in fields cy.get('#name').type(name); cy.get('#description').type(description); // Click the create button and wait for role to be made cy.get('[data-cy=submitBtn]').click(); cy.get('.breadcrumb-item.active').should('not.have.text', 'Create'); this.getFirstTableCell(name).should('exist'); } edit(name: string, description: string) { this.navigateEdit(name); // Waits for data to load cy.contains('grafana'); // fill in fields with new values cy.get('#description').clear().type(description); // Click the edit button and check new values are present in table cy.get('[data-cy=submitBtn]').click(); cy.get('.breadcrumb-item.active').should('not.have.text', 'Edit'); this.getFirstTableCell(name).should('exist'); this.getFirstTableCell(description).should('exist'); } }
1,254
29.609756
73
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/user-mgmt.e2e-spec.ts
import { UserMgmtPageHelper } from './user-mgmt.po'; describe('User Management page', () => { const userMgmt = new UserMgmtPageHelper(); const user_name = 'e2e_user_mgmt_user'; beforeEach(() => { cy.login(); userMgmt.navigateTo(); }); describe('breadcrumb tests', () => { it('should check breadcrumb on users tab of user management page', () => { userMgmt.expectBreadcrumbText('Users'); }); it('should check breadcrumb on user creation page', () => { userMgmt.navigateTo('create'); userMgmt.expectBreadcrumbText('Create'); }); }); describe('user create, edit & delete test', () => { it('should create a user', () => { userMgmt.create(user_name, 'cool_password', 'Jeff', '[email protected]'); }); it('should edit a user', () => { userMgmt.edit(user_name, 'cool_password_number_2', 'Geoff', 'w@m'); }); it('should delete a user', () => { userMgmt.delete(user_name); }); }); });
991
25.810811
87
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/ui/user-mgmt.po.ts
import { PageHelper } from '../page-helper.po'; export class UserMgmtPageHelper extends PageHelper { pages = { index: { url: '#/user-management/users', id: 'cd-user-list' }, create: { url: '#/user-management/users/create', id: 'cd-user-form' } }; create(username: string, password: string, name: string, email: string) { this.navigateTo('create'); // fill in fields cy.get('#username').type(username); cy.get('#password').type(password); cy.get('#confirmpassword').type(password); cy.get('#name').type(name); cy.get('#email').type(email); // Click the create button and wait for user to be made cy.get('[data-cy=submitBtn]').click(); this.getFirstTableCell(username).should('exist'); } edit(username: string, password: string, name: string, email: string) { this.navigateEdit(username); // fill in fields with new values cy.get('#password').clear().type(password); cy.get('#confirmpassword').clear().type(password); cy.get('#name').clear().type(name); cy.get('#email').clear().type(email); // Click the edit button and check new values are present in table const editButton = cy.get('[data-cy=submitBtn]'); editButton.click(); this.getFirstTableCell(email).should('exist'); this.getFirstTableCell(name).should('exist'); } }
1,335
32.4
75
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/visualTests/dashboard.vrt-spec.ts
import { LoginPageHelper } from '../ui/login.po'; describe('Dashboard Landing Page', () => { const login = new LoginPageHelper(); beforeEach(() => { cy.eyesOpen({ testName: 'Dashboard Component' }); }); afterEach(() => { cy.eyesClose(); }); it('should take screenshot of dashboard landing page', () => { login.navigateTo(); login.doLogin(); cy.get('[aria-label="Status card"]').should('be.visible'); cy.get('[aria-label="Inventory card"]').should('be.visible'); cy.get('[aria-label="Cluster utilization card"]').should('be.visible'); cy.eyesCheckWindow({ tag: 'Dashboard landing page' }); }); });
657
25.32
75
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/e2e/visualTests/login.vrt-spec.ts
describe('Login Page', () => { beforeEach(() => { cy.visit('#/login'); cy.eyesOpen({ appName: 'Ceph', testName: 'Login Component Check' }); }); afterEach(() => { cy.eyesClose(); }); it('types login credentials and takes screenshot', () => { cy.get('[name=username]').type('admin'); cy.get('#password').type('admin'); cy.eyesCheckWindow({ tag: 'Login Screen with credentials typed' }); }); });
447
21.4
71
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/support/commands.ts
declare global { namespace Cypress { interface Chainable<Subject> { login(username?: string, password?: string): void; logToConsole(message: string, optional?: any): void; text(): Chainable<string>; ceph2Login(username?: string, password?: string): Chainable<any>; checkAccessibility(subject: any, axeOptions?: any, skip?: boolean): void; } } } // Disabling tslint rule since cypress-cucumber has // issues with absolute import paths. // This can be removed when // https://github.com/cypress-io/cypress-browserify-preprocessor/issues/53 // is fixed. /* tslint:disable*/ import { CdHelperClass } from '../../src/app/shared/classes/cd-helper.class'; import { Permissions } from '../../src/app/shared/models/permissions'; import { table } from 'table'; /* tslint:enable*/ let auth: any; const fillAuth = () => { window.localStorage.setItem('dashboard_username', auth.username); window.localStorage.setItem('dashboard_permissions', auth.permissions); window.localStorage.setItem('user_pwd_expiration_date', auth.pwdExpirationDate); window.localStorage.setItem('user_pwd_update_required', auth.pwdUpdateRequired); window.localStorage.setItem('sso', auth.sso); }; Cypress.Commands.add('login', (username, password) => { cy.session([username, password], () => { requestAuth(username, password).then((resp) => { auth = resp.body; auth.permissions = JSON.stringify(new Permissions(auth.permissions)); auth.pwdExpirationDate = String(auth.pwdExpirationDate); auth.pwdUpdateRequired = String(auth.pwdUpdateRequired); auth.sso = String(auth.sso); fillAuth(); }); }); }); Cypress.Commands.add('ceph2Login', (username, password) => { const url: string = Cypress.env('CEPH2_URL'); cy.session([username, password, url], () => { requestAuth(username, password, url).then((resp) => { auth = resp.body; auth.permissions = JSON.stringify(new Permissions(auth.permissions)); auth.pwdExpirationDate = String(auth.pwdExpirationDate); auth.pwdUpdateRequired = String(auth.pwdUpdateRequired); auth.sso = String(auth.sso); const args = { username: auth.username, permissions: auth.permissions, pwdExpirationDate: auth.pwdExpirationDate, pwdUpdateRequired: auth.pwdUpdateRequired, sso: auth.sso }; // @ts-ignore cy.origin( url, { args }, ({ uname, permissions, pwdExpirationDate, pwdUpdateRequired, sso }: any) => { window.localStorage.setItem('dashboard_username', uname); window.localStorage.setItem('dashboard_permissions', permissions); window.localStorage.setItem('user_pwd_expiration_date', pwdExpirationDate); window.localStorage.setItem('user_pwd_update_required', pwdUpdateRequired); window.localStorage.setItem('sso', sso); } ); }); }); }); function requestAuth(username: string, password: string, url = '') { username = username ? username : Cypress.env('LOGIN_USER'); password = password ? password : Cypress.env('LOGIN_PWD'); return cy.request({ method: 'POST', url: !url ? 'api/auth' : `${url}api/auth`, headers: { Accept: CdHelperClass.cdVersionHeader('1', '0') }, body: { username: username, password: password } }); } // @ts-ignore Cypress.Commands.add('text', { prevSubject: true }, (subject: any) => { return subject.text(); }); Cypress.Commands.add('logToConsole', (message: string, optional?: any) => { cy.task('log', { message: `(${new Date().toISOString()}) ${message}`, optional }); }); // Print cypress-axe violations to the terminal function a11yErrorLogger(violations: any) { const violationData = violations.flatMap(({ id, impact, description, nodes }: any) => { return nodes.flatMap(({ html }: any) => { return [ ['Test', Cypress.currentTest.title], ['Error', id], ['Impact', impact], ['Description', description], ['Element', html], ['', ''] ]; }); }); cy.task('log', { message: table(violationData, { header: { alignment: 'left', content: Cypress.spec.relative } }) }); } Cypress.Commands.add('checkAccessibility', (subject: any, axeOptions?: any, skip?: boolean) => { cy.checkA11y(subject, axeOptions, a11yErrorLogger, skip); });
4,383
34.072
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/support/e2e.ts
import '@applitools/eyes-cypress/commands'; import 'cypress-axe'; import './commands'; afterEach(() => { cy.visit('#/403'); }); Cypress.on('uncaught:exception', (err: Error) => { if ( err.message.includes('ResizeObserver loop limit exceeded') || err.message.includes('api/prometheus/rules') || err.message.includes('NG0100: ExpressionChangedAfterItHasBeenCheckedError') ) { return false; } return true; });
436
20.85
79
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/cypress/support/eyes-index.d.ts
import '@applitools/eyes-cypress';
35
17
34
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/index.html
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Ceph</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="icon" type="image/x-icon" id="cdFavicon" href="favicon.ico"> </head> <body> <noscript> <div class="noscript container" ng-if="false"> <div class="jumbotron alert alert-danger"> <h2 i18n>JavaScript required!</h2> <p i18n>A browser with JavaScript enabled is required in order to use this service.</p> <p i18n>When using Internet Explorer, please check your security settings and add this address to your trusted sites.</p> </div> </div> </noscript> <cd-root></cd-root> </body> </html>
734
28.4
129
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/jestGlobalMocks.ts
Object.defineProperty(window, 'getComputedStyle', { value: () => ({ getPropertyValue: () => { return ''; } }) });
132
15.625
51
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/main.ts
import { ApplicationRef, enableProdMode, isDevMode } from '@angular/core'; import { enableDebugTools } from '@angular/platform-browser'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } platformBrowserDynamic() .bootstrapModule(AppModule) .then((moduleRef) => { if (isDevMode()) { // source: https://medium.com/@dmitrymogilko/profiling-angular-change-detection-c00605862b9f const applicationRef = moduleRef.injector.get(ApplicationRef); const componentRef = applicationRef.components[0]; // allows to run `ng.profiler.timeChangeDetection();` enableDebugTools(componentRef); } }) .catch((err) => console.log(err)); // eslint-disable-line no-console
880
35.708333
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/polyfills.ts
/*************************************************************************************************** * Load `$localize` onto the global scope - used if i18n tags appear in Angular templates. */ import '@angular/localize/init'; /** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported after ZoneJS that should be loaded before your main * file. * * The current setup is for so-called "evergreen" browsers; the last versions of browsers that * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. * * Learn more in https://angular.io/guide/browser-support */ /*************************************************************************************************** * BROWSER POLYFILLS */ /** IE10 and IE11 requires the following for the Reflect API. */ // import 'core-js/es6/reflect'; /*************************************************************************************************** * Zone JS is required by Angular itself. */ import 'zone.js/dist/zone'; // Included with Angular CLI. /*************************************************************************************************** * APPLICATION IMPORTS */ /** * Date, currency, decimal and percent pipes. * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 */ // import 'intl'; // Run `npm install --save intl`. /** * Need to import at least one locale-data with intl. */ // import 'intl/locale-data/jsonp/en';
1,773
37.565217
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/setupJest.ts
import '@angular/localize/init'; import 'jest-preset-angular/setup-jest'; import './jestGlobalMocks'; process.on('unhandledRejection', (error) => { const stack = error['stack'] || ''; // Avoid potential hang on test failure when running tests in parallel. throw `WARNING: unhandled rejection: ${error} ${stack}`; });
326
26.25
73
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/typings.d.ts
/* SystemJS module definition */ declare var module: NodeModule; interface NodeModule { id: string; }
104
16.5
32
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/app-routing.module.ts
import { Injectable, NgModule } from '@angular/core'; import { ActivatedRouteSnapshot, PreloadAllModules, RouterModule, Routes } from '@angular/router'; import _ from 'lodash'; import { CephfsListComponent } from './ceph/cephfs/cephfs-list/cephfs-list.component'; import { ConfigurationFormComponent } from './ceph/cluster/configuration/configuration-form/configuration-form.component'; import { ConfigurationComponent } from './ceph/cluster/configuration/configuration.component'; import { CreateClusterComponent } from './ceph/cluster/create-cluster/create-cluster.component'; import { CrushmapComponent } from './ceph/cluster/crushmap/crushmap.component'; import { HostFormComponent } from './ceph/cluster/hosts/host-form/host-form.component'; import { HostsComponent } from './ceph/cluster/hosts/hosts.component'; import { InventoryComponent } from './ceph/cluster/inventory/inventory.component'; import { LogsComponent } from './ceph/cluster/logs/logs.component'; import { MgrModuleFormComponent } from './ceph/cluster/mgr-modules/mgr-module-form/mgr-module-form.component'; import { MgrModuleListComponent } from './ceph/cluster/mgr-modules/mgr-module-list/mgr-module-list.component'; import { MonitorComponent } from './ceph/cluster/monitor/monitor.component'; import { OsdFormComponent } from './ceph/cluster/osd/osd-form/osd-form.component'; import { OsdListComponent } from './ceph/cluster/osd/osd-list/osd-list.component'; import { ActiveAlertListComponent } from './ceph/cluster/prometheus/active-alert-list/active-alert-list.component'; import { RulesListComponent } from './ceph/cluster/prometheus/rules-list/rules-list.component'; import { SilenceFormComponent } from './ceph/cluster/prometheus/silence-form/silence-form.component'; import { SilenceListComponent } from './ceph/cluster/prometheus/silence-list/silence-list.component'; import { ServiceFormComponent } from './ceph/cluster/services/service-form/service-form.component'; import { ServicesComponent } from './ceph/cluster/services/services.component'; import { TelemetryComponent } from './ceph/cluster/telemetry/telemetry.component'; import { DashboardComponent } from './ceph/dashboard/dashboard/dashboard.component'; import { NfsFormComponent } from './ceph/nfs/nfs-form/nfs-form.component'; import { NfsListComponent } from './ceph/nfs/nfs-list/nfs-list.component'; import { PerformanceCounterComponent } from './ceph/performance-counter/performance-counter/performance-counter.component'; import { LoginPasswordFormComponent } from './core/auth/login-password-form/login-password-form.component'; import { LoginComponent } from './core/auth/login/login.component'; import { UserPasswordFormComponent } from './core/auth/user-password-form/user-password-form.component'; import { ErrorComponent } from './core/error/error.component'; import { BlankLayoutComponent } from './core/layouts/blank-layout/blank-layout.component'; import { LoginLayoutComponent } from './core/layouts/login-layout/login-layout.component'; import { WorkbenchLayoutComponent } from './core/layouts/workbench-layout/workbench-layout.component'; import { ApiDocsComponent } from './core/navigation/api-docs/api-docs.component'; import { ActionLabels, URLVerbs } from './shared/constants/app.constants'; import { CrudFormComponent } from './shared/forms/crud-form/crud-form.component'; import { CRUDTableComponent } from './shared/datatable/crud-table/crud-table.component'; import { BreadcrumbsResolver, IBreadcrumb } from './shared/models/breadcrumbs'; import { AuthGuardService } from './shared/services/auth-guard.service'; import { ChangePasswordGuardService } from './shared/services/change-password-guard.service'; import { FeatureTogglesGuardService } from './shared/services/feature-toggles-guard.service'; import { ModuleStatusGuardService } from './shared/services/module-status-guard.service'; import { NoSsoGuardService } from './shared/services/no-sso-guard.service'; import { UpgradeComponent } from './ceph/cluster/upgrade/upgrade.component'; @Injectable() export class PerformanceCounterBreadcrumbsResolver extends BreadcrumbsResolver { resolve(route: ActivatedRouteSnapshot) { const result: IBreadcrumb[] = []; const fromPath = route.queryParams.fromLink || null; let fromText = ''; switch (fromPath) { case '/monitor': fromText = 'Monitors'; break; case '/hosts': fromText = 'Hosts'; break; } result.push({ text: 'Cluster', path: null }); result.push({ text: fromText, path: fromPath }); result.push({ text: 'Performance Counters', path: '' }); return result; } } @Injectable() export class StartCaseBreadcrumbsResolver extends BreadcrumbsResolver { resolve(route: ActivatedRouteSnapshot) { const path = route.params.name; const text = _.startCase(path); return [{ text: `${text}/Edit`, path: path }]; } } const routes: Routes = [ // Dashboard { path: '', redirectTo: 'dashboard', pathMatch: 'full' }, { path: 'api-docs', component: ApiDocsComponent }, { path: '', component: WorkbenchLayoutComponent, canActivate: [AuthGuardService, ChangePasswordGuardService], canActivateChild: [AuthGuardService, ChangePasswordGuardService], children: [ { path: 'dashboard', component: DashboardComponent }, { path: 'error', component: ErrorComponent }, // Cluster { path: 'expand-cluster', component: CreateClusterComponent, canActivate: [ModuleStatusGuardService], data: { moduleStatusGuardConfig: { uiApiPath: 'orchestrator', redirectTo: 'dashboard', backend: 'cephadm' }, breadcrumbs: 'Expand Cluster' } }, { path: 'hosts', component: HostsComponent, data: { breadcrumbs: 'Cluster/Hosts' }, children: [ { path: URLVerbs.ADD, component: HostFormComponent, outlet: 'modal' } ] }, { path: 'ceph-users', component: CRUDTableComponent, data: { breadcrumbs: 'Cluster/Ceph Users', resource: '[email protected]' } }, { path: 'cluster/user/create', component: CrudFormComponent, data: { breadcrumbs: 'Cluster/Ceph Users/Create', resource: '[email protected]' } }, { path: 'cluster/user/import', component: CrudFormComponent, data: { breadcrumbs: 'Cluster/Ceph Users/Import', resource: '[email protected]' } }, { path: 'cluster/user/edit', component: CrudFormComponent, data: { breadcrumbs: 'Cluster/Ceph Users/Edit', resource: '[email protected]' } }, { path: 'monitor', component: MonitorComponent, data: { breadcrumbs: 'Cluster/Monitors' } }, { path: 'services', component: ServicesComponent, canActivate: [ModuleStatusGuardService], data: { moduleStatusGuardConfig: { uiApiPath: 'orchestrator', redirectTo: 'error', section: 'orch', section_info: 'Orchestrator', header: 'Orchestrator is not available' }, breadcrumbs: 'Cluster/Services' }, children: [ { path: URLVerbs.CREATE, component: ServiceFormComponent, outlet: 'modal' }, { path: `${URLVerbs.EDIT}/:type/:name`, component: ServiceFormComponent, outlet: 'modal' } ] }, { path: 'inventory', canActivate: [ModuleStatusGuardService], component: InventoryComponent, data: { moduleStatusGuardConfig: { uiApiPath: 'orchestrator', redirectTo: 'error', section: 'orch', section_info: 'Orchestrator', header: 'Orchestrator is not available' }, breadcrumbs: 'Cluster/Physical Disks' } }, { path: 'osd', data: { breadcrumbs: 'Cluster/OSDs' }, children: [ { path: '', component: OsdListComponent }, { path: URLVerbs.CREATE, component: OsdFormComponent, data: { breadcrumbs: ActionLabels.CREATE } } ] }, { path: 'configuration', data: { breadcrumbs: 'Cluster/Configuration' }, children: [ { path: '', component: ConfigurationComponent }, { path: 'edit/:name', component: ConfigurationFormComponent, data: { breadcrumbs: ActionLabels.EDIT } } ] }, { path: 'crush-map', component: CrushmapComponent, data: { breadcrumbs: 'Cluster/CRUSH map' } }, { path: 'logs', component: LogsComponent, data: { breadcrumbs: 'Cluster/Logs' } }, { path: 'telemetry', component: TelemetryComponent, data: { breadcrumbs: 'Telemetry configuration' } }, { path: 'monitoring', data: { breadcrumbs: 'Cluster/Alerts' }, children: [ { path: '', redirectTo: 'active-alerts', pathMatch: 'full' }, { path: 'active-alerts', data: { breadcrumbs: 'Active Alerts' }, component: ActiveAlertListComponent }, { path: 'alerts', data: { breadcrumbs: 'Alerts' }, component: RulesListComponent }, { path: 'silences', data: { breadcrumbs: 'Silences' }, children: [ { path: '', component: SilenceListComponent }, { path: URLVerbs.CREATE, component: SilenceFormComponent, data: { breadcrumbs: `${ActionLabels.CREATE} Silence` } }, { path: `${URLVerbs.CREATE}/:id`, component: SilenceFormComponent, data: { breadcrumbs: ActionLabels.CREATE } }, { path: `${URLVerbs.EDIT}/:id`, component: SilenceFormComponent, data: { breadcrumbs: ActionLabels.EDIT } }, { path: `${URLVerbs.RECREATE}/:id`, component: SilenceFormComponent, data: { breadcrumbs: ActionLabels.RECREATE } } ] } ] }, { path: 'upgrade', component: UpgradeComponent, data: { breadcrumbs: 'Cluster/Upgrade' } }, { path: 'perf_counters/:type/:id', component: PerformanceCounterComponent, data: { breadcrumbs: PerformanceCounterBreadcrumbsResolver } }, // Mgr modules { path: 'mgr-modules', data: { breadcrumbs: 'Cluster/Manager Modules' }, children: [ { path: '', component: MgrModuleListComponent }, { path: 'edit/:name', component: MgrModuleFormComponent, data: { breadcrumbs: StartCaseBreadcrumbsResolver } } ] }, // Pools { path: 'pool', data: { breadcrumbs: 'Pools' }, loadChildren: () => import('./ceph/pool/pool.module').then((m) => m.RoutedPoolModule) }, // Block { path: 'block', data: { breadcrumbs: true, text: 'Block', path: null }, loadChildren: () => import('./ceph/block/block.module').then((m) => m.RoutedBlockModule) }, // File Systems { path: 'cephfs', component: CephfsListComponent, canActivate: [FeatureTogglesGuardService], data: { breadcrumbs: 'File Systems' } }, // Object Gateway { path: 'rgw', canActivate: [FeatureTogglesGuardService, ModuleStatusGuardService], data: { moduleStatusGuardConfig: { uiApiPath: 'rgw', redirectTo: 'error', section: 'rgw', section_info: 'Object Gateway', header: 'The Object Gateway Service is not configured' }, breadcrumbs: true, text: 'Object Gateway', path: null }, loadChildren: () => import('./ceph/rgw/rgw.module').then((m) => m.RoutedRgwModule) }, // User/Role Management { path: 'user-management', data: { breadcrumbs: 'User management', path: null }, loadChildren: () => import('./core/auth/auth.module').then((m) => m.RoutedAuthModule) }, // User Profile { path: 'user-profile', data: { breadcrumbs: 'User profile', path: null }, children: [ { path: URLVerbs.EDIT, component: UserPasswordFormComponent, canActivate: [NoSsoGuardService], data: { breadcrumbs: ActionLabels.EDIT } } ] }, // NFS { path: 'nfs', canActivateChild: [FeatureTogglesGuardService, ModuleStatusGuardService], data: { moduleStatusGuardConfig: { uiApiPath: 'nfs-ganesha', redirectTo: 'error', section: 'nfs-ganesha', section_info: 'NFS GANESHA', header: 'NFS-Ganesha is not configured' }, breadcrumbs: 'NFS' }, children: [ { path: '', component: NfsListComponent }, { path: URLVerbs.CREATE, component: NfsFormComponent, data: { breadcrumbs: ActionLabels.CREATE } }, { path: `${URLVerbs.EDIT}/:cluster_id/:export_id`, component: NfsFormComponent, data: { breadcrumbs: ActionLabels.EDIT } } ] } ] }, { path: '', component: LoginLayoutComponent, children: [ { path: 'login', component: LoginComponent }, { path: 'login-change-password', component: LoginPasswordFormComponent, canActivate: [NoSsoGuardService] } ] }, { path: '', component: BlankLayoutComponent, children: [{ path: '**', redirectTo: '/error' }] } ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { useHash: true, preloadingStrategy: PreloadAllModules, relativeLinkResolution: 'legacy' }) ], exports: [RouterModule], providers: [StartCaseBreadcrumbsResolver, PerformanceCounterBreadcrumbsResolver] }) export class AppRoutingModule {}
14,900
33.413395
123
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/app.component.html
<router-outlet></router-outlet>
32
15.5
31
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/app.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { configureTestBed } from '~/testing/unit-test-helper'; import { AppComponent } from './app.component'; describe('AppComponent', () => { let component: AppComponent; let fixture: ComponentFixture<AppComponent>; configureTestBed({ declarations: [AppComponent], imports: [RouterTestingModule] }); beforeEach(() => { fixture = TestBed.createComponent(AppComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
681
25.230769
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/app.component.ts
import { Component } from '@angular/core'; import { NgbPopoverConfig, NgbTooltipConfig } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'cd-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { constructor(popoverConfig: NgbPopoverConfig, tooltipConfig: NgbTooltipConfig) { popoverConfig.autoClose = 'outside'; popoverConfig.container = 'body'; popoverConfig.placement = 'bottom'; tooltipConfig.container = 'body'; } }
516
26.210526
81
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/app.module.ts
import { APP_BASE_HREF } from '@angular/common'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { ErrorHandler, NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ToastrModule } from 'ngx-toastr'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { CephModule } from './ceph/ceph.module'; import { CoreModule } from './core/core.module'; import { ApiInterceptorService } from './shared/services/api-interceptor.service'; import { JsErrorHandler } from './shared/services/js-error-handler.service'; import { SharedModule } from './shared/shared.module'; @NgModule({ declarations: [AppComponent], imports: [ HttpClientModule, BrowserModule, BrowserAnimationsModule, ToastrModule.forRoot({ positionClass: 'toast-top-right', preventDuplicates: true, enableHtml: true }), AppRoutingModule, CoreModule, SharedModule, CephModule ], exports: [SharedModule], providers: [ { provide: ErrorHandler, useClass: JsErrorHandler }, { provide: HTTP_INTERCEPTORS, useClass: ApiInterceptorService, multi: true }, { provide: APP_BASE_HREF, useValue: '/' + (window.location.pathname.split('/', 1)[1] || '') } ], bootstrap: [AppComponent] }) export class AppModule {}
1,511
28.076923
82
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/ceph.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { CephfsModule } from './cephfs/cephfs.module'; import { ClusterModule } from './cluster/cluster.module'; import { DashboardModule } from './dashboard/dashboard.module'; import { NfsModule } from './nfs/nfs.module'; import { PerformanceCounterModule } from './performance-counter/performance-counter.module'; @NgModule({ imports: [ CommonModule, ClusterModule, DashboardModule, PerformanceCounterModule, CephfsModule, NfsModule, SharedModule ], declarations: [] }) export class CephModule {}
681
27.416667
92
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/block.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule, Routes } from '@angular/router'; import { TreeModule } from '@circlon/angular-tree-component'; import { NgbNavModule, NgbPopoverModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'; import { NgxPipeFunctionModule } from 'ngx-pipe-function'; import { ActionLabels, URLVerbs } from '~/app/shared/constants/app.constants'; import { FeatureTogglesGuardService } from '~/app/shared/services/feature-toggles-guard.service'; import { ModuleStatusGuardService } from '~/app/shared/services/module-status-guard.service'; import { SharedModule } from '~/app/shared/shared.module'; import { IscsiSettingComponent } from './iscsi-setting/iscsi-setting.component'; import { IscsiTabsComponent } from './iscsi-tabs/iscsi-tabs.component'; import { IscsiTargetDetailsComponent } from './iscsi-target-details/iscsi-target-details.component'; import { IscsiTargetDiscoveryModalComponent } from './iscsi-target-discovery-modal/iscsi-target-discovery-modal.component'; import { IscsiTargetFormComponent } from './iscsi-target-form/iscsi-target-form.component'; import { IscsiTargetImageSettingsModalComponent } from './iscsi-target-image-settings-modal/iscsi-target-image-settings-modal.component'; import { IscsiTargetIqnSettingsModalComponent } from './iscsi-target-iqn-settings-modal/iscsi-target-iqn-settings-modal.component'; import { IscsiTargetListComponent } from './iscsi-target-list/iscsi-target-list.component'; import { IscsiComponent } from './iscsi/iscsi.component'; import { MirroringModule } from './mirroring/mirroring.module'; import { OverviewComponent as RbdMirroringComponent } from './mirroring/overview/overview.component'; import { PoolEditModeModalComponent } from './mirroring/pool-edit-mode-modal/pool-edit-mode-modal.component'; import { RbdConfigurationFormComponent } from './rbd-configuration-form/rbd-configuration-form.component'; import { RbdConfigurationListComponent } from './rbd-configuration-list/rbd-configuration-list.component'; import { RbdDetailsComponent } from './rbd-details/rbd-details.component'; import { RbdFormComponent } from './rbd-form/rbd-form.component'; import { RbdListComponent } from './rbd-list/rbd-list.component'; import { RbdNamespaceFormModalComponent } from './rbd-namespace-form/rbd-namespace-form-modal.component'; import { RbdNamespaceListComponent } from './rbd-namespace-list/rbd-namespace-list.component'; import { RbdPerformanceComponent } from './rbd-performance/rbd-performance.component'; import { RbdSnapshotFormModalComponent } from './rbd-snapshot-form/rbd-snapshot-form-modal.component'; import { RbdSnapshotListComponent } from './rbd-snapshot-list/rbd-snapshot-list.component'; import { RbdTabsComponent } from './rbd-tabs/rbd-tabs.component'; import { RbdTrashListComponent } from './rbd-trash-list/rbd-trash-list.component'; import { RbdTrashMoveModalComponent } from './rbd-trash-move-modal/rbd-trash-move-modal.component'; import { RbdTrashPurgeModalComponent } from './rbd-trash-purge-modal/rbd-trash-purge-modal.component'; import { RbdTrashRestoreModalComponent } from './rbd-trash-restore-modal/rbd-trash-restore-modal.component'; @NgModule({ imports: [ CommonModule, MirroringModule, FormsModule, ReactiveFormsModule, NgbNavModule, NgbPopoverModule, NgbTooltipModule, NgxPipeFunctionModule, SharedModule, RouterModule, TreeModule ], declarations: [ RbdListComponent, IscsiComponent, IscsiSettingComponent, IscsiTabsComponent, IscsiTargetListComponent, RbdDetailsComponent, RbdFormComponent, RbdNamespaceFormModalComponent, RbdNamespaceListComponent, RbdSnapshotListComponent, RbdSnapshotFormModalComponent, RbdTrashListComponent, RbdTrashMoveModalComponent, RbdTrashRestoreModalComponent, RbdTrashPurgeModalComponent, IscsiTargetDetailsComponent, IscsiTargetFormComponent, IscsiTargetImageSettingsModalComponent, IscsiTargetIqnSettingsModalComponent, IscsiTargetDiscoveryModalComponent, RbdConfigurationListComponent, RbdConfigurationFormComponent, RbdTabsComponent, RbdPerformanceComponent ], exports: [RbdConfigurationListComponent, RbdConfigurationFormComponent] }) export class BlockModule {} /* The following breakdown is needed to allow importing block.module without the routes (e.g.: this module is imported by pool.module for RBD QoS components) */ const routes: Routes = [ { path: '', redirectTo: 'rbd', pathMatch: 'full' }, { path: 'rbd', canActivate: [FeatureTogglesGuardService, ModuleStatusGuardService], data: { moduleStatusGuardConfig: { uiApiPath: 'block/rbd', redirectTo: 'error', header: $localize`Block Pool is not configured`, button_name: $localize`Configure Default pool`, button_route: '/pool/create', component: 'Default Pool', uiConfig: true }, breadcrumbs: 'Images' }, children: [ { path: '', component: RbdListComponent }, { path: 'namespaces', component: RbdNamespaceListComponent, data: { breadcrumbs: 'Namespaces' } }, { path: 'trash', component: RbdTrashListComponent, data: { breadcrumbs: 'Trash' } }, { path: 'performance', component: RbdPerformanceComponent, data: { breadcrumbs: 'Overall Performance' } }, { path: URLVerbs.CREATE, component: RbdFormComponent, data: { breadcrumbs: ActionLabels.CREATE } }, { path: `${URLVerbs.EDIT}/:image_spec`, component: RbdFormComponent, data: { breadcrumbs: ActionLabels.EDIT } }, { path: `${URLVerbs.CLONE}/:image_spec/:snap`, component: RbdFormComponent, data: { breadcrumbs: ActionLabels.CLONE } }, { path: `${URLVerbs.COPY}/:image_spec`, component: RbdFormComponent, data: { breadcrumbs: ActionLabels.COPY } }, { path: `${URLVerbs.COPY}/:image_spec/:snap`, component: RbdFormComponent, data: { breadcrumbs: ActionLabels.COPY } } ] }, { path: 'mirroring', component: RbdMirroringComponent, canActivate: [FeatureTogglesGuardService, ModuleStatusGuardService], data: { moduleStatusGuardConfig: { uiApiPath: 'block/mirroring', redirectTo: 'error', header: $localize`Block Mirroring is not configured`, button_name: $localize`Configure Block Mirroring`, button_title: $localize`This will create \"rbd-mirror\" service and a replicated Block pool`, component: 'Block Mirroring', uiConfig: true }, breadcrumbs: 'Mirroring' }, children: [ { path: `${URLVerbs.EDIT}/:pool_name`, component: PoolEditModeModalComponent, outlet: 'modal' } ] }, // iSCSI { path: 'iscsi', canActivate: [FeatureTogglesGuardService], data: { breadcrumbs: 'iSCSI' }, children: [ { path: '', redirectTo: 'overview', pathMatch: 'full' }, { path: 'overview', component: IscsiComponent, data: { breadcrumbs: 'Overview' } }, { path: 'targets', data: { breadcrumbs: 'Targets' }, children: [ { path: '', component: IscsiTargetListComponent }, { path: URLVerbs.CREATE, component: IscsiTargetFormComponent, data: { breadcrumbs: ActionLabels.CREATE } }, { path: `${URLVerbs.EDIT}/:target_iqn`, component: IscsiTargetFormComponent, data: { breadcrumbs: ActionLabels.EDIT } } ] } ] } ]; @NgModule({ imports: [BlockModule, RouterModule.forChild(routes)] }) export class RoutedBlockModule {}
7,991
37.423077
137
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-setting/iscsi-setting.component.html
<div class="form-group" [formGroup]="settingsForm"> <label class="col-form-label" for="{{ setting }}">{{ setting }}</label> <select id="{{ setting }}" name="{{ setting }}" *ngIf="limits['type'] === 'enum'" class="form-control" [formControlName]="setting"> <option [ngValue]="null"></option> <option *ngFor="let opt of limits['values']" [ngValue]="opt">{{ opt }}</option> </select> <span *ngIf="limits['type'] !== 'enum'"> <input type="number" *ngIf="limits['type'] === 'int'" class="form-control" [formControlName]="setting"> <input type="text" *ngIf="limits['type'] === 'str'" class="form-control" [formControlName]="setting"> <ng-container *ngIf="limits['type'] === 'bool'"> <br> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" [id]="setting + 'True'" [value]="true" [formControlName]="setting" class="custom-control-input"> <label class="custom-control-label" [for]="setting + 'True'">Yes</label> </div> <div class="custom-control custom-radio custom-control-inline"> <input type="radio" [id]="setting + 'False'" [value]="false" class="custom-control-input" [formControlName]="setting"> <label class="custom-control-label" [for]="setting + 'False'">No</label> </div> </ng-container> </span> <span class="invalid-feedback" *ngIf="settingsForm.showError(setting, formDir, 'min')"> <ng-container i18n>Must be greater than or equal to {{ limits['min'] }}.</ng-container> </span> <span class="invalid-feedback" *ngIf="settingsForm.showError(setting, formDir, 'max')"> <ng-container i18n>Must be less than or equal to {{ limits['max'] }}.</ng-container> </span> </div>
2,016
33.775862
91
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-setting/iscsi-setting.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormControl, NgForm, ReactiveFormsModule } from '@angular/forms'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { IscsiSettingComponent } from './iscsi-setting.component'; describe('IscsiSettingComponent', () => { let component: IscsiSettingComponent; let fixture: ComponentFixture<IscsiSettingComponent>; configureTestBed({ imports: [SharedModule, ReactiveFormsModule], declarations: [IscsiSettingComponent] }); beforeEach(() => { fixture = TestBed.createComponent(IscsiSettingComponent); component = fixture.componentInstance; component.settingsForm = new CdFormGroup({ max_data_area_mb: new FormControl() }); component.formDir = new NgForm([], []); component.setting = 'max_data_area_mb'; component.limits = { type: 'int', min: 1, max: 2048 }; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,160
29.552632
74
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-setting/iscsi-setting.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { NgForm, ValidatorFn, Validators } from '@angular/forms'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; @Component({ selector: 'cd-iscsi-setting', templateUrl: './iscsi-setting.component.html', styleUrls: ['./iscsi-setting.component.scss'] }) export class IscsiSettingComponent implements OnInit { @Input() settingsForm: CdFormGroup; @Input() formDir: NgForm; @Input() setting: string; @Input() limits: object; ngOnInit() { const validators: ValidatorFn[] = []; if ('min' in this.limits) { validators.push(Validators.min(this.limits['min'])); } if ('max' in this.limits) { validators.push(Validators.max(this.limits['max'])); } this.settingsForm.get(this.setting).setValidators(validators); } }
844
25.40625
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-tabs/iscsi-tabs.component.html
<ul class="nav nav-tabs"> <li class="nav-item"> <a class="nav-link" routerLink="/block/iscsi/overview" routerLinkActive="active" ariaCurrentWhenActive="page" i18n>Overview</a> </li> <li class="nav-item"> <a class="nav-link" routerLink="/block/iscsi/targets" routerLinkActive="active" ariaCurrentWhenActive="page" i18n>Targets</a> </li> </ul>
414
23.411765
41
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-tabs/iscsi-tabs.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { IscsiTabsComponent } from './iscsi-tabs.component'; describe('IscsiTabsComponent', () => { let component: IscsiTabsComponent; let fixture: ComponentFixture<IscsiTabsComponent>; configureTestBed({ imports: [SharedModule, RouterTestingModule, NgbNavModule], declarations: [IscsiTabsComponent] }); beforeEach(() => { fixture = TestBed.createComponent(IscsiTabsComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
871
29.068966
66
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-tabs/iscsi-tabs.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'cd-iscsi-tabs', templateUrl: './iscsi-tabs.component.html', styleUrls: ['./iscsi-tabs.component.scss'] }) export class IscsiTabsComponent {}
215
23
45
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-details/iscsi-target-details.component.html
<div class="row"> <div class="col-6"> <legend i18n>iSCSI Topology</legend> <tree-root #tree [nodes]="nodes" [options]="treeOptions" (updateData)="onUpdateData()"> <ng-template #treeNodeTemplate let-node let-index="index"> <i [class]="node.data.cdIcon"></i> <span>{{ node.data.name }}</span> &nbsp; <span class="badge" [ngClass]="{'badge-success': ['logged_in'].includes(node.data.status), 'badge-danger': ['logged_out'].includes(node.data.status)}"> {{ node.data.status }} </span> </ng-template> </tree-root> </div> <div class="col-6 metadata" *ngIf="data"> <legend>{{ title }}</legend> <cd-table #detailTable [data]="data" columnMode="flex" [columns]="columns" [limit]="0"> </cd-table> </div> </div> <ng-template #highlightTpl let-row="row" let-value="value"> <span *ngIf="row.default === undefined || row.default === row.current">{{ value }}</span> <strong *ngIf="row.default !== undefined && row.default !== row.current">{{ value }}</strong> </ng-template>
1,248
28.738095
145
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-details/iscsi-target-details.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { TreeModel, TreeModule } from '@circlon/angular-tree-component'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { IscsiTargetDetailsComponent } from './iscsi-target-details.component'; describe('IscsiTargetDetailsComponent', () => { let component: IscsiTargetDetailsComponent; let fixture: ComponentFixture<IscsiTargetDetailsComponent>; configureTestBed({ declarations: [IscsiTargetDetailsComponent], imports: [BrowserAnimationsModule, TreeModule, SharedModule] }); beforeEach(() => { fixture = TestBed.createComponent(IscsiTargetDetailsComponent); component = fixture.componentInstance; component.settings = { config: { minimum_gateways: 2 }, disk_default_controls: { 'backstore:1': { hw_max_sectors: 1024, max_data_area_mb: 8 }, 'backstore:2': { hw_max_sectors: 1024, max_data_area_mb: 8 } }, target_default_controls: { cmdsn_depth: 128, dataout_timeout: 20 }, backstores: ['backstore:1', 'backstore:2'], default_backstore: 'backstore:1' }; component.selection = undefined; component.selection = { target_iqn: 'iqn.2003-01.com.redhat.iscsi-gw:iscsi-igw', portals: [{ host: 'node1', ip: '192.168.100.201' }], disks: [ { pool: 'rbd', image: 'disk_1', backstore: 'backstore:1', controls: { hw_max_sectors: 1 } } ], clients: [ { client_iqn: 'iqn.1994-05.com.redhat:rh7-client', luns: [{ pool: 'rbd', image: 'disk_1' }], auth: { user: 'myiscsiusername' }, info: { alias: 'myhost', ip_address: ['192.168.200.1'], state: { LOGGED_IN: ['node1'] } } } ], groups: [], target_controls: { dataout_timeout: 2 } }; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should empty data and generateTree when ngOnChanges is called', () => { const tempData = [{ current: 'baz', default: 'bar', displayName: 'foo' }]; component.data = tempData; fixture.detectChanges(); expect(component.data).toEqual(tempData); expect(component.metadata).toEqual({}); expect(component.nodes).toEqual([]); component.ngOnChanges(); expect(component.data).toBeUndefined(); expect(component.metadata).toEqual({ 'client_iqn.1994-05.com.redhat:rh7-client': { user: 'myiscsiusername', alias: 'myhost', ip_address: ['192.168.200.1'], logged_in: ['node1'] }, disk_rbd_disk_1: { backstore: 'backstore:1', controls: { hw_max_sectors: 1 } }, root: { dataout_timeout: 2 } }); expect(component.nodes).toEqual([ { cdIcon: 'fa fa-lg fa fa-bullseye', cdId: 'root', children: [ { cdIcon: 'fa fa-lg fa fa-hdd-o', children: [ { cdIcon: 'fa fa-hdd-o', cdId: 'disk_rbd_disk_1', name: 'rbd/disk_1' } ], isExpanded: true, name: 'Disks' }, { cdIcon: 'fa fa-lg fa fa-server', children: [ { cdIcon: 'fa fa-server', name: 'node1:192.168.100.201' } ], isExpanded: true, name: 'Portals' }, { cdIcon: 'fa fa-lg fa fa-user', children: [ { cdIcon: 'fa fa-user', cdId: 'client_iqn.1994-05.com.redhat:rh7-client', children: [ { cdIcon: 'fa fa-hdd-o', cdId: 'disk_rbd_disk_1', name: 'rbd/disk_1' } ], name: 'iqn.1994-05.com.redhat:rh7-client', status: 'logged_in' } ], isExpanded: true, name: 'Initiators' }, { cdIcon: 'fa fa-lg fa fa-users', children: [], isExpanded: true, name: 'Groups' } ], isExpanded: true, name: 'iqn.2003-01.com.redhat.iscsi-gw:iscsi-igw' } ]); }); describe('should update data when onNodeSelected is called', () => { let tree: TreeModel; beforeEach(() => { component.ngOnChanges(); tree = component.tree.treeModel; fixture.detectChanges(); }); it('with target selected', () => { const node = tree.getNodeBy({ data: { cdId: 'root' } }); component.onNodeSelected(tree, node); expect(component.data).toEqual([ { current: 128, default: 128, displayName: 'cmdsn_depth' }, { current: 2, default: 20, displayName: 'dataout_timeout' } ]); }); it('with disk selected', () => { const node = tree.getNodeBy({ data: { cdId: 'disk_rbd_disk_1' } }); component.onNodeSelected(tree, node); expect(component.data).toEqual([ { current: 1, default: 1024, displayName: 'hw_max_sectors' }, { current: 8, default: 8, displayName: 'max_data_area_mb' }, { current: 'backstore:1', default: 'backstore:1', displayName: 'backstore' } ]); }); it('with initiator selected', () => { const node = tree.getNodeBy({ data: { cdId: 'client_iqn.1994-05.com.redhat:rh7-client' } }); component.onNodeSelected(tree, node); expect(component.data).toEqual([ { current: 'myiscsiusername', default: undefined, displayName: 'user' }, { current: 'myhost', default: undefined, displayName: 'alias' }, { current: ['192.168.200.1'], default: undefined, displayName: 'ip_address' }, { current: ['node1'], default: undefined, displayName: 'logged_in' } ]); }); it('with any other selected', () => { const node = tree.getNodeBy({ data: { name: 'Disks' } }); component.onNodeSelected(tree, node); expect(component.data).toBeUndefined(); }); }); });
6,432
29.927885
98
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-details/iscsi-target-details.component.ts
import { Component, Input, OnChanges, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { ITreeOptions, TreeComponent, TreeModel, TreeNode, TREE_ACTIONS } from '@circlon/angular-tree-component'; import _ from 'lodash'; import { TableComponent } from '~/app/shared/datatable/table/table.component'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { BooleanTextPipe } from '~/app/shared/pipes/boolean-text.pipe'; import { IscsiBackstorePipe } from '~/app/shared/pipes/iscsi-backstore.pipe'; @Component({ selector: 'cd-iscsi-target-details', templateUrl: './iscsi-target-details.component.html', styleUrls: ['./iscsi-target-details.component.scss'] }) export class IscsiTargetDetailsComponent implements OnChanges, OnInit { @Input() selection: any; @Input() settings: any; @Input() cephIscsiConfigVersion: number; @ViewChild('highlightTpl', { static: true }) highlightTpl: TemplateRef<any>; private detailTable: TableComponent; @ViewChild('detailTable') set content(content: TableComponent) { this.detailTable = content; if (content) { content.updateColumns(); } } @ViewChild('tree') tree: TreeComponent; icons = Icons; columns: CdTableColumn[]; data: any; metadata: any = {}; selectedItem: any; title: string; nodes: any[] = []; treeOptions: ITreeOptions = { useVirtualScroll: true, actionMapping: { mouse: { click: this.onNodeSelected.bind(this) } } }; constructor( private iscsiBackstorePipe: IscsiBackstorePipe, private booleanTextPipe: BooleanTextPipe ) {} ngOnInit() { this.columns = [ { prop: 'displayName', name: $localize`Name`, flexGrow: 1, cellTemplate: this.highlightTpl }, { prop: 'current', name: $localize`Current`, flexGrow: 1, cellTemplate: this.highlightTpl }, { prop: 'default', name: $localize`Default`, flexGrow: 1, cellTemplate: this.highlightTpl } ]; } ngOnChanges() { if (this.selection) { this.selectedItem = this.selection; this.generateTree(); } this.data = undefined; } private generateTree() { const target_meta = _.cloneDeep(this.selectedItem.target_controls); // Target level authentication was introduced in ceph-iscsi config v11 if (this.cephIscsiConfigVersion > 10) { _.extend(target_meta, _.cloneDeep(this.selectedItem.auth)); } this.metadata = { root: target_meta }; const cssClasses = { target: { expanded: _.join( this.selectedItem.cdExecuting ? [Icons.large, Icons.spinner, Icons.spin] : [Icons.large, Icons.bullseye], ' ' ) }, initiators: { expanded: _.join([Icons.large, Icons.user], ' '), leaf: _.join([Icons.user], ' ') }, groups: { expanded: _.join([Icons.large, Icons.users], ' '), leaf: _.join([Icons.users], ' ') }, disks: { expanded: _.join([Icons.large, Icons.disk], ' '), leaf: _.join([Icons.disk], ' ') }, portals: { expanded: _.join([Icons.large, Icons.server], ' '), leaf: _.join([Icons.server], ' ') } }; const disks: any[] = []; _.forEach(this.selectedItem.disks, (disk) => { const cdId = 'disk_' + disk.pool + '_' + disk.image; this.metadata[cdId] = { controls: disk.controls, backstore: disk.backstore }; ['wwn', 'lun'].forEach((k) => { if (k in disk) { this.metadata[cdId][k] = disk[k]; } }); disks.push({ name: `${disk.pool}/${disk.image}`, cdId: cdId, cdIcon: cssClasses.disks.leaf }); }); const portals: any[] = []; _.forEach(this.selectedItem.portals, (portal) => { portals.push({ name: `${portal.host}:${portal.ip}`, cdIcon: cssClasses.portals.leaf }); }); const clients: any[] = []; _.forEach(this.selectedItem.clients, (client) => { const client_metadata = _.cloneDeep(client.auth); if (client.info) { _.extend(client_metadata, client.info); delete client_metadata['state']; _.forEach(Object.keys(client.info.state), (state) => { client_metadata[state.toLowerCase()] = client.info.state[state]; }); } this.metadata['client_' + client.client_iqn] = client_metadata; const luns: any[] = []; client.luns.forEach((lun: Record<string, any>) => { luns.push({ name: `${lun.pool}/${lun.image}`, cdId: 'disk_' + lun.pool + '_' + lun.image, cdIcon: cssClasses.disks.leaf }); }); let status = ''; if (client.info) { status = Object.keys(client.info.state).includes('LOGGED_IN') ? 'logged_in' : 'logged_out'; } clients.push({ name: client.client_iqn, status: status, cdId: 'client_' + client.client_iqn, children: luns, cdIcon: cssClasses.initiators.leaf }); }); const groups: any[] = []; _.forEach(this.selectedItem.groups, (group) => { const luns: any[] = []; group.disks.forEach((disk: Record<string, any>) => { luns.push({ name: `${disk.pool}/${disk.image}`, cdId: 'disk_' + disk.pool + '_' + disk.image, cdIcon: cssClasses.disks.leaf }); }); const initiators: any[] = []; group.members.forEach((member: string) => { initiators.push({ name: member, cdId: 'client_' + member }); }); groups.push({ name: group.group_id, cdIcon: cssClasses.groups.leaf, children: [ { name: 'Disks', children: luns, cdIcon: cssClasses.disks.expanded }, { name: 'Initiators', children: initiators, cdIcon: cssClasses.initiators.expanded } ] }); }); this.nodes = [ { name: this.selectedItem.target_iqn, cdId: 'root', isExpanded: true, cdIcon: cssClasses.target.expanded, children: [ { name: 'Disks', isExpanded: true, children: disks, cdIcon: cssClasses.disks.expanded }, { name: 'Portals', isExpanded: true, children: portals, cdIcon: cssClasses.portals.expanded }, { name: 'Initiators', isExpanded: true, children: clients, cdIcon: cssClasses.initiators.expanded }, { name: 'Groups', isExpanded: true, children: groups, cdIcon: cssClasses.groups.expanded } ] } ]; } private format(value: any) { if (typeof value === 'boolean') { return this.booleanTextPipe.transform(value); } return value; } onNodeSelected(tree: TreeModel, node: TreeNode) { TREE_ACTIONS.ACTIVATE(tree, node, true); if (node.data.cdId) { this.title = node.data.name; const tempData = this.metadata[node.data.cdId] || {}; if (node.data.cdId === 'root') { this.detailTable?.toggleColumn({ prop: 'default', isHidden: true }); this.data = _.map(this.settings.target_default_controls, (value, key) => { value = this.format(value); return { displayName: key, default: value, current: !_.isUndefined(tempData[key]) ? this.format(tempData[key]) : value }; }); // Target level authentication was introduced in ceph-iscsi config v11 if (this.cephIscsiConfigVersion > 10) { ['user', 'password', 'mutual_user', 'mutual_password'].forEach((key) => { this.data.push({ displayName: key, default: null, current: tempData[key] }); }); } } else if (node.data.cdId.toString().startsWith('disk_')) { this.detailTable?.toggleColumn({ prop: 'default', isHidden: true }); this.data = _.map(this.settings.disk_default_controls[tempData.backstore], (value, key) => { value = this.format(value); return { displayName: key, default: value, current: !_.isUndefined(tempData.controls[key]) ? this.format(tempData.controls[key]) : value }; }); this.data.push({ displayName: 'backstore', default: this.iscsiBackstorePipe.transform(this.settings.default_backstore), current: this.iscsiBackstorePipe.transform(tempData.backstore) }); ['wwn', 'lun'].forEach((k) => { if (k in tempData) { this.data.push({ displayName: k, default: undefined, current: tempData[k] }); } }); } else { this.detailTable?.toggleColumn({ prop: 'default', isHidden: false }); this.data = _.map(tempData, (value, key) => { return { displayName: key, default: undefined, current: this.format(value) }; }); } } else { this.data = undefined; } this.detailTable?.updateColumns(); } onUpdateData() { this.tree.treeModel.expandAll(); } }
9,658
26.835735
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-discovery-modal/iscsi-target-discovery-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container class="modal-title" i18n>Discovery Authentication</ng-container> <ng-container class="modal-content"> <form name="discoveryForm" #formDir="ngForm" [formGroup]="discoveryForm" novalidate> <div class="modal-body"> <!-- User --> <div class="form-group row"> <label class="cd-col-form-label" for="user" i18n>User</label> <div class="cd-col-form-input"> <input id="user" class="form-control" formControlName="user" type="text" autocomplete="off"> <span class="invalid-feedback" *ngIf="discoveryForm.showError('user', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="discoveryForm.showError('user', formDir, 'pattern')" i18n>User names must have a length of 8 to 64 characters and can contain alphanumeric characters, '.', '@', '-', '_' or ':'.</span> </div> </div> <!-- Password --> <div class="form-group row"> <label class="cd-col-form-label" for="password" i18n>Password</label> <div class="cd-col-form-input"> <div class="input-group"> <input id="password" class="form-control" formControlName="password" type="password" autocomplete="new-password"> <button type="button" class="btn btn-light" cdPasswordButton="password"> </button> <cd-copy-2-clipboard-button source="password"> </cd-copy-2-clipboard-button> </div> <span class="invalid-feedback" *ngIf="discoveryForm.showError('password', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="discoveryForm.showError('password', formDir, 'pattern')" i18n>Passwords must have a length of 12 to 16 characters and can contain alphanumeric characters, '@', '-', '_' or '/'.</span> </div> </div> <!-- mutual_user --> <div class="form-group row"> <label class="cd-col-form-label" for="mutual_user"> <ng-container i18n>Mutual User</ng-container> </label> <div class="cd-col-form-input"> <input id="mutual_user" class="form-control" formControlName="mutual_user" type="text" autocomplete="off"> <span class="invalid-feedback" *ngIf="discoveryForm.showError('mutual_user', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="discoveryForm.showError('mutual_user', formDir, 'pattern')" i18n>User names must have a length of 8 to 64 characters and can contain alphanumeric characters, '.', '@', '-', '_' or ':'.</span> </div> </div> <!-- mutual_password --> <div class="form-group row"> <label class="cd-col-form-label" for="mutual_password" i18n>Mutual Password</label> <div class="cd-col-form-input"> <div class="input-group"> <input id="mutual_password" class="form-control" formControlName="mutual_password" type="password" autocomplete="new-password"> <button type="button" class="btn btn-light" cdPasswordButton="mutual_password"> </button> <cd-copy-2-clipboard-button source="mutual_password"> </cd-copy-2-clipboard-button> </div> <span class="invalid-feedback" *ngIf="discoveryForm.showError('mutual_password', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="discoveryForm.showError('mutual_password', formDir, 'pattern')" i18n>Passwords must have a length of 12 to 16 characters and can contain alphanumeric characters, '@', '-', '_' or '/'.</span> </div> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="submitAction()" [form]="discoveryForm" [showSubmit]="hasPermission" [submitText]="actionLabels.SUBMIT"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
5,101
38.550388
90
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-discovery-modal/iscsi-target-discovery-modal.component.spec.ts
import { HttpClientTestingModule, HttpTestingController, TestRequest } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { Permission } from '~/app/shared/models/permissions'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FormHelper, IscsiHelper } from '~/testing/unit-test-helper'; import { IscsiTargetDiscoveryModalComponent } from './iscsi-target-discovery-modal.component'; describe('IscsiTargetDiscoveryModalComponent', () => { let component: IscsiTargetDiscoveryModalComponent; let fixture: ComponentFixture<IscsiTargetDiscoveryModalComponent>; let httpTesting: HttpTestingController; let req: TestRequest; const elem = (css: string) => fixture.debugElement.query(By.css(css)); const elemDisabled = (css: string) => elem(css).nativeElement.disabled; configureTestBed({ declarations: [IscsiTargetDiscoveryModalComponent], imports: [ HttpClientTestingModule, ReactiveFormsModule, SharedModule, ToastrModule.forRoot(), RouterTestingModule ], providers: [NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(IscsiTargetDiscoveryModalComponent); component = fixture.componentInstance; httpTesting = TestBed.inject(HttpTestingController); }); describe('with update permissions', () => { beforeEach(() => { component.permission = new Permission(['update']); fixture.detectChanges(); req = httpTesting.expectOne('api/iscsi/discoveryauth'); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should create form', () => { expect(component.discoveryForm.value).toEqual({ user: '', password: '', mutual_user: '', mutual_password: '' }); }); it('should patch form', () => { req.flush({ user: 'foo', password: 'bar', mutual_user: 'mutual_foo', mutual_password: 'mutual_bar' }); expect(component.discoveryForm.value).toEqual({ user: 'foo', password: 'bar', mutual_user: 'mutual_foo', mutual_password: 'mutual_bar' }); }); it('should submit new values', () => { component.discoveryForm.patchValue({ user: 'new_user', password: 'new_pass', mutual_user: 'mutual_new_user', mutual_password: 'mutual_new_pass' }); component.submitAction(); const submit_req = httpTesting.expectOne('api/iscsi/discoveryauth'); expect(submit_req.request.method).toBe('PUT'); expect(submit_req.request.body).toEqual({ user: 'new_user', password: 'new_pass', mutual_user: 'mutual_new_user', mutual_password: 'mutual_new_pass' }); }); it('should enable form if user has update permission', () => { expect(elemDisabled('input#user')).toBeFalsy(); expect(elemDisabled('input#password')).toBeFalsy(); expect(elemDisabled('input#mutual_user')).toBeFalsy(); expect(elemDisabled('input#mutual_password')).toBeFalsy(); expect(elem('cd-submit-button')).toBeDefined(); }); }); it('should disabled form if user does not have update permission', () => { component.permission = new Permission(['read', 'create', 'delete']); fixture.detectChanges(); req = httpTesting.expectOne('api/iscsi/discoveryauth'); expect(elemDisabled('input#user')).toBeTruthy(); expect(elemDisabled('input#password')).toBeTruthy(); expect(elemDisabled('input#mutual_user')).toBeTruthy(); expect(elemDisabled('input#mutual_password')).toBeTruthy(); expect(elem('cd-submit-button')).toBeNull(); }); it('should validate authentication', () => { component.permission = new Permission(['read', 'create', 'update', 'delete']); fixture.detectChanges(); const control = component.discoveryForm; const formHelper = new FormHelper(control); formHelper.expectValid(control); IscsiHelper.validateUser(formHelper, 'user'); IscsiHelper.validatePassword(formHelper, 'password'); IscsiHelper.validateUser(formHelper, 'mutual_user'); IscsiHelper.validatePassword(formHelper, 'mutual_password'); }); });
4,545
32.925373
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-discovery-modal/iscsi-target-discovery-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { FormControl, Validators } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { IscsiService } from '~/app/shared/api/iscsi.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { NotificationType } from '~/app/shared/enum/notification-type.enum'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { CdValidators } from '~/app/shared/forms/cd-validators'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { NotificationService } from '~/app/shared/services/notification.service'; @Component({ selector: 'cd-iscsi-target-discovery-modal', templateUrl: './iscsi-target-discovery-modal.component.html', styleUrls: ['./iscsi-target-discovery-modal.component.scss'] }) export class IscsiTargetDiscoveryModalComponent implements OnInit { discoveryForm: CdFormGroup; permission: Permission; hasPermission: boolean; USER_REGEX = /^[\w\.:@_-]{8,64}$/; PASSWORD_REGEX = /^[\w@\-_\/]{12,16}$/; constructor( private authStorageService: AuthStorageService, public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private iscsiService: IscsiService, private notificationService: NotificationService ) { this.permission = this.authStorageService.getPermissions().iscsi; } ngOnInit() { this.hasPermission = this.permission.update; this.createForm(); this.iscsiService.getDiscovery().subscribe((auth) => { this.discoveryForm.patchValue(auth); }); } createForm() { this.discoveryForm = new CdFormGroup({ user: new FormControl({ value: '', disabled: !this.hasPermission }), password: new FormControl({ value: '', disabled: !this.hasPermission }), mutual_user: new FormControl({ value: '', disabled: !this.hasPermission }), mutual_password: new FormControl({ value: '', disabled: !this.hasPermission }) }); CdValidators.validateIf( this.discoveryForm.get('user'), () => this.discoveryForm.getValue('password') || this.discoveryForm.getValue('mutual_user') || this.discoveryForm.getValue('mutual_password'), [Validators.required], [Validators.pattern(this.USER_REGEX)], [ this.discoveryForm.get('password'), this.discoveryForm.get('mutual_user'), this.discoveryForm.get('mutual_password') ] ); CdValidators.validateIf( this.discoveryForm.get('password'), () => this.discoveryForm.getValue('user') || this.discoveryForm.getValue('mutual_user') || this.discoveryForm.getValue('mutual_password'), [Validators.required], [Validators.pattern(this.PASSWORD_REGEX)], [ this.discoveryForm.get('user'), this.discoveryForm.get('mutual_user'), this.discoveryForm.get('mutual_password') ] ); CdValidators.validateIf( this.discoveryForm.get('mutual_user'), () => this.discoveryForm.getValue('mutual_password'), [Validators.required], [Validators.pattern(this.USER_REGEX)], [ this.discoveryForm.get('user'), this.discoveryForm.get('password'), this.discoveryForm.get('mutual_password') ] ); CdValidators.validateIf( this.discoveryForm.get('mutual_password'), () => this.discoveryForm.getValue('mutual_user'), [Validators.required], [Validators.pattern(this.PASSWORD_REGEX)], [ this.discoveryForm.get('user'), this.discoveryForm.get('password'), this.discoveryForm.get('mutual_user') ] ); } submitAction() { this.iscsiService.updateDiscovery(this.discoveryForm.value).subscribe( () => { this.notificationService.show( NotificationType.success, $localize`Updated discovery authentication` ); this.activeModal.close(); }, () => { this.discoveryForm.setErrors({ cdSubmitButton: true }); } ); } }
4,161
32.564516
84
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-form/iscsi-target-form.component.html
<div class="cd-col-form" *cdFormLoading="loading"> <form name="targetForm" #formDir="ngForm" [formGroup]="targetForm" novalidate> <div class="card"> <div i18n="form title" class="card-header">{{ action | titlecase }} {{ resource | upperFirst }}</div> <div class="card-body"> <!-- Target IQN --> <div class="form-group row"> <label class="cd-col-form-label required" for="target_iqn" i18n>Target IQN</label> <div class="cd-col-form-input"> <div class="input-group"> <input class="form-control" type="text" id="target_iqn" name="target_iqn" formControlName="target_iqn" cdTrim /> <button class="btn btn-light" id="ecp-info-button" type="button" (click)="targetSettingsModal()"> <i [ngClass]="[icons.deepCheck]" aria-hidden="true"></i> </button> </div> <span class="invalid-feedback" *ngIf="targetForm.showError('target_iqn', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="targetForm.showError('target_iqn', formDir, 'pattern')" i18n>IQN has wrong pattern.</span> <span class="invalid-feedback" *ngIf="targetForm.showError('target_iqn', formDir, 'iqn')"> <ng-container i18n>An IQN has the following notation 'iqn.$year-$month.$reversedAddress:$definedName'</ng-container> <br> <ng-container i18n>For example: iqn.2016-06.org.dashboard:storage:disk.sn-a8675309</ng-container> <br> <a target="_blank" href="https://en.wikipedia.org/wiki/ISCSI#Addressing" i18n>More information</a> </span> <span class="form-text text-muted" *ngIf="hasAdvancedSettings(targetForm.getValue('target_controls'))" i18n>This target has modified advanced settings.</span> <hr /> </div> </div> <!-- Portals --> <div class="form-group row"> <label class="cd-col-form-label required" for="portals" i18n>Portals</label> <div class="cd-col-form-input"> <ng-container *ngFor="let portal of portals.value; let i = index"> <div class="input-group cd-mb"> <input class="cd-form-control" type="text" [value]="portal" disabled /> <button class="btn btn-light" type="button" (click)="removePortal(i, portal)"> <i [ngClass]="[icons.destroy]" aria-hidden="true"></i> </button> </div> </ng-container> <div class="row"> <div class="col-md-12"> <cd-select [data]="portals.value" [options]="portalsSelections" [messages]="messages.portals" (selection)="onPortalSelection($event)" elemClass="btn btn-light float-end"> <i [ngClass]="[icons.add]"></i> <ng-container i18n>Add portal</ng-container> </cd-select> </div> </div> <input class="form-control" type="hidden" id="portals" name="portals" formControlName="portals" /> <span class="invalid-feedback" *ngIf="targetForm.showError('portals', formDir, 'minGateways')" i18n>At least {{ minimum_gateways }} gateways are required.</span> <hr /> </div> </div> <!-- Images --> <div class="form-group row"> <label class="cd-col-form-label" for="disks" i18n>Images</label> <div class="cd-col-form-input"> <ng-container *ngFor="let image of targetForm.getValue('disks'); let i = index"> <div class="input-group cd-mb"> <input class="cd-form-control" type="text" [value]="image" disabled /> <div class="input-group-text" *ngIf="api_version >= 1">lun: {{ imagesSettings[image]['lun'] }}</div> <button class="btn btn-light" type="button" (click)="imageSettingsModal(image)"> <i [ngClass]="[icons.deepCheck]" aria-hidden="true"></i> </button> <button class="btn btn-light" type="button" (click)="removeImage(i, image)"> <i [ngClass]="[icons.destroy]" aria-hidden="true"></i> </button> </div> <span class="form-text text-muted"> <ng-container *ngIf="backstores.length > 1" i18n>Backstore: {{ imagesSettings[image].backstore | iscsiBackstore }}.&nbsp;</ng-container> <ng-container *ngIf="hasAdvancedSettings(imagesSettings[image][imagesSettings[image].backstore])" i18n>This image has modified settings.</ng-container> </span> </ng-container> <input class="form-control" type="hidden" id="disks" name="disks" formControlName="disks" /> <span class="invalid-feedback" *ngIf="targetForm.showError('disks', formDir, 'dupLunId')" i18n>Duplicated LUN numbers.</span> <span class="invalid-feedback" *ngIf="targetForm.showError('disks', formDir, 'dupWwn')" i18n>Duplicated WWN.</span> <div class="row"> <div class="col-md-12"> <cd-select [data]="disks.value" [options]="imagesSelections" [messages]="messages.images" (selection)="onImageSelection($event)" elemClass="btn btn-light float-end"> <i [ngClass]="[icons.add]"></i> <ng-container i18n>Add image</ng-container> </cd-select> </div> </div> <hr /> </div> </div> <!-- acl_enabled --> <div class="form-group row"> <div class="cd-col-form-offset"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" formControlName="acl_enabled" name="acl_enabled" id="acl_enabled"> <label for="acl_enabled" class="custom-control-label" i18n>ACL authentication</label> </div> <hr /> </div> </div> <!-- Target level authentication was introduced in ceph-iscsi config v11 --> <div formGroupName="auth" *ngIf="cephIscsiConfigVersion > 10 && !targetForm.getValue('acl_enabled')"> <!-- Target user --> <div class="form-group row"> <label class="cd-col-form-label" for="target_user"> <ng-container i18n>User</ng-container> </label> <div class="cd-col-form-input"> <input class="form-control" type="text" autocomplete="off" id="target_user" name="target_user" formControlName="user" /> <span class="invalid-feedback" *ngIf="targetForm.showError('user', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="targetForm.showError('user', formDir, 'pattern')" i18n>User names must have a length of 8 to 64 characters and can contain alphanumeric characters, '.', '@', '-', '_' or ':'.</span> </div> </div> <!-- Target password --> <div class="form-group row"> <label class="cd-col-form-label" for="target_password"> <ng-container i18n>Password</ng-container> </label> <div class="cd-col-form-input"> <div class="input-group"> <input class="form-control" type="password" autocomplete="new-password" id="target_password" name="target_password" formControlName="password" /> <button type="button" class="btn btn-light" cdPasswordButton="target_password"> </button> <cd-copy-2-clipboard-button source="target_password"> </cd-copy-2-clipboard-button> </div> <span class="invalid-feedback" *ngIf="targetForm.showError('password', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="targetForm.showError('password', formDir, 'pattern')" i18n>Passwords must have a length of 12 to 16 characters and can contain alphanumeric characters, '@', '-', '_' or '/'.</span> </div> </div> <!-- Target mutual_user --> <div class="form-group row"> <label class="cd-col-form-label" for="target_mutual_user"> <ng-container i18n>Mutual User</ng-container> </label> <div class="cd-col-form-input"> <input class="form-control" type="text" autocomplete="off" id="target_mutual_user" name="target_mutual_user" formControlName="mutual_user" /> <span class="invalid-feedback" *ngIf="targetForm.showError('mutual_user', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="targetForm.showError('mutual_user', formDir, 'pattern')" i18n>User names must have a length of 8 to 64 characters and can contain alphanumeric characters, '.', '@', '-', '_' or ':'.</span> </div> </div> <!-- Target mutual_password --> <div class="form-group row"> <label class="cd-col-form-label" for="target_mutual_password"> <ng-container i18n>Mutual Password</ng-container> </label> <div class="cd-col-form-input"> <div class="input-group"> <input class="form-control" type="password" autocomplete="new-password" id="target_mutual_password" name="target_mutual_password" formControlName="mutual_password" /> <button type="button" class="btn btn-light" cdPasswordButton="target_mutual_password"> </button> <cd-copy-2-clipboard-button source="target_mutual_password"> </cd-copy-2-clipboard-button> </div> <span class="invalid-feedback" *ngIf="targetForm.showError('mutual_password', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="targetForm.showError('mutual_password', formDir, 'pattern')" i18n>Passwords must have a length of 12 to 16 characters and can contain alphanumeric characters, '@', '-', '_' or '/'.</span> </div> </div> </div> <!-- Initiators --> <div class="form-group row" *ngIf="targetForm.getValue('acl_enabled')"> <label class="cd-col-form-label" for="initiators" i18n>Initiators</label> <div class="cd-col-form-input" formArrayName="initiators"> <div class="card mb-2" *ngFor="let initiator of initiators.controls; let ii = index" [formGroup]="initiator"> <div class="card-header"> <ng-container i18n>Initiator</ng-container>: {{ initiator.getValue('client_iqn') }} <button type="button" class="btn-close float-end" (click)="removeInitiator(ii)"> </button> </div> <div class="card-body"> <!-- Initiator: Name --> <div class="form-group row"> <label class="cd-col-form-label required" for="client_iqn" i18n>Client IQN</label> <div class="cd-col-form-input"> <input class="form-control" type="text" formControlName="client_iqn" cdTrim (blur)="updatedInitiatorSelector()"> <span class="invalid-feedback" *ngIf="initiator.showError('client_iqn', formDir, 'notUnique')" i18n>Initiator IQN needs to be unique.</span> <span class="invalid-feedback" *ngIf="initiator.showError('client_iqn', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="initiator.showError('client_iqn', formDir, 'pattern')" i18n>IQN has wrong pattern.</span> </div> </div> <ng-container formGroupName="auth"> <!-- Initiator: User --> <div class="form-group row"> <label class="cd-col-form-label" for="user" i18n>User</label> <div class="cd-col-form-input"> <input [id]="'user' + ii" class="form-control" formControlName="user" autocomplete="off" type="text"> <span class="invalid-feedback" *ngIf="initiator.showError('user', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="initiator.showError('user', formDir, 'pattern')" i18n>User names must have a length of 8 to 64 characters and can contain alphanumeric characters, '.', '@', '-', '_' or ':'.</span> </div> </div> <!-- Initiator: Password --> <div class="form-group row"> <label class="cd-col-form-label" for="password" i18n>Password</label> <div class="cd-col-form-input"> <div class="input-group"> <input [id]="'password' + ii" class="form-control" formControlName="password" autocomplete="new-password" type="password"> <button type="button" class="btn btn-light" [cdPasswordButton]="'password' + ii"> </button> <cd-copy-2-clipboard-button [source]="'password' + ii"> </cd-copy-2-clipboard-button> </div> <span class="invalid-feedback" *ngIf="initiator.showError('password', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="initiator.showError('password', formDir, 'pattern')" i18n>Passwords must have a length of 12 to 16 characters and can contain alphanumeric characters, '@', '-', '_' or '/'.</span> </div> </div> <!-- Initiator: mutual_user --> <div class="form-group row"> <label class="cd-col-form-label" for="mutual_user"> <ng-container i18n>Mutual User</ng-container> </label> <div class="cd-col-form-input"> <input [id]="'mutual_user' + ii" class="form-control" formControlName="mutual_user" autocomplete="off" type="text"> <span class="invalid-feedback" *ngIf="initiator.showError('mutual_user', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="initiator.showError('mutual_user', formDir, 'pattern')" i18n>User names must have a length of 8 to 64 characters and can contain alphanumeric characters, '.', '@', '-', '_' or ':'.</span> </div> </div> <!-- Initiator: mutual_password --> <div class="form-group row"> <label class="cd-col-form-label" for="mutual_password" i18n>Mutual Password</label> <div class="cd-col-form-input"> <div class="input-group"> <input [id]="'mutual_password' + ii" class="form-control" formControlName="mutual_password" autocomplete="new-password" type="password"> <button type="button" class="btn btn-light" [cdPasswordButton]="'mutual_password' + ii"> </button> <cd-copy-2-clipboard-button [source]="'mutual_password' + ii"> </cd-copy-2-clipboard-button> </div> <span class="invalid-feedback" *ngIf="initiator.showError('mutual_password', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="initiator.showError('mutual_password', formDir, 'pattern')" i18n>Passwords must have a length of 12 to 16 characters and can contain alphanumeric characters, '@', '-', '_' or '/'.</span> </div> </div> </ng-container> <!-- Initiator: Images --> <div class="form-group row"> <label class="cd-col-form-label" for="luns" i18n>Images</label> <div class="cd-col-form-input"> <ng-container *ngFor="let image of initiator.getValue('luns'); let li = index"> <div class="input-group cd-mb"> <input class="cd-form-control" type="text" [value]="image" disabled /> <button class="btn btn-light" type="button" (click)="removeInitiatorImage(initiator, li, ii, image)"> <i [ngClass]="[icons.destroy]" aria-hidden="true"></i> </button> </div> </ng-container> <span *ngIf="initiator.getValue('cdIsInGroup')" i18n>Initiator belongs to a group. Images will be configure in the group.</span> <div class="row" *ngIf="!initiator.getValue('cdIsInGroup')"> <div class="col-md-12"> <cd-select [data]="initiator.getValue('luns')" [options]="imagesInitiatorSelections[ii]" [messages]="messages.initiatorImage" elemClass="btn btn-light float-end"> <i [ngClass]="[icons.add]"></i> <ng-container i18n>Add image</ng-container> </cd-select> </div> </div> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <span class="form-text text-muted" *ngIf="initiators.controls.length === 0" i18n>No items added.</span> <button (click)="addInitiator(); false" class="btn btn-light float-end"> <i [ngClass]="[icons.add]"></i> <ng-container i18n>Add initiator</ng-container> </button> </div> </div> <hr /> </div> </div> <!-- Groups --> <div class="form-group row" *ngIf="targetForm.getValue('acl_enabled')"> <label class="cd-col-form-label" for="initiators" i18n>Groups</label> <div class="cd-col-form-input" formArrayName="groups"> <div class="card mb-2" *ngFor="let group of groups.controls; let gi = index" [formGroup]="group"> <div class="card-header"> <ng-container i18n>Group</ng-container>: {{ group.getValue('group_id') }} <button type="button" class="btn-close float-end" (click)="removeGroup(gi)"> </button> </div> <div class="card-body"> <!-- Group: group_id --> <div class="form-group row"> <label class="cd-col-form-label required" for="group_id" i18n>Name</label> <div class="cd-col-form-input"> <input class="form-control" type="text" formControlName="group_id"> </div> </div> <!-- Group: members --> <div class="form-group row"> <label class="cd-col-form-label" for="members"> <ng-container i18n>Initiators</ng-container> </label> <div class="cd-col-form-input"> <ng-container *ngFor="let member of group.getValue('members'); let i = index"> <div class="input-group cd-mb"> <input class="cd-form-control" type="text" [value]="member" disabled /> <button class="btn btn-light" type="button" (click)="removeGroupInitiator(group, i, gi)"> <i [ngClass]="[icons.destroy]" aria-hidden="true"></i> </button> </div> </ng-container> <div class="row"> <div class="col-md-12"> <cd-select [data]="group.getValue('members')" [options]="groupMembersSelections[gi]" [messages]="messages.groupInitiator" (selection)="onGroupMemberSelection($event, gi)" elemClass="btn btn-light float-end"> <i [ngClass]="[icons.add]"></i> <ng-container i18n>Add initiator</ng-container> </cd-select> </div> </div> <hr /> </div> </div> <!-- Group: disks --> <div class="form-group row"> <label class="cd-col-form-label" for="disks"> <ng-container i18n>Images</ng-container> </label> <div class="cd-col-form-input"> <ng-container *ngFor="let disk of group.getValue('disks'); let i = index"> <div class="input-group cd-mb"> <input class="cd-form-control" type="text" [value]="disk" disabled /> <button class="btn btn-light" type="button" (click)="removeGroupDisk(group, i, gi)"> <i [ngClass]="[icons.destroy]" aria-hidden="true"></i> </button> </div> </ng-container> <div class="row"> <div class="col-md-12"> <cd-select [data]="group.getValue('disks')" [options]="groupDiskSelections[gi]" [messages]="messages.initiatorImage" elemClass="btn btn-light float-end"> <i [ngClass]="[icons.add]"></i> <ng-container i18n>Add image</ng-container> </cd-select> </div> </div> <hr /> </div> </div> </div> </div> <div class="row"> <div class="col-md-12"> <span class="form-text text-muted" *ngIf="groups.controls.length === 0" i18n>No items added.</span> <button (click)="addGroup(); false" class="btn btn-light float-end"> <i [ngClass]="[icons.add]"></i> <ng-container i18n>Add group</ng-container> </button> </div> </div> </div> </div> </div> <div class="card-footer"> <cd-form-button-panel (submitActionEvent)="submit()" [form]="targetForm" [submitText]="(action | titlecase) + ' ' + (resource | upperFirst)" wrappingClass="text-right"></cd-form-button-panel> </div> </div> </form> </div>
28,650
41.698957
122
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-form/iscsi-target-form.component.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { ActivatedRoute } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { LoadingPanelComponent } from '~/app/shared/components/loading-panel/loading-panel.component'; import { SelectOption } from '~/app/shared/components/select/select-option.model'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { SharedModule } from '~/app/shared/shared.module'; import { ActivatedRouteStub } from '~/testing/activated-route-stub'; import { configureTestBed, FormHelper, IscsiHelper } from '~/testing/unit-test-helper'; import { IscsiTargetFormComponent } from './iscsi-target-form.component'; describe('IscsiTargetFormComponent', () => { let component: IscsiTargetFormComponent; let fixture: ComponentFixture<IscsiTargetFormComponent>; let httpTesting: HttpTestingController; let activatedRoute: ActivatedRouteStub; const SETTINGS = { config: { minimum_gateways: 2 }, disk_default_controls: { 'backstore:1': { hw_max_sectors: 1024, osd_op_timeout: 30 }, 'backstore:2': { qfull_timeout: 5 } }, target_default_controls: { cmdsn_depth: 128, dataout_timeout: 20, immediate_data: true }, required_rbd_features: { 'backstore:1': 0, 'backstore:2': 0 }, unsupported_rbd_features: { 'backstore:1': 0, 'backstore:2': 0 }, backstores: ['backstore:1', 'backstore:2'], default_backstore: 'backstore:1', api_version: 1 }; const LIST_TARGET: any[] = [ { target_iqn: 'iqn.2003-01.com.redhat.iscsi-gw:iscsi-igw', portals: [{ host: 'node1', ip: '192.168.100.201' }], disks: [ { pool: 'rbd', image: 'disk_1', controls: {}, backstore: 'backstore:1', wwn: '64af6678-9694-4367-bacc-f8eb0baa' } ], clients: [ { client_iqn: 'iqn.1994-05.com.redhat:rh7-client', luns: [{ pool: 'rbd', image: 'disk_1', lun: 0 }], auth: { user: 'myiscsiusername', password: 'myiscsipassword', mutual_user: null, mutual_password: null } } ], groups: [], target_controls: {} } ]; const PORTALS = [ { name: 'node1', ip_addresses: ['192.168.100.201', '10.0.2.15'] }, { name: 'node2', ip_addresses: ['192.168.100.202'] } ]; const VERSION = { ceph_iscsi_config_version: 11 }; const RBD_LIST: any[] = [ { value: [], pool_name: 'ganesha' }, { value: [ { size: 96636764160, obj_size: 4194304, num_objs: 23040, order: 22, block_name_prefix: 'rbd_data.148162fb31a8', name: 'disk_1', id: '148162fb31a8', pool_name: 'rbd', features: 61, features_name: ['deep-flatten', 'exclusive-lock', 'fast-diff', 'layering', 'object-map'], timestamp: '2019-01-18T10:44:26Z', stripe_count: 1, stripe_unit: 4194304, data_pool: null, parent: null, snapshots: [], total_disk_usage: 0, disk_usage: 0 }, { size: 119185342464, obj_size: 4194304, num_objs: 28416, order: 22, block_name_prefix: 'rbd_data.14b292cee6cb', name: 'disk_2', id: '14b292cee6cb', pool_name: 'rbd', features: 61, features_name: ['deep-flatten', 'exclusive-lock', 'fast-diff', 'layering', 'object-map'], timestamp: '2019-01-18T10:45:56Z', stripe_count: 1, stripe_unit: 4194304, data_pool: null, parent: null, snapshots: [], total_disk_usage: 0, disk_usage: 0 } ], pool_name: 'rbd' } ]; configureTestBed( { declarations: [IscsiTargetFormComponent], imports: [ SharedModule, ReactiveFormsModule, HttpClientTestingModule, RouterTestingModule, ToastrModule.forRoot() ], providers: [ { provide: ActivatedRoute, useValue: new ActivatedRouteStub({ target_iqn: undefined }) } ] }, [LoadingPanelComponent] ); beforeEach(() => { fixture = TestBed.createComponent(IscsiTargetFormComponent); component = fixture.componentInstance; httpTesting = TestBed.inject(HttpTestingController); activatedRoute = <ActivatedRouteStub>TestBed.inject(ActivatedRoute); fixture.detectChanges(); httpTesting.expectOne('ui-api/iscsi/settings').flush(SETTINGS); httpTesting.expectOne('ui-api/iscsi/portals').flush(PORTALS); httpTesting.expectOne('ui-api/iscsi/version').flush(VERSION); httpTesting.expectOne('api/block/image?offset=0&limit=-1&search=&sort=+name').flush(RBD_LIST); httpTesting.expectOne('api/iscsi/target').flush(LIST_TARGET); httpTesting.verify(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should only show images not used in other targets', () => { expect(component.imagesAll).toEqual([RBD_LIST[1]['value'][1]]); expect(component.imagesSelections).toEqual([ { description: '', name: 'rbd/disk_2', selected: false, enabled: true } ]); }); it('should generate portals selectOptions', () => { expect(component.portalsSelections).toEqual([ { description: '', name: 'node1:192.168.100.201', selected: false, enabled: true }, { description: '', name: 'node1:10.0.2.15', selected: false, enabled: true }, { description: '', name: 'node2:192.168.100.202', selected: false, enabled: true } ]); }); it('should create the form', () => { expect(component.targetForm.value).toEqual({ disks: [], groups: [], initiators: [], acl_enabled: false, auth: { password: '', user: '', mutual_password: '', mutual_user: '' }, portals: [], target_controls: {}, target_iqn: component.targetForm.value.target_iqn }); }); it('should prepare data when selecting an image', () => { expect(component.imagesSettings).toEqual({}); component.onImageSelection({ option: { name: 'rbd/disk_2', selected: true } }); expect(component.imagesSettings).toEqual({ 'rbd/disk_2': { lun: 0, backstore: 'backstore:1', 'backstore:1': {} } }); }); it('should clean data when removing an image', () => { component.onImageSelection({ option: { name: 'rbd/disk_2', selected: true } }); component.addGroup(); component.groups.controls[0].patchValue({ group_id: 'foo', disks: ['rbd/disk_2'] }); expect(component.groups.controls[0].value).toEqual({ disks: ['rbd/disk_2'], group_id: 'foo', members: [] }); component.onImageSelection({ option: { name: 'rbd/disk_2', selected: false } }); expect(component.groups.controls[0].value).toEqual({ disks: [], group_id: 'foo', members: [] }); expect(component.imagesSettings).toEqual({ 'rbd/disk_2': { lun: 0, backstore: 'backstore:1', 'backstore:1': {} } }); }); it('should validate authentication', () => { const control = component.targetForm; const formHelper = new FormHelper(control as CdFormGroup); formHelper.expectValid('auth'); validateAuth(formHelper); }); describe('should test initiators', () => { beforeEach(() => { component.onImageSelection({ option: { name: 'rbd/disk_2', selected: true } }); component.targetForm.patchValue({ disks: ['rbd/disk_2'], acl_enabled: true }); component.addGroup().patchValue({ name: 'group_1' }); component.addGroup().patchValue({ name: 'group_2' }); component.addInitiator(); component.initiators.controls[0].patchValue({ client_iqn: 'iqn.initiator' }); component.updatedInitiatorSelector(); }); it('should prepare data when creating an initiator', () => { expect(component.initiators.controls.length).toBe(1); expect(component.initiators.controls[0].value).toEqual({ auth: { mutual_password: '', mutual_user: '', password: '', user: '' }, cdIsInGroup: false, client_iqn: 'iqn.initiator', luns: [] }); expect(component.imagesInitiatorSelections).toEqual([ [{ description: '', name: 'rbd/disk_2', selected: false, enabled: true }] ]); expect(component.groupMembersSelections).toEqual([ [{ description: '', name: 'iqn.initiator', selected: false, enabled: true }], [{ description: '', name: 'iqn.initiator', selected: false, enabled: true }] ]); }); it('should update data when changing an initiator name', () => { expect(component.groupMembersSelections).toEqual([ [{ description: '', name: 'iqn.initiator', selected: false, enabled: true }], [{ description: '', name: 'iqn.initiator', selected: false, enabled: true }] ]); component.initiators.controls[0].patchValue({ client_iqn: 'iqn.initiator_new' }); component.updatedInitiatorSelector(); expect(component.groupMembersSelections).toEqual([ [{ description: '', name: 'iqn.initiator_new', selected: false, enabled: true }], [{ description: '', name: 'iqn.initiator_new', selected: false, enabled: true }] ]); }); it('should clean data when removing an initiator', () => { component.groups.controls[0].patchValue({ group_id: 'foo', members: ['iqn.initiator'] }); expect(component.groups.controls[0].value).toEqual({ disks: [], group_id: 'foo', members: ['iqn.initiator'] }); component.removeInitiator(0); expect(component.groups.controls[0].value).toEqual({ disks: [], group_id: 'foo', members: [] }); expect(component.groupMembersSelections).toEqual([[], []]); expect(component.imagesInitiatorSelections).toEqual([]); }); it('should remove images in the initiator when added in a group', () => { component.initiators.controls[0].patchValue({ luns: ['rbd/disk_2'] }); component.imagesInitiatorSelections[0] = [ { description: '', enabled: true, name: 'rbd/disk_2', selected: true } ]; expect(component.initiators.controls[0].value).toEqual({ auth: { mutual_password: '', mutual_user: '', password: '', user: '' }, cdIsInGroup: false, client_iqn: 'iqn.initiator', luns: ['rbd/disk_2'] }); component.groups.controls[0].patchValue({ group_id: 'foo', members: ['iqn.initiator'] }); component.onGroupMemberSelection( { option: { name: 'iqn.initiator', selected: true } }, 0 ); expect(component.initiators.controls[0].value).toEqual({ auth: { mutual_password: '', mutual_user: '', password: '', user: '' }, cdIsInGroup: true, client_iqn: 'iqn.initiator', luns: [] }); expect(component.imagesInitiatorSelections[0]).toEqual([ { description: '', enabled: true, name: 'rbd/disk_2', selected: false } ]); }); it('should disabled the initiator when selected', () => { expect(component.groupMembersSelections).toEqual([ [{ description: '', enabled: true, name: 'iqn.initiator', selected: false }], [{ description: '', enabled: true, name: 'iqn.initiator', selected: false }] ]); component.groupMembersSelections[0][0].selected = true; component.onGroupMemberSelection({ option: { name: 'iqn.initiator', selected: true } }, 0); expect(component.groupMembersSelections).toEqual([ [{ description: '', enabled: false, name: 'iqn.initiator', selected: true }], [{ description: '', enabled: false, name: 'iqn.initiator', selected: false }] ]); }); describe('should remove from group', () => { beforeEach(() => { component.onGroupMemberSelection( { option: new SelectOption(true, 'iqn.initiator', '') }, 0 ); component.groupDiskSelections[0][0].selected = true; component.groups.controls[0].patchValue({ disks: ['rbd/disk_2'], members: ['iqn.initiator'] }); expect(component.initiators.value[0].luns).toEqual([]); expect(component.imagesInitiatorSelections[0]).toEqual([ { description: '', enabled: true, name: 'rbd/disk_2', selected: false } ]); expect(component.initiators.value[0].cdIsInGroup).toBe(true); }); it('should update initiator images when deselecting', () => { component.onGroupMemberSelection( { option: new SelectOption(false, 'iqn.initiator', '') }, 0 ); expect(component.initiators.value[0].luns).toEqual(['rbd/disk_2']); expect(component.imagesInitiatorSelections[0]).toEqual([ { description: '', enabled: true, name: 'rbd/disk_2', selected: true } ]); expect(component.initiators.value[0].cdIsInGroup).toBe(false); }); it('should update initiator when removing', () => { component.removeGroupInitiator(component.groups.controls[0] as CdFormGroup, 0, 0); expect(component.initiators.value[0].luns).toEqual(['rbd/disk_2']); expect(component.imagesInitiatorSelections[0]).toEqual([ { description: '', enabled: true, name: 'rbd/disk_2', selected: true } ]); expect(component.initiators.value[0].cdIsInGroup).toBe(false); }); }); it('should validate authentication', () => { const control = component.initiators.controls[0]; const formHelper = new FormHelper(control as CdFormGroup); formHelper.expectValid(control); validateAuth(formHelper); }); }); describe('should submit request', () => { beforeEach(() => { component.onImageSelection({ option: { name: 'rbd/disk_2', selected: true } }); component.targetForm.patchValue({ disks: ['rbd/disk_2'], acl_enabled: true }); component.portals.setValue(['node1:192.168.100.201', 'node2:192.168.100.202']); component.addInitiator().patchValue({ client_iqn: 'iqn.initiator' }); component.addGroup().patchValue({ group_id: 'foo', members: ['iqn.initiator'], disks: ['rbd/disk_2'] }); }); it('should call update', () => { activatedRoute.setParams({ target_iqn: 'iqn.iscsi' }); component.isEdit = true; component.target_iqn = 'iqn.iscsi'; component.submit(); const req = httpTesting.expectOne('api/iscsi/target/iqn.iscsi'); expect(req.request.method).toBe('PUT'); expect(req.request.body).toEqual({ clients: [ { auth: { mutual_password: '', mutual_user: '', password: '', user: '' }, client_iqn: 'iqn.initiator', luns: [] } ], disks: [ { backstore: 'backstore:1', controls: {}, image: 'disk_2', pool: 'rbd', lun: 0, wwn: undefined } ], groups: [ { disks: [{ image: 'disk_2', pool: 'rbd' }], group_id: 'foo', members: ['iqn.initiator'] } ], new_target_iqn: component.targetForm.value.target_iqn, portals: [ { host: 'node1', ip: '192.168.100.201' }, { host: 'node2', ip: '192.168.100.202' } ], target_controls: {}, target_iqn: component.target_iqn, acl_enabled: true, auth: { password: '', user: '', mutual_password: '', mutual_user: '' } }); }); it('should call create', () => { component.submit(); const req = httpTesting.expectOne('api/iscsi/target'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ clients: [ { auth: { mutual_password: '', mutual_user: '', password: '', user: '' }, client_iqn: 'iqn.initiator', luns: [] } ], disks: [ { backstore: 'backstore:1', controls: {}, image: 'disk_2', pool: 'rbd', lun: 0, wwn: undefined } ], groups: [ { disks: [{ image: 'disk_2', pool: 'rbd' }], group_id: 'foo', members: ['iqn.initiator'] } ], portals: [ { host: 'node1', ip: '192.168.100.201' }, { host: 'node2', ip: '192.168.100.202' } ], target_controls: {}, target_iqn: component.targetForm.value.target_iqn, acl_enabled: true, auth: { password: '', user: '', mutual_password: '', mutual_user: '' } }); }); it('should call create with acl_enabled disabled', () => { component.targetForm.patchValue({ acl_enabled: false }); component.submit(); const req = httpTesting.expectOne('api/iscsi/target'); expect(req.request.method).toBe('POST'); expect(req.request.body).toEqual({ clients: [], disks: [ { backstore: 'backstore:1', controls: {}, image: 'disk_2', pool: 'rbd', lun: 0, wwn: undefined } ], groups: [], acl_enabled: false, auth: { password: '', user: '', mutual_password: '', mutual_user: '' }, portals: [ { host: 'node1', ip: '192.168.100.201' }, { host: 'node2', ip: '192.168.100.202' } ], target_controls: {}, target_iqn: component.targetForm.value.target_iqn }); }); }); function validateAuth(formHelper: FormHelper) { IscsiHelper.validateUser(formHelper, 'auth.user'); IscsiHelper.validatePassword(formHelper, 'auth.password'); IscsiHelper.validateUser(formHelper, 'auth.mutual_user'); IscsiHelper.validatePassword(formHelper, 'auth.mutual_password'); } });
18,774
30.607744
102
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-form/iscsi-target-form.component.ts
import { Component, OnInit } from '@angular/core'; import { FormArray, FormControl, Validators } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { forkJoin } from 'rxjs'; import { IscsiService } from '~/app/shared/api/iscsi.service'; import { RbdService } from '~/app/shared/api/rbd.service'; import { SelectMessages } from '~/app/shared/components/select/select-messages.model'; import { SelectOption } from '~/app/shared/components/select/select-option.model'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdForm } from '~/app/shared/forms/cd-form'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { CdValidators } from '~/app/shared/forms/cd-validators'; import { CdTableFetchDataContext } from '~/app/shared/models/cd-table-fetch-data-context'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { ModalService } from '~/app/shared/services/modal.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { IscsiTargetImageSettingsModalComponent } from '../iscsi-target-image-settings-modal/iscsi-target-image-settings-modal.component'; import { IscsiTargetIqnSettingsModalComponent } from '../iscsi-target-iqn-settings-modal/iscsi-target-iqn-settings-modal.component'; @Component({ selector: 'cd-iscsi-target-form', templateUrl: './iscsi-target-form.component.html', styleUrls: ['./iscsi-target-form.component.scss'] }) export class IscsiTargetFormComponent extends CdForm implements OnInit { cephIscsiConfigVersion: number; targetForm: CdFormGroup; modalRef: NgbModalRef; api_version = 0; minimum_gateways = 1; target_default_controls: any; target_controls_limits: any; disk_default_controls: any; disk_controls_limits: any; backstores: string[]; default_backstore: string; unsupported_rbd_features: any; required_rbd_features: any; icons = Icons; isEdit = false; target_iqn: string; imagesAll: any[]; imagesSelections: SelectOption[]; portalsSelections: SelectOption[] = []; imagesInitiatorSelections: SelectOption[][] = []; groupDiskSelections: SelectOption[][] = []; groupMembersSelections: SelectOption[][] = []; imagesSettings: any = {}; messages = { portals: new SelectMessages({ noOptions: $localize`There are no portals available.` }), images: new SelectMessages({ noOptions: $localize`There are no images available.` }), initiatorImage: new SelectMessages({ noOptions: $localize`There are no images available. Please make sure you add an image to the target.` }), groupInitiator: new SelectMessages({ noOptions: $localize`There are no initiators available. Please make sure you add an initiator to the target.` }) }; IQN_REGEX = /^iqn\.(19|20)\d\d-(0[1-9]|1[0-2])\.\D{2,3}(\.[A-Za-z0-9-]+)+(:[A-Za-z0-9-\.]+)*$/; USER_REGEX = /^[\w\.:@_-]{8,64}$/; PASSWORD_REGEX = /^[\w@\-_\/]{12,16}$/; action: string; resource: string; constructor( private iscsiService: IscsiService, private modalService: ModalService, private rbdService: RbdService, private router: Router, private route: ActivatedRoute, private taskWrapper: TaskWrapperService, public actionLabels: ActionLabelsI18n ) { super(); this.resource = $localize`target`; } ngOnInit() { const rbdListContext = new CdTableFetchDataContext(() => undefined); /* limit -1 to specify all images */ rbdListContext.pageInfo.limit = -1; const promises: any[] = [ this.iscsiService.listTargets(), /* tslint:disable:no-empty */ this.rbdService.list(rbdListContext.toParams()), this.iscsiService.portals(), this.iscsiService.settings(), this.iscsiService.version() ]; if (this.router.url.startsWith('/block/iscsi/targets/edit')) { this.isEdit = true; this.route.params.subscribe((params: { target_iqn: string }) => { this.target_iqn = decodeURIComponent(params.target_iqn); promises.push(this.iscsiService.getTarget(this.target_iqn)); }); } this.action = this.isEdit ? this.actionLabels.EDIT : this.actionLabels.CREATE; forkJoin(promises).subscribe((data: any[]) => { // iscsiService.listTargets const usedImages = _(data[0]) .filter((target) => target.target_iqn !== this.target_iqn) .flatMap((target) => target.disks) .map((image) => `${image.pool}/${image.image}`) .value(); // iscsiService.settings() if ('api_version' in data[3]) { this.api_version = data[3].api_version; } this.minimum_gateways = data[3].config.minimum_gateways; this.target_default_controls = data[3].target_default_controls; this.target_controls_limits = data[3].target_controls_limits; this.disk_default_controls = data[3].disk_default_controls; this.disk_controls_limits = data[3].disk_controls_limits; this.backstores = data[3].backstores; this.default_backstore = data[3].default_backstore; this.unsupported_rbd_features = data[3].unsupported_rbd_features; this.required_rbd_features = data[3].required_rbd_features; // rbdService.list() this.imagesAll = _(data[1]) .flatMap((pool) => pool.value) .filter((image) => { // Namespaces are not supported by ceph-iscsi if (image.namespace) { return false; } const imageId = `${image.pool_name}/${image.name}`; if (usedImages.indexOf(imageId) !== -1) { return false; } const validBackstores = this.getValidBackstores(image); if (validBackstores.length === 0) { return false; } return true; }) .value(); this.imagesSelections = this.imagesAll.map( (image) => new SelectOption(false, `${image.pool_name}/${image.name}`, '') ); // iscsiService.portals() const portals: SelectOption[] = []; data[2].forEach((portal: Record<string, any>) => { portal.ip_addresses.forEach((ip: string) => { portals.push(new SelectOption(false, portal.name + ':' + ip, '')); }); }); this.portalsSelections = [...portals]; // iscsiService.version() this.cephIscsiConfigVersion = data[4]['ceph_iscsi_config_version']; this.createForm(); // iscsiService.getTarget() if (data[5]) { this.resolveModel(data[5]); } this.loadingReady(); }); } createForm() { this.targetForm = new CdFormGroup({ target_iqn: new FormControl('iqn.2001-07.com.ceph:' + Date.now(), { validators: [Validators.required, Validators.pattern(this.IQN_REGEX)] }), target_controls: new FormControl({}), portals: new FormControl([], { validators: [ CdValidators.custom('minGateways', (value: any[]) => { const gateways = _.uniq(value.map((elem) => elem.split(':')[0])); return gateways.length < Math.max(1, this.minimum_gateways); }) ] }), disks: new FormControl([], { validators: [ CdValidators.custom('dupLunId', (value: any[]) => { const lunIds = this.getLunIds(value); return lunIds.length !== _.uniq(lunIds).length; }), CdValidators.custom('dupWwn', (value: any[]) => { const wwns = this.getWwns(value); return wwns.length !== _.uniq(wwns).length; }) ] }), initiators: new FormArray([]), groups: new FormArray([]), acl_enabled: new FormControl(false) }); // Target level authentication was introduced in ceph-iscsi config v11 if (this.cephIscsiConfigVersion > 10) { const authFormGroup = new CdFormGroup({ user: new FormControl(''), password: new FormControl(''), mutual_user: new FormControl(''), mutual_password: new FormControl('') }); this.setAuthValidator(authFormGroup); this.targetForm.addControl('auth', authFormGroup); } } resolveModel(res: Record<string, any>) { this.targetForm.patchValue({ target_iqn: res.target_iqn, target_controls: res.target_controls, acl_enabled: res.acl_enabled }); // Target level authentication was introduced in ceph-iscsi config v11 if (this.cephIscsiConfigVersion > 10) { this.targetForm.patchValue({ auth: res.auth }); } const portals: any[] = []; _.forEach(res.portals, (portal) => { const id = `${portal.host}:${portal.ip}`; portals.push(id); }); this.targetForm.patchValue({ portals: portals }); const disks: any[] = []; _.forEach(res.disks, (disk) => { const id = `${disk.pool}/${disk.image}`; disks.push(id); this.imagesSettings[id] = { backstore: disk.backstore }; this.imagesSettings[id][disk.backstore] = disk.controls; if ('lun' in disk) { this.imagesSettings[id]['lun'] = disk.lun; } if ('wwn' in disk) { this.imagesSettings[id]['wwn'] = disk.wwn; } this.onImageSelection({ option: { name: id, selected: true } }); }); this.targetForm.patchValue({ disks: disks }); _.forEach(res.clients, (client) => { const initiator = this.addInitiator(); client.luns = _.map(client.luns, (lun) => `${lun.pool}/${lun.image}`); initiator.patchValue(client); // updatedInitiatorSelector() }); (res.groups as any[]).forEach((group: any, group_index: number) => { const fg = this.addGroup(); group.disks = _.map(group.disks, (disk) => `${disk.pool}/${disk.image}`); fg.patchValue(group); _.forEach(group.members, (member) => { this.onGroupMemberSelection({ option: new SelectOption(true, member, '') }, group_index); }); }); } hasAdvancedSettings(settings: any) { return Object.values(settings).length > 0; } // Portals get portals() { return this.targetForm.get('portals') as FormControl; } onPortalSelection() { this.portals.setValue(this.portals.value); } removePortal(index: number, portal: string) { this.portalsSelections.forEach((value) => { if (value.name === portal) { value.selected = false; } }); this.portals.value.splice(index, 1); this.portals.setValue(this.portals.value); return false; } // Images get disks() { return this.targetForm.get('disks') as FormControl; } removeImage(index: number, image: string) { this.imagesSelections.forEach((value) => { if (value.name === image) { value.selected = false; } }); this.disks.value.splice(index, 1); this.removeImageRefs(image); this.targetForm.get('disks').updateValueAndValidity({ emitEvent: false }); return false; } removeImageRefs(name: string) { this.initiators.controls.forEach((element) => { const newImages = element.value.luns.filter((item: string) => item !== name); element.get('luns').setValue(newImages); }); this.groups.controls.forEach((element) => { const newDisks = element.value.disks.filter((item: string) => item !== name); element.get('disks').setValue(newDisks); }); _.forEach(this.imagesInitiatorSelections, (selections, i) => { this.imagesInitiatorSelections[i] = selections.filter((item: any) => item.name !== name); }); _.forEach(this.groupDiskSelections, (selections, i) => { this.groupDiskSelections[i] = selections.filter((item: any) => item.name !== name); }); } getDefaultBackstore(imageId: string) { let result = this.default_backstore; const image = this.getImageById(imageId); if (!this.validFeatures(image, this.default_backstore)) { this.backstores.forEach((backstore) => { if (backstore !== this.default_backstore) { if (this.validFeatures(image, backstore)) { result = backstore; } } }); } return result; } isLunIdInUse(lunId: string, imageId: string) { const images = this.disks.value.filter((currentImageId: string) => currentImageId !== imageId); return this.getLunIds(images).includes(lunId); } getLunIds(images: object) { return _.map(images, (image) => this.imagesSettings[image]['lun']); } nextLunId(imageId: string) { const images = this.disks.value.filter((currentImageId: string) => currentImageId !== imageId); const lunIdsInUse = this.getLunIds(images); let lunIdCandidate = 0; while (lunIdsInUse.includes(lunIdCandidate)) { lunIdCandidate++; } return lunIdCandidate; } getWwns(images: object) { const wwns = _.map(images, (image) => this.imagesSettings[image]['wwn']); return wwns.filter((wwn) => _.isString(wwn) && wwn !== ''); } onImageSelection($event: any) { const option = $event.option; if (option.selected) { if (!this.imagesSettings[option.name]) { const defaultBackstore = this.getDefaultBackstore(option.name); this.imagesSettings[option.name] = { backstore: defaultBackstore, lun: this.nextLunId(option.name) }; this.imagesSettings[option.name][defaultBackstore] = {}; } else if (this.isLunIdInUse(this.imagesSettings[option.name]['lun'], option.name)) { // If the lun id is now in use, we have to generate a new one this.imagesSettings[option.name]['lun'] = this.nextLunId(option.name); } _.forEach(this.imagesInitiatorSelections, (selections, i) => { selections.push(new SelectOption(false, option.name, '')); this.imagesInitiatorSelections[i] = [...selections]; }); _.forEach(this.groupDiskSelections, (selections, i) => { selections.push(new SelectOption(false, option.name, '')); this.groupDiskSelections[i] = [...selections]; }); } else { this.removeImageRefs(option.name); } this.targetForm.get('disks').updateValueAndValidity({ emitEvent: false }); } // Initiators get initiators() { return this.targetForm.get('initiators') as FormArray; } addInitiator() { const fg = new CdFormGroup({ client_iqn: new FormControl('', { validators: [ Validators.required, CdValidators.custom('notUnique', (client_iqn: string) => { const flattened = this.initiators.controls.reduce(function (accumulator, currentValue) { return accumulator.concat(currentValue.value.client_iqn); }, []); return flattened.indexOf(client_iqn) !== flattened.lastIndexOf(client_iqn); }), Validators.pattern(this.IQN_REGEX) ] }), auth: new CdFormGroup({ user: new FormControl(''), password: new FormControl(''), mutual_user: new FormControl(''), mutual_password: new FormControl('') }), luns: new FormControl([]), cdIsInGroup: new FormControl(false) }); this.setAuthValidator(fg); this.initiators.push(fg); _.forEach(this.groupMembersSelections, (selections, i) => { selections.push(new SelectOption(false, '', '')); this.groupMembersSelections[i] = [...selections]; }); const disks = _.map( this.targetForm.getValue('disks'), (disk) => new SelectOption(false, disk, '') ); this.imagesInitiatorSelections.push(disks); return fg; } setAuthValidator(fg: CdFormGroup) { CdValidators.validateIf( fg.get('user'), () => fg.getValue('password') || fg.getValue('mutual_user') || fg.getValue('mutual_password'), [Validators.required], [Validators.pattern(this.USER_REGEX)], [fg.get('password'), fg.get('mutual_user'), fg.get('mutual_password')] ); CdValidators.validateIf( fg.get('password'), () => fg.getValue('user') || fg.getValue('mutual_user') || fg.getValue('mutual_password'), [Validators.required], [Validators.pattern(this.PASSWORD_REGEX)], [fg.get('user'), fg.get('mutual_user'), fg.get('mutual_password')] ); CdValidators.validateIf( fg.get('mutual_user'), () => fg.getValue('mutual_password'), [Validators.required], [Validators.pattern(this.USER_REGEX)], [fg.get('user'), fg.get('password'), fg.get('mutual_password')] ); CdValidators.validateIf( fg.get('mutual_password'), () => fg.getValue('mutual_user'), [Validators.required], [Validators.pattern(this.PASSWORD_REGEX)], [fg.get('user'), fg.get('password'), fg.get('mutual_user')] ); } removeInitiator(index: number) { const removed = this.initiators.value[index]; this.initiators.removeAt(index); _.forEach(this.groupMembersSelections, (selections, i) => { selections.splice(index, 1); this.groupMembersSelections[i] = [...selections]; }); this.groups.controls.forEach((element) => { const newMembers = element.value.members.filter( (item: string) => item !== removed.client_iqn ); element.get('members').setValue(newMembers); }); this.imagesInitiatorSelections.splice(index, 1); } updatedInitiatorSelector() { // Validate all client_iqn this.initiators.controls.forEach((control) => { control.get('client_iqn').updateValueAndValidity({ emitEvent: false }); }); // Update Group Initiator Selector _.forEach(this.groupMembersSelections, (group, group_index) => { _.forEach(group, (elem, index) => { const oldName = elem.name; elem.name = this.initiators.controls[index].value.client_iqn; this.groups.controls.forEach((element) => { const members = element.value.members; const i = members.indexOf(oldName); if (i !== -1) { members[i] = elem.name; } element.get('members').setValue(members); }); }); this.groupMembersSelections[group_index] = [...this.groupMembersSelections[group_index]]; }); } removeInitiatorImage(initiator: any, lun_index: number, initiator_index: number, image: string) { const luns = initiator.getValue('luns'); luns.splice(lun_index, 1); initiator.patchValue({ luns: luns }); this.imagesInitiatorSelections[initiator_index].forEach((value: Record<string, any>) => { if (value.name === image) { value.selected = false; } }); return false; } // Groups get groups() { return this.targetForm.get('groups') as FormArray; } addGroup() { const fg = new CdFormGroup({ group_id: new FormControl('', { validators: [Validators.required] }), members: new FormControl([]), disks: new FormControl([]) }); this.groups.push(fg); const disks = _.map( this.targetForm.getValue('disks'), (disk) => new SelectOption(false, disk, '') ); this.groupDiskSelections.push(disks); const initiators = _.map( this.initiators.value, (initiator) => new SelectOption(false, initiator.client_iqn, '', !initiator.cdIsInGroup) ); this.groupMembersSelections.push(initiators); return fg; } removeGroup(index: number) { // Remove group and disk selections this.groups.removeAt(index); // Free initiator from group const selectedMembers = this.groupMembersSelections[index].filter((value) => value.selected); selectedMembers.forEach((selection) => { selection.selected = false; this.onGroupMemberSelection({ option: selection }, index); }); this.groupMembersSelections.splice(index, 1); this.groupDiskSelections.splice(index, 1); } onGroupMemberSelection($event: any, group_index: number) { const option = $event.option; let luns: string[] = []; if (!option.selected) { const selectedDisks = this.groupDiskSelections[group_index].filter((value) => value.selected); luns = selectedDisks.map((value) => value.name); } this.initiators.controls.forEach((element, index) => { if (element.value.client_iqn === option.name) { element.patchValue({ luns: luns }); element.get('cdIsInGroup').setValue(option.selected); // Members can only be at one group at a time, so when a member is selected // in one group we need to disable its selection in other groups _.forEach(this.groupMembersSelections, (group) => { group[index].enabled = !option.selected; }); this.imagesInitiatorSelections[index].forEach((image) => { image.selected = luns.includes(image.name); }); } }); } removeGroupInitiator(group: CdFormGroup, member_index: number, group_index: number) { const name = group.getValue('members')[member_index]; group.getValue('members').splice(member_index, 1); this.onGroupMemberSelection({ option: new SelectOption(false, name, '') }, group_index); } removeGroupDisk(group: CdFormGroup, disk_index: number, group_index: number) { const name = group.getValue('disks')[disk_index]; group.getValue('disks').splice(disk_index, 1); this.groupDiskSelections[group_index].forEach((value) => { if (value.name === name) { value.selected = false; } }); this.groupDiskSelections[group_index] = [...this.groupDiskSelections[group_index]]; } submit() { const formValue = _.cloneDeep(this.targetForm.value); const request: Record<string, any> = { target_iqn: this.targetForm.getValue('target_iqn'), target_controls: this.targetForm.getValue('target_controls'), acl_enabled: this.targetForm.getValue('acl_enabled'), portals: [], disks: [], clients: [], groups: [] }; // Target level authentication was introduced in ceph-iscsi config v11 if (this.cephIscsiConfigVersion > 10) { const targetAuth: CdFormGroup = this.targetForm.get('auth') as CdFormGroup; if (!targetAuth.getValue('user')) { targetAuth.get('user').setValue(''); } if (!targetAuth.getValue('password')) { targetAuth.get('password').setValue(''); } if (!targetAuth.getValue('mutual_user')) { targetAuth.get('mutual_user').setValue(''); } if (!targetAuth.getValue('mutual_password')) { targetAuth.get('mutual_password').setValue(''); } const acl_enabled = this.targetForm.getValue('acl_enabled'); request['auth'] = { user: acl_enabled ? '' : targetAuth.getValue('user'), password: acl_enabled ? '' : targetAuth.getValue('password'), mutual_user: acl_enabled ? '' : targetAuth.getValue('mutual_user'), mutual_password: acl_enabled ? '' : targetAuth.getValue('mutual_password') }; } // Disks formValue.disks.forEach((disk: string) => { const imageSplit = disk.split('/'); const backstore = this.imagesSettings[disk].backstore; request.disks.push({ pool: imageSplit[0], image: imageSplit[1], backstore: backstore, controls: this.imagesSettings[disk][backstore], lun: this.imagesSettings[disk]['lun'], wwn: this.imagesSettings[disk]['wwn'] }); }); // Portals formValue.portals.forEach((portal: string) => { const index = portal.indexOf(':'); request.portals.push({ host: portal.substring(0, index), ip: portal.substring(index + 1) }); }); // Clients if (request.acl_enabled) { formValue.initiators.forEach((initiator: Record<string, any>) => { if (!initiator.auth.user) { initiator.auth.user = ''; } if (!initiator.auth.password) { initiator.auth.password = ''; } if (!initiator.auth.mutual_user) { initiator.auth.mutual_user = ''; } if (!initiator.auth.mutual_password) { initiator.auth.mutual_password = ''; } delete initiator.cdIsInGroup; const newLuns: any[] = []; initiator.luns.forEach((lun: string) => { const imageSplit = lun.split('/'); newLuns.push({ pool: imageSplit[0], image: imageSplit[1] }); }); initiator.luns = newLuns; }); request.clients = formValue.initiators; } // Groups if (request.acl_enabled) { formValue.groups.forEach((group: Record<string, any>) => { const newDisks: any[] = []; group.disks.forEach((disk: string) => { const imageSplit = disk.split('/'); newDisks.push({ pool: imageSplit[0], image: imageSplit[1] }); }); group.disks = newDisks; }); request.groups = formValue.groups; } let wrapTask; if (this.isEdit) { request['new_target_iqn'] = request.target_iqn; request.target_iqn = this.target_iqn; wrapTask = this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('iscsi/target/edit', { target_iqn: request.target_iqn }), call: this.iscsiService.updateTarget(this.target_iqn, request) }); } else { wrapTask = this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('iscsi/target/create', { target_iqn: request.target_iqn }), call: this.iscsiService.createTarget(request) }); } wrapTask.subscribe({ error: () => { this.targetForm.setErrors({ cdSubmitButton: true }); }, complete: () => this.router.navigate(['/block/iscsi/targets']) }); } targetSettingsModal() { const initialState = { target_controls: this.targetForm.get('target_controls'), target_default_controls: this.target_default_controls, target_controls_limits: this.target_controls_limits }; this.modalRef = this.modalService.show(IscsiTargetIqnSettingsModalComponent, initialState); } imageSettingsModal(image: string) { const initialState = { imagesSettings: this.imagesSettings, image: image, api_version: this.api_version, disk_default_controls: this.disk_default_controls, disk_controls_limits: this.disk_controls_limits, backstores: this.getValidBackstores(this.getImageById(image)), control: this.targetForm.get('disks') }; this.modalRef = this.modalService.show(IscsiTargetImageSettingsModalComponent, initialState); } validFeatures(image: Record<string, any>, backstore: string) { const imageFeatures = image.features; const requiredFeatures = this.required_rbd_features[backstore]; const unsupportedFeatures = this.unsupported_rbd_features[backstore]; // eslint-disable-next-line no-bitwise const validRequiredFeatures = (imageFeatures & requiredFeatures) === requiredFeatures; // eslint-disable-next-line no-bitwise const validSupportedFeatures = (imageFeatures & unsupportedFeatures) === 0; return validRequiredFeatures && validSupportedFeatures; } getImageById(imageId: string) { return this.imagesAll.find((image) => imageId === `${image.pool_name}/${image.name}`); } getValidBackstores(image: object) { return this.backstores.filter((backstore) => this.validFeatures(image, backstore)); } }
27,540
32.464156
138
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-image-settings-modal/iscsi-target-image-settings-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container class="modal-title"> <ng-container i18n>Configure</ng-container>&nbsp; <small>{{ image }}</small> </ng-container> <ng-container class="modal-content"> <form name="settingsForm" class="form" #formDir="ngForm" [formGroup]="settingsForm" novalidate> <div class="modal-body"> <p class="alert-warning" i18n>Changing these parameters from their default values is usually not necessary.</p> <span *ngIf="api_version >= 1"> <legend class="cd-header" i18n>Identifier</legend> <!-- LUN --> <div class="form-group row"> <div class="col-sm-12"> <label class="col-form-label required" for="lun" i18n>lun</label> <input type="number" class="form-control" id="lun" name="lun" formControlName="lun"> <span class="invalid-feedback" *ngIf="settingsForm.showError('lun', formDir, 'required')" i18n>This field is required.</span> </div> </div> <!-- WWN --> <div class="form-group row"> <div class="col-sm-12"> <label class="col-form-label" for="wwn" i18n>wwn</label> <input type="text" class="form-control" id="wwn" name="wwn" formControlName="wwn"> </div> </div> </span> <legend class="cd-header" i18n>Settings</legend> <!-- BACKSTORE --> <div class="form-group row"> <div class="col-sm-12"> <label class="col-form-label" i18n>Backstore</label> <select id="backstore" name="backstore" class="form-select" formControlName="backstore"> <option *ngFor="let bs of backstores" [value]="bs">{{ bs | iscsiBackstore }}</option> </select> </div> </div> <!-- CONTROLS --> <ng-container *ngFor="let bs of backstores"> <ng-container *ngIf="settingsForm.value['backstore'] === bs"> <div class="form-group row" *ngFor="let setting of disk_default_controls[bs] | keyvalue"> <div class="col-sm-12"> <cd-iscsi-setting [settingsForm]="settingsForm" [formDir]="formDir" [setting]="setting.key" [limits]="getDiskControlLimits(bs, setting.key)"></cd-iscsi-setting> </div> </div> </ng-container> </ng-container> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="save()" [form]="settingsForm" [submitText]="actionLabels.UPDATE"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
3,275
34.225806
102
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-image-settings-modal/iscsi-target-image-settings-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { IscsiSettingComponent } from '../iscsi-setting/iscsi-setting.component'; import { IscsiTargetImageSettingsModalComponent } from './iscsi-target-image-settings-modal.component'; describe('IscsiTargetImageSettingsModalComponent', () => { let component: IscsiTargetImageSettingsModalComponent; let fixture: ComponentFixture<IscsiTargetImageSettingsModalComponent>; configureTestBed({ declarations: [IscsiTargetImageSettingsModalComponent, IscsiSettingComponent], imports: [SharedModule, ReactiveFormsModule, HttpClientTestingModule, RouterTestingModule], providers: [NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(IscsiTargetImageSettingsModalComponent); component = fixture.componentInstance; component.imagesSettings = { 'rbd/disk_1': { backstore: 'backstore:1', 'backstore:1': {} } }; component.image = 'rbd/disk_1'; component.disk_default_controls = { 'backstore:1': { foo: 1, bar: 2 }, 'backstore:2': { baz: 3 } }; component.disk_controls_limits = { 'backstore:1': { foo: { min: 1, max: 512, type: 'int' }, bar: { min: 1, max: 512, type: 'int' } }, 'backstore:2': { baz: { min: 1, max: 512, type: 'int' } } }; component.backstores = ['backstore:1', 'backstore:2']; component.control = new FormControl(); component.ngOnInit(); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should fill the form', () => { expect(component.settingsForm.value).toEqual({ lun: null, wwn: null, backstore: 'backstore:1', foo: null, bar: null, baz: null }); }); it('should save changes to imagesSettings', () => { component.settingsForm.controls['foo'].setValue(1234); expect(component.imagesSettings).toEqual({ 'rbd/disk_1': { backstore: 'backstore:1', 'backstore:1': {} } }); component.save(); expect(component.imagesSettings).toEqual({ 'rbd/disk_1': { lun: null, wwn: null, backstore: 'backstore:1', 'backstore:1': { foo: 1234 } } }); }); });
2,806
27.353535
103
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-image-settings-modal/iscsi-target-image-settings-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { AbstractControl, FormControl } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { IscsiService } from '~/app/shared/api/iscsi.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; @Component({ selector: 'cd-iscsi-target-image-settings-modal', templateUrl: './iscsi-target-image-settings-modal.component.html', styleUrls: ['./iscsi-target-image-settings-modal.component.scss'] }) export class IscsiTargetImageSettingsModalComponent implements OnInit { image: string; imagesSettings: any; api_version: number; disk_default_controls: any; disk_controls_limits: any; backstores: any; control: AbstractControl; settingsForm: CdFormGroup; constructor( public activeModal: NgbActiveModal, public iscsiService: IscsiService, public actionLabels: ActionLabelsI18n ) {} ngOnInit() { const fg: Record<string, FormControl> = { backstore: new FormControl(this.imagesSettings[this.image]['backstore']), lun: new FormControl(this.imagesSettings[this.image]['lun']), wwn: new FormControl(this.imagesSettings[this.image]['wwn']) }; _.forEach(this.backstores, (backstore) => { const model = this.imagesSettings[this.image][backstore] || {}; _.forIn(this.disk_default_controls[backstore], (_value, key) => { fg[key] = new FormControl(model[key]); }); }); this.settingsForm = new CdFormGroup(fg); } getDiskControlLimits(backstore: string, setting: string) { if (this.disk_controls_limits) { return this.disk_controls_limits[backstore][setting]; } // backward compatibility return { type: 'int' }; } save() { const backstore = this.settingsForm.controls['backstore'].value; const lun = this.settingsForm.controls['lun'].value; const wwn = this.settingsForm.controls['wwn'].value; const settings = {}; _.forIn(this.settingsForm.controls, (control, key) => { if ( !(control.value === '' || control.value === null) && key in this.disk_default_controls[this.settingsForm.value['backstore']] ) { settings[key] = control.value; // If one setting belongs to multiple backstores, we have to update it in all backstores _.forEach(this.backstores, (currentBackstore) => { if (currentBackstore !== backstore) { const model = this.imagesSettings[this.image][currentBackstore] || {}; if (key in model) { this.imagesSettings[this.image][currentBackstore][key] = control.value; } } }); } }); this.imagesSettings[this.image]['backstore'] = backstore; this.imagesSettings[this.image]['lun'] = lun; this.imagesSettings[this.image]['wwn'] = wwn; this.imagesSettings[this.image][backstore] = settings; this.imagesSettings = { ...this.imagesSettings }; this.control.updateValueAndValidity({ emitEvent: false }); this.activeModal.close(); } }
3,152
34.829545
96
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-iqn-settings-modal/iscsi-target-iqn-settings-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container class="modal-title" i18n>Advanced Settings</ng-container> <ng-container class="modal-content"> <form name="settingsForm" #formDir="ngForm" [formGroup]="settingsForm" novalidate> <div class="modal-body"> <p class="alert-warning" i18n>Changing these parameters from their default values is usually not necessary.</p> <div class="form-group row" *ngFor="let setting of settingsForm.controls | keyvalue"> <div class="col-sm-12"> <cd-iscsi-setting [settingsForm]="settingsForm" [formDir]="formDir" [setting]="setting.key" [limits]="getTargetControlLimits(setting.key)"></cd-iscsi-setting> </div> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="save()" [form]="settingsForm" [submitText]="actionLabels.UPDATE"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
1,182
34.848485
97
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-iqn-settings-modal/iscsi-target-iqn-settings-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormControl, ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { IscsiSettingComponent } from '../iscsi-setting/iscsi-setting.component'; import { IscsiTargetIqnSettingsModalComponent } from './iscsi-target-iqn-settings-modal.component'; describe('IscsiTargetIqnSettingsModalComponent', () => { let component: IscsiTargetIqnSettingsModalComponent; let fixture: ComponentFixture<IscsiTargetIqnSettingsModalComponent>; configureTestBed({ declarations: [IscsiTargetIqnSettingsModalComponent, IscsiSettingComponent], imports: [SharedModule, ReactiveFormsModule, HttpClientTestingModule, RouterTestingModule], providers: [NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(IscsiTargetIqnSettingsModalComponent); component = fixture.componentInstance; component.target_controls = new FormControl({}); component.target_default_controls = { cmdsn_depth: 1, dataout_timeout: 2, first_burst_length: true }; component.target_controls_limits = { cmdsn_depth: { min: 1, max: 512, type: 'int' }, dataout_timeout: { min: 2, max: 60, type: 'int' }, first_burst_length: { max: 16777215, min: 512, type: 'int' } }; component.ngOnInit(); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should fill the settingsForm', () => { expect(component.settingsForm.value).toEqual({ cmdsn_depth: null, dataout_timeout: null, first_burst_length: null }); }); it('should save changes to target_controls', () => { component.settingsForm.patchValue({ dataout_timeout: 1234 }); expect(component.target_controls.value).toEqual({}); component.save(); expect(component.target_controls.value).toEqual({ dataout_timeout: 1234 }); }); });
2,317
31.194444
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-iqn-settings-modal/iscsi-target-iqn-settings-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { IscsiService } from '~/app/shared/api/iscsi.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; @Component({ selector: 'cd-iscsi-target-iqn-settings-modal', templateUrl: './iscsi-target-iqn-settings-modal.component.html', styleUrls: ['./iscsi-target-iqn-settings-modal.component.scss'] }) export class IscsiTargetIqnSettingsModalComponent implements OnInit { target_controls: FormControl; target_default_controls: any; target_controls_limits: any; settingsForm: CdFormGroup; constructor( public activeModal: NgbActiveModal, public iscsiService: IscsiService, public actionLabels: ActionLabelsI18n ) {} ngOnInit() { const fg: Record<string, FormControl> = {}; _.forIn(this.target_default_controls, (_value, key) => { fg[key] = new FormControl(this.target_controls.value[key]); }); this.settingsForm = new CdFormGroup(fg); } save() { const settings = {}; _.forIn(this.settingsForm.controls, (control, key) => { if (!(control.value === '' || control.value === null)) { settings[key] = control.value; } }); this.target_controls.setValue(settings); this.activeModal.close(); } getTargetControlLimits(setting: string) { if (this.target_controls_limits) { return this.target_controls_limits[setting]; } // backward compatibility if (['Yes', 'No'].includes(this.target_default_controls[setting])) { return { type: 'bool' }; } return { type: 'int' }; } }
1,782
28.229508
72
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-list/iscsi-target-list.component.html
<cd-iscsi-tabs></cd-iscsi-tabs> <cd-alert-panel type="info" *ngIf="available === false" title="iSCSI Targets not available" i18n-title> <ng-container i18n>Please consult the <cd-doc section="iscsi"></cd-doc> on how to configure and enable the iSCSI Targets management functionality.</ng-container> <ng-container *ngIf="status"> <br> <span i18n>Available information:</span> <pre>{{ status }}</pre> </ng-container> </cd-alert-panel> <cd-table #table *ngIf="available === true" [data]="targets" columnMode="flex" [columns]="columns" identifier="target_iqn" forceIdentifier="true" selectionType="single" [hasDetails]="true" [autoReload]="false" [status]="tableStatus" (fetchData)="getTargets()" (setExpandedRow)="setExpandedRow($event)" (updateSelection)="updateSelection($event)"> <div class="table-actions btn-toolbar"> <cd-table-actions class="btn-group" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> <button class="btn btn-light" type="button" (click)="configureDiscoveryAuth()"> <i [ngClass]="[icons.key]" aria-hidden="true"> </i> <ng-container i18n>Discovery authentication</ng-container> </button> </div> <cd-iscsi-target-details cdTableDetail *ngIf="expandedRow" [cephIscsiConfigVersion]="cephIscsiConfigVersion" [selection]="expandedRow" [settings]="settings"></cd-iscsi-target-details> </cd-table>
1,812
32.574074
90
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-list/iscsi-target-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { TreeModule } from '@circlon/angular-tree-component'; import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { BehaviorSubject, of } from 'rxjs'; import { IscsiService } from '~/app/shared/api/iscsi.service'; import { TableActionsComponent } from '~/app/shared/datatable/table-actions/table-actions.component'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { ExecutingTask } from '~/app/shared/models/executing-task'; import { SummaryService } from '~/app/shared/services/summary.service'; import { TaskListService } from '~/app/shared/services/task-list.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, expectItemTasks, PermissionHelper } from '~/testing/unit-test-helper'; import { IscsiTabsComponent } from '../iscsi-tabs/iscsi-tabs.component'; import { IscsiTargetDetailsComponent } from '../iscsi-target-details/iscsi-target-details.component'; import { IscsiTargetListComponent } from './iscsi-target-list.component'; describe('IscsiTargetListComponent', () => { let component: IscsiTargetListComponent; let fixture: ComponentFixture<IscsiTargetListComponent>; let summaryService: SummaryService; let iscsiService: IscsiService; const refresh = (data: any) => { summaryService['summaryDataSource'].next(data); }; configureTestBed({ imports: [ BrowserAnimationsModule, HttpClientTestingModule, RouterTestingModule, SharedModule, TreeModule, ToastrModule.forRoot(), NgbNavModule ], declarations: [IscsiTargetListComponent, IscsiTabsComponent, IscsiTargetDetailsComponent], providers: [TaskListService] }); beforeEach(() => { fixture = TestBed.createComponent(IscsiTargetListComponent); component = fixture.componentInstance; summaryService = TestBed.inject(SummaryService); iscsiService = TestBed.inject(IscsiService); // this is needed because summaryService isn't being reset after each test. summaryService['summaryDataSource'] = new BehaviorSubject(null); summaryService['summaryData$'] = summaryService['summaryDataSource'].asObservable(); spyOn(iscsiService, 'status').and.returnValue(of({ available: true })); spyOn(iscsiService, 'version').and.returnValue(of({ ceph_iscsi_config_version: 11 })); spyOn(component, 'setTableRefreshTimeout').and.stub(); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('after ngOnInit', () => { beforeEach(() => { spyOn(iscsiService, 'listTargets').and.callThrough(); fixture.detectChanges(); }); it('should load targets on init', () => { refresh({}); expect(iscsiService.status).toHaveBeenCalled(); expect(iscsiService.listTargets).toHaveBeenCalled(); }); it('should not load targets on init because no data', () => { refresh(undefined); expect(iscsiService.listTargets).not.toHaveBeenCalled(); }); it('should call error function on init when summary service fails', () => { spyOn(component.table, 'reset'); summaryService['summaryDataSource'].error(undefined); expect(component.table.reset).toHaveBeenCalled(); }); it('should call settings on the getTargets methods', () => { spyOn(iscsiService, 'settings').and.callThrough(); component.getTargets(); expect(iscsiService.settings).toHaveBeenCalled(); }); }); describe('handling of executing tasks', () => { let targets: any[]; const addTarget = (name: string) => { const model: any = { target_iqn: name, portals: [{ host: 'node1', ip: '192.168.100.201' }], disks: [{ pool: 'rbd', image: 'disk_1', controls: {} }], clients: [ { client_iqn: 'iqn.1994-05.com.redhat:rh7-client', luns: [{ pool: 'rbd', image: 'disk_1' }], auth: { user: 'myiscsiusername', password: 'myiscsipassword', mutual_user: null, mutual_password: null } } ], groups: [], target_controls: {} }; targets.push(model); }; const addTask = (name: string, target_iqn: string) => { const task = new ExecutingTask(); task.name = name; switch (task.name) { case 'iscsi/target/create': task.metadata = { target_iqn: target_iqn }; break; case 'iscsi/target/delete': task.metadata = { target_iqn: target_iqn }; break; default: task.metadata = { target_iqn: target_iqn }; break; } summaryService.addRunningTask(task); }; beforeEach(() => { targets = []; addTarget('iqn.a'); addTarget('iqn.b'); addTarget('iqn.c'); component.targets = targets; refresh({ executing_tasks: [], finished_tasks: [] }); spyOn(iscsiService, 'listTargets').and.callFake(() => of(targets)); fixture.detectChanges(); }); it('should gets all targets without tasks', () => { expect(component.targets.length).toBe(3); expect(component.targets.every((target) => !target.cdExecuting)).toBeTruthy(); }); it('should add a new target from a task', () => { addTask('iscsi/target/create', 'iqn.d'); expect(component.targets.length).toBe(4); expectItemTasks(component.targets[0], undefined); expectItemTasks(component.targets[1], undefined); expectItemTasks(component.targets[2], undefined); expectItemTasks(component.targets[3], 'Creating'); }); it('should show when an existing target is being modified', () => { addTask('iscsi/target/delete', 'iqn.b'); expect(component.targets.length).toBe(3); expectItemTasks(component.targets[1], 'Deleting'); }); }); describe('handling of actions', () => { beforeEach(() => { fixture.detectChanges(); }); let action: CdTableAction; const getAction = (name: string): CdTableAction => { return component.tableActions.find((tableAction) => tableAction.name === name); }; describe('edit', () => { beforeEach(() => { action = getAction('Edit'); }); it('should be disabled if no gateways', () => { component.selection.selected = [ { id: '-1' } ]; expect(action.disable(undefined)).toBe('Unavailable gateway(s)'); }); it('should be enabled if active sessions', () => { component.selection.selected = [ { id: '-1', info: { num_sessions: 1 } } ]; expect(action.disable(undefined)).toBeFalsy(); }); it('should be enabled if no active sessions', () => { component.selection.selected = [ { id: '-1', info: { num_sessions: 0 } } ]; expect(action.disable(undefined)).toBeFalsy(); }); }); describe('delete', () => { beforeEach(() => { action = getAction('Delete'); }); it('should be disabled if no gateways', () => { component.selection.selected = [ { id: '-1' } ]; expect(action.disable(undefined)).toBe('Unavailable gateway(s)'); }); it('should be disabled if active sessions', () => { component.selection.selected = [ { id: '-1', info: { num_sessions: 1 } } ]; expect(action.disable(undefined)).toBe('Target has active sessions'); }); it('should be enabled if no active sessions', () => { component.selection.selected = [ { id: '-1', info: { num_sessions: 0 } } ]; expect(action.disable(undefined)).toBeFalsy(); }); }); }); it('should test all TableActions combinations', () => { const permissionHelper: PermissionHelper = new PermissionHelper(component.permission); const tableActions: TableActionsComponent = permissionHelper.setPermissionsAndGetActions( component.tableActions ); expect(tableActions).toEqual({ 'create,update,delete': { actions: ['Create', 'Edit', 'Delete'], primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,update': { actions: ['Create', 'Edit'], primary: { multiple: 'Create', executing: 'Edit', single: 'Edit', no: 'Create' } }, 'create,delete': { actions: ['Create', 'Delete'], primary: { multiple: 'Create', executing: 'Delete', single: 'Delete', no: 'Create' } }, create: { actions: ['Create'], primary: { multiple: 'Create', executing: 'Create', single: 'Create', no: 'Create' } }, 'update,delete': { actions: ['Edit', 'Delete'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, update: { actions: ['Edit'], primary: { multiple: 'Edit', executing: 'Edit', single: 'Edit', no: 'Edit' } }, delete: { actions: ['Delete'], primary: { multiple: 'Delete', executing: 'Delete', single: 'Delete', no: 'Delete' } }, 'no-permissions': { actions: [], primary: { multiple: '', executing: '', single: '', no: '' } } }); }); });
9,946
31.087097
101
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi-target-list/iscsi-target-list.component.ts
import { Component, NgZone, OnDestroy, OnInit, ViewChild } from '@angular/core'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { Subscription } from 'rxjs'; import { IscsiService } from '~/app/shared/api/iscsi.service'; import { ListWithDetails } from '~/app/shared/classes/list-with-details.class'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { TableComponent } from '~/app/shared/datatable/table/table.component'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableColumn } from '~/app/shared/models/cd-table-column'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { Permission } from '~/app/shared/models/permissions'; import { Task } from '~/app/shared/models/task'; import { JoinPipe } from '~/app/shared/pipes/join.pipe'; import { NotAvailablePipe } from '~/app/shared/pipes/not-available.pipe'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { TaskListService } from '~/app/shared/services/task-list.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { IscsiTargetDiscoveryModalComponent } from '../iscsi-target-discovery-modal/iscsi-target-discovery-modal.component'; @Component({ selector: 'cd-iscsi-target-list', templateUrl: './iscsi-target-list.component.html', styleUrls: ['./iscsi-target-list.component.scss'], providers: [TaskListService] }) export class IscsiTargetListComponent extends ListWithDetails implements OnInit, OnDestroy { @ViewChild(TableComponent) table: TableComponent; available: boolean = undefined; columns: CdTableColumn[]; modalRef: NgbModalRef; permission: Permission; selection = new CdTableSelection(); cephIscsiConfigVersion: number; settings: any; status: string; summaryDataSubscription: Subscription; tableActions: CdTableAction[]; targets: any[] = []; icons = Icons; builders = { 'iscsi/target/create': (metadata: object) => { return { target_iqn: metadata['target_iqn'] }; } }; constructor( private authStorageService: AuthStorageService, private iscsiService: IscsiService, private joinPipe: JoinPipe, private taskListService: TaskListService, private notAvailablePipe: NotAvailablePipe, private modalService: ModalService, private taskWrapper: TaskWrapperService, public actionLabels: ActionLabelsI18n, protected ngZone: NgZone ) { super(ngZone); this.permission = this.authStorageService.getPermissions().iscsi; this.tableActions = [ { permission: 'create', icon: Icons.add, routerLink: () => '/block/iscsi/targets/create', name: this.actionLabels.CREATE }, { permission: 'update', icon: Icons.edit, routerLink: () => `/block/iscsi/targets/edit/${this.selection.first().target_iqn}`, name: this.actionLabels.EDIT, disable: () => this.getEditDisableDesc() }, { permission: 'delete', icon: Icons.destroy, click: () => this.deleteIscsiTargetModal(), name: this.actionLabels.DELETE, disable: () => this.getDeleteDisableDesc() } ]; } ngOnInit() { this.columns = [ { name: $localize`Target`, prop: 'target_iqn', flexGrow: 2, cellTransformation: CellTemplate.executing }, { name: $localize`Portals`, prop: 'cdPortals', pipe: this.joinPipe, flexGrow: 2 }, { name: $localize`Images`, prop: 'cdImages', pipe: this.joinPipe, flexGrow: 2 }, { name: $localize`# Sessions`, prop: 'info.num_sessions', pipe: this.notAvailablePipe, flexGrow: 1 } ]; this.iscsiService.status().subscribe((result: any) => { this.available = result.available; if (!result.available) { this.status = result.message; } }); } getTargets() { if (this.available) { this.setTableRefreshTimeout(); this.iscsiService.version().subscribe((res: any) => { this.cephIscsiConfigVersion = res['ceph_iscsi_config_version']; }); this.taskListService.init( () => this.iscsiService.listTargets(), (resp) => this.prepareResponse(resp), (targets) => (this.targets = targets), () => this.onFetchError(), this.taskFilter, this.itemFilter, this.builders ); this.iscsiService.settings().subscribe((settings: any) => { this.settings = settings; }); } } ngOnDestroy() { if (this.summaryDataSubscription) { this.summaryDataSubscription.unsubscribe(); } } getEditDisableDesc(): string | boolean { const first = this.selection.first(); if (first && first?.cdExecuting) { return first.cdExecuting; } if (first && _.isUndefined(first?.['info'])) { return $localize`Unavailable gateway(s)`; } return !first; } getDeleteDisableDesc(): string | boolean { const first = this.selection.first(); if (first?.cdExecuting) { return first.cdExecuting; } if (first && _.isUndefined(first?.['info'])) { return $localize`Unavailable gateway(s)`; } if (first && first?.['info']?.['num_sessions']) { return $localize`Target has active sessions`; } return !first; } prepareResponse(resp: any): any[] { resp.forEach((element: Record<string, any>) => { element.cdPortals = element.portals.map( (portal: Record<string, any>) => `${portal.host}:${portal.ip}` ); element.cdImages = element.disks.map( (disk: Record<string, any>) => `${disk.pool}/${disk.image}` ); }); return resp; } onFetchError() { this.table.reset(); // Disable loading indicator. } itemFilter(entry: Record<string, any>, task: Task) { return entry.target_iqn === task.metadata['target_iqn']; } taskFilter(task: Task) { return ['iscsi/target/create', 'iscsi/target/edit', 'iscsi/target/delete'].includes(task.name); } updateSelection(selection: CdTableSelection) { this.selection = selection; } deleteIscsiTargetModal() { const target_iqn = this.selection.first().target_iqn; this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: $localize`iSCSI target`, itemNames: [target_iqn], submitActionObservable: () => this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('iscsi/target/delete', { target_iqn: target_iqn }), call: this.iscsiService.deleteTarget(target_iqn) }) }); } configureDiscoveryAuth() { this.modalService.show(IscsiTargetDiscoveryModalComponent); } }
7,330
29.168724
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi/iscsi.component.html
<cd-iscsi-tabs></cd-iscsi-tabs> <legend i18n>Gateways</legend> <div> <cd-table [data]="gateways" (fetchData)="refresh()" [columns]="gatewaysColumns"> </cd-table> </div> <legend i18n>Images</legend> <div> <cd-table [data]="images" [columns]="imagesColumns"> </cd-table> </div> <ng-template #iscsiSparklineTpl let-row="row" let-value="value"> <span *ngIf="row.backstore === 'user:rbd'"> <cd-sparkline [data]="value" [isBinary]="row.cdIsBinary"></cd-sparkline> </span> <span *ngIf="row.backstore !== 'user:rbd'" class="text-muted"> n/a </span> </ng-template> <ng-template #iscsiPerSecondTpl let-row="row" let-value="value"> <span *ngIf="row.backstore === 'user:rbd'"> {{ value }} /s </span> <span *ngIf="row.backstore !== 'user:rbd'" class="text-muted"> n/a </span> </ng-template> <ng-template #iscsiRelativeDateTpl let-row="row" let-value="value"> <span *ngIf="row.backstore === 'user:rbd'"> {{ value | relativeDate | notAvailable }} </span> <span *ngIf="row.backstore !== 'user:rbd'" class="text-muted"> n/a </span> </ng-template>
1,247
22.111111
61
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi/iscsi.component.spec.ts
import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { of } from 'rxjs'; import { IscsiService } from '~/app/shared/api/iscsi.service'; import { CephShortVersionPipe } from '~/app/shared/pipes/ceph-short-version.pipe'; import { DimlessPipe } from '~/app/shared/pipes/dimless.pipe'; import { IscsiBackstorePipe } from '~/app/shared/pipes/iscsi-backstore.pipe'; import { FormatterService } from '~/app/shared/services/formatter.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { IscsiComponent } from './iscsi.component'; describe('IscsiComponent', () => { let component: IscsiComponent; let fixture: ComponentFixture<IscsiComponent>; let iscsiService: IscsiService; let tcmuiscsiData: Record<string, any>; const fakeService = { overview: () => { return new Promise(function () { return; }); } }; configureTestBed({ imports: [BrowserAnimationsModule, SharedModule], declarations: [IscsiComponent], schemas: [NO_ERRORS_SCHEMA], providers: [ CephShortVersionPipe, DimlessPipe, FormatterService, IscsiBackstorePipe, { provide: IscsiService, useValue: fakeService } ] }); beforeEach(() => { fixture = TestBed.createComponent(IscsiComponent); component = fixture.componentInstance; iscsiService = TestBed.inject(IscsiService); fixture.detectChanges(); tcmuiscsiData = { images: [] }; spyOn(iscsiService, 'overview').and.callFake(() => of(tcmuiscsiData)); }); it('should create', () => { expect(component).toBeTruthy(); }); it('should refresh without stats available', () => { tcmuiscsiData.images.push({}); component.refresh(); expect(component.images[0].cdIsBinary).toBe(true); }); it('should refresh with stats', () => { tcmuiscsiData.images.push({ stats_history: { rd_bytes: [ [1540551220, 0.0], [1540551225, 0.0], [1540551230, 0.0] ], wr_bytes: [ [1540551220, 0.0], [1540551225, 0.0], [1540551230, 0.0] ] } }); component.refresh(); expect(component.images[0].stats_history).toEqual({ rd_bytes: [0, 0, 0], wr_bytes: [0, 0, 0] }); expect(component.images[0].cdIsBinary).toBe(true); }); });
2,519
29
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/iscsi/iscsi.component.ts
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { IscsiService } from '~/app/shared/api/iscsi.service'; import { CellTemplate } from '~/app/shared/enum/cell-template.enum'; import { DimlessPipe } from '~/app/shared/pipes/dimless.pipe'; import { IscsiBackstorePipe } from '~/app/shared/pipes/iscsi-backstore.pipe'; @Component({ selector: 'cd-iscsi', templateUrl: './iscsi.component.html', styleUrls: ['./iscsi.component.scss'] }) export class IscsiComponent implements OnInit { @ViewChild('iscsiSparklineTpl', { static: true }) iscsiSparklineTpl: TemplateRef<any>; @ViewChild('iscsiPerSecondTpl', { static: true }) iscsiPerSecondTpl: TemplateRef<any>; @ViewChild('iscsiRelativeDateTpl', { static: true }) iscsiRelativeDateTpl: TemplateRef<any>; gateways: any[] = []; gatewaysColumns: any; images: any[] = []; imagesColumns: any; constructor( private iscsiService: IscsiService, private dimlessPipe: DimlessPipe, private iscsiBackstorePipe: IscsiBackstorePipe ) {} ngOnInit() { this.gatewaysColumns = [ { name: $localize`Name`, prop: 'name' }, { name: $localize`State`, prop: 'state', flexGrow: 1, cellTransformation: CellTemplate.badge, customTemplateConfig: { map: { up: { class: 'badge-success' }, down: { class: 'badge-danger' } } } }, { name: $localize`# Targets`, prop: 'num_targets' }, { name: $localize`# Sessions`, prop: 'num_sessions' } ]; this.imagesColumns = [ { name: $localize`Pool`, prop: 'pool' }, { name: $localize`Image`, prop: 'image' }, { name: $localize`Backstore`, prop: 'backstore', pipe: this.iscsiBackstorePipe }, { name: $localize`Read Bytes`, prop: 'stats_history.rd_bytes', cellTemplate: this.iscsiSparklineTpl }, { name: $localize`Write Bytes`, prop: 'stats_history.wr_bytes', cellTemplate: this.iscsiSparklineTpl }, { name: $localize`Read Ops`, prop: 'stats.rd', pipe: this.dimlessPipe, cellTemplate: this.iscsiPerSecondTpl }, { name: $localize`Write Ops`, prop: 'stats.wr', pipe: this.dimlessPipe, cellTemplate: this.iscsiPerSecondTpl }, { name: $localize`A/O Since`, prop: 'optimized_since', cellTemplate: this.iscsiRelativeDateTpl } ]; } refresh() { this.iscsiService.overview().subscribe((overview: object) => { this.gateways = overview['gateways']; this.images = overview['images']; this.images.map((image) => { if (image.stats_history) { image.stats_history.rd_bytes = image.stats_history.rd_bytes.map((i: any) => i[1]); image.stats_history.wr_bytes = image.stats_history.wr_bytes.map((i: any) => i[1]); } image.cdIsBinary = true; return image; }); }); } }
3,157
25.762712
92
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/mirror-health-color.pipe.spec.ts
import { MirrorHealthColorPipe } from './mirror-health-color.pipe'; describe('MirrorHealthColorPipe', () => { const pipe = new MirrorHealthColorPipe(); it('create an instance', () => { expect(pipe).toBeTruthy(); }); it('transforms "warning"', () => { expect(pipe.transform('warning')).toBe('badge badge-warning'); }); it('transforms "error"', () => { expect(pipe.transform('error')).toBe('badge badge-danger'); }); it('transforms "success"', () => { expect(pipe.transform('success')).toBe('badge badge-success'); }); it('transforms others', () => { expect(pipe.transform('abc')).toBe('badge badge-info'); }); });
661
24.461538
67
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/mirror-health-color.pipe.ts
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'mirrorHealthColor' }) export class MirrorHealthColorPipe implements PipeTransform { transform(value: any): any { if (value === 'warning') { return 'badge badge-warning'; } else if (value === 'error') { return 'badge badge-danger'; } else if (value === 'success') { return 'badge badge-success'; } return 'badge badge-info'; } }
441
23.555556
61
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/mirroring.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterModule } from '@angular/router'; import { NgbNavModule, NgbProgressbarModule, NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap'; import { SharedModule } from '~/app/shared/shared.module'; import { BootstrapCreateModalComponent } from './bootstrap-create-modal/bootstrap-create-modal.component'; import { BootstrapImportModalComponent } from './bootstrap-import-modal/bootstrap-import-modal.component'; import { DaemonListComponent } from './daemon-list/daemon-list.component'; import { ImageListComponent } from './image-list/image-list.component'; import { MirrorHealthColorPipe } from './mirror-health-color.pipe'; import { OverviewComponent } from './overview/overview.component'; import { PoolEditModeModalComponent } from './pool-edit-mode-modal/pool-edit-mode-modal.component'; import { PoolEditPeerModalComponent } from './pool-edit-peer-modal/pool-edit-peer-modal.component'; import { PoolListComponent } from './pool-list/pool-list.component'; @NgModule({ imports: [ CommonModule, SharedModule, NgbNavModule, RouterModule, FormsModule, ReactiveFormsModule, NgbProgressbarModule, NgbTooltipModule ], declarations: [ BootstrapCreateModalComponent, BootstrapImportModalComponent, DaemonListComponent, ImageListComponent, OverviewComponent, PoolEditModeModalComponent, PoolEditPeerModalComponent, PoolListComponent, MirrorHealthColorPipe ], exports: [OverviewComponent] }) export class MirroringModule {}
1,666
36.886364
106
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/bootstrap-create-modal/bootstrap-create-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container i18n class="modal-title">Create Bootstrap Token</ng-container> <ng-container class="modal-content"> <form name="createBootstrapForm" class="form" #formDir="ngForm" [formGroup]="createBootstrapForm" novalidate> <div class="modal-body"> <p> <ng-container i18n>To create a bootstrap token which can be imported by a peer site cluster, provide the local site's name, select which pools will have mirroring enabled, and click&nbsp; <kbd>Generate</kbd>.</ng-container> </p> <div class="form-group"> <label class="col-form-label required" for="siteName" i18n>Site Name</label> <input class="form-control" type="text" placeholder="Name..." i18n-placeholder id="siteName" name="siteName" formControlName="siteName" autofocus> <span *ngIf="createBootstrapForm.showError('siteName', formDir, 'required')" class="invalid-feedback" i18n>This field is required.</span> </div> <div class="form-group" formGroupName="pools"> <label class="col-form-label required" for="pools" i18n>Pools</label> <div class="custom-control custom-checkbox" *ngFor="let pool of pools"> <input type="checkbox" class="custom-control-input" id="{{ pool.name }}" name="{{ pool.name }}" formControlName="{{ pool.name }}"> <label class="custom-control-label" for="{{ pool.name }}">{{ pool.name }}</label> </div> <span *ngIf="createBootstrapForm.showError('pools', formDir, 'requirePool')" class="invalid-feedback" i18n>At least one pool is required.</span> </div> <cd-submit-button class="mb-4 float-end" i18n [form]="createBootstrapForm" (submitAction)="generate()">Generate</cd-submit-button> <div class="form-group"> <label class="col-form-label" for="token"> <span i18n>Token</span> </label> <textarea class="form-control resize-vertical" placeholder="Generated token..." i18n-placeholder id="token" formControlName="token" readonly> </textarea> </div> <cd-copy-2-clipboard-button class="float-end" source="token"> </cd-copy-2-clipboard-button> </div> <div class="modal-footer"> <cd-back-button (backAction)="activeModal.close()" name="Close" i18n-name> </cd-back-button> </div> </form> </ng-container> </cd-modal>
3,171
35.045455
86
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/bootstrap-create-modal/bootstrap-create-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FormHelper } from '~/testing/unit-test-helper'; import { BootstrapCreateModalComponent } from './bootstrap-create-modal.component'; describe('BootstrapCreateModalComponent', () => { let component: BootstrapCreateModalComponent; let fixture: ComponentFixture<BootstrapCreateModalComponent>; let notificationService: NotificationService; let rbdMirroringService: RbdMirroringService; let formHelper: FormHelper; configureTestBed({ declarations: [BootstrapCreateModalComponent], imports: [ HttpClientTestingModule, ReactiveFormsModule, RouterTestingModule, SharedModule, ToastrModule.forRoot() ], providers: [NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(BootstrapCreateModalComponent); component = fixture.componentInstance; component.siteName = 'site-A'; notificationService = TestBed.inject(NotificationService); spyOn(notificationService, 'show').and.stub(); rbdMirroringService = TestBed.inject(RbdMirroringService); formHelper = new FormHelper(component.createBootstrapForm); spyOn(rbdMirroringService, 'getSiteName').and.callFake(() => of({ site_name: 'site-A' })); spyOn(rbdMirroringService, 'subscribeSummary').and.callFake((call) => of({ content_data: { pools: [ { name: 'pool1', mirror_mode: 'disabled' }, { name: 'pool2', mirror_mode: 'disabled' }, { name: 'pool3', mirror_mode: 'disabled' } ] } }).subscribe(call) ); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('generate token', () => { beforeEach(() => { spyOn(rbdMirroringService, 'refresh').and.stub(); spyOn(component.activeModal, 'close').and.callThrough(); fixture.detectChanges(); }); afterEach(() => { expect(rbdMirroringService.getSiteName).toHaveBeenCalledTimes(1); expect(rbdMirroringService.subscribeSummary).toHaveBeenCalledTimes(1); expect(rbdMirroringService.refresh).toHaveBeenCalledTimes(1); }); it('should generate a bootstrap token', () => { spyOn(rbdMirroringService, 'setSiteName').and.callFake(() => of({ site_name: 'new-site-A' })); spyOn(rbdMirroringService, 'updatePool').and.callFake(() => of({})); spyOn(rbdMirroringService, 'createBootstrapToken').and.callFake(() => of({ token: 'token' })); component.createBootstrapForm.patchValue({ siteName: 'new-site-A', pools: { pool1: true, pool3: true } }); component.generate(); expect(rbdMirroringService.setSiteName).toHaveBeenCalledWith('new-site-A'); expect(rbdMirroringService.updatePool).toHaveBeenCalledWith('pool1', { mirror_mode: 'image' }); expect(rbdMirroringService.updatePool).toHaveBeenCalledWith('pool3', { mirror_mode: 'image' }); expect(rbdMirroringService.createBootstrapToken).toHaveBeenCalledWith('pool3'); expect(component.createBootstrapForm.getValue('token')).toBe('token'); }); }); describe('form validation', () => { beforeEach(() => { fixture.detectChanges(); }); it('should require a site name', () => { formHelper.expectErrorChange('siteName', '', 'required'); }); it('should require at least one pool', () => { formHelper.expectError(component.createBootstrapForm.get('pools'), 'requirePool'); }); }); });
4,091
34.894737
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/bootstrap-create-modal/bootstrap-create-modal.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { concat, forkJoin, Subscription } from 'rxjs'; import { last, tap } from 'rxjs/operators'; import { Pool } from '~/app/ceph/pool/pool'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; @Component({ selector: 'cd-bootstrap-create-modal', templateUrl: './bootstrap-create-modal.component.html', styleUrls: ['./bootstrap-create-modal.component.scss'] }) export class BootstrapCreateModalComponent implements OnDestroy, OnInit { siteName: string; pools: any[] = []; token: string; subs: Subscription; createBootstrapForm: CdFormGroup; constructor( public activeModal: NgbActiveModal, private rbdMirroringService: RbdMirroringService, private taskWrapper: TaskWrapperService ) { this.createForm(); } createForm() { this.createBootstrapForm = new CdFormGroup({ siteName: new FormControl('', { validators: [Validators.required] }), pools: new FormGroup( {}, { validators: [this.validatePools()] } ), token: new FormControl('', {}) }); } ngOnInit() { this.createBootstrapForm.get('siteName').setValue(this.siteName); this.rbdMirroringService.getSiteName().subscribe((response: any) => { this.createBootstrapForm.get('siteName').setValue(response.site_name); }); this.subs = this.rbdMirroringService.subscribeSummary((data) => { const pools = data.content_data.pools; this.pools = pools.reduce((acc: any[], pool: Pool) => { acc.push({ name: pool['name'], mirror_mode: pool['mirror_mode'] }); return acc; }, []); const poolsControl = this.createBootstrapForm.get('pools') as FormGroup; _.each(this.pools, (pool) => { const poolName = pool['name']; const mirroring_disabled = pool['mirror_mode'] === 'disabled'; const control = poolsControl.controls[poolName]; if (control) { if (mirroring_disabled && control.disabled) { control.enable(); } else if (!mirroring_disabled && control.enabled) { control.disable(); control.setValue(true); } } else { poolsControl.addControl( poolName, new FormControl({ value: !mirroring_disabled, disabled: !mirroring_disabled }) ); } }); }); } ngOnDestroy() { if (this.subs) { this.subs.unsubscribe(); } } validatePools(): ValidatorFn { return (poolsControl: FormGroup): { [key: string]: any } => { let checkedCount = 0; _.each(poolsControl.controls, (control) => { if (control.value === true) { ++checkedCount; } }); if (checkedCount > 0) { return null; } return { requirePool: true }; }; } generate() { this.createBootstrapForm.get('token').setValue(''); let bootstrapPoolName = ''; const poolNames: string[] = []; const poolsControl = this.createBootstrapForm.get('pools') as FormGroup; _.each(poolsControl.controls, (control, poolName) => { if (control.value === true) { bootstrapPoolName = poolName; if (!control.disabled) { poolNames.push(poolName); } } }); const poolModeRequest = { mirror_mode: 'image' }; const apiActionsObs = concat( this.rbdMirroringService.setSiteName(this.createBootstrapForm.getValue('siteName')), forkJoin( poolNames.map((poolName) => this.rbdMirroringService.updatePool(poolName, poolModeRequest)) ), this.rbdMirroringService .createBootstrapToken(bootstrapPoolName) .pipe(tap((data: any) => this.createBootstrapForm.get('token').setValue(data['token']))) ).pipe(last()); const finishHandler = () => { this.rbdMirroringService.refresh(); this.createBootstrapForm.setErrors({ cdSubmitButton: true }); }; const taskObs = this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/mirroring/bootstrap/create', {}), call: apiActionsObs }); taskObs.subscribe({ error: finishHandler, complete: finishHandler }); } }
4,646
29.175325
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/bootstrap-import-modal/bootstrap-import-modal.component.html
<cd-modal [modalRef]="activeModal"> <ng-container i18n class="modal-title">Import Bootstrap Token</ng-container> <ng-container class="modal-content"> <form name="importBootstrapForm" class="form" #formDir="ngForm" [formGroup]="importBootstrapForm" novalidate> <div class="modal-body"> <p> <ng-container i18n>To import a bootstrap token which was created by a peer site cluster, provide the local site's name, select which pools will have mirroring enabled, provide the generated token, and click&nbsp;<kbd>Import</kbd>.</ng-container> </p> <div class="form-group"> <label class="col-form-label required" for="siteName" i18n>Site Name</label> <input class="form-control" type="text" placeholder="Name..." i18n-placeholder id="siteName" name="siteName" formControlName="siteName" autofocus> <span *ngIf="importBootstrapForm.showError('siteName', formDir, 'required')" class="invalid-feedback" i18n>This field is required.</span> </div> <div class="form-group"> <label class="col-form-label" for="direction"> <span i18n>Direction</span> </label> <select id="direction" name="direction" class="form-control" formControlName="direction"> <option *ngFor="let direction of directions" [value]="direction.key">{{ direction.desc }}</option> </select> </div> <div class="form-group" formGroupName="pools"> <label class="col-form-label required" for="pools" i18n>Pools</label> <div class="custom-control custom-checkbox" *ngFor="let pool of pools"> <input type="checkbox" class="custom-control-input" id="{{ pool.name }}" name="{{ pool.name }}" formControlName="{{ pool.name }}"> <label class="custom-control-label" for="{{ pool.name }}">{{ pool.name }}</label> </div> <span *ngIf="importBootstrapForm.showError('pools', formDir, 'requirePool')" class="invalid-feedback" i18n>At least one pool is required.</span> </div> <div class="form-group"> <label class="col-form-label required" for="token" i18n>Token</label> <textarea class="form-control resize-vertical" placeholder="Generated token..." i18n-placeholder id="token" formControlName="token"> </textarea> <span *ngIf="importBootstrapForm.showError('token', formDir, 'required')" class="invalid-feedback" i18n>This field is required.</span> <span *ngIf="importBootstrapForm.showError('token', formDir, 'invalidToken')" class="invalid-feedback" i18n>The token is invalid.</span> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="import()" [form]="importBootstrapForm" [submitText]="actionLabels.SUBMIT"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
3,686
37.010309
88
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/bootstrap-import-modal/bootstrap-import-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FormHelper } from '~/testing/unit-test-helper'; import { BootstrapImportModalComponent } from './bootstrap-import-modal.component'; describe('BootstrapImportModalComponent', () => { let component: BootstrapImportModalComponent; let fixture: ComponentFixture<BootstrapImportModalComponent>; let notificationService: NotificationService; let rbdMirroringService: RbdMirroringService; let formHelper: FormHelper; configureTestBed({ declarations: [BootstrapImportModalComponent], imports: [ HttpClientTestingModule, ReactiveFormsModule, RouterTestingModule, SharedModule, ToastrModule.forRoot() ], providers: [NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(BootstrapImportModalComponent); component = fixture.componentInstance; component.siteName = 'site-A'; notificationService = TestBed.inject(NotificationService); spyOn(notificationService, 'show').and.stub(); rbdMirroringService = TestBed.inject(RbdMirroringService); formHelper = new FormHelper(component.importBootstrapForm); spyOn(rbdMirroringService, 'getSiteName').and.callFake(() => of({ site_name: 'site-A' })); spyOn(rbdMirroringService, 'subscribeSummary').and.callFake((call) => of({ content_data: { pools: [ { name: 'pool1', mirror_mode: 'disabled' }, { name: 'pool2', mirror_mode: 'disabled' }, { name: 'pool3', mirror_mode: 'disabled' } ] } }).subscribe(call) ); }); it('should import', () => { expect(component).toBeTruthy(); }); describe('import token', () => { beforeEach(() => { spyOn(rbdMirroringService, 'refresh').and.stub(); spyOn(component.activeModal, 'close').and.callThrough(); fixture.detectChanges(); }); afterEach(() => { expect(rbdMirroringService.getSiteName).toHaveBeenCalledTimes(1); expect(rbdMirroringService.subscribeSummary).toHaveBeenCalledTimes(1); expect(rbdMirroringService.refresh).toHaveBeenCalledTimes(1); }); it('should generate a bootstrap token', () => { spyOn(rbdMirroringService, 'setSiteName').and.callFake(() => of({ site_name: 'new-site-A' })); spyOn(rbdMirroringService, 'updatePool').and.callFake(() => of({})); spyOn(rbdMirroringService, 'importBootstrapToken').and.callFake(() => of({ token: 'token' })); component.importBootstrapForm.patchValue({ siteName: 'new-site-A', pools: { pool1: true, pool3: true }, token: 'e30=' }); component.import(); expect(rbdMirroringService.setSiteName).toHaveBeenCalledWith('new-site-A'); expect(rbdMirroringService.updatePool).toHaveBeenCalledWith('pool1', { mirror_mode: 'image' }); expect(rbdMirroringService.updatePool).toHaveBeenCalledWith('pool3', { mirror_mode: 'image' }); expect(rbdMirroringService.importBootstrapToken).toHaveBeenCalledWith( 'pool1', 'rx-tx', 'e30=' ); expect(rbdMirroringService.importBootstrapToken).toHaveBeenCalledWith( 'pool3', 'rx-tx', 'e30=' ); }); }); describe('form validation', () => { beforeEach(() => { fixture.detectChanges(); }); it('should require a site name', () => { formHelper.expectErrorChange('siteName', '', 'required'); }); it('should require at least one pool', () => { formHelper.expectError(component.importBootstrapForm.get('pools'), 'requirePool'); }); it('should require a token', () => { formHelper.expectErrorChange('token', '', 'required'); }); it('should verify token is base64-encoded JSON', () => { formHelper.expectErrorChange('token', 'VEVTVA==', 'invalidToken'); formHelper.expectErrorChange('token', 'e2RmYXNqZGZrbH0=', 'invalidToken'); }); }); });
4,552
33.492424
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/bootstrap-import-modal/bootstrap-import-modal.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormControl, FormGroup, ValidatorFn, Validators } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import _ from 'lodash'; import { concat, forkJoin, Observable, Subscription } from 'rxjs'; import { last } from 'rxjs/operators'; import { Pool } from '~/app/ceph/pool/pool'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; @Component({ selector: 'cd-bootstrap-import-modal', templateUrl: './bootstrap-import-modal.component.html', styleUrls: ['./bootstrap-import-modal.component.scss'] }) export class BootstrapImportModalComponent implements OnInit, OnDestroy { siteName: string; pools: any[] = []; token: string; subs: Subscription; importBootstrapForm: CdFormGroup; directions: Array<any> = [ { key: 'rx-tx', desc: 'Bidirectional' }, { key: 'rx', desc: 'Unidirectional (receive-only)' } ]; constructor( public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private rbdMirroringService: RbdMirroringService, private taskWrapper: TaskWrapperService ) { this.createForm(); } createForm() { this.importBootstrapForm = new CdFormGroup({ siteName: new FormControl('', { validators: [Validators.required] }), direction: new FormControl('rx-tx', {}), pools: new FormGroup( {}, { validators: [this.validatePools()] } ), token: new FormControl('', { validators: [Validators.required, this.validateToken()] }) }); } ngOnInit() { this.rbdMirroringService.getSiteName().subscribe((response: any) => { this.importBootstrapForm.get('siteName').setValue(response.site_name); }); this.subs = this.rbdMirroringService.subscribeSummary((data) => { const pools = data.content_data.pools; this.pools = pools.reduce((acc: any[], pool: Pool) => { acc.push({ name: pool['name'], mirror_mode: pool['mirror_mode'] }); return acc; }, []); const poolsControl = this.importBootstrapForm.get('pools') as FormGroup; _.each(this.pools, (pool) => { const poolName = pool['name']; const mirroring_disabled = pool['mirror_mode'] === 'disabled'; const control = poolsControl.controls[poolName]; if (control) { if (mirroring_disabled && control.disabled) { control.enable(); } else if (!mirroring_disabled && control.enabled) { control.disable(); control.setValue(true); } } else { poolsControl.addControl( poolName, new FormControl({ value: !mirroring_disabled, disabled: !mirroring_disabled }) ); } }); }); } ngOnDestroy() { if (this.subs) { this.subs.unsubscribe(); } } validatePools(): ValidatorFn { return (poolsControl: FormGroup): { [key: string]: any } => { let checkedCount = 0; _.each(poolsControl.controls, (control) => { if (control.value === true) { ++checkedCount; } }); if (checkedCount > 0) { return null; } return { requirePool: true }; }; } validateToken(): ValidatorFn { return (token: FormControl): { [key: string]: any } => { try { if (JSON.parse(atob(token.value))) { return null; } } catch (error) {} return { invalidToken: true }; }; } import() { const bootstrapPoolNames: string[] = []; const poolNames: string[] = []; const poolsControl = this.importBootstrapForm.get('pools') as FormGroup; _.each(poolsControl.controls, (control, poolName) => { if (control.value === true) { bootstrapPoolNames.push(poolName); if (!control.disabled) { poolNames.push(poolName); } } }); const poolModeRequest = { mirror_mode: 'image' }; let apiActionsObs: Observable<any> = concat( this.rbdMirroringService.setSiteName(this.importBootstrapForm.getValue('siteName')), forkJoin( poolNames.map((poolName) => this.rbdMirroringService.updatePool(poolName, poolModeRequest)) ) ); apiActionsObs = bootstrapPoolNames .reduce((obs, poolName) => { return concat( obs, this.rbdMirroringService.importBootstrapToken( poolName, this.importBootstrapForm.getValue('direction'), this.importBootstrapForm.getValue('token') ) ); }, apiActionsObs) .pipe(last()); const finishHandler = () => { this.rbdMirroringService.refresh(); this.importBootstrapForm.setErrors({ cdSubmitButton: true }); }; const taskObs = this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/mirroring/bootstrap/import', {}), call: apiActionsObs }); taskObs.subscribe({ error: finishHandler, complete: () => { finishHandler(); this.activeModal.close(); } }); } }
5,447
27.978723
99
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/daemon-list/daemon-list.component.html
<cd-table [data]="data" columnMode="flex" [columns]="columns" [autoReload]="-1" (fetchData)="refresh()" [status]="tableStatus"> </cd-table> <ng-template #healthTmpl let-row="row" let-value="value"> <span [ngClass]="row.health_color | mirrorHealthColor">{{ value }}</span> </ng-template>
366
25.214286
75
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/daemon-list/daemon-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { MirrorHealthColorPipe } from '../mirror-health-color.pipe'; import { DaemonListComponent } from './daemon-list.component'; describe('DaemonListComponent', () => { let component: DaemonListComponent; let fixture: ComponentFixture<DaemonListComponent>; configureTestBed({ declarations: [DaemonListComponent, MirrorHealthColorPipe], imports: [BrowserAnimationsModule, SharedModule, HttpClientTestingModule] }); beforeEach(() => { fixture = TestBed.createComponent(DaemonListComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,014
34
79
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/daemon-list/daemon-list.component.ts
import { Component, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { Subscription } from 'rxjs'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { TableStatusViewCache } from '~/app/shared/classes/table-status-view-cache'; import { CephShortVersionPipe } from '~/app/shared/pipes/ceph-short-version.pipe'; @Component({ selector: 'cd-mirroring-daemons', templateUrl: './daemon-list.component.html', styleUrls: ['./daemon-list.component.scss'] }) export class DaemonListComponent implements OnInit, OnDestroy { @ViewChild('healthTmpl', { static: true }) healthTmpl: TemplateRef<any>; subs: Subscription; data: []; columns: {}; tableStatus = new TableStatusViewCache(); constructor( private rbdMirroringService: RbdMirroringService, private cephShortVersionPipe: CephShortVersionPipe ) {} ngOnInit() { this.columns = [ { prop: 'instance_id', name: $localize`Instance`, flexGrow: 2 }, { prop: 'id', name: $localize`ID`, flexGrow: 2 }, { prop: 'server_hostname', name: $localize`Hostname`, flexGrow: 2 }, { prop: 'version', name: $localize`Version`, pipe: this.cephShortVersionPipe, flexGrow: 2 }, { prop: 'health', name: $localize`Health`, cellTemplate: this.healthTmpl, flexGrow: 1 } ]; this.subs = this.rbdMirroringService.subscribeSummary((data) => { this.data = data.content_data.daemons; this.tableStatus = new TableStatusViewCache(data.status); }); } ngOnDestroy(): void { this.subs.unsubscribe(); } refresh() { this.rbdMirroringService.refresh(); } }
1,712
26.190476
85
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/image-list/image-list.component.html
<nav ngbNav #nav="ngbNav" class="nav-tabs" cdStatefulTab="image-list"> <ng-container ngbNavItem="issues"> <a ngbNavLink i18n>Issues ({{ image_error.data.length }})</a> <ng-template ngbNavContent> <cd-table [data]="image_error.data" columnMode="flex" [columns]="image_error.columns" [autoReload]="-1" (fetchData)="refresh()" [status]="tableStatus"> </cd-table> </ng-template> </ng-container> <ng-container ngbNavItem="syncing"> <a ngbNavLink i18n>Syncing ({{ image_syncing.data.length }})</a> <ng-template ngbNavContent> <cd-table [data]="image_syncing.data" columnMode="flex" [columns]="image_syncing.columns" [autoReload]="-1" (fetchData)="refresh()" [status]="tableStatus"> </cd-table> </ng-template> </ng-container> <ng-container ngbNavItem="ready"> <a ngbNavLink i18n>Ready ({{ image_ready.data.length }})</a> <ng-template ngbNavContent> <cd-table [data]="image_ready.data" columnMode="flex" [columns]="image_ready.columns" [autoReload]="-1" (fetchData)="refresh()" [status]="tableStatus"> </cd-table> </ng-template> </ng-container> </nav> <div [ngbNavOutlet]="nav"></div> <ng-template #stateTmpl let-row="row" let-value="value"> <span [ngClass]="row.state_color | mirrorHealthColor">{{ value }}</span> </ng-template> <ng-template #progressTmpl let-row="row" let-value="value"> <div *ngIf="row.state === 'Replaying'"> </div> <div class="w-100 h-100 d-flex justify-content-center align-items-center"> <ngb-progressbar *ngIf="row.state === 'Replaying'" type="info" class="w-100" [value]="value" [showValue]="true"></ngb-progressbar> </div> </ng-template>
2,070
29.910448
76
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/image-list/image-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NgbNavModule, NgbProgressbarModule } from '@ng-bootstrap/ng-bootstrap'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { MirrorHealthColorPipe } from '../mirror-health-color.pipe'; import { ImageListComponent } from './image-list.component'; describe('ImageListComponent', () => { let component: ImageListComponent; let fixture: ComponentFixture<ImageListComponent>; configureTestBed({ declarations: [ImageListComponent, MirrorHealthColorPipe], imports: [ BrowserAnimationsModule, SharedModule, NgbNavModule, NgbProgressbarModule, HttpClientTestingModule ] }); beforeEach(() => { fixture = TestBed.createComponent(ImageListComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,161
30.405405
80
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/image-list/image-list.component.ts
import { Component, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { Subscription } from 'rxjs'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { TableStatusViewCache } from '~/app/shared/classes/table-status-view-cache'; @Component({ selector: 'cd-mirroring-images', templateUrl: './image-list.component.html', styleUrls: ['./image-list.component.scss'] }) export class ImageListComponent implements OnInit, OnDestroy { @ViewChild('stateTmpl', { static: true }) stateTmpl: TemplateRef<any>; @ViewChild('syncTmpl', { static: true }) syncTmpl: TemplateRef<any>; @ViewChild('progressTmpl', { static: true }) progressTmpl: TemplateRef<any>; subs: Subscription; image_error: Record<string, any> = { data: [], columns: {} }; image_syncing: Record<string, any> = { data: [], columns: {} }; image_ready: Record<string, any> = { data: [], columns: {} }; tableStatus = new TableStatusViewCache(); constructor(private rbdMirroringService: RbdMirroringService) {} ngOnInit() { this.image_error.columns = [ { prop: 'pool_name', name: $localize`Pool`, flexGrow: 2 }, { prop: 'name', name: $localize`Image`, flexGrow: 2 }, { prop: 'state', name: $localize`State`, cellTemplate: this.stateTmpl, flexGrow: 1 }, { prop: 'description', name: $localize`Issue`, flexGrow: 4 } ]; this.image_syncing.columns = [ { prop: 'pool_name', name: $localize`Pool`, flexGrow: 2 }, { prop: 'name', name: $localize`Image`, flexGrow: 2 }, { prop: 'state', name: $localize`State`, cellTemplate: this.stateTmpl, flexGrow: 1 }, { prop: 'syncing_percent', name: $localize`Progress`, cellTemplate: this.progressTmpl, flexGrow: 2 }, { prop: 'bytes_per_second', name: $localize`Bytes per second`, flexGrow: 2 }, { prop: 'entries_behind_primary', name: $localize`Entries behind primary`, flexGrow: 2 } ]; this.image_ready.columns = [ { prop: 'pool_name', name: $localize`Pool`, flexGrow: 2 }, { prop: 'name', name: $localize`Image`, flexGrow: 2 }, { prop: 'state', name: $localize`State`, cellTemplate: this.stateTmpl, flexGrow: 1 }, { prop: 'description', name: $localize`Description`, flexGrow: 4 } ]; this.subs = this.rbdMirroringService.subscribeSummary((data) => { this.image_error.data = data.content_data.image_error; this.image_syncing.data = data.content_data.image_syncing; this.image_ready.data = data.content_data.image_ready; this.tableStatus = new TableStatusViewCache(data.status); }); } ngOnDestroy(): void { this.subs.unsubscribe(); } refresh() { this.rbdMirroringService.refresh(); } }
2,910
28.11
94
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/overview/overview.component.html
<form name="rbdmirroringForm" #formDir="ngForm" [formGroup]="rbdmirroringForm" novalidate> <div class="row mb-3"> <div class="col-md-auto"> <label class="col-form-label" for="siteName" i18n>Site Name</label></div> <div class="col-sm-4 d-flex"> <input type="text" class="form-control" id="siteName" name="siteName" formControlName="siteName" [attr.disabled]="!editing ? true : null"> <button class="btn btn-light" id="editSiteName" (click)="updateSiteName()" [attr.title]="editing ? 'Save' : 'Edit'"> <i [ngClass]="icons.edit" *ngIf="!editing"></i> <i [ngClass]="icons.check" *ngIf="editing"></i> </button> <cd-copy-2-clipboard-button [source]="siteName" [byId]="false"> </cd-copy-2-clipboard-button> </div> <div class="col"> <cd-table-actions class="table-actions float-end" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> </div> </div> </form> <div class="row"> <div class="col-sm-6"> <legend i18n>Daemons</legend> <div> <cd-mirroring-daemons> </cd-mirroring-daemons> </div> </div> <div class="col-sm-6"> <legend i18n>Pools</legend> <div> <cd-mirroring-pools> </cd-mirroring-pools> </div> </div> </div> <div class="row"> <div class="col-md-12"> <legend i18n>Images</legend> <div> <cd-mirroring-images> </cd-mirroring-images> </div> </div> </div>
1,756
24.463768
55
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/overview/overview.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbNavModule, NgbProgressbarModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { DaemonListComponent } from '../daemon-list/daemon-list.component'; import { ImageListComponent } from '../image-list/image-list.component'; import { MirrorHealthColorPipe } from '../mirror-health-color.pipe'; import { PoolListComponent } from '../pool-list/pool-list.component'; import { OverviewComponent } from './overview.component'; describe('OverviewComponent', () => { let component: OverviewComponent; let fixture: ComponentFixture<OverviewComponent>; let rbdMirroringService: RbdMirroringService; configureTestBed({ declarations: [ DaemonListComponent, ImageListComponent, MirrorHealthColorPipe, OverviewComponent, PoolListComponent ], imports: [ BrowserAnimationsModule, SharedModule, NgbNavModule, NgbProgressbarModule, HttpClientTestingModule, RouterTestingModule, ReactiveFormsModule, ToastrModule.forRoot() ] }); beforeEach(() => { fixture = TestBed.createComponent(OverviewComponent); component = fixture.componentInstance; rbdMirroringService = TestBed.inject(RbdMirroringService); component.siteName = 'site-A'; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('edit site name', () => { beforeEach(() => { spyOn(rbdMirroringService, 'getSiteName').and.callFake(() => of({ site_name: 'site-A' })); spyOn(rbdMirroringService, 'refresh').and.stub(); fixture.detectChanges(); }); afterEach(() => { expect(rbdMirroringService.refresh).toHaveBeenCalledTimes(1); }); it('should call setSiteName', () => { component.editing = true; spyOn(rbdMirroringService, 'setSiteName').and.callFake(() => of({ site_name: 'new-site-A' })); component.rbdmirroringForm.patchValue({ siteName: 'new-site-A' }); component.updateSiteName(); expect(rbdMirroringService.setSiteName).toHaveBeenCalledWith('new-site-A'); }); }); });
2,709
32.875
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/overview/overview.component.ts
import { Component, OnDestroy, OnInit } from '@angular/core'; import { FormControl } from '@angular/forms'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { Subscription } from 'rxjs'; import { Pool } from '~/app/ceph/pool/pool'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { Icons } from '~/app/shared/enum/icons.enum'; import { ViewCacheStatus } from '~/app/shared/enum/view-cache-status.enum'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { BootstrapCreateModalComponent } from '../bootstrap-create-modal/bootstrap-create-modal.component'; import { BootstrapImportModalComponent } from '../bootstrap-import-modal/bootstrap-import-modal.component'; @Component({ selector: 'cd-mirroring', templateUrl: './overview.component.html', styleUrls: ['./overview.component.scss'] }) export class OverviewComponent implements OnInit, OnDestroy { rbdmirroringForm: CdFormGroup; permission: Permission; tableActions: CdTableAction[]; selection = new CdTableSelection(); modalRef: NgbModalRef; peersExist = true; siteName: any; status: ViewCacheStatus; private subs = new Subscription(); editing = false; icons = Icons; constructor( private authStorageService: AuthStorageService, private rbdMirroringService: RbdMirroringService, private modalService: ModalService, private taskWrapper: TaskWrapperService ) { this.permission = this.authStorageService.getPermissions().rbdMirroring; const createBootstrapAction: CdTableAction = { permission: 'update', icon: Icons.upload, click: () => this.createBootstrapModal(), name: $localize`Create Bootstrap Token`, canBePrimary: () => true, disable: () => false }; const importBootstrapAction: CdTableAction = { permission: 'update', icon: Icons.download, click: () => this.importBootstrapModal(), name: $localize`Import Bootstrap Token`, disable: () => false }; this.tableActions = [createBootstrapAction, importBootstrapAction]; } ngOnInit() { this.createForm(); this.subs.add(this.rbdMirroringService.startPolling()); this.subs.add( this.rbdMirroringService.subscribeSummary((data) => { this.status = data.content_data.status; this.peersExist = !!data.content_data.pools.find((o: Pool) => o['peer_uuids'].length > 0); }) ); this.rbdMirroringService.getSiteName().subscribe((response: any) => { this.siteName = response.site_name; this.rbdmirroringForm.get('siteName').setValue(this.siteName); }); } private createForm() { this.rbdmirroringForm = new CdFormGroup({ siteName: new FormControl({ value: '', disabled: true }) }); } ngOnDestroy(): void { this.subs.unsubscribe(); } updateSiteName() { if (this.editing) { const action = this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/mirroring/site_name/edit', {}), call: this.rbdMirroringService.setSiteName(this.rbdmirroringForm.getValue('siteName')) }); action.subscribe({ complete: () => { this.rbdMirroringService.refresh(); } }); } this.editing = !this.editing; } createBootstrapModal() { const initialState = { siteName: this.siteName }; this.modalRef = this.modalService.show(BootstrapCreateModalComponent, initialState); } importBootstrapModal() { const initialState = { siteName: this.siteName }; this.modalRef = this.modalService.show(BootstrapImportModalComponent, initialState); } }
4,151
33.032787
107
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/pool-edit-mode-modal/pool-edit-mode-modal.component.html
<cd-modal [modalRef]="activeModal" pageURL="mirroring"> <ng-container i18n class="modal-title">Edit pool mirror mode</ng-container> <ng-container class="modal-content"> <form name="editModeForm" class="form" #formDir="ngForm" [formGroup]="editModeForm" novalidate> <div class="modal-body"> <p> <ng-container i18n>To edit the mirror mode for pool&nbsp; <kbd>{{ poolName }}</kbd>, select a new mode from the list and click&nbsp; <kbd>Update</kbd>.</ng-container> </p> <div class="form-group"> <label class="col-form-label" for="mirrorMode"> <span i18n>Mode</span> </label> <select id="mirrorMode" name="mirrorMode" class="form-select" formControlName="mirrorMode"> <option *ngFor="let mirrorMode of mirrorModes" [value]="mirrorMode.id">{{ mirrorMode.name }}</option> </select> <span class="invalid-feedback" *ngIf="editModeForm.showError('mirrorMode', formDir, 'cannotDisable')" i18n>Peer clusters must be removed prior to disabling mirror.</span> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="update()" [form]="editModeForm" [submitText]="actionLabels.UPDATE"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
1,598
34.533333
88
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/pool-edit-mode-modal/pool-edit-mode-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { ActivatedRoute } from '@angular/router'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { ActivatedRouteStub } from '~/testing/activated-route-stub'; import { configureTestBed, FormHelper } from '~/testing/unit-test-helper'; import { PoolEditModeModalComponent } from './pool-edit-mode-modal.component'; describe('PoolEditModeModalComponent', () => { let component: PoolEditModeModalComponent; let fixture: ComponentFixture<PoolEditModeModalComponent>; let notificationService: NotificationService; let rbdMirroringService: RbdMirroringService; let formHelper: FormHelper; let activatedRoute: ActivatedRouteStub; configureTestBed({ declarations: [PoolEditModeModalComponent], imports: [ HttpClientTestingModule, ReactiveFormsModule, RouterTestingModule, SharedModule, ToastrModule.forRoot() ], providers: [ NgbActiveModal, { provide: ActivatedRoute, useValue: new ActivatedRouteStub({ pool_name: 'somePool' }) } ] }); beforeEach(() => { fixture = TestBed.createComponent(PoolEditModeModalComponent); component = fixture.componentInstance; component.poolName = 'somePool'; notificationService = TestBed.inject(NotificationService); spyOn(notificationService, 'show').and.stub(); rbdMirroringService = TestBed.inject(RbdMirroringService); activatedRoute = <ActivatedRouteStub>TestBed.inject(ActivatedRoute); formHelper = new FormHelper(component.editModeForm); fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('update pool mode', () => { beforeEach(() => { spyOn(component.activeModal, 'close').and.callThrough(); }); it('should call updatePool', () => { activatedRoute.setParams({ pool_name: 'somePool' }); spyOn(rbdMirroringService, 'updatePool').and.callFake(() => of('')); component.editModeForm.patchValue({ mirrorMode: 'disabled' }); component.update(); expect(rbdMirroringService.updatePool).toHaveBeenCalledWith('somePool', { mirror_mode: 'disabled' }); }); }); describe('form validation', () => { it('should prevent disabling mirroring if peers exist', () => { component.peerExists = true; formHelper.expectErrorChange('mirrorMode', 'disabled', 'cannotDisable'); }); }); });
2,965
33.091954
81
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/pool-edit-mode-modal/pool-edit-mode-modal.component.ts
import { Location } from '@angular/common'; import { Component, OnDestroy, OnInit } from '@angular/core'; import { AbstractControl, FormControl, Validators } from '@angular/forms'; import { ActivatedRoute } from '@angular/router'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { Subscription } from 'rxjs'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { PoolEditModeResponseModel } from './pool-edit-mode-response.model'; @Component({ selector: 'cd-pool-edit-mode-modal', templateUrl: './pool-edit-mode-modal.component.html', styleUrls: ['./pool-edit-mode-modal.component.scss'] }) export class PoolEditModeModalComponent implements OnInit, OnDestroy { poolName: string; subs: Subscription; editModeForm: CdFormGroup; bsConfig = { containerClass: 'theme-default' }; pattern: string; response: PoolEditModeResponseModel; peerExists = false; mirrorModes: Array<{ id: string; name: string }> = [ { id: 'disabled', name: $localize`Disabled` }, { id: 'pool', name: $localize`Pool` }, { id: 'image', name: $localize`Image` } ]; constructor( public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private rbdMirroringService: RbdMirroringService, private taskWrapper: TaskWrapperService, private route: ActivatedRoute, private location: Location ) { this.createForm(); } createForm() { this.editModeForm = new CdFormGroup({ mirrorMode: new FormControl('', { validators: [Validators.required, this.validateMode.bind(this)] }) }); } ngOnInit() { this.route.params.subscribe((params: { pool_name: string }) => { this.poolName = params.pool_name; }); this.pattern = `${this.poolName}`; this.rbdMirroringService.getPool(this.poolName).subscribe((resp: PoolEditModeResponseModel) => { this.setResponse(resp); }); this.subs = this.rbdMirroringService.subscribeSummary((data) => { this.peerExists = false; const poolData = data.content_data.pools; const pool = poolData.find((o: any) => this.poolName === o['name']); this.peerExists = pool && pool['peer_uuids'].length; }); } ngOnDestroy(): void { this.subs.unsubscribe(); } validateMode(control: AbstractControl) { if (control.value === 'disabled' && this.peerExists) { return { cannotDisable: { value: control.value } }; } return null; } setResponse(response: PoolEditModeResponseModel) { this.editModeForm.get('mirrorMode').setValue(response.mirror_mode); } update() { const request = new PoolEditModeResponseModel(); request.mirror_mode = this.editModeForm.getValue('mirrorMode'); const action = this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/mirroring/pool/edit', { pool_name: this.poolName }), call: this.rbdMirroringService.updatePool(this.poolName, request) }); action.subscribe({ error: () => this.editModeForm.setErrors({ cdSubmitButton: true }), complete: () => { this.rbdMirroringService.refresh(); this.location.back(); } }); } }
3,482
30.098214
100
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/pool-edit-mode-modal/pool-edit-mode-response.model.ts
export class PoolEditModeResponseModel { mirror_mode: string; }
66
15.75
40
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/pool-edit-peer-modal/pool-edit-peer-modal.component.html
<cd-modal [modalRef]="activeModal"> <span class="modal-title" i18n>{mode, select, edit {Edit} other {Add}} pool mirror peer</span> <ng-container class="modal-content"> <form name="editPeerForm" class="form" #formDir="ngForm" [formGroup]="editPeerForm" novalidate> <div class="modal-body"> <p> <span i18n>{mode, select, edit {Edit} other {Add}} the pool mirror peer attributes for pool <kbd>{{ poolName }}</kbd> and click <kbd>Submit</kbd>.</span> </p> <div class="form-group"> <label class="col-form-label required" for="clusterName" i18n>Cluster Name</label> <input class="form-control" type="text" placeholder="Name..." i18n-placeholder id="clusterName" name="clusterName" formControlName="clusterName" autofocus> <span class="invalid-feedback" *ngIf="editPeerForm.showError('clusterName', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="editPeerForm.showError('clusterName', formDir, 'invalidClusterName')" i18n>The cluster name is not valid.</span> </div> <div class="form-group"> <label class="col-form-label required" for="clientID" i18n>CephX ID</label> <input class="form-control" type="text" placeholder="CephX ID..." i18n-placeholder id="clientID" name="clientID" formControlName="clientID"> <span class="invalid-feedback" *ngIf="editPeerForm.showError('clientID', formDir, 'required')" i18n>This field is required.</span> <span class="invalid-feedback" *ngIf="editPeerForm.showError('clientID', formDir, 'invalidClientID')" i18n>The CephX ID is not valid.</span> </div> <div class="form-group"> <label class="col-form-label" for="monAddr"> <span i18n>Monitor Addresses</span> </label> <input class="form-control" type="text" placeholder="Comma-delimited addresses..." i18n-placeholder id="monAddr" name="monAddr" formControlName="monAddr"> <span class="invalid-feedback" *ngIf="editPeerForm.showError('monAddr', formDir, 'invalidMonAddr')" i18n>The monitory address is not valid.</span> </div> <div class="form-group"> <label class="col-form-label" for="key"> <span i18n>CephX Key</span> </label> <input class="form-control" type="text" placeholder="Base64-encoded key..." i18n-placeholder id="key" name="key" formControlName="key"> <span class="invalid-feedback" *ngIf="editPeerForm.showError('key', formDir, 'invalidKey')" i18n>CephX key must be base64 encoded.</span> </div> </div> <div class="modal-footer"> <cd-form-button-panel (submitActionEvent)="update()" [form]="editPeerForm" [submitText]="actionLabels.SUBMIT"></cd-form-button-panel> </div> </form> </ng-container> </cd-modal>
3,722
35.861386
92
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/pool-edit-peer-modal/pool-edit-peer-modal.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import { of } from 'rxjs'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { NotificationService } from '~/app/shared/services/notification.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FormHelper } from '~/testing/unit-test-helper'; import { PoolEditPeerModalComponent } from './pool-edit-peer-modal.component'; import { PoolEditPeerResponseModel } from './pool-edit-peer-response.model'; describe('PoolEditPeerModalComponent', () => { let component: PoolEditPeerModalComponent; let fixture: ComponentFixture<PoolEditPeerModalComponent>; let notificationService: NotificationService; let rbdMirroringService: RbdMirroringService; let formHelper: FormHelper; configureTestBed({ declarations: [PoolEditPeerModalComponent], imports: [ HttpClientTestingModule, ReactiveFormsModule, RouterTestingModule, SharedModule, ToastrModule.forRoot() ], providers: [NgbActiveModal] }); beforeEach(() => { fixture = TestBed.createComponent(PoolEditPeerModalComponent); component = fixture.componentInstance; component.mode = 'add'; component.poolName = 'somePool'; notificationService = TestBed.inject(NotificationService); spyOn(notificationService, 'show').and.stub(); rbdMirroringService = TestBed.inject(RbdMirroringService); formHelper = new FormHelper(component.editPeerForm); }); it('should create', () => { expect(component).toBeTruthy(); }); describe('add pool peer', () => { beforeEach(() => { component.mode = 'add'; component.peerUUID = undefined; spyOn(rbdMirroringService, 'refresh').and.stub(); spyOn(component.activeModal, 'close').and.callThrough(); fixture.detectChanges(); }); afterEach(() => { expect(rbdMirroringService.refresh).toHaveBeenCalledTimes(1); expect(component.activeModal.close).toHaveBeenCalledTimes(1); }); it('should call addPeer', () => { spyOn(rbdMirroringService, 'addPeer').and.callFake(() => of('')); component.editPeerForm.patchValue({ clusterName: 'cluster', clientID: 'id', monAddr: 'mon_host', key: 'dGVzdA==' }); component.update(); expect(rbdMirroringService.addPeer).toHaveBeenCalledWith('somePool', { cluster_name: 'cluster', client_id: 'id', mon_host: 'mon_host', key: 'dGVzdA==' }); }); }); describe('edit pool peer', () => { beforeEach(() => { component.mode = 'edit'; component.peerUUID = 'somePeer'; const response = new PoolEditPeerResponseModel(); response.uuid = 'somePeer'; response.cluster_name = 'cluster'; response.client_id = 'id'; response.mon_host = '1.2.3.4:1234'; response.key = 'dGVzdA=='; spyOn(rbdMirroringService, 'getPeer').and.callFake(() => of(response)); spyOn(rbdMirroringService, 'refresh').and.stub(); spyOn(component.activeModal, 'close').and.callThrough(); fixture.detectChanges(); }); afterEach(() => { expect(rbdMirroringService.getPeer).toHaveBeenCalledWith('somePool', 'somePeer'); expect(rbdMirroringService.refresh).toHaveBeenCalledTimes(1); expect(component.activeModal.close).toHaveBeenCalledTimes(1); }); it('should call updatePeer', () => { spyOn(rbdMirroringService, 'updatePeer').and.callFake(() => of('')); component.update(); expect(rbdMirroringService.updatePeer).toHaveBeenCalledWith('somePool', 'somePeer', { cluster_name: 'cluster', client_id: 'id', mon_host: '1.2.3.4:1234', key: 'dGVzdA==' }); }); }); describe('form validation', () => { beforeEach(() => { fixture.detectChanges(); }); it('should validate cluster name', () => { formHelper.expectErrorChange('clusterName', '', 'required'); formHelper.expectErrorChange('clusterName', ' ', 'invalidClusterName'); }); it('should validate client ID', () => { formHelper.expectErrorChange('clientID', '', 'required'); formHelper.expectErrorChange('clientID', 'client.id', 'invalidClientID'); }); it('should validate monitor address', () => { formHelper.expectErrorChange('monAddr', '@', 'invalidMonAddr'); }); it('should validate key', () => { formHelper.expectErrorChange('key', '(', 'invalidKey'); }); }); });
4,848
31.543624
91
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/pool-edit-peer-modal/pool-edit-peer-modal.component.ts
import { Component, OnInit } from '@angular/core'; import { AbstractControl, FormControl, Validators } from '@angular/forms'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { ActionLabelsI18n } from '~/app/shared/constants/app.constants'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { PoolEditPeerResponseModel } from './pool-edit-peer-response.model'; @Component({ selector: 'cd-pool-edit-peer-modal', templateUrl: './pool-edit-peer-modal.component.html', styleUrls: ['./pool-edit-peer-modal.component.scss'] }) export class PoolEditPeerModalComponent implements OnInit { mode: string; poolName: string; peerUUID: string; editPeerForm: CdFormGroup; bsConfig = { containerClass: 'theme-default' }; pattern: string; response: PoolEditPeerResponseModel; constructor( public activeModal: NgbActiveModal, public actionLabels: ActionLabelsI18n, private rbdMirroringService: RbdMirroringService, private taskWrapper: TaskWrapperService ) { this.createForm(); } createForm() { this.editPeerForm = new CdFormGroup({ clusterName: new FormControl('', { validators: [Validators.required, this.validateClusterName] }), clientID: new FormControl('', { validators: [Validators.required, this.validateClientID] }), monAddr: new FormControl('', { validators: [this.validateMonAddr] }), key: new FormControl('', { validators: [this.validateKey] }) }); } ngOnInit() { this.pattern = `${this.poolName}/${this.peerUUID}`; if (this.mode === 'edit') { this.rbdMirroringService .getPeer(this.poolName, this.peerUUID) .subscribe((resp: PoolEditPeerResponseModel) => { this.setResponse(resp); }); } } validateClusterName(control: AbstractControl) { if (!control.value.match(/^[\w\-_]*$/)) { return { invalidClusterName: { value: control.value } }; } return undefined; } validateClientID(control: AbstractControl) { if (!control.value.match(/^(?!client\.)[\w\-_.]*$/)) { return { invalidClientID: { value: control.value } }; } return undefined; } validateMonAddr(control: AbstractControl) { if (!control.value.match(/^[,; ]*([\w.\-_\[\]]+(:[\d]+)?[,; ]*)*$/)) { return { invalidMonAddr: { value: control.value } }; } return undefined; } validateKey(control: AbstractControl) { try { if (control.value === '' || !!atob(control.value)) { return null; } } catch (error) {} return { invalidKey: { value: control.value } }; } setResponse(response: PoolEditPeerResponseModel) { this.response = response; this.editPeerForm.get('clusterName').setValue(response.cluster_name); this.editPeerForm.get('clientID').setValue(response.client_id); this.editPeerForm.get('monAddr').setValue(response.mon_host); this.editPeerForm.get('key').setValue(response.key); } update() { const request = new PoolEditPeerResponseModel(); request.cluster_name = this.editPeerForm.getValue('clusterName'); request.client_id = this.editPeerForm.getValue('clientID'); request.mon_host = this.editPeerForm.getValue('monAddr'); request.key = this.editPeerForm.getValue('key'); let action; if (this.mode === 'edit') { action = this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/mirroring/peer/edit', { pool_name: this.poolName }), call: this.rbdMirroringService.updatePeer(this.poolName, this.peerUUID, request) }); } else { action = this.taskWrapper.wrapTaskAroundCall({ task: new FinishedTask('rbd/mirroring/peer/add', { pool_name: this.poolName }), call: this.rbdMirroringService.addPeer(this.poolName, request) }); } action.subscribe({ error: () => this.editPeerForm.setErrors({ cdSubmitButton: true }), complete: () => { this.rbdMirroringService.refresh(); this.activeModal.close(); } }); } }
4,343
29.591549
88
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/pool-edit-peer-modal/pool-edit-peer-response.model.ts
export class PoolEditPeerResponseModel { cluster_name: string; client_id: string; mon_host: string; key: string; uuid: string; }
139
16.5
40
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/pool-list/pool-list.component.html
<cd-table [data]="data" columnMode="flex" [columns]="columns" identifier="name" forceIdentifier="true" [autoReload]="-1" (fetchData)="refresh()" selectionType="single" (updateSelection)="updateSelection($event)" [status]="tableStatus"> <cd-table-actions class="table-actions" [permission]="permission" [selection]="selection" [tableActions]="tableActions"> </cd-table-actions> </cd-table> <ng-template #healthTmpl let-row="row" let-value="value"> <span [ngClass]="row.health_color | mirrorHealthColor">{{ value }}</span> </ng-template> <ng-template #localTmpl> <span i18n i18n-ngbTooltip ngbTooltip="Local image count"># Local</span> </ng-template> <ng-template #remoteTmpl> <span i18n i18n-ngbTooltip ngbTooltip="Remote image count"># Remote</span> </ng-template> <router-outlet name="modal"></router-outlet>
1,029
29.294118
75
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/pool-list/pool-list.component.spec.ts
import { HttpClientTestingModule } from '@angular/common/http/testing'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { RouterTestingModule } from '@angular/router/testing'; import { ToastrModule } from 'ngx-toastr'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed } from '~/testing/unit-test-helper'; import { MirrorHealthColorPipe } from '../mirror-health-color.pipe'; import { PoolListComponent } from './pool-list.component'; describe('PoolListComponent', () => { let component: PoolListComponent; let fixture: ComponentFixture<PoolListComponent>; configureTestBed({ declarations: [PoolListComponent, MirrorHealthColorPipe], imports: [ BrowserAnimationsModule, SharedModule, HttpClientTestingModule, RouterTestingModule, ToastrModule.forRoot() ] }); beforeEach(() => { fixture = TestBed.createComponent(PoolListComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
1,188
30.289474
79
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/pool-list/pool-list.component.ts
import { Component, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { Router } from '@angular/router'; import { NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; import { Observable, Subscriber, Subscription } from 'rxjs'; import { RbdMirroringService } from '~/app/shared/api/rbd-mirroring.service'; import { TableStatusViewCache } from '~/app/shared/classes/table-status-view-cache'; import { CriticalConfirmationModalComponent } from '~/app/shared/components/critical-confirmation-modal/critical-confirmation-modal.component'; import { URLVerbs } from '~/app/shared/constants/app.constants'; import { Icons } from '~/app/shared/enum/icons.enum'; import { CdTableAction } from '~/app/shared/models/cd-table-action'; import { CdTableSelection } from '~/app/shared/models/cd-table-selection'; import { FinishedTask } from '~/app/shared/models/finished-task'; import { Permission } from '~/app/shared/models/permissions'; import { AuthStorageService } from '~/app/shared/services/auth-storage.service'; import { ModalService } from '~/app/shared/services/modal.service'; import { TaskWrapperService } from '~/app/shared/services/task-wrapper.service'; import { PoolEditPeerModalComponent } from '../pool-edit-peer-modal/pool-edit-peer-modal.component'; const BASE_URL = '/block/mirroring'; @Component({ selector: 'cd-mirroring-pools', templateUrl: './pool-list.component.html', styleUrls: ['./pool-list.component.scss'] }) export class PoolListComponent implements OnInit, OnDestroy { @ViewChild('healthTmpl', { static: true }) healthTmpl: TemplateRef<any>; @ViewChild('localTmpl', { static: true }) localTmpl: TemplateRef<any>; @ViewChild('remoteTmpl', { static: true }) remoteTmpl: TemplateRef<any>; subs: Subscription; permission: Permission; tableActions: CdTableAction[]; selection = new CdTableSelection(); modalRef: NgbModalRef; data: []; columns: {}; tableStatus = new TableStatusViewCache(); constructor( private authStorageService: AuthStorageService, private rbdMirroringService: RbdMirroringService, private modalService: ModalService, private taskWrapper: TaskWrapperService, private router: Router ) { this.data = []; this.permission = this.authStorageService.getPermissions().rbdMirroring; const editModeAction: CdTableAction = { permission: 'update', icon: Icons.edit, click: () => this.editModeModal(), name: $localize`Edit Mode`, canBePrimary: () => true }; const addPeerAction: CdTableAction = { permission: 'create', icon: Icons.add, name: $localize`Add Peer`, click: () => this.editPeersModal('add'), disable: () => !this.selection.first() || this.selection.first().mirror_mode === 'disabled', visible: () => !this.getPeerUUID(), canBePrimary: () => false }; const editPeerAction: CdTableAction = { permission: 'update', icon: Icons.exchange, name: $localize`Edit Peer`, click: () => this.editPeersModal('edit'), visible: () => !!this.getPeerUUID() }; const deletePeerAction: CdTableAction = { permission: 'delete', icon: Icons.destroy, name: $localize`Delete Peer`, click: () => this.deletePeersModal(), visible: () => !!this.getPeerUUID() }; this.tableActions = [editModeAction, addPeerAction, editPeerAction, deletePeerAction]; } ngOnInit() { this.columns = [ { prop: 'name', name: $localize`Name`, flexGrow: 2 }, { prop: 'mirror_mode', name: $localize`Mode`, flexGrow: 2 }, { prop: 'leader_id', name: $localize`Leader`, flexGrow: 2 }, { prop: 'image_local_count', name: $localize`# Local`, headerTemplate: this.localTmpl, flexGrow: 2 }, { prop: 'image_remote_count', name: $localize`# Remote`, headerTemplate: this.remoteTmpl, flexGrow: 2 }, { prop: 'health', name: $localize`Health`, cellTemplate: this.healthTmpl, flexGrow: 1 } ]; this.subs = this.rbdMirroringService.subscribeSummary((data) => { this.data = data.content_data.pools; this.tableStatus = new TableStatusViewCache(data.status); }); } ngOnDestroy(): void { this.subs.unsubscribe(); } refresh() { this.rbdMirroringService.refresh(); } editModeModal() { this.router.navigate([ BASE_URL, { outlets: { modal: [URLVerbs.EDIT, this.selection.first().name] } } ]); } editPeersModal(mode: string) { const initialState = { poolName: this.selection.first().name, mode: mode }; if (mode === 'edit') { initialState['peerUUID'] = this.getPeerUUID(); } this.modalRef = this.modalService.show(PoolEditPeerModalComponent, initialState); } deletePeersModal() { const poolName = this.selection.first().name; const peerUUID = this.getPeerUUID(); this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, { itemDescription: $localize`mirror peer`, itemNames: [`${poolName} (${peerUUID})`], submitActionObservable: () => new Observable((observer: Subscriber<any>) => { this.taskWrapper .wrapTaskAroundCall({ task: new FinishedTask('rbd/mirroring/peer/delete', { pool_name: poolName }), call: this.rbdMirroringService.deletePeer(poolName, peerUUID) }) .subscribe({ error: (resp) => observer.error(resp), complete: () => { this.rbdMirroringService.refresh(); observer.complete(); } }); }) }); } getPeerUUID(): any { const selection = this.selection.first(); const pool = this.data.find((o) => selection && selection.name === o['name']); if (pool && pool['peer_uuids']) { return pool['peer_uuids'][0]; } return undefined; } updateSelection(selection: CdTableSelection) { this.selection = selection; } }
6,112
31.343915
143
ts
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-configuration-form/rbd-configuration-form.component.html
<fieldset #cfgFormGroup [formGroup]="form.get('configuration')"> <legend i18n>RBD Configuration</legend> <div *ngFor="let section of rbdConfigurationService.sections" class="col-12"> <h4 class="cd-header"> <span (click)="toggleSectionVisibility(section.class)" class="collapsible"> {{ section.heading }} <i [ngClass]="!sectionVisibility[section.class] ? icons.addCircle : icons.minusCircle" aria-hidden="true"></i> </span> </h4> <div class="{{ section.class }}" [hidden]="!sectionVisibility[section.class]"> <div class="form-group row" *ngFor="let option of section.options"> <label class="cd-col-form-label" [for]="option.name">{{ option.displayName }}<cd-helper>{{ option.description }}</cd-helper></label> <div class="cd-col-form-input {{ section.heading }}"> <div class="input-group"> <ng-container [ngSwitch]="option.type"> <ng-container *ngSwitchCase="configurationType.milliseconds"> <input [id]="option.name" [name]="option.name" [formControlName]="option.name" type="text" class="form-control" [ngDataReady]="ngDataReady" cdMilliseconds> </ng-container> <ng-container *ngSwitchCase="configurationType.bps"> <input [id]="option.name" [name]="option.name" [formControlName]="option.name" type="text" class="form-control" defaultUnit="b" [ngDataReady]="ngDataReady" cdDimlessBinaryPerSecond> </ng-container> <ng-container *ngSwitchCase="configurationType.iops"> <input [id]="option.name" [name]="option.name" [formControlName]="option.name" type="text" class="form-control" [ngDataReady]="ngDataReady" cdIops> </ng-container> </ng-container> <button class="btn btn-light" type="button" data-toggle="button" [ngClass]="{'active': isDisabled(option.name)}" title="Remove the local configuration value. The parent configuration value will be inherited and used instead." i18n-title (click)="reset(option.name)"> <i [ngClass]="[icons.erase]" aria-hidden="true"></i> </button> </div> <span i18n class="invalid-feedback" *ngIf="form.showError('configuration.' + option.name, cfgFormGroup, 'min')">The minimum value is 0</span> </div> </div> </div> </div> </fieldset>
3,075
41.136986
132
html
null
ceph-main/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/rbd-configuration-form/rbd-configuration-form.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ReactiveFormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { ReplaySubject } from 'rxjs'; import { DirectivesModule } from '~/app/shared/directives/directives.module'; import { CdFormGroup } from '~/app/shared/forms/cd-form-group'; import { RbdConfigurationSourceField } from '~/app/shared/models/configuration'; import { DimlessBinaryPerSecondPipe } from '~/app/shared/pipes/dimless-binary-per-second.pipe'; import { FormatterService } from '~/app/shared/services/formatter.service'; import { RbdConfigurationService } from '~/app/shared/services/rbd-configuration.service'; import { SharedModule } from '~/app/shared/shared.module'; import { configureTestBed, FormHelper } from '~/testing/unit-test-helper'; import { RbdConfigurationFormComponent } from './rbd-configuration-form.component'; describe('RbdConfigurationFormComponent', () => { let component: RbdConfigurationFormComponent; let fixture: ComponentFixture<RbdConfigurationFormComponent>; let sections: any[]; let fh: FormHelper; configureTestBed({ imports: [ReactiveFormsModule, DirectivesModule, SharedModule], declarations: [RbdConfigurationFormComponent], providers: [RbdConfigurationService, FormatterService, DimlessBinaryPerSecondPipe] }); beforeEach(() => { fixture = TestBed.createComponent(RbdConfigurationFormComponent); component = fixture.componentInstance; component.form = new CdFormGroup({}, null); fh = new FormHelper(component.form); fixture.detectChanges(); sections = TestBed.inject(RbdConfigurationService).sections; }); it('should create', () => { expect(component).toBeTruthy(); }); it('should create all form fields mentioned in RbdConfiguration::OPTIONS', () => { /* Test form creation on a TypeScript level */ const actual = Object.keys((component.form.get('configuration') as CdFormGroup).controls); const expected = sections .map((section) => section.options) .reduce((a, b) => a.concat(b)) .map((option: Record<string, any>) => option.name); expect(actual).toEqual(expected); /* Test form creation on a template level */ const controlDebugElements = fixture.debugElement.queryAll(By.css('input.form-control')); expect(controlDebugElements.length).toBe(expected.length); controlDebugElements.forEach((element) => expect(element.nativeElement).toBeTruthy()); }); it('should only contain values of changed controls if submitted', () => { let values = {}; component.changes.subscribe((getDirtyValues: Function) => { values = getDirtyValues(); }); fh.setValue('configuration.rbd_qos_bps_limit', 0, true); fixture.detectChanges(); expect(values).toEqual({ rbd_qos_bps_limit: 0 }); }); describe('test loading of initial data for editing', () => { beforeEach(() => { component.initializeData = new ReplaySubject<any>(1); fixture.detectChanges(); component.ngOnInit(); }); it('should return dirty values without any units', () => { let dirtyValues = {}; component.changes.subscribe((getDirtyValues: Function) => { dirtyValues = getDirtyValues(); }); fh.setValue('configuration.rbd_qos_bps_limit', 55, true); fh.setValue('configuration.rbd_qos_iops_limit', 22, true); expect(dirtyValues['rbd_qos_bps_limit']).toBe(55); expect(dirtyValues['rbd_qos_iops_limit']).toBe(22); }); it('should load initial data into forms', () => { component.initializeData.next({ initialData: [ { name: 'rbd_qos_bps_limit', value: 55, source: 1 } ], sourceType: RbdConfigurationSourceField.pool }); expect(component.form.getValue('configuration.rbd_qos_bps_limit')).toEqual('55 B/s'); }); it('should not load initial data if the source is not the pool itself', () => { component.initializeData.next({ initialData: [ { name: 'rbd_qos_bps_limit', value: 55, source: RbdConfigurationSourceField.image }, { name: 'rbd_qos_iops_limit', value: 22, source: RbdConfigurationSourceField.global } ], sourceType: RbdConfigurationSourceField.pool }); expect(component.form.getValue('configuration.rbd_qos_iops_limit')).toEqual('0 IOPS'); expect(component.form.getValue('configuration.rbd_qos_bps_limit')).toEqual('0 B/s'); }); it('should not load initial data if the source is not the image itself', () => { component.initializeData.next({ initialData: [ { name: 'rbd_qos_bps_limit', value: 55, source: RbdConfigurationSourceField.pool }, { name: 'rbd_qos_iops_limit', value: 22, source: RbdConfigurationSourceField.global } ], sourceType: RbdConfigurationSourceField.image }); expect(component.form.getValue('configuration.rbd_qos_iops_limit')).toEqual('0 IOPS'); expect(component.form.getValue('configuration.rbd_qos_bps_limit')).toEqual('0 B/s'); }); it('should always have formatted results', () => { component.initializeData.next({ initialData: [ { name: 'rbd_qos_bps_limit', value: 55, source: RbdConfigurationSourceField.image }, { name: 'rbd_qos_iops_limit', value: 22, source: RbdConfigurationSourceField.image }, { name: 'rbd_qos_read_bps_limit', value: null, // incorrect type source: RbdConfigurationSourceField.image }, { name: 'rbd_qos_read_bps_limit', value: undefined, // incorrect type source: RbdConfigurationSourceField.image } ], sourceType: RbdConfigurationSourceField.image }); expect(component.form.getValue('configuration.rbd_qos_iops_limit')).toEqual('22 IOPS'); expect(component.form.getValue('configuration.rbd_qos_bps_limit')).toEqual('55 B/s'); expect(component.form.getValue('configuration.rbd_qos_read_bps_limit')).toEqual('0 B/s'); expect(component.form.getValue('configuration.rbd_qos_read_bps_limit')).toEqual('0 B/s'); }); }); it('should reset the corresponding form field correctly', () => { const fieldName = 'rbd_qos_bps_limit'; const getValue = () => component.form.get(`configuration.${fieldName}`).value; // Initialization fh.setValue(`configuration.${fieldName}`, 418, true); expect(getValue()).toBe(418); // Reset component.reset(fieldName); expect(getValue()).toBe(null); // Restore component.reset(fieldName); expect(getValue()).toBe(418); // Reset component.reset(fieldName); expect(getValue()).toBe(null); // Restore component.reset(fieldName); expect(getValue()).toBe(418); }); describe('should verify that getDirtyValues() returns correctly', () => { let data: any; beforeEach(() => { component.initializeData = new ReplaySubject<any>(1); fixture.detectChanges(); component.ngOnInit(); data = { initialData: [ { name: 'rbd_qos_bps_limit', value: 0, source: RbdConfigurationSourceField.image }, { name: 'rbd_qos_iops_limit', value: 0, source: RbdConfigurationSourceField.image }, { name: 'rbd_qos_read_bps_limit', value: 0, source: RbdConfigurationSourceField.image }, { name: 'rbd_qos_read_iops_limit', value: 0, source: RbdConfigurationSourceField.image }, { name: 'rbd_qos_read_iops_burst', value: 0, source: RbdConfigurationSourceField.image }, { name: 'rbd_qos_write_bps_burst', value: undefined, source: RbdConfigurationSourceField.global }, { name: 'rbd_qos_write_iops_burst', value: null, source: RbdConfigurationSourceField.global } ], sourceType: RbdConfigurationSourceField.image }; component.initializeData.next(data); }); it('should return an empty object', () => { expect(component.getDirtyValues()).toEqual({}); expect(component.getDirtyValues(true, RbdConfigurationSourceField.image)).toEqual({}); }); it('should return dirty values', () => { component.form.get('configuration.rbd_qos_write_bps_burst').markAsDirty(); expect(component.getDirtyValues()).toEqual({ rbd_qos_write_bps_burst: 0 }); component.form.get('configuration.rbd_qos_write_iops_burst').markAsDirty(); expect(component.getDirtyValues()).toEqual({ rbd_qos_write_iops_burst: 0, rbd_qos_write_bps_burst: 0 }); }); it('should also return all local values if they do not contain their initial values', () => { // Change value for all options data.initialData = data.initialData.map((o: Record<string, any>) => { o.value = 22; return o; }); // Mark some dirty ['rbd_qos_read_iops_limit', 'rbd_qos_write_bps_burst'].forEach((option) => { component.form.get(`configuration.${option}`).markAsDirty(); }); expect(component.getDirtyValues(true, RbdConfigurationSourceField.image)).toEqual({ rbd_qos_read_iops_limit: 0, rbd_qos_write_bps_burst: 0 }); }); it('should throw an error if used incorrectly', () => { expect(() => component.getDirtyValues(true)).toThrowError( /^ProgrammingError: If local values shall be included/ ); }); }); });
10,069
33.135593
97
ts