<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var assert = require('assert-plus');
var common = require('../../../lib/common');
var net = require('net');
var restify = require('restify');

function uuidToDockerId(uuid) {
    return (uuid + uuid).replace(/-/g, '');
}

function uuidToShortDockerId(uuid) {
    return uuid.replace(/-/g, '').slice(0, 12);
}

function vmobjToContainer(opts, obj)
{
    assert.object(opts, 'opts');
    assert.arrayOfObject(opts.imgs, 'opts.imgs');
    assert.object(opts.log, 'opts.log');
    assert.object(obj, 'obj');
    assert.string(obj.alias, 'obj.alias');

    var boot_timestamp = new Date(obj.boot_timestamp);
    var cmd = [];
    var container = {};
    var exittime;
    var imgs = opts.imgs; // XXX imgs is a hack until we have better lookup
    //var log = opts.log;
    var now = new Date();
    var uptime = Math.floor((now - boot_timestamp) / 1000);
    var quoted_args = [];

    if (obj.internal_metadata && obj.internal_metadata['docker:id']) {
        container.Id = obj.internal_metadata['docker:id'];
    } else {
        // Fallback to the shortend docker id format from the UUID
        container.Id = obj.uuid.replace(/-/g, '').substr(0, 12);
    }

    if (obj.create_timestamp) {
        container.Created
            = Math.floor((new Date(obj.create_timestamp)).getTime()/1000);
    } else {
        container.Created = 0;
    }

    if (obj.internal_metadata && obj.internal_metadata['docker:entrypoint']) {
        cmd = cmd.concat(
            JSON.parse(obj.internal_metadata['docker:entrypoint']));
    }
    if (obj.internal_metadata && obj.internal_metadata['docker:cmd']) {
        cmd = cmd.concat(JSON.parse(obj.internal_metadata['docker:cmd']));
    }

    // When the arguments have spaces in them, we want to quote them with single
    // quotes as does:
    //
    /* JSSTYLED */
    // https://github.com/docker/docker/blob/3ec695924009421f9b1f79368e9e5b1e3e2ca94f/daemon/list.go#L127-L141
    cmd.slice(1).forEach(function (arg) {
        if (arg.indexOf(' ') === -1) {
            quoted_args.push(arg);
        } else {
            quoted_args.push('\'' + arg + '\'');
        }
    });
    container.Command = cmd.slice(0, 1).concat(quoted_args).join(' ');

    // Names: ['/redis32'] -- others are links
    container.Names = [];
    container.Names.push('/' + obj.alias);

    if (obj.state == 'running') {
        container.Status = 'Up ' + common.humanDuration(uptime);
    } else if (obj.state == 'stopped') {
        if (obj.hasOwnProperty('exit_status')
            && obj.hasOwnProperty('exit_timestamp')) {

            exittime
                = Math.floor((now - (new Date(obj.exit_timestamp))) / 1000);
            container.Status = 'Exited (' + obj.exit_status + ') '
                + common.humanDuration(exittime) + ' ago';
        } else {
            // Most likely in this case the container never started yet.
            // Empty string is what docker daemon currently does on Ubuntu
            container.Status = '';
        }
    } else {
        container.Status = '';
    }

    // docker ps shows the image repo tag
    container.Image = getImage(imgs, obj.image_uuid).RepoTags[0];

    return (container);
}

// XXX hack
function getImage(imgs, uuid)
{
    var found_image;

    imgs.forEach(function (image) {<commit_msg>DOCKER-285: add ports to docker ps output<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var assert = require('assert-plus');
var common = require('../../../lib/common');
var net = require('net');
var restify = require('restify');

function uuidToDockerId(uuid) {
    return (uuid + uuid).replace(/-/g, '');
}

function uuidToShortDockerId(uuid) {
    return uuid.replace(/-/g, '').slice(0, 12);
}

function vmobjToContainer(opts, obj)
{
    assert.object(opts, 'opts');
    assert.arrayOfObject(opts.imgs, 'opts.imgs');
    assert.object(opts.log, 'opts.log');
    assert.object(obj, 'obj');
    assert.string(obj.alias, 'obj.alias');

    var boot_timestamp = new Date(obj.boot_timestamp);
    var cmd = [];
    var container = {};
    var exittime;
    var imgs = opts.imgs; // XXX imgs is a hack until we have better lookup
    //var log = opts.log;
    var now = new Date();
    var uptime = Math.floor((now - boot_timestamp) / 1000);
    var quoted_args = [];
    var im = obj.internal_metadata;
    var image;
    var publishedPorts;
    var seenPorts = [];

    if (im && im['docker:id']) {
        container.Id = im['docker:id'];
    } else {
        // Fallback to the shortend docker id format from the UUID
        container.Id = obj.uuid.replace(/-/g, '').substr(0, 12);
    }

    if (obj.create_timestamp) {
        container.Created
            = Math.floor((new Date(obj.create_timestamp)).getTime()/1000);
    } else {
        container.Created = 0;
    }

    if (im && im['docker:entrypoint']) {
        cmd = cmd.concat(
            JSON.parse(im['docker:entrypoint']));
    }
    if (im && im['docker:cmd']) {
        cmd = cmd.concat(JSON.parse(im['docker:cmd']));
    }

    // When the arguments have spaces in them, we want to quote them with single
    // quotes as does:
    //
    /* JSSTYLED */
    // https://github.com/docker/docker/blob/3ec695924009421f9b1f79368e9e5b1e3e2ca94f/daemon/list.go#L127-L141
    cmd.slice(1).forEach(function (arg) {
        if (arg.indexOf(' ') === -1) {
            quoted_args.push(arg);
        } else {
            quoted_args.push('\'' + arg + '\'');
        }
    });
    container.Command = cmd.slice(0, 1).concat(quoted_args).join(' ');

    // Names: ['/redis32'] -- others are links
    container.Names = [];
    container.Names.push('/' + obj.alias);

    if (obj.state == 'running') {
        container.Status = 'Up ' + common.humanDuration(uptime);
    } else if (obj.state == 'stopped') {
        if (obj.hasOwnProperty('exit_status')
            && obj.hasOwnProperty('exit_timestamp')) {

            exittime
                = Math.floor((now - (new Date(obj.exit_timestamp))) / 1000);
            container.Status = 'Exited (' + obj.exit_status + ') '
                + common.humanDuration(exittime) + ' ago';
        } else {
            // Most likely in this case the container never started yet.
            // Empty string is what docker daemon currently does on Ubuntu
            container.Status = '';
        }
    } else {
        container.Status = '';
    }

    // docker ps shows the image repo tag
    image = getImage(imgs, obj.image_uuid);
    container.Image = image.RepoTags[0];

    // Ports, nginx examples below for 'docker ps':
    //  not exposed: {"PrivatePort":80,"Type":"tcp"}
    //  -P {"IP":"0.0.0.0","PrivatePort":80,"PublicPort":49158,"Type":"tcp"}
    //  -p 80:80 {"IP":"0.0.0.0","PrivatePort":80,"PublicPort":80,"Type":"tcp"}
    container.Ports = [];
    if (im) {
        // Add the exposed ports:
        ['tcp', 'udp'].forEach(function (proto) {
            var protoField = 'docker:' + proto + '_published_ports';
            publishedPorts = JSON.parse(im[protoField] || '[]');
            publishedPorts.forEach(function (port) {
                container.Ports.push({
                    'IP': '0.0.0.0',
                    // sdc-docker doesn't allow a different port mapping.
                    'PrivatePort': port,
                    'PublicPort': port,
                    'Type': proto
                });
                seenPorts.push(port);
            });
        });

        // Add the non-exposed ports:
        if (image.ExposedPorts) {
            Object.keys(image.ExposedPorts).forEach(function (portAndProto) {
                // portAndProto looks like: "80/tcp"
                var portStr = portAndProto.split('/', 1)[0];
                var proto = portAndProto.slice(portStr.length+1);
                var port = parseInt(portStr, 10);
                if (seenPorts.indexOf(port) == -1) {
                    container.Ports.push({
                        'PrivatePort': port,
                        'Type': proto
                    });
                    seenPorts.push(port);
                }
            });
        }
    }

    return (container);
}

// XXX hack
function getImage(imgs, uuid)
{
    var found_image;

    imgs.forEach(function (image) {
{'fraction_non_alphanumeric': 0.15457267910619674, 'fraction_numerical': 0.020041465100207326, 'mean_word_length': 2.175932699341624, 'pattern_counts': {'":': 10, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 3, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5077426', 'n_tokens_mistral': 2836, 'n_tokens_neox': 2670, 'n_words': 618}