All files / src/app/ceph/block/rbd-snapshot-list rbd-snapshot-list.component.ts

68.03% Statements 100/147
75.38% Branches 49/65
40% Functions 14/35
72.09% Lines 93/129

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 2876x   6x 6x 6x 6x   6x 6x 6x 6x 6x     6x 6x 6x   6x 6x 6x 6x 6x 6x 6x 6x 6x 6x               6x   27x   6x   6x   6x   6x   6x     27x                 27x   1x 1x 1x       27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x   27x 27x 27x 27x 27x 27x 27x         27x 27x 27x 27x 27x     6x 24x                                                                         6x 3x 35x     3x 7x                 3x 7x   7x               6x 2x 2x 2x 2x 1x       1x   2x 2x                         6x 1x     6x 1x     6x                                                         6x 1x 1x 1x         1x                                   1x       6x                                 6x                     6x     6x  
import { Component, Input, OnChanges, OnInit, TemplateRef, ViewChild } from '@angular/core';
 
import { I18n } from '@ngx-translate/i18n-polyfill';
import * as moment from 'moment';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';
import { of } from 'rxjs';
 
import { RbdService } from '../../../shared/api/rbd.service';
import { ConfirmationModalComponent } from '../../../shared/components/confirmation-modal/confirmation-modal.component';
import { CriticalConfirmationModalComponent } from '../../../shared/components/critical-confirmation-modal/critical-confirmation-modal.component';
import { ActionLabelsI18n } from '../../../shared/constants/app.constants';
import { CellTemplate } from '../../../shared/enum/cell-template.enum';
import { CdTableAction } from '../../../shared/models/cd-table-action';
import { CdTableColumn } from '../../../shared/models/cd-table-column';
import { CdTableSelection } from '../../../shared/models/cd-table-selection';
import { ExecutingTask } from '../../../shared/models/executing-task';
import { FinishedTask } from '../../../shared/models/finished-task';
import { Permission } from '../../../shared/models/permissions';
import { CdDatePipe } from '../../../shared/pipes/cd-date.pipe';
import { DimlessBinaryPipe } from '../../../shared/pipes/dimless-binary.pipe';
import { AuthStorageService } from '../../../shared/services/auth-storage.service';
import { NotificationService } from '../../../shared/services/notification.service';
import { SummaryService } from '../../../shared/services/summary.service';
import { TaskListService } from '../../../shared/services/task-list.service';
import { TaskManagerService } from '../../../shared/services/task-manager.service';
import { RbdSnapshotFormComponent } from '../rbd-snapshot-form/rbd-snapshot-form.component';
import { RbdSnapshotActionsModel } from './rbd-snapshot-actions.model';
import { RbdSnapshotModel } from './rbd-snapshot.model';
 
@Component({
  selector: 'cd-rbd-snapshot-list',
  template: require('./rbd-snapshot-list.component.html'),
  styles: [],
  providers: [TaskListService]
})
export class RbdSnapshotListComponent implements OnInit, OnChanges {
  @Input()
  snapshots: RbdSnapshotModel[] = [];
  @Input()
  poolName: string;
  @Input()
  rbdName: string;
  @ViewChild('nameTpl')
  nameTpl: TemplateRef<any>;
  @ViewChild('protectTpl')
  protectTpl: TemplateRef<any>;
  @ViewChild('rollbackTpl')
  rollbackTpl: TemplateRef<any>;
 
  permission: Permission;
  selection = new CdTableSelection();
  tableActions: CdTableAction[];
 
  data: RbdSnapshotModel[];
 
  columns: CdTableColumn[];
 
  modalRef: BsModalRef;
 
  builders = {
    'rbd/snap/create': (metadata) => {
      const model = new RbdSnapshotModel();
      model.name = metadata['snapshot_name'];
      return model;
    }
  };
 
  constructor(
    private authStorageService: AuthStorageService,
    private modalService: BsModalService,
    private dimlessBinaryPipe: DimlessBinaryPipe,
    private cdDatePipe: CdDatePipe,
    private rbdService: RbdService,
    private taskManagerService: TaskManagerService,
    private notificationService: NotificationService,
    private summaryService: SummaryService,
    private taskListService: TaskListService,
    private i18n: I18n,
    private actionLabels: ActionLabelsI18n
  ) {
    this.permission = this.authStorageService.getPermissions().rbdImage;
    const actions = new RbdSnapshotActionsModel(this.i18n, this.actionLabels);
    actions.create.click = () => this.openCreateSnapshotModal();
    actions.rename.click = () => this.openEditSnapshotModal();
    actions.protect.click = () => this.toggleProtection();
    actions.unprotect.click = () => this.toggleProtection();
    const getImageUri = () =>
      this.selection.first() &&
      `${encodeURIComponent(this.poolName)}/${encodeURIComponent(
        this.rbdName
      )}/${encodeURIComponent(this.selection.first().name)}`;
    actions.clone.routerLink = () => `/block/rbd/clone/${getImageUri()}`;
    actions.copy.routerLink = () => `/block/rbd/copy/${getImageUri()}`;
    actions.rollback.click = () => this.rollbackModal();
    actions.deleteSnap.click = () => this.deleteSnapshotModal();
    this.tableActions = actions.ordering;
  }
 
  ngOnInit() {
    this.columns = [
      {
        name: this.i18n('Name'),
        prop: 'name',
        cellTransformation: CellTemplate.executing,
        flexGrow: 2
      },
      {
        name: this.i18n('Size'),
        prop: 'size',
        flexGrow: 1,
        cellClass: 'text-right',
        pipe: this.dimlessBinaryPipe
      },
      {
        name: this.i18n('Provisioned'),
        prop: 'disk_usage',
        flexGrow: 1,
        cellClass: 'text-right',
        pipe: this.dimlessBinaryPipe
      },
      {
        name: this.i18n('State'),
        prop: 'is_protected',
        flexGrow: 1,
        cellClass: 'text-center',
        cellTemplate: this.protectTpl
      },
      {
        name: this.i18n('Created'),
        prop: 'timestamp',
        flexGrow: 1,
        pipe: this.cdDatePipe
      }
    ];
  }
 
  ngOnChanges() {
    const itemFilter = (entry, task) => {
      return entry.name === task.metadata['snapshot_name'];
    };
 
    const taskFilter = (task) => {
      return (
        ['rbd/snap/create', 'rbd/snap/delete', 'rbd/snap/edit', 'rbd/snap/rollback'].includes(
          task.name
        ) &&
        this.poolName === task.metadata['pool_name'] &&
        this.rbdName === task.metadata['image_name']
      );
    };
 
    this.taskListService.init(
      () => of(this.snapshots),
      null,
      (items) => (this.data = items),
      () => (this.data = this.snapshots),
      taskFilter,
      itemFilter,
      this.builders
    );
  }
 
  private openSnapshotModal(taskName: string, snapName: string = null) {
    this.modalRef = this.modalService.show(RbdSnapshotFormComponent);
    this.modalRef.content.poolName = this.poolName;
    this.modalRef.content.imageName = this.rbdName;
    if (snapName) {
      this.modalRef.content.setEditing();
    } else {
      // Auto-create a name for the snapshot: <image_name>_<timestamp_ISO_8601>
      // https://en.wikipedia.org/wiki/ISO_8601
      snapName = `${this.rbdName}_${moment().toISOString(true)}`;
    }
    this.modalRef.content.setSnapName(snapName);
    this.modalRef.content.onSubmit.subscribe((snapshotName: string) => {
      const executingTask = new ExecutingTask();
      executingTask.name = taskName;
      executingTask.metadata = {
        image_name: this.rbdName,
        pool_name: this.poolName,
        snapshot_name: snapshotName
      };
      this.summaryService.addRunningTask(executingTask);
      this.ngOnChanges();
    });
  }
 
  openCreateSnapshotModal() {
    this.openSnapshotModal('rbd/snap/create');
  }
 
  openEditSnapshotModal() {
    this.openSnapshotModal('rbd/snap/edit', this.selection.first().name);
  }
 
  toggleProtection() {
    const snapshotName = this.selection.first().name;
    const isProtected = this.selection.first().is_protected;
    const finishedTask = new FinishedTask();
    finishedTask.name = 'rbd/snap/edit';
    finishedTask.metadata = {
      pool_name: this.poolName,
      image_name: this.rbdName,
      snapshot_name: snapshotName
    };
    this.rbdService
      .protectSnapshot(this.poolName, this.rbdName, snapshotName, !isProtected)
      .toPromise()
      .then(() => {
        const executingTask = new ExecutingTask();
        executingTask.name = finishedTask.name;
        executingTask.metadata = finishedTask.metadata;
        this.summaryService.addRunningTask(executingTask);
        this.ngOnChanges();
        this.taskManagerService.subscribe(
          finishedTask.name,
          finishedTask.metadata,
          (asyncFinishedTask: FinishedTask) => {
            this.notificationService.notifyTask(asyncFinishedTask);
          }
        );
      });
  }
 
  _asyncTask(task: string, taskName: string, snapshotName: string) {
    const finishedTask = new FinishedTask();
    finishedTask.name = taskName;
    finishedTask.metadata = {
      pool_name: this.poolName,
      image_name: this.rbdName,
      snapshot_name: snapshotName
    };
    this.rbdService[task](this.poolName, this.rbdName, snapshotName)
      .toPromise()
      .then(() => {
        const executingTask = new ExecutingTask();
        executingTask.name = finishedTask.name;
        executingTask.metadata = finishedTask.metadata;
        this.summaryService.addRunningTask(executingTask);
        this.modalRef.hide();
        this.ngOnChanges();
        this.taskManagerService.subscribe(
          executingTask.name,
          executingTask.metadata,
          (asyncFinishedTask: FinishedTask) => {
            this.notificationService.notifyTask(asyncFinishedTask);
          }
        );
      })
      .catch(() => {
        this.modalRef.content.stopLoadingSpinner();
      });
  }
 
  rollbackModal() {
    const snapshotName = this.selection.selected[0].name;
    const initialState = {
      titleText: this.i18n('RBD snapshot rollback'),
      buttonText: this.i18n('Rollback'),
      bodyTpl: this.rollbackTpl,
      bodyData: {
        snapName: `${this.poolName}/${this.rbdName}@${snapshotName}`
      },
      onSubmit: () => {
        this._asyncTask('rollbackSnapshot', 'rbd/snap/rollback', snapshotName);
      }
    };
 
    this.modalRef = this.modalService.show(ConfirmationModalComponent, { initialState });
  }
 
  deleteSnapshotModal() {
    const snapshotName = this.selection.selected[0].name;
    this.modalRef = this.modalService.show(CriticalConfirmationModalComponent, {
      initialState: {
        itemDescription: this.i18n('RBD snapshot'),
        itemNames: [snapshotName],
        submitAction: () => this._asyncTask('deleteSnapshot', 'rbd/snap/delete', snapshotName)
      }
    });
  }
 
  updateSelection(selection: CdTableSelection) {
    this.selection = selection;
  }
}