<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 2016 Joyent, Inc.
 */

var bunyan = require('bunyan');
var libuuid = require('libuuid');
var test = require('tape');
var util = require('util');

var CNAPI = require('../lib/index').CNAPI;



// --- Globals

var CNAPI_URL = 'http://' + (process.env.CNAPI_IP || '10.99.99.22');

var SERVER = null;
var testVmUuid = libuuid.create();
var testVmAlias = 'nodesdcclientstest-cnapi-' + testVmUuid.split('-')[0];
var TASK = null;
var CUSTOMER = process.env.UFDS_ADMIN_UUID;


// --- Helpers

function waitForVmState(t, cnapi, state, callback) {
    var finished = false;
    var error;

    var timeout = setTimeout(function () {
        if (finished) {
            return;
        }

        if (error) {
            callback(error);
            return;
        } else {
            callback(new Error('timed out waiting on vm state'));
            return;
        }
    }, 30000);

    function check() {
        cnapi.getVm(SERVER, testVmUuid, function (err, vm) {
            error = err;
            if (err) {
                setTimeout(check, 3000);
                return;
            }
            t.comment('test VM ' + testVmUuid + ' state: ' + vm.state);

            if (vm.state === state) {
                clearTimeout(timeout);
                callback();
                return;
            }

            setTimeout(check, 3000);
        });
    }

    check();
}

function waitForTask(t, cnapi, callback) {
    var finished = false;
    var error;

    var tasktimeout;

    var timeout = setTimeout(function () {
        clearTimeout(tasktimeout);
        if (finished) {
            return;
        }

        if (error) {
            callback(error);
            return;
        } else {
            callback(new Error('timed out waiting on task at '
                + (new Date()).toISOString()));
            return;
        }
    }, 50000);

    function check() {
        cnapi.getTask(TASK, function (err, task) {
            error = err;
            if (finished) {
                return;
            }
            if (err) {
                t.comment('CNAPI getTask err: ' + err.message);
                if (err.message === 'no such task found') {
                    setTimeout(check, 3000);
                    return;
                }
                clearTimeout(timeout);
                finished = true;
                callback(err);
                return;
            }

            t.comment('[' + (new Date()).toISOString() + '] CNAPI task '
                + TASK + ' status: ' + task.status);

            if (task.status == 'failure') {
                clearTimeout(timeout);
                finished = true;
                callback(new Error(
                    'Task failed ' + util.inspect(task, { depth: null })));
                return;
            }

            if (task.status == 'complete') {
                clearTimeout(timeout);
                finished = true;
                callback(null);
                return;
            }

            tasktimeout = setTimeout(check, 3000);
            return;
        });
    }

    check();
}


// --- Tests

test('cnapi', function (tt) {
    var cnapi;

    tt.test(' setup', function (t) {
        cnapi = new CNAPI({
            url: CNAPI_URL,
            retry: {
                retries: 1,
                minTimeout: 1000
            },
            log: new bunyan.createLogger({
                name: 'cnapi_unit_test',
                stream: process.stderr,
                level: (process.env.LOG_LEVEL || 'info'),
                serializers: bunyan.stdSerializers
            })
        });
        t.end();
    });

    tt.test(' list servers', function (t) {
        cnapi.listServers({ headnode: true }, function (err, servers) {
            t.ifError(err);
            t.ok(servers);
            SERVER = servers[0].uuid;
            t.end();
        });
    });

    tt.test(' get server', function (t) {
        cnapi.getServer(SERVER, function (err, server) {
            t.ifError(err);
            t.ok(server);
            t.end();
        });
    });

    tt.test(' create vm', function (t) {
        var opts = {
            uuid: testVmUuid,
            alias: testVmAlias,
            owner_uuid: CUSTOMER,
            brand: 'joyent',
            // This is sdc-smartos@1.6.3, which works for as long as it is<commit_msg>TOOLS-1852 sdc-clients: Fix cnapi test to run even if there is a down headnode Reviewed by: <NAME> <<EMAIL>><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) 2017, Joyent, Inc.
 */

var bunyan = require('bunyan');
var libuuid = require('libuuid');
var test = require('tape');
var util = require('util');

var CNAPI = require('../lib/index').CNAPI;



// --- Globals

var CNAPI_URL = 'http://' + (process.env.CNAPI_IP || '10.99.99.22');

var SERVER = null;
var testVmUuid = libuuid.create();
var testVmAlias = 'nodesdcclientstest-cnapi-' + testVmUuid.split('-')[0];
var TASK = null;
var CUSTOMER = process.env.UFDS_ADMIN_UUID;


// --- Helpers

function waitForVmState(t, cnapi, state, callback) {
    var finished = false;
    var error;

    var timeout = setTimeout(function () {
        if (finished) {
            return;
        }

        if (error) {
            callback(error);
            return;
        } else {
            callback(new Error('timed out waiting on vm state'));
            return;
        }
    }, 30000);

    function check() {
        cnapi.getVm(SERVER, testVmUuid, function (err, vm) {
            error = err;
            if (err) {
                setTimeout(check, 3000);
                return;
            }
            t.comment('test VM ' + testVmUuid + ' state: ' + vm.state);

            if (vm.state === state) {
                clearTimeout(timeout);
                callback();
                return;
            }

            setTimeout(check, 3000);
        });
    }

    check();
}

function waitForTask(t, cnapi, callback) {
    var finished = false;
    var error;

    var tasktimeout;

    var timeout = setTimeout(function () {
        clearTimeout(tasktimeout);
        if (finished) {
            return;
        }

        if (error) {
            callback(error);
            return;
        } else {
            callback(new Error('timed out waiting on task at '
                + (new Date()).toISOString()));
            return;
        }
    }, 50000);

    function check() {
        cnapi.getTask(TASK, function (err, task) {
            error = err;
            if (finished) {
                return;
            }
            if (err) {
                t.comment('CNAPI getTask err: ' + err.message);
                if (err.message === 'no such task found') {
                    setTimeout(check, 3000);
                    return;
                }
                clearTimeout(timeout);
                finished = true;
                callback(err);
                return;
            }

            t.comment('[' + (new Date()).toISOString() + '] CNAPI task '
                + TASK + ' status: ' + task.status);

            if (task.status == 'failure') {
                clearTimeout(timeout);
                finished = true;
                callback(new Error(
                    'Task failed ' + util.inspect(task, { depth: null })));
                return;
            }

            if (task.status == 'complete') {
                clearTimeout(timeout);
                finished = true;
                callback(null);
                return;
            }

            tasktimeout = setTimeout(check, 3000);
            return;
        });
    }

    check();
}


// --- Tests

test('cnapi', function (tt) {
    var cnapi;

    tt.test(' setup', function (t) {
        cnapi = new CNAPI({
            url: CNAPI_URL,
            retry: {
                retries: 1,
                minTimeout: 1000
            },
            log: new bunyan.createLogger({
                name: 'nodesdcclientstest-cnapi',
                stream: process.stderr,
                level: (process.env.LOG_LEVEL || 'info'),
                serializers: bunyan.stdSerializers
            })
        });
        t.end();
    });

    tt.test(' list servers', function (t) {
        cnapi.listServers({ headnode: true }, function (err, servers) {
            t.ifError(err, err);

            // Choose a running server for subsequent tests.
            SERVER = servers.filter(function (s) {
                return (s.status === 'running');
            })[0].uuid;

            t.end();
        });
    });

    tt.test(' get server', function (t) {
        cnapi.getServer(SERVER, function (err, server) {
            t.ifError(err);
            t.ok(server);
            t.end();
        });
    });

    tt.test(' create vm', function (t) {
        var opts = {
            uuid: testVmUuid,
            alias: testVmAlias,
            owner_uuid: CUSTOMER,
            brand: 'joyent',
            // This is sdc-smartos@1.6.3, which works for as long as it is
{'fraction_non_alphanumeric': 0.12826502442132087, 'fraction_numerical': 0.01146740284561478, 'mean_word_length': 1.3924307848615698, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 6, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, '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': '6495282', 'n_tokens_mistral': 2858, 'n_tokens_neox': 2662, 'n_words': 673}