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 30 31 32 33 34 35 36 37 38

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 已提交
39 40 41 42

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

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

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

  form: FormGroup;
59 60

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

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

  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('');
  }
173 174

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

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

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

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

H
haijiao.yin 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
  /**
   * 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 {
208
    const dialogData = {data: {namespaces: this.namespaces}};
H
haijiao.yin 已提交
209
    const dialogDef = this.dialog_.open(CreateNamespaceDialog, dialogData);
S
Shu Muto 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
    dialogDef
      .afterClosed()
      .take(1)
      .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 已提交
225 226 227
  }

  handleCreateSecretDialog(): void {
228
    const dialogData = {data: {namespace: this.namespace.value}};
H
haijiao.yin 已提交
229
    const dialogDef = this.dialog_.open(CreateSecretDialog, dialogData);
S
Shu Muto 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
    dialogDef
      .afterClosed()
      .take(1)
      .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 已提交
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
  }

  /**
   * 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,
280 281
      imagePullSecret: this.imagePullSecret.value ? this.imagePullSecret.value : null,
      containerCommand: this.containerCommand.value ? this.containerCommand.value : null,
M
Marcin Maciaszczyk 已提交
282
      containerCommandArgs: this.containerCommandArgs.value ? this.containerCommandArgs.value : null,
H
haijiao.yin 已提交
283 284 285 286 287 288 289
      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,
290
      cpuRequirement: this.isNumber(this.cpuRequirement.value) ? this.cpuRequirement.value : null,
M
Marcin Maciaszczyk 已提交
291
      memoryRequirement: this.isNumber(this.memoryRequirement.value) ? `${this.memoryRequirement.value}Mi` : null,
H
haijiao.yin 已提交
292
      labels: this.toBackendApiLabels(labels),
S
Shu Muto 已提交
293
      runAsPrivileged: this.runAsPrivileged.value,
H
haijiao.yin 已提交
294 295
    };
    this.create_.deploy(spec);
296 297
  }
}