"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
//@ts-ignore
var k8s = require("@kubernetes/client-node");
var mslib_1 = require("mslib");
/**
 * K8S操作API
 */
var ApiClient = /** @class */ (function () {
    function ApiClient(config) {
        this.config = config;
        this.id = this.config.id;
        this.name = this.config.name;
        this.makeApiClient();
    }
    ApiClient.prototype.makeApiClient = function () {
        var kc = new k8s.KubeConfig();
        var cluster = {
            name: this.config.name,
            server: this.config.apiUrl,
            caData: this.config.ca
        };
        var user = {
            certData: this.config.cc,
            keyData: this.config.ck,
        };
        var context = {
            name: 'my-context',
            cluster: cluster.name,
        };
        kc.loadFromOptions({
            clusters: [cluster],
            users: [user],
            contexts: [context],
            currentContext: context.name,
        });
        this.appApi = kc.makeApiClient(k8s.AppsV1Api);
        this.coreApi = kc.makeApiClient(k8s.CoreV1Api);
    };
    /**
    * 获取Deplyment
    * @param namespace 命名空间
    * @param name deplyment名称
    */
    ApiClient.prototype.getDeplyment = function (namespaceName, name) {
        return __awaiter(this, void 0, void 0, function () {
            var response, e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.appApi.readNamespacedDeployment(name, namespaceName)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 2:
                        e_1 = _a.sent();
                        mslib_1.logger.error('[K8S-API] getDeplyment error ==========>' + JSON.stringify(e_1));
                        return [2 /*return*/, this.errorToOpResult(e_1)];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 创建一个新的部署
     * @param namespace
     * @param params
     */
    ApiClient.prototype.createDeployment = function (namespace, params) {
        return __awaiter(this, void 0, void 0, function () {
            var deploymentSpec, selector, template, deplyment, response, e_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        deploymentSpec = new k8s.V1DeploymentSpec();
                        deploymentSpec.replicas = params.replicas || 1;
                        selector = new k8s.V1LabelSelector();
                        selector.matchLabels = {
                            'app': params.deployId
                        };
                        deploymentSpec.selector = selector;
                        template = new k8s.V1PodTemplateSpec();
                        template.metadata = {
                            labels: selector.matchLabels
                        };
                        template.spec = this.createV1PodSpec(params);
                        deploymentSpec.template = template;
                        deplyment = new k8s.V1Deployment();
                        deplyment.metadata = this.createMetadata(namespace, params);
                        deplyment.spec = deploymentSpec;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        mslib_1.logger.debug('[K8S-API] createDeployment begin ==========>' + JSON.stringify(deplyment));
                        return [4 /*yield*/, this.appApi.createNamespacedDeployment(namespace, deplyment)];
                    case 2:
                        response = _a.sent();
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 3:
                        e_2 = _a.sent();
                        mslib_1.logger.error('[K8S-API] createDeployment error ==========>' + JSON.stringify(e_2));
                        return [2 /*return*/, this.errorToOpResult(e_2)];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 删除部署
     * @param namespace
     * @param name 部署名称
     */
    ApiClient.prototype.deleteDeployment = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var op, deployment, response, e_3;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.getDeplyment(namespace, name)];
                    case 1:
                        op = _a.sent();
                        if (!op.isSuccess()) {
                            return [2 /*return*/, op];
                        }
                        deployment = op.data;
                        deployment.spec.replicas = 0;
                        _a.label = 2;
                    case 2:
                        _a.trys.push([2, 5, , 6]);
                        return [4 /*yield*/, this.appApi.replaceNamespacedDeployment(name, namespace, deployment)];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, this.appApi.deleteNamespacedDeployment(name, namespace)];
                    case 4:
                        response = _a.sent();
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 5:
                        e_3 = _a.sent();
                        mslib_1.logger.error('[K8S-API] deleteDeployment error ==========>' + JSON.stringify(e_3));
                        return [2 /*return*/, this.errorToOpResult(e_3)];
                    case 6: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 获取指定 POD
     * @param namespace
     */
    ApiClient.prototype.getPod = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var response, e_4;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.coreApi.readNamespacedPod(name, namespace)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 2:
                        e_4 = _a.sent();
                        mslib_1.logger.error('[K8S-API] getPod error ==========>' + JSON.stringify(e_4));
                        return [2 /*return*/, this.errorToOpResult(e_4)];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 获取POD 列表
     * @param namespace
     */
    ApiClient.prototype.getPodList = function (namespace) {
        return __awaiter(this, void 0, void 0, function () {
            var response, e_5;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, this.coreApi.listNamespacedPod(namespace)];
                    case 1:
                        response = _a.sent();
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 2:
                        e_5 = _a.sent();
                        mslib_1.logger.error('[K8S-API] getPodList error ==========>' + JSON.stringify(e_5));
                        return [2 /*return*/, this.errorToOpResult(e_5)];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
   * 创建一个新的POD
   * @param namespace
   * @param params
   */
    ApiClient.prototype.createPod = function (namespace, params, forceCreate) {
        if (forceCreate === void 0) { forceCreate = false; }
        return __awaiter(this, void 0, void 0, function () {
            var pod, response, e_6;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        pod = new k8s.V1Pod();
                        pod.metadata = this.createMetadata(namespace, params);
                        pod.spec = this.createV1PodSpec(params);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 5, , 6]);
                        mslib_1.logger.debug('[K8S-API] createPOD begin ==========>' + JSON.stringify(pod));
                        if (!forceCreate) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.deletePod(namespace, params.appName)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [4 /*yield*/, this.coreApi.createNamespacedPod(namespace, pod)];
                    case 4:
                        response = _a.sent();
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 5:
                        e_6 = _a.sent();
                        mslib_1.logger.error('[K8S-API] createPod error ==========>' + JSON.stringify(e_6));
                        return [2 /*return*/, this.errorToOpResult(e_6)];
                    case 6: return [2 /*return*/];
                }
            });
        });
    };
    /**
  * 创建一个新的POD
  * @param namespace
  * @param params
  */
    ApiClient.prototype.createPodAndPvc = function (namespace, params, pvc) {
        return __awaiter(this, void 0, void 0, function () {
            var op, sleepSeconds, e_7;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 10, , 11]);
                        mslib_1.logger.debug('[K8S-API] createPodAndPvc begin ==========>', params);
                        if (!pvc) return [3 /*break*/, 9];
                        params.pvc.name = pvc.name;
                        return [4 /*yield*/, this.createPVC(namespace, pvc, false)];
                    case 1:
                        op = _a.sent();
                        if (!op.isSuccess()) {
                            return [2 /*return*/, op];
                        }
                        sleepSeconds = 1;
                        _a.label = 2;
                    case 2:
                        if (!(sleepSeconds < 30)) return [3 /*break*/, 9];
                        return [4 /*yield*/, this.sleep(1000)];
                    case 3:
                        _a.sent();
                        sleepSeconds++;
                        return [4 /*yield*/, this.getPVC(namespace, pvc.name)];
                    case 4:
                        op = _a.sent();
                        if (!(op.isSuccess() && op.data.status.phase === 'Bound')) return [3 /*break*/, 8];
                        return [4 /*yield*/, this.createPod(namespace, params, false)];
                    case 5:
                        op = _a.sent();
                        if (!!op.isSuccess()) return [3 /*break*/, 7];
                        return [4 /*yield*/, this.deletePVC(namespace, pvc.name)];
                    case 6:
                        _a.sent();
                        _a.label = 7;
                    case 7: return [2 /*return*/, op];
                    case 8: return [3 /*break*/, 2];
                    case 9: return [2 /*return*/, mslib_1.OpResult.error('创建PVC超时......')];
                    case 10:
                        e_7 = _a.sent();
                        mslib_1.logger.error('[K8S-API] createPodAndPvc error ==========>' + JSON.stringify(e_7));
                        return [2 /*return*/, this.errorToOpResult(e_7)];
                    case 11: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 删除POD
     * @param namespace
     * @param name POD名称
     */
    ApiClient.prototype.deletePod = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var response, e_8;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        mslib_1.logger.debug('[K8S-API] deletePod begin ==========>namespace:%s,name:%s', namespace, name);
                        return [4 /*yield*/, this.coreApi.deleteNamespacedPod(name, namespace)];
                    case 1:
                        response = _a.sent();
                        mslib_1.logger.debug('[K8S-API] deletePod end ==========>namespace:%s,name:%s' + JSON.stringify(response));
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 2:
                        e_8 = _a.sent();
                        mslib_1.logger.error('[K8S-API] deletePod error ==========>' + JSON.stringify(e_8));
                        return [2 /*return*/, this.errorToOpResult(e_8)];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 获取指定 PVC
     * @param namespace
     */
    ApiClient.prototype.getPVC = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var response, e_9;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        mslib_1.logger.debug('[K8S-API] getPVC begin ==========>namespace:%s,name:%s', namespace, name);
                        return [4 /*yield*/, this.coreApi.readNamespacedPersistentVolumeClaim(name, namespace)];
                    case 1:
                        response = _a.sent();
                        mslib_1.logger.debug('[K8S-API] getPVC end ==========>' + JSON.stringify(response));
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 2:
                        e_9 = _a.sent();
                        mslib_1.logger.error('[K8S-API] getPVC error ==========>' + JSON.stringify(e_9));
                        return [2 /*return*/, this.errorToOpResult(e_9)];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
       * 创建一个新的 PVC
       * @param namespace
       * @param params
       */
    ApiClient.prototype.createPVC = function (namespace, params, forceCreate) {
        if (forceCreate === void 0) { forceCreate = false; }
        return __awaiter(this, void 0, void 0, function () {
            var pvc, storage, response, e_10;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        pvc = new k8s.V1PersistentVolumeClaim();
                        pvc.metadata = {
                            name: params.name
                        };
                        pvc.spec = new k8s.V1PersistentVolumeClaimSpec();
                        pvc.spec.accessModes = [params.accessModes || 'ReadWriteOnce'];
                        storage = params.storage;
                        if (!storage.endsWith('Gi')) {
                            storage = params.storage + 'Gi';
                        }
                        pvc.spec.resources = {
                            requests: {
                                storage: storage
                            }
                        };
                        pvc.spec.storageClassName = params.storageClassName;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 5, , 6]);
                        mslib_1.logger.debug('[K8S-API] createPVC begin ==========>' + JSON.stringify(pvc));
                        if (!forceCreate) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.deletePVC(namespace, params.name)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [4 /*yield*/, this.coreApi.createNamespacedPersistentVolumeClaim(namespace, pvc)];
                    case 4:
                        response = _a.sent();
                        mslib_1.logger.debug('[K8S-API] createPVC end ==========>' + JSON.stringify(response));
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 5:
                        e_10 = _a.sent();
                        mslib_1.logger.error('[K8S-API] createPVC error ==========>' + JSON.stringify(e_10));
                        return [2 /*return*/, this.errorToOpResult(e_10)];
                    case 6: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 删除PVC
     * @param namespace
     * @param name PVC名称
     */
    ApiClient.prototype.deletePVC = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var response, e_11;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        mslib_1.logger.debug('[K8S-API] deletePVC begin ==========>namespace:%s,name:%s', namespace, name);
                        return [4 /*yield*/, this.coreApi.deleteNamespacedPersistentVolumeClaim(name, namespace)];
                    case 1:
                        response = _a.sent();
                        mslib_1.logger.debug('[K8S-API] deletePVC end ==========>' + JSON.stringify(response));
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 2:
                        e_11 = _a.sent();
                        mslib_1.logger.error('[K8S-API] deletePod error ==========>' + JSON.stringify(e_11));
                        return [2 /*return*/, this.errorToOpResult(e_11)];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 创建服务
     * @param namespace
     * @param param
     */
    ApiClient.prototype.createService = function (namespace, param, forceCreate) {
        if (forceCreate === void 0) { forceCreate = false; }
        return __awaiter(this, void 0, void 0, function () {
            var metadata, service, _i, _a, port, servicePort, response, e_12;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        metadata = new k8s.V1ObjectMeta();
                        metadata.namespace = namespace;
                        metadata.name = param.name;
                        if (this.config.cloudProvider === 'ALIYUN') {
                            metadata.annotations = this.createAliyunSLBMetadataAnnotations(param);
                        }
                        service = new k8s.V1Service();
                        service.metadata = metadata;
                        service.spec = new k8s.V1ServiceSpec();
                        service.spec.selector = {
                            "app": param.podLabel
                        };
                        service.spec.externalTrafficPolicy = 'Cluster';
                        service.spec.type = param.type || 'LoadBalancer';
                        service.spec.ports = [];
                        for (_i = 0, _a = param.ports; _i < _a.length; _i++) {
                            port = _a[_i];
                            servicePort = new k8s.V1ServicePort();
                            servicePort.port = port.nodePort;
                            servicePort.targetPort = port.targetPort;
                            servicePort.protocol = port.protocol;
                            servicePort.name = 'p' + port.targetPort;
                            service.spec.ports.push(servicePort);
                        }
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 5, , 6]);
                        mslib_1.logger.debug('[K8S-API] createService begin ==========>' + JSON.stringify(service));
                        if (!forceCreate) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.deleteService(namespace, param.name)];
                    case 2:
                        _b.sent();
                        _b.label = 3;
                    case 3: return [4 /*yield*/, this.coreApi.createNamespacedService(namespace, service)];
                    case 4:
                        response = _b.sent();
                        mslib_1.logger.debug('[K8S-API] createService end ==========>' + JSON.stringify(response));
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 5:
                        e_12 = _b.sent();
                        mslib_1.logger.error('[K8S-API] createService error ==========>', e_12);
                        return [2 /*return*/, this.errorToOpResult(e_12)];
                    case 6: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 删除服务
     * @param namespace
     * @param name 服务名称
     */
    ApiClient.prototype.deleteService = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var response, e_13;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        mslib_1.logger.debug('[K8S-API] deleteService begin ==========>namespace:%s,name:%s', namespace, name);
                        return [4 /*yield*/, this.coreApi.deleteNamespacedService(name, namespace)];
                    case 1:
                        response = _a.sent();
                        mslib_1.logger.debug('[K8S-API] deleteService end ==========>' + JSON.stringify(response));
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 2:
                        e_13 = _a.sent();
                        mslib_1.logger.error('[K8S-API] deleteService error ==========>' + JSON.stringify(e_13));
                        return [2 /*return*/, this.errorToOpResult(e_13)];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 获取服务信息
     * @param namespace
     * @param name 服务名称
     */
    ApiClient.prototype.getService = function (namespace, name) {
        return __awaiter(this, void 0, void 0, function () {
            var response, e_14;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        mslib_1.logger.debug('[K8S-API] getService begin ==========>namespace:%s,name:%s', namespace, name);
                        return [4 /*yield*/, this.coreApi.readNamespacedService(name, namespace)];
                    case 1:
                        response = _a.sent();
                        mslib_1.logger.debug('[K8S-API] getService end ==========>' + JSON.stringify(response));
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 2:
                        e_14 = _a.sent();
                        mslib_1.logger.error('[K8S-API] getService error ==========>' + JSON.stringify(e_14));
                        return [2 /*return*/, this.errorToOpResult(e_14)];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
   * 获取服务信息列表
   * @param namespace
   * @param name 服务名称
   */
    ApiClient.prototype.getServiceList = function (namespace) {
        return __awaiter(this, void 0, void 0, function () {
            var response, e_15;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        mslib_1.logger.debug('[K8S-API] getServiceList begin ==========>namespace:%s', namespace);
                        return [4 /*yield*/, this.coreApi.listNamespacedService(namespace)];
                    case 1:
                        response = _a.sent();
                        mslib_1.logger.debug('[K8S-API] getServiceList end ==========>' + JSON.stringify(response));
                        return [2 /*return*/, mslib_1.OpResult.success('OK', response.body)];
                    case 2:
                        e_15 = _a.sent();
                        mslib_1.logger.error('[K8S-API] getServiceList error ==========>' + JSON.stringify(e_15));
                        return [2 /*return*/, this.errorToOpResult(e_15)];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 阿里云SLB注解
     * @param param
     */
    ApiClient.prototype.createAliyunSLBMetadataAnnotations = function (param) {
        var result = {};
        if (param.slbId) {
            result['service.beta.kubernetes.io/alicloud-loadbalancer-id'] = param.slbId;
        }
        if (param.networkType === 'intranet') { //内网
            result['service.beta.kubernetes.io/alicloud-loadbalancer-address-type'] = 'intranet';
        }
        else { //外网
            //slb规格默认简约型
            result['service.beta.kubernetes.io/alibaba-cloud-loadbalancer-spec'] = 'slb.s1.small';
            var has443 = param.ports.find(function (it) { return it.targetPort === 443; });
            var has80 = param.ports.find(function (it) { return it.targetPort === 80; });
            var slbports = has443 ? ['https:443'] : [];
            if (has80) {
                slbports.push('http:80');
            }
            if (slbports.length > 0) {
                result['service.beta.kubernetes.io/alibaba-cloud-loadbalancer-protocol-port'] = slbports.join(',');
            }
        }
        return result;
    };
    ApiClient.prototype.createMetadata = function (namespace, params) {
        var metadata = new k8s.V1ObjectMeta();
        metadata.labels = params.labels || {};
        metadata.labels['app'] = params.deployId;
        metadata.namespace = namespace;
        metadata.name = params.appName;
        return metadata;
    };
    ApiClient.prototype.createV1PodSpec = function (params) {
        var spec = new k8s.V1PodSpec();
        var container = new k8s.V1Container();
        container.name = params.appName;
        if (params.command) {
            container.command = [params.command];
        }
        if (params.envs) {
            var envs_1 = [];
            var keys = Object.keys(params.envs);
            keys.forEach(function (key) {
                var env = new k8s.V1EnvVar();
                env.name = key;
                env.value = params.envs[key];
                envs_1.push(env);
            });
            container.env = envs_1;
        }
        container.image = params.image;
        if (params.ports) {
            var ports = [];
            container.ports = ports;
            for (var _i = 0, _a = params.ports; _i < _a.length; _i++) {
                var row = _a[_i];
                ports.push({
                    name: 'p' + row.port,
                    containerPort: parseInt(row.port.toString()),
                    protocol: row.protocol
                });
            }
            container.ports = ports;
        }
        var memory = params.memory + 'Gi';
        if (parseFloat(memory) < 1) { //小于1G
            var value = parseInt((parseFloat(memory) * 1024) + '');
            if (value < 128) {
                value = 128;
            }
            else if (value > 128 && value < 256) {
                value = 256;
            }
            memory = value + 'Mi';
        }
        container.resources = {
            limits: {
                cpu: params.cpu,
                memory: memory
            },
            requests: {
                cpu: params.cpu,
                memory: memory
            }
        };
        spec.containers = [container];
        if (params.imagePullSecret) {
            spec.imagePullSecrets = [{
                    name: params.imagePullSecret
                }];
        }
        if (params.pvc) {
            container.volumeMounts = [
                {
                    name: params.pvc.name,
                    mountPath: params.pvc.mountPath
                }
            ];
            spec.volumes = [
                {
                    name: params.pvc.name,
                    persistentVolumeClaim: {
                        claimName: params.pvc.name
                    }
                }
            ];
        }
        return spec;
    };
    ApiClient.prototype.errorToOpResult = function (error) {
        var message = error.message;
        if (error.response && error.response.body) {
            message = error.response.body.status + ' : ' + error.response.body.message;
        }
        return mslib_1.OpResult.error(message);
    };
    ApiClient.prototype.sleep = function (ms) {
        return new Promise(function (resolve) { return setTimeout(resolve, ms); });
    };
    return ApiClient;
}());
exports.ApiClient = ApiClient;
//# sourceMappingURL=ApiClient.js.map