All files / lib index.ts

88.46% Statements 92/104
79.03% Branches 49/62
90% Functions 9/10
88.46% Lines 92/104

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 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 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 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 2791x                         9x 8x 18x 8x         1x               18x   18x 15x 28x 6x         18x       9x   9x 1x   1x 1x   1x           1x               9x       11x 11x 8x 8x           3x                   9x   9x   9x 5x 5x 5x 5x               9x                   9x   9x 5x 5x       5x       5x       5x 1x       9x         9x       9x 9x 5x 5x 5x       9x 9x 1x     9x     9x 9x     9x 1x       9x 1x     9x 9x 1x     9x 1x     9x 2x     9x 1x     9x                 1x   9x   9x   9x 9x 9x           9x   9x 9x   9x 5x   5x       5x           9x         9x 5x     9x             1x 9x   9x 5x     9x                 1x                           1x  
import * as yaml from 'js-yaml';
import * as ComposeModels from './composeModels';
import * as DockerModels from './dockerModels';
 
export interface NetworkMap {
    [id: string]: DockerModels.Network;
}
 
/**
 * Get the service name as at stack creation time
 * @param service
 */
function getServiceName(service: DockerModels.Service): string {
    if (service.Spec.Labels) {
        for (const label in service.Spec.Labels) {
            if (label === 'com.docker.stack.namespace') {
                return service.Spec.Name.replace(service.Spec.Labels[label] + '_', '');
            }
        }
    }
 
    return service.Spec.Name;
}
 
/**
 * Remove Docker-internal labels added by Docker CLI
 * @param labels
 */
function stripDockerLabels(labels: {[name: string]: string} | undefined): {[name: string]: string} {
    const result: {[name: string]: string} = {};
 
    if (labels) {
        for (const key in labels) {
            if (!(key === 'com.docker.stack.image') && !(key === 'com.docker.stack.namespace')) {
                result[key] = labels[key];
            }
        }
    }
 
    return result;
}
 
function parseMounts(service: DockerModels.Service): ComposeModels.Mount[] {
    const mounts: ComposeModels.Mount[] = [];
 
    if (service.Spec.TaskTemplate.ContainerSpec.Mounts) {
        const dockerMounts: DockerModels.Mount[] = service.Spec.TaskTemplate.ContainerSpec.Mounts;
 
        for (const dockerMount of dockerMounts) {
            let stackPrefix = '';
 
            Iif (dockerMount.VolumeOptions && dockerMount.VolumeOptions.Labels) {
                if (dockerMount.VolumeOptions.Labels['com.docker.stack.namespace']) {
                    stackPrefix = dockerMount.VolumeOptions.Labels['com.docker.stack.namespace'] + '_';
                }
            }
 
            mounts.push({
                type: dockerMount.Type,
                source: dockerMount.Source.replace(stackPrefix, ''),
                target: dockerMount.Target,
            });
        }
    }
 
    return mounts;
}
 
function getNetworkName(network: DockerModels.Network): string {
    Eif (network.Labels) {
        for (const label in network.Labels) {
            Eif (label === 'com.docker.stack.namespace') {
                return network.Name.replace(network.Labels[label] + '_', '');
            }
        }
    }
 
    // Network was not created as part of a stack
    return network.Name;
}
 
/**
 * Returns the networks from the NetworkMap according to the given service
 * @param {DockerModels.Service} service
 * @param {NetworkMap} networkMap
 * @returns {string[]}
 */
function parseNetworks(service: DockerModels.Service, networkMap: NetworkMap): DockerModels.Network[] {
    const result: DockerModels.Network[] = [];
 
    const networks = service.Spec.TaskTemplate.Networks;
 
    if (networks) {
        for (const network of networks) {
            Eif (network.Target) {
                Eif (networkMap[network.Target]) {
                    result.push(networkMap[network.Target]);
                } else {
                    throw new Error('Network ID not found in NetworkMap: ' + network.Target);
                }
            }
        }
    }
 
    return result;
}
 
/**
 * Create intermediate structure to help with Stack networks
 *
 * @param {NetworkMap} networkMap
 * @returns {{[name: string]: ComposeModels.StackNetwork}}
 */
function createStackNetworkMap(networkMap: NetworkMap): {[name: string]: ComposeModels.StackNetwork} {
    const result: {[name: string]: ComposeModels.StackNetwork} = {};
 
    for (const networkId in networkMap) {
        const dockerNetwork = networkMap[networkId];
        Iif (!dockerNetwork) {
            throw new Error('undefined network in NetworkMap');
        }
 
        Iif (!dockerNetwork.Driver) {
            throw new Error('Network in NetworkMap does not have a driver: ' + networkId);
        }
 
        result[getNetworkName(networkMap[networkId])] = {
            driver: dockerNetwork.Driver,
        };
 
        if (dockerNetwork.Labels && !(dockerNetwork.Labels["com.docker.stack.namespace"])) {
            result[getNetworkName(networkMap[networkId])].external = true;
        }
    }
 
    return result;
}
 
function parseService(service: DockerModels.Service, networkMap: NetworkMap): ComposeModels.Service {
 
    const result: ComposeModels.Service = {
        image: service.Spec.TaskTemplate.ContainerSpec.Image.split('@')[0],
    };
 
    const networks: DockerModels.Network[] = parseNetworks(service, networkMap);
    if (networks.length !== 0) {
        for (const net of networks) {
            result.networks = [];
            result.networks.push(getNetworkName(net));
        }
    }
 
    const mounts: ComposeModels.Mount[] = parseMounts(service);
    if (mounts.length !== 0) {
        result.volumes = mounts;
    }
 
    const deployBlob: any = {};
 
    // Labels
    const labelsService: {[name: string]: string} = stripDockerLabels(service.Spec.Labels);
    const labelsContainer: {[name: string]: string} = stripDockerLabels(service.Spec.TaskTemplate.ContainerSpec.Labels);
 
    // Labels attached to service
    if (Object.keys(labelsService).length !== 0 ) {
        deployBlob.labels = labelsService;
    }
 
    // Labels attached to container
    if (Object.keys(labelsContainer).length !== 0 ) {
        result.labels = labelsContainer;
    }
 
    let constraints: string[] = [];
    if (service.Spec.TaskTemplate.Placement && service.Spec.TaskTemplate.Placement.Constraints) {
        constraints = service.Spec.TaskTemplate.Placement.Constraints;
    }
 
    if (constraints.length !== 0) {
        deployBlob.placement = {constraints};
    }
 
    if (Object.keys(labelsService).length + constraints.length > 0) {
        result.deploy = deployBlob;
    }
 
    if (service.Spec.TaskTemplate.ContainerSpec.Env) {
        result.environment = service.Spec.TaskTemplate.ContainerSpec.Env;
    }
 
    return result;
}
 
/**
 * Generate a docker-compose string from a list of JSON service documents
 *
 * @param services Array of Services to generate a compose file from
 * @param networks Map of network ID -> network name
 */
export function compose(services: DockerModels.Service[], networkMap: NetworkMap): string {
 
    const stackNetworkMap = createStackNetworkMap(networkMap);
 
    const servicesBlob: {[name: string]: ComposeModels.Service} = {};
 
    for (const dockerService of services) {
        const composeService = parseService(dockerService, networkMap);
        servicesBlob[getServiceName(dockerService)] = composeService;
    }
 
    // TODO(egeldenhuys): The logic here seems a bit convoluted and cam most
    // likely be simplified
 
    const networksBlob: {[name: string]: ComposeModels.StackNetwork} = {};
 
    for (const serviceName in servicesBlob) {
        const composeService = servicesBlob[serviceName];
 
        if (composeService.networks) {
            for (const networkName of composeService.networks) {
 
                Iif (!stackNetworkMap[networkName]) {
                    throw new Error('undefined network in StackNetworkMap: ' + networkName);
                }
 
                networksBlob[networkName] = stackNetworkMap[networkName];
            }
        }
 
    }
 
    const stackFile: ComposeModels.StackFile = {
        version: '3.3',
        services: servicesBlob,
    };
 
    if (Object.keys(networksBlob).length !== 0) {
        stackFile.networks = networksBlob;
    }
 
    return yaml.safeDump(stackFile);
}
 
/**
 * Create a network map to allow generating a docker-compose file
 * @param networks Array of Network objects from Docker
 */
export function createNetworkMap(networks: DockerModels.Network[]): NetworkMap {
    const result: {[id: string]: DockerModels.Network} = {};
 
    for (const net of networks) {
        result[net.Id] = net;
    }
 
    return result;
}
 
/**
 * Return a list of network IDs that require inspection
 *
 * This is required to create a NetworkMap
 * @param services
 */
export function getNetworkIds(services: DockerModels.Service[]): string[] {
    const result: string[] = [];
 
    for (const service of services) {
        if (service.Spec.TaskTemplate.Networks) {
            for (const net of service.Spec.TaskTemplate.Networks) {
                result.push(net.Target);
            }
        }
    }
 
    return result;
}
 
export default compose;