"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
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 });
var typescript_ioc_1 = require("typescript-ioc");
var mslib_1 = require("mslib");
var K8SDeployParamBuilder_1 = require("./K8SDeployParamBuilder");
var K8SClientFactory_1 = require("./K8SClientFactory");
/**
 * K8S服务部署
 * @date 2021-06-01 10:34:32
 * @author 吴锋霖
 */
var K8SDeployService = /** @class */ (function () {
    function K8SDeployService() {
    }
    /**
     * 服务部署
     * @param deployConfig 部署配置
     * @param loggerBuilder 日志构建器
     */
    K8SDeployService.prototype.deploy = function (deployConfig, loggerBuilder) {
        return __awaiter(this, void 0, void 0, function () {
            var op, namespace, buildResult, k8sClient, _i, _a, param, deployParam, pvcParam, serviceParam;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        loggerBuilder.appendln("\u51C6\u5907\u5F00\u59CB\u6784\u5EFA\u90E8\u7F72\u53C2\u6570......" + deployConfig.id + "/" + deployConfig.name);
                        return [4 /*yield*/, this.k8sDeployParamBuilder.build(deployConfig, loggerBuilder)];
                    case 1:
                        op = _b.sent();
                        if (!op.isSuccess()) {
                            return [2 /*return*/, op];
                        }
                        namespace = deployConfig.envCode.toLowerCase();
                        buildResult = op.data;
                        k8sClient = this.k8sClientFactory.getClient(deployConfig.k8sId);
                        loggerBuilder.appendln("\u53C2\u6570\u6784\u5EFA\u5B8C\u6210\uFF0C\u51C6\u5907\u5F00\u59CB\u90E8\u7F72K8S---[" + deployConfig.name + "]\u81F3[" + k8sClient.name + "/" + deployConfig.envCode.toLowerCase() + "]");
                        _i = 0, _a = buildResult.deployParams;
                        _b.label = 2;
                    case 2:
                        if (!(_i < _a.length)) return [3 /*break*/, 8];
                        param = _a[_i];
                        deployParam = param.deployParam;
                        pvcParam = param.pvcParam;
                        if (!pvcParam) return [3 /*break*/, 4];
                        return [4 /*yield*/, k8sClient.createPodAndPvc(namespace, deployParam, pvcParam)];
                    case 3:
                        op = _b.sent();
                        return [3 /*break*/, 6];
                    case 4: return [4 /*yield*/, k8sClient.createPod(namespace, deployParam)];
                    case 5:
                        op = _b.sent();
                        _b.label = 6;
                    case 6:
                        if (!op.isSuccess()) {
                            loggerBuilder.appendln("\u90E8\u7F72POD\u5931\u8D25: " + op.message + " ......");
                            return [2 /*return*/, op];
                        }
                        _b.label = 7;
                    case 7:
                        _i++;
                        return [3 /*break*/, 2];
                    case 8:
                        if (!buildResult.serviceParam) return [3 /*break*/, 10];
                        loggerBuilder.appendln("POD\u521B\u5EFA\u5B8C\u6210\uFF0C\u51C6\u5907\u521B\u5EFAService......");
                        serviceParam = buildResult.serviceParam;
                        return [4 /*yield*/, k8sClient.createService(namespace, serviceParam, true)];
                    case 9:
                        op = _b.sent();
                        if (!op.isSuccess()) {
                            loggerBuilder.appendln("\u90E8\u7F72Service\u5931\u8D25: " + op.message + " ......");
                            return [2 /*return*/, op];
                        }
                        _b.label = 10;
                    case 10: return [4 /*yield*/, this.closeOldDeployment(deployConfig, loggerBuilder)];
                    case 11:
                        _b.sent();
                        loggerBuilder.appendln("\u90E8\u7F72\u5B8C\u6210......");
                        return [2 /*return*/, op];
                }
            });
        });
    };
    /**
    * 关闭服务部署
    * @param deployConfig 部署配置
    * @param loggerBuilder 日志构建器
    */
    K8SDeployService.prototype.close = function (deployConfig, loggerBuilder) {
        return __awaiter(this, void 0, void 0, function () {
            var namespace, k8sClient, op, podList, _i, podList_1, pod, name;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        loggerBuilder.appendln('准备关闭部署.....' + deployConfig.id);
                        namespace = deployConfig.envCode.toLowerCase();
                        k8sClient = this.k8sClientFactory.getClient(deployConfig.k8sId);
                        return [4 /*yield*/, this.listPod(deployConfig.k8sId, namespace, deployConfig.id)];
                    case 1:
                        op = _a.sent();
                        if (!op.isSuccess()) {
                            loggerBuilder.appendln('获取POD列表异常:' + op.message);
                            return [2 /*return*/];
                        }
                        podList = op.data;
                        _i = 0, podList_1 = podList;
                        _a.label = 2;
                    case 2:
                        if (!(_i < podList_1.length)) return [3 /*break*/, 5];
                        pod = podList_1[_i];
                        name = pod.metadata.name;
                        return [4 /*yield*/, this.closePod(k8sClient, namespace, name, loggerBuilder)];
                    case 3:
                        op = _a.sent();
                        if (!op.isSuccess()) {
                            return [2 /*return*/, op];
                        }
                        _a.label = 4;
                    case 4:
                        _i++;
                        return [3 /*break*/, 2];
                    case 5:
                        //2. 删除Service
                        // op = await k8sClient.getServiceList(namespace)
                        // if (!op.isSuccess()) {
                        //     loggerBuilder.appendln('获取Service列表异常:' + op.message)
                        //     return;
                        // }
                        // for (let service of op.data.items) {
                        //     if (service.spec.selector.app === deployConfig.id) {
                        //         op = await k8sClient.deleteService(namespace, service.metadata.name)
                        //         if (!op.isSuccess()) {
                        //             loggerBuilder.appendln(`删除Service[${service.metadata.name}]失败 : ${op.message}`)
                        //             return op
                        //         }
                        //         loggerBuilder.appendln(`删除Service[${service.metadata.name}]成功`)
                        //     }
                        // }
                        loggerBuilder.appendln('关闭部署完成');
                        return [2 /*return*/, mslib_1.OpResult.success('OK')];
                }
            });
        });
    };
    K8SDeployService.prototype.listPod = function (k8sId, namespace, deployId) {
        return __awaiter(this, void 0, void 0, function () {
            var k8sClient, op, podList, result, _i, _a, pod, labels;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        k8sClient = this.k8sClientFactory.getClient(k8sId);
                        return [4 /*yield*/, k8sClient.getPodList(namespace)];
                    case 1:
                        op = _b.sent();
                        if (!op.isSuccess()) {
                            return [2 /*return*/, op];
                        }
                        podList = op.data;
                        result = [];
                        for (_i = 0, _a = podList.items; _i < _a.length; _i++) {
                            pod = _a[_i];
                            labels = pod.metadata.labels;
                            if (labels.deployId === deployId) {
                                result.push(pod);
                            }
                        }
                        return [2 /*return*/, mslib_1.OpResult.success('OK', podList)];
                }
            });
        });
    };
    /**
     * 关闭其他旧的部署
     */
    K8SDeployService.prototype.closeOldDeployment = function (deployConfig, loggerBuilder) {
        return __awaiter(this, void 0, void 0, function () {
            var namespace, k8sClient, op, podList, _i, _a, pod, name, labels;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!deployConfig.deployTag) {
                            return [2 /*return*/];
                        }
                        loggerBuilder.appendln('准备删除旧的POD.....');
                        namespace = deployConfig.envCode.toLowerCase();
                        k8sClient = this.k8sClientFactory.getClient(deployConfig.k8sId);
                        return [4 /*yield*/, k8sClient.getPodList(namespace)];
                    case 1:
                        op = _b.sent();
                        if (!op.isSuccess()) {
                            loggerBuilder.appendln('获取POD列表异常:' + op.message);
                            return [2 /*return*/];
                        }
                        podList = op.data;
                        _i = 0, _a = podList.items;
                        _b.label = 2;
                    case 2:
                        if (!(_i < _a.length)) return [3 /*break*/, 5];
                        pod = _a[_i];
                        name = pod.metadata.name;
                        labels = pod.metadata.labels;
                        if (!(labels.deployId === deployConfig.id && labels.deployTag !== deployConfig.deployTag)) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.closePod(k8sClient, namespace, name, loggerBuilder)];
                    case 3:
                        _b.sent();
                        _b.label = 4;
                    case 4:
                        _i++;
                        return [3 /*break*/, 2];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    K8SDeployService.prototype.closePod = function (k8sClient, namespace, name, loggerBuilder) {
        return __awaiter(this, void 0, void 0, function () {
            var op;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, k8sClient.deletePod(namespace, name)];
                    case 1:
                        op = _a.sent();
                        if (op.isSuccess()) {
                            loggerBuilder.appendln("\u5220\u9664POD[" + name + "]\u64CD\u4F5C\u6210\u529F");
                        }
                        else {
                            loggerBuilder.appendln("\u5220\u9664POD[" + name + "]\u64CD\u4F5C\u5931\u8D25\uFF1A" + op.message);
                            return [2 /*return*/, op];
                        }
                        return [4 /*yield*/, k8sClient.getPVC(namespace, name)];
                    case 2:
                        op = _a.sent();
                        if (!op.isSuccess()) {
                            return [2 /*return*/, mslib_1.OpResult.success('OK')];
                        }
                        return [4 /*yield*/, k8sClient.deletePVC(namespace, name)];
                    case 3:
                        op = _a.sent();
                        if (op.isSuccess()) {
                            loggerBuilder.appendln("\u5220\u9664PVC[" + name + "]\u64CD\u4F5C\u6210\u529F");
                        }
                        else {
                            loggerBuilder.appendln("\u5220\u9664PVC[" + name + "]\u64CD\u4F5C\u5931\u8D25\uFF1A" + op.message);
                        }
                        return [2 /*return*/, op];
                }
            });
        });
    };
    __decorate([
        typescript_ioc_1.Inject,
        __metadata("design:type", K8SDeployParamBuilder_1.K8SDeployParamBuilder)
    ], K8SDeployService.prototype, "k8sDeployParamBuilder", void 0);
    __decorate([
        typescript_ioc_1.Inject,
        __metadata("design:type", K8SClientFactory_1.K8SClientFactory
        /**
         * 服务部署
         * @param deployConfig 部署配置
         * @param loggerBuilder 日志构建器
         */
        )
    ], K8SDeployService.prototype, "k8sClientFactory", void 0);
    return K8SDeployService;
}());
exports.K8SDeployService = K8SDeployService;
//# sourceMappingURL=K8SDeployService.js.map