summaryrefslogtreecommitdiffstats
path: root/src/pybind/mgr/dashboard/frontend/src/app/ceph/block/mirroring/bootstrap-import-modal/bootstrap-import-modal.component.ts
blob: d79096f6be6fea81ef934a762028d0f4d2ddda8e (plain)
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
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();
      }
    });
  }
}