component.ts 9.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright 2017 The Kubernetes Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

15 16
import {HttpClient} from '@angular/common/http';
import {Component, OnInit} from '@angular/core';
S
Shu Muto 已提交
17
import {AbstractControl, FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';
S
Sebastian Florek 已提交
18
import {MatDialog} from '@angular/material/dialog';
19
import {ActivatedRoute} from '@angular/router';
S
Shu Muto 已提交
20 21 22 23 24 25 26 27 28
import {
  AppDeploymentSpec,
  EnvironmentVariable,
  Namespace,
  NamespaceList,
  PortMapping,
  Protocols,
  SecretList,
} from '@api/backendapi';
29
import {take} from 'rxjs/operators';
30 31 32 33 34 35 36 37 38 39

import {CreateService} from '../../../common/services/create/service';
import {HistoryService} from '../../../common/services/global/history';
import {NamespaceService} from '../../../common/services/global/namespace';

import {CreateNamespaceDialog} from './createnamespace/dialog';
import {CreateSecretDialog} from './createsecret/dialog';
import {DeployLabel} from './deploylabel/deploylabel';
import {validateUniqueName} from './validator/uniquename.validator';
import {FormValidators} from './validator/validators';
H
haijiao.yin 已提交
40 41 42 43

// Label keys for predefined labels
const APP_LABEL_KEY = 'k8s-app';

S
Shu Muto 已提交
44 45 46 47 48
@Component({
  selector: 'kd-create-from-form',
  templateUrl: './template.html',
  styleUrls: ['./style.scss'],
})
H
haijiao.yin 已提交
49
export class CreateFromFormComponent implements OnInit {
50 51
  readonly nameMaxLength = 24;

H
haijiao.yin 已提交
52 53 54 55 56 57 58 59
  showMoreOptions_ = false;
  namespaces: string[];
  protocols: string[];
  secrets: string[];
  isExternal = false;
  labelArr: DeployLabel[] = [];

  form: FormGroup;
60 61

  constructor(
S
Shu Muto 已提交
62 63 64 65 66 67
    private readonly namespace_: NamespaceService,
    private readonly create_: CreateService,
    private readonly history_: HistoryService,
    private readonly http_: HttpClient,
    private readonly route_: ActivatedRoute,
    private readonly fb_: FormBuilder,
68
    private readonly dialog_: MatDialog
S
Shu Muto 已提交
69
  ) {}
H
haijiao.yin 已提交
70 71 72

  ngOnInit(): void {
    this.form = this.fb_.group({
S
Shu Muto 已提交
73
      name: ['', Validators.compose([Validators.required, FormValidators.namePattern])],
H
haijiao.yin 已提交
74
      containerImage: ['', Validators.required],
S
Shu Muto 已提交
75
      replicas: [1, Validators.compose([Validators.required, FormValidators.isInteger])],
H
haijiao.yin 已提交
76
      description: [''],
S
Shu Muto 已提交
77
      namespace: [this.route_.snapshot.params.namespace || '', Validators.required],
H
haijiao.yin 已提交
78
      imagePullSecret: [''],
S
Shu Muto 已提交
79 80
      cpuRequirement: ['', Validators.compose([Validators.min(0), FormValidators.isInteger])],
      memoryRequirement: ['', Validators.compose([Validators.min(0), FormValidators.isInteger])],
H
haijiao.yin 已提交
81 82 83 84 85
      containerCommand: [''],
      containerCommandArgs: [''],
      runAsPrivileged: [false],
      portMappings: this.fb_.control([]),
      variables: this.fb_.control([]),
S
Shu Muto 已提交
86
      labels: this.fb_.control([]),
H
haijiao.yin 已提交
87
    });
S
Shu Muto 已提交
88
    this.labelArr = [new DeployLabel(APP_LABEL_KEY, '', false), new DeployLabel()];
H
haijiao.yin 已提交
89 90
    this.name.valueChanges.subscribe(v => {
      this.labelArr[0].value = v;
91
      this.labels.patchValue([{index: 0, value: v}]);
H
haijiao.yin 已提交
92 93 94 95 96 97 98
    });
    this.namespace.valueChanges.subscribe((namespace: string) => {
      this.name.clearAsyncValidators();
      this.name.setAsyncValidators(validateUniqueName(this.http_, namespace));
      this.name.updateValueAndValidity();
    });
    this.http_.get('api/v1/namespace').subscribe((result: NamespaceList) => {
99
      this.namespaces = result.namespaces.map((namespace: Namespace) => namespace.objectMeta.name);
H
haijiao.yin 已提交
100
      this.namespace.patchValue(
S
Shu Muto 已提交
101 102
        !this.namespace_.areMultipleNamespacesSelected()
          ? this.route_.snapshot.params.namespace || this.namespaces[0]
103
          : this.namespaces[0]
S
Shu Muto 已提交
104
      );
H
haijiao.yin 已提交
105
    });
S
Shu Muto 已提交
106 107 108
    this.http_
      .get('api/v1/appdeployment/protocols')
      .subscribe((protocols: Protocols) => (this.protocols = protocols.protocols));
H
haijiao.yin 已提交
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
  }

  get name(): AbstractControl {
    return this.form.get('name');
  }

  get containerImage(): AbstractControl {
    return this.form.get('containerImage');
  }

  get replicas(): AbstractControl {
    return this.form.get('replicas');
  }

  get description(): AbstractControl {
    return this.form.get('description');
  }

  get namespace(): AbstractControl {
    return this.form.get('namespace');
  }

  get imagePullSecret(): AbstractControl {
    return this.form.get('imagePullSecret');
  }

  get cpuRequirement(): AbstractControl {
    return this.form.get('cpuRequirement');
  }

  get memoryRequirement(): AbstractControl {
    return this.form.get('memoryRequirement');
  }

  get containerCommand(): AbstractControl {
    return this.form.get('containerCommand');
  }

  get containerCommandArgs(): AbstractControl {
    return this.form.get('containerCommandArgs');
  }

  get runAsPrivileged(): AbstractControl {
    return this.form.get('runAsPrivileged');
  }

  get portMappings(): FormArray {
    return this.form.get('portMappings') as FormArray;
  }

  get variables(): FormArray {
    return this.form.get('variables') as FormArray;
  }

  get labels(): FormArray {
    return this.form.get('labels') as FormArray;
  }

  changeExternal(isExternal: boolean): void {
    this.isExternal = isExternal;
  }

  resetImagePullSecret(): void {
    this.imagePullSecret.patchValue('');
  }
174 175

  isCreateDisabled(): boolean {
H
haijiao.yin 已提交
176
    return !this.form.valid || this.create_.isDeployDisabled();
177 178
  }

H
haijiao.yin 已提交
179
  getSecrets(): void {
180 181 182
    this.http_.get(`api/v1/secret/${this.namespace.value}`).subscribe((result: SecretList) => {
      this.secrets = result.secrets.map(secret => secret.objectMeta.name);
    });
H
haijiao.yin 已提交
183
  }
184 185

  cancel(): void {
186
    this.history_.goToPreviousState('overview');
187 188 189 190 191 192
  }

  areMultipleNamespacesSelected(): boolean {
    return this.namespace_.areMultipleNamespacesSelected();
  }

H
haijiao.yin 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
  /**
   * Returns true if more options have been enabled and should be shown, false otherwise.
   */
  isMoreOptionsEnabled(): boolean {
    return this.showMoreOptions_;
  }

  /**
   * Shows or hides more options.
   * @export
   */
  switchMoreOptions(): void {
    this.showMoreOptions_ = !this.showMoreOptions_;
  }

  handleNamespaceDialog(): void {
209
    const dialogData = {data: {namespaces: this.namespaces}};
H
haijiao.yin 已提交
210
    const dialogDef = this.dialog_.open(CreateNamespaceDialog, dialogData);
S
Shu Muto 已提交
211 212
    dialogDef
      .afterClosed()
213
      .pipe(take(1))
S
Shu Muto 已提交
214 215 216 217 218 219 220 221 222 223 224 225
      .subscribe(answer => {
        /**
         * Handles namespace dialog result. If namespace was created successfully then it
         * will be selected, otherwise first namespace will be selected.
         */
        if (answer) {
          this.namespaces.push(answer);
          this.namespace.patchValue(answer);
        } else {
          this.namespace.patchValue(this.namespaces[0]);
        }
      });
H
haijiao.yin 已提交
226 227 228
  }

  handleCreateSecretDialog(): void {
229
    const dialogData = {data: {namespace: this.namespace.value}};
H
haijiao.yin 已提交
230
    const dialogDef = this.dialog_.open(CreateSecretDialog, dialogData);
S
Shu Muto 已提交
231 232
    dialogDef
      .afterClosed()
233
      .pipe(take(1))
S
Shu Muto 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246
      .subscribe(response => {
        /**
         * Handles create secret dialog result. If the secret was created successfully, then it
         * will be selected,
         * otherwise None is selected.
         */
        if (response) {
          this.secrets.push(response);
          this.imagePullSecret.patchValue(response);
        } else {
          this.imagePullSecret.patchValue('');
        }
      });
H
haijiao.yin 已提交
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
  }

  /**
   * Returns true when the given port mapping is filled by the user, i.e., is not empty.
   */
  isPortMappingFilled(portMapping: PortMapping): boolean {
    return !!portMapping.port && !!portMapping.targetPort;
  }

  isVariableFilled(variable: EnvironmentVariable): boolean {
    return !!variable.name;
  }

  isNumber(value: string): boolean {
    return typeof value === 'number' && !isNaN(value);
  }

  /**
   * Converts array of DeployLabel to array of backend api label.
   */
  toBackendApiLabels(labels: DeployLabel[]): DeployLabel[] {
    labels[0].key = this.labelArr[0].key;
    labels[0].value = this.labelArr[0].value;
    return labels.filter((label: DeployLabel) => {
      return label.key.length !== 0 && label.value.length !== 0;
    });
  }

  deploy(): void {
    const portMappings = this.portMappings.value.portMappings || [];
    const variables = this.variables.value.variables || [];
    const labels = this.labels.value.labels || [];
    const spec: AppDeploymentSpec = {
      containerImage: this.containerImage.value,
281 282
      imagePullSecret: this.imagePullSecret.value ? this.imagePullSecret.value : null,
      containerCommand: this.containerCommand.value ? this.containerCommand.value : null,
M
Marcin Maciaszczyk 已提交
283
      containerCommandArgs: this.containerCommandArgs.value ? this.containerCommandArgs.value : null,
H
haijiao.yin 已提交
284 285 286 287 288 289 290
      isExternal: this.isExternal,
      name: this.name.value,
      description: this.description.value ? this.description.value : null,
      portMappings: portMappings.filter(this.isPortMappingFilled),
      variables: variables.filter(this.isVariableFilled),
      replicas: this.replicas.value,
      namespace: this.namespace.value,
291
      cpuRequirement: this.isNumber(this.cpuRequirement.value) ? this.cpuRequirement.value : null,
M
Marcin Maciaszczyk 已提交
292
      memoryRequirement: this.isNumber(this.memoryRequirement.value) ? `${this.memoryRequirement.value}Mi` : null,
H
haijiao.yin 已提交
293
      labels: this.toBackendApiLabels(labels),
S
Shu Muto 已提交
294
      runAsPrivileged: this.runAsPrivileged.value,
H
haijiao.yin 已提交
295 296
    };
    this.create_.deploy(spec);
297 298
  }
}