"use strict";
/*
 * Copyright © 2020 Atomist, Inc.
 *
 * 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.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.serviceTemplate = exports.upsertService = void 0;
const logger_1 = require("@atomist/automation-client/lib/util/logger");
const _ = require("lodash");
const error_1 = require("../support/error");
const retry_1 = require("../support/retry");
const labels_1 = require("./labels");
const metadata_1 = require("./metadata");
const patch_1 = require("./patch");
const request_1 = require("./request");
const resource_1 = require("./resource");
/**
 * If `req.port` is truthy, create a service if it does not exist and
 * patch it if it does.  Any provided `req.serviceSpec` is merged
 * using [[serviceTemplate]] before creating/patching.
 *
 * @param req Kuberenetes application request
 * @return Kubernetes resource spec used to create/patch resource, or undefined if port not defined
 */
async function upsertService(req) {
    const slug = request_1.appName(req);
    if (!req.port) {
        logger_1.logger.debug(`Port not provided, will not create service ${slug}`);
        return undefined;
    }
    const spec = await serviceTemplate(req);
    try {
        await req.clients.core.readNamespacedService(spec.metadata.name, spec.metadata.namespace);
    }
    catch (e) {
        logger_1.logger.debug(`Failed to read service ${slug}, creating: ${error_1.k8sErrMsg(e)}`);
        logger_1.logger.info(`Creating service ${slug} using '${resource_1.logObject(spec)}'`);
        await retry_1.logRetry(() => req.clients.core.createNamespacedService(spec.metadata.namespace, spec), `create service ${slug}`);
        return spec;
    }
    logger_1.logger.info(`Service ${slug} exists, patching using '${resource_1.logObject(spec)}'`);
    await retry_1.logRetry(() => req.clients.core.patchNamespacedService(spec.metadata.name, spec.metadata.namespace, spec, undefined, undefined, undefined, undefined, patch_1.patchHeaders(req)), `patch service ${slug}`);
    return spec;
}
exports.upsertService = upsertService;
/**
 * Create service spec to front a Kubernetes application.  If the
 * request has a `serviceSpec`, it is merged into the spec created
 * by this function using `lodash.merge(default, req.serviceSpec)`.
 *
 * It is possible to override the service name using the
 * [[KubernetesApplication.serviceSpec]].  If you do this, make sure
 * you know what you are doing.
 *
 * @param req service template request
 * @return service resource specification
 */
async function serviceTemplate(req) {
    const labels = labels_1.applicationLabels(req);
    const matchers = labels_1.matchLabels(req);
    const metadata = metadata_1.metadataTemplate({
        name: req.name,
        namespace: req.ns,
        labels,
    });
    const apiVersion = "v1";
    const kind = "Service";
    const s = {
        apiVersion,
        kind,
        metadata,
        spec: {
            ports: [
                {
                    name: "http",
                    port: req.port,
                    targetPort: "http",
                },
            ],
            selector: matchers,
            type: "NodePort",
        },
    };
    if (req.serviceSpec) {
        _.merge(s, req.serviceSpec, { apiVersion, kind });
        s.metadata.namespace = req.ns;
    }
    return s;
}
exports.serviceTemplate = serviceTemplate;
//# sourceMappingURL=service.js.map