示例#1
0
test('mget TESTDIR/01.data TESTDIR/02.data TESTDIR/03.data', function (t) {
    var argv = [
        MGET,
        sprintf('%s/%02d.data', TESTDIR, 1),
        sprintf('%s/%02d.data', TESTDIR, 2),
        sprintf('%s/%02d.data', TESTDIR, 3)
    ];

    /*
     * We expect "mget" to download the three files and emit them on stdout in
     * order, without interstitial linefeeds.
     */
    var expected = 'abc';

    forkExecWait({
        argv: argv
    }, function (err, info) {
        t.ifError(err, err);

        t.equal(info.stderr, '', 'no stderr');
        t.equal(info.stdout, expected, 'stdout from mget');

        t.done();
    });
});
 return this.changes.map(function (ch) {
     return sprintf('update instance "%s" (%s)\n' +
             'of service "%s" to image %s\n', ch.inst.instance,
             ch.inst.alias, ch.service.name, ch.image.uuid) +
         common.indent(sprintf('(%s@%s)',
             ch.image.name, ch.image.version));
 }).join('\n');
示例#3
0
    function (t) {

    var argv = [
        MGET,
        sprintf('%s/%02d.txt', TESTDIR, 1),
        sprintf('%s/%02d.txt', TESTDIR, 2),
        sprintf('%s/%s.txt', TESTDIR, 'XX'),
        sprintf('%s/%02d.txt', TESTDIR, 3)
    ];

    /*
     * We expect "mget" to download the two files and store the contents in the
     * temporary file we nominated.  It will then fail to download the file
     * that does not exist, and the program will stop.
     */
    var expected = [
        'first',
        'file (01)',
        'second',
        'file (02)'
    ].join('\n') + '\n';

    forkExecWait({
        argv: argv
    }, function (err, info) {
        t.ok(err, 'must fail');

        t.ok(info.stderr.match(/^mget: ResourceNotFoundError/, 'stderr'));
        t.equal(info.stdout, expected, 'expected stdout');

        t.done();
    });
});
示例#4
0
    this.changes.forEach(function summarizeChange(ch) {
        if (ch.type === 'update-instance') {
            out.push(sprintf('update instance "%s" (%s)\n' +
                        'of service "%s" to image %s\n', ch.inst.instance,
                        ch.inst.alias, ch.service.name, ch.image.uuid),
                    common.indent(sprintf('(%s@%s)',
                        ch.image.name, ch.image.version)));
        } else {
            var word = (ch.type === 'rollback-service') ?
                'rollback' : 'update';
            var img = ch.image;
            var msg = sprintf('%s "%s" service to image %s\n',
                        word, ch.service.name, img.uuid) +
                    common.indent(sprintf('(%s@%s)', img.name, img.version));

            if (ch.insts) {
                msg += ':\n';
                msg += ch.insts.map(function (inst) {
                    return common.indent(sprintf(
                        'instance "%s" (%s) on server %s',
                        inst.zonename, inst.alias, inst.server));
                }).join('\n');
            } else if (ch.inst) {
                msg += ':\n';
                msg += common.indent(sprintf(
                        'instance "%s" (%s) on server %s',
                        ch.inst.zonename, ch.inst.alias, ch.inst.server));
            }
            out.push(msg);
        }
    });
示例#5
0
	jsprim.forEachKey(nInstancesBySvc, function (svcname, n) {
		var i, instid, cnname;
		instancesBySvc[svcname] = [];
		for (i = 0; i < n; i++) {
			instid = sprintf('svc-%s-%d', svcname, i);
			/*
			 * We use only two different CN uuids to make sure that
			 * we re-use CNs for a given service.  That's in order
			 * to make sure that "global" scoped templates do not
			 * generate multiple probes for the same CN just because
			 * there are two instances of a service on that CN.
			 */
			cnname = sprintf('server-uuid-%d', i % 2);
			instancesBySvc[svcname].push(instid);
			instances[instid] = new instance_info.InstanceInfo({
			    'uuid': instid,
			    'svcname': svcname,
			    'server_uuid': cnname,
			    'local': true,
			    'metadata': {
				'sector': '7G'
			    }
			});

			servernames[cnname] = true;
		}
	});
示例#6
0
test('mget TESTDIR/01.txt TESTDIR/02.txt TESTDIR/03.txt', function (t) {
    var argv = [
        MGET,
        sprintf('%s/%02d.txt', TESTDIR, 1),
        sprintf('%s/%02d.txt', TESTDIR, 2),
        sprintf('%s/%02d.txt', TESTDIR, 3)
    ];

    /*
     * We expect "mget" to download the three files and emit them to stdout in
     * order.
     */
    var expected = [
        'first',
        'file (01)',
        'second',
        'file (02)',
        'third',
        'file (03)'
    ].join('\n') + '\n';

    forkExecWait({
        argv: argv
    }, function (err, info) {
        t.ifError(err, err);

        t.equal(info.stderr, '', 'no stderr');
        t.equal(info.stdout, expected, 'stdout from mget');

        t.done();
    });
});
示例#7
0
UpdateAgentV1.prototype.summarize = function uaSummarize() {
    var c0 = this.changes[0];
    var img = c0.image;
    var out = [sprintf('update "%s" service to image %s ',
                c0.service.name, img.uuid),
            common.indent(sprintf('%s@%s', img.name, img.version)),
            sprintf('in %d servers', c0.insts.length)];
    return out.join('\n');
};
示例#8
0
UpdateDockerlogger.prototype.summarize = function udSummarize() {

    var c0 = this.changes[0];
    var img = c0.image;
    var out = [
        sprintf('update "dockerlogger" service to image %s ', img.uuid),
        common.indent(sprintf('%s@%s', img.name, img.version)),
        sprintf('in %s servers', (
                    c0.insts.length ?
                    c0.insts.length : 'all the setup'))
    ];
    return out.join('\n');
};
示例#9
0
/**
 * Multiple ImgadmErrors in a group.
 */
function MultiError(errs) {
    assert.arrayOfObject(errs, 'errs');
    var lines = [sprintf('multiple (%d) API errors', errs.length)];
    for (var i = 0; i < errs.length; i++) {
        var err = errs[i];
        lines.push(sprintf('    error (%s): %s', err.code, err.message));
    }
    ImgadmError.call(this, {
        cause: errs[0],
        message: lines.join('\n'),
        code: 'MultiError',
        exitStatus: 1
    });
}
示例#10
0
 this.subcmdOrder.forEach(function (name) {
     var func = self.subcmds[name];
     if (func.hidden) {
         return;
     }
     var names = name;
     if (func.aliases) {
         names += sprintf(' (%s)', func.aliases.join(', '));
     }
     var desc = (func.help || '').split('\n', 1)[0];
     desc = desc.replace(/{{name}}/g, self.name);
     var line = sprintf(cmdTemplate, names, desc);
     lines.push(line);
 });
示例#11
0
 Object.keys(this.subcmds).forEach(function (name) {
     var func = self.subcmds[name];
     if (func.hidden) {
         return;
     }
     var names = name;
     if (func.aliases) {
         names += sprintf(' (%s)', func.aliases.join(', '));
     }
     var desc = (func.description ?
         func.description.split('\n', 1)[0] : '');
     desc = desc.replace(/\$NAME/g, self.name);
     var line = sprintf(cmdTemplate, names, desc);
     lines.push(line);
 });
示例#12
0
/*
 * Given a base directory, and a Date, generate the absolute path of the log
 * file to which we would write a sample for that timestamp.
 */
function usageFilePath(basedir, dt) {
    var h = alignDateToHour(dt);
    var sfx = sprintf('%04d-%02d-%02dT%02d.log',
      h.getUTCFullYear(), h.getUTCMonth() + 1, h.getUTCDate(),
      h.getUTCHours());
    return (path.join(basedir, sfx));
}
示例#13
0
		keys.forEach(function (key) {
			if (key != 'name') {
				if (!fc[key])
					values.push(shEscape(key));
				else
					values.push(sprintf('%s=%s',
					    shEscape(key),
					    shEscape(fc[key].toString())));
			}

			if (key == 'date' || key == 'aggr') {
				hasextra = true;
				return;
			}

			if (key == 'step' || key == 'name' || key == 'field')
				return;

			/*
			 * XXX Blow up here if we encounter a field
			 * configuration that we don't know how to serialize.
			 * It would be nice if we could verify this statically,
			 * or at least if the field configuration object ("fc")
			 * had a more rigid set of fields with prefixed names so
			 * that if someone adds a new field, they could
			 * reasonably be asked to look for references like this
			 * one.
			 */
			throw (new VError('internal error: don\'t know how ' +
			    'serialize field property "%s"', key));
		});
示例#14
0
 function onFirstLevelEnd() {
     //This means that the entry isn't in the log yet, so we close
     // everything and fail out.
     log.debug('ending due to first level end');
     return (end(new error.TermMismatchError(sprintf(
         'no clog entry at index %d', firstEntry.index))));
 }
示例#15
0
	it('should generate and write to file stylus string', function *() {
		try {
			var tree = yield TransformerPipe(this.filesTree, this.logger, [
				TransformerStylus.treeToTree.bind({}),
				TransformerAutoprefixer.treeToTree.bind({
					options: {
						browsers: this.browsers
					}
				})
			]);

			yield tree.writeContentToFiles();

			var contentByPipeA = yield cofse.readFile(this.destA, { encoding: 'utf8' });
			var contentShouldBeA = yield cofse.readFile(this.destExpectA, { encoding: 'utf8' });

			var contentByPipeB = yield cofse.readFile(this.destA, { encoding: 'utf8' });
			var contentShouldBeB = yield cofse.readFile(this.destExpectA, { encoding: 'utf8' });

			expect(contentByPipeA).equal(contentShouldBeA);
			expect(contentByPipeB).equal(contentShouldBeB);
		}
		catch (error) {
			console.error(sprintf('%r', error));
			throw new Error('error');
		}
	});
示例#16
0
 opts.alarms.forEach(function (a) {
     console.log(sprintf(fmt,
                         a.id,
                         a.probe.role,
                         a.machine.substr(0, 7),
                         a.probe.name));
 });
示例#17
0
文件: fabrics.js 项目: joyent/sdcadm
 fs.readFile(conf, { format: 'utf8' }, function (err, data) {
     if (err) {
         cb(new errors.ValidationError(err,
             sprintf('failed to read %s: %s', conf, err.message)));
         return;
     }
     try {
         data = JSON.parse(data);
     } catch (e) {
         cb(new errors.ValidationError(e,
             sprintf('%s in not a valid JSON file', conf)));
         return;
     }
     self.data = data;
     cb(null);
 });
示例#18
0
文件: fabrics.js 项目: joyent/sdcadm
        function (err, pool) {
        if (err) {
            if (napiUserError(err, 'uuid')) {
                cb(new errors.ValidationError(err,
                    sprintf('failed to find resource pool: %s, it ' +
                        'either does not exist or is invalid',
                    self.data.sdc_underlay_pool)));
                return;
            } else {
                cb(new errors.SDCClientError(err, 'napi'));
                return;
            }
        }

        /* All networks on a pool should have the same tag */
        self.sdcadm.napi.getNetwork(pool.networks[0],
            function (neterr, net) {
            if (neterr) {
                return cb(new errors.SDCClientError(neterr, 'napi'));
            }
            if (net.nic_tag !== self.data.sdc_underly_tag) {
                return cb(new errors.ValidationError(sprintf('specified ' +
                    'network pool %s has nic tag %s, which does not ' +
                    'match fabric configuration "sdc_underlay_tag": %s',
                    self.data.sdc_underlay_pool,
                    net.nic_tag,
                    self.data.sdc_underlay_tag)));
            }
            return cb(null);
        });
    });
示例#19
0
CLI.prototype.do_delete_key = function (subcmd, opts, args, callback) {
    var self = this;
    if (opts.help) {
        this.do_help('help', {}, [subcmd], callback);
        return;
    } else if (args.length !== 2) {
        return callback(new errors.UsageError(sprintf(
            'incorrect number of arguments: "%s"', args.join(' '))));
    }
    var loginOrUuid = args[0];
    var keyNameOrFp = args[1];

    var client;
    async.series([
        function getClient(next) {
            self.getMasterUfdsClient(function (cErr, client_) {
                if (cErr)
                    return callback(cErr);
                client = client_;
                next();
            });
        },
        function deleteKey(next) {
            client.deleteKey(loginOrUuid, keyNameOrFp, next);
        },
        function print(next) {
            p('Key "%s" deleted from user "%s"', keyNameOrFp, loginOrUuid);
            next();
        },
        function closeClient(next) {
            client.close(next);
        }
    ], callback);
};
示例#20
0
文件: index.js 项目: joyent/vera
function raftSummary(r) {
    return (sprintf(
        '%s %9s term: %3d, t-out: %2d, leader: %s, commitIdx: %d\n',
        r.id, r.state, r.currentTerm(), r.leaderTimeout,
        r.leaderId === undefined ? 'undefd' : r.leaderId,
        r.stateMachine.commitIndex));
}
BunyanPrettyPrinter.prototype._transform = function (chunk, _, callback)
{
	var component = chunk.component || chunk.name;
	var message = chunk.msg;
	var stream = this;
	var level;

	switch (chunk.level) {
	case mod_bunyan.TRACE:		level = 'TRACE'; break;
	case mod_bunyan.DEBUG:		level = 'DEBUG'; break;
	case mod_bunyan.INFO:		level = 'INFO';  break;
	case mod_bunyan.WARN:		level = 'WARN';  break;
	case mod_bunyan.ERROR:		level = 'ERROR'; break;
	case mod_bunyan.FATAL:		level = 'FATAL'; break;
	default:			level = '?????'; break;
	}

	this.push(sprintf('[%5s] %s: %s\n', level, component, message));

	mod_jsprim.forEachKey(chunk, function (key, value) {
		if (bunyanStdKeys.hasOwnProperty(key))
			return;
		stream.push(sprintf('  %10s: %j\n', key, value));
	});

	callback();
};
示例#22
0
文件: index.js 项目: joyent/vera
function messageBusSummary(m) {
    var s = '';
    s += sprintf(
        'Messages:%s\n',
        Object.keys(m.messages).length === 0 ? ' (none)' : '');
    Object.keys(m.messages).forEach(function (mi) {
        var me = m.messages[mi];
        var prefix = sprintf('%s -> %s', me.from, me.to);
        if (me.message.operation === 'requestVote') {
            s += sprintf(
                '  reqVote %s: term %3d, logIndex: %3d, logTerm: %3d\n',
                prefix, me.message.term, me.message.lastLogIndex,
                me.message.lastLogTerm);
        } else if (me.message.operation === 'appendEntries') {
            s += sprintf(
                '  appEntr %s: term %3d, leader: %s, commitIndex: %3d\n',
                prefix, me.message.term, me.message.leaderId,
                me.message.commitIndex);
        } else if (me.message.operation === 'installSnapshot') {
            s += sprintf(
                '  intSnap %s\n', prefix);
        } else {
            s += sprintf(
                ' unknown message: ', me);
        }
    });
    return (s);
}
示例#23
0
文件: index.js 项目: joyent/vera
                function tryOnce() {

                    //Error out if this is taking "too long".  This is really
                    // just a safety valve so I don't have infinite loops.
                    // Alternatively, I could just set the election timeout
                    // really low on raft-0, but I might as well excercise
                    // leader election as much as possible.
                    s += sprintf('%d:\n%s\n', x, c.toString());
                    if (x++ === 1000) {
                        console.error(s);
                        return (subcb(
                            new Error('leader election took too long')));
                    }

                    //End condition is when there is one leader and the rest
                    // followers.
                    var states = { 'leader': 0, 'follower': 0, 'candidate': 0 };
                    Object.keys(c.peers).forEach(function (p) {
                        ++states[c.peers[p].state];
                    });
                    if (states['leader'] === 1 &&
                        states['follower'] === peers.length - 1) {
                        return (subcb());
                    }

                    //Otherwise, move the cluster along...
                    c.tick(tryOnce);
                }
示例#24
0
CLI.prototype.do_get = function (subcmd, opts, args, callback) {
    if (opts.help) {
        this.do_help('help', {}, [subcmd], callback);
        return;
    } else if (args.length !== 1) {
        return callback(new errors.UsageError(sprintf(
            'incorrect number of arguments: "%s"', args.join(' '))));
    }
    var loginOrUuid = args[0];
    this.getLocalUfdsClient(function (cErr, client) {
        if (cErr)
            return callback(cErr);
        client.getUser(loginOrUuid, function (err, user) {
            if (err) {
                return callback(new errors.APIError(err));
            } else if (!user) {
                return callback(new errors.NoSuchUser(user));
            } else if (opts.ldif) {
                delete user.controls;
                var preferred = [
                    'dn',
                    'uuid',
                    'login',
                    'email',
                    'cn',
                    'givenname',
                    'sn'
                ];
                function preferredFirst(a, b) {
                    var aIdx = preferred.indexOf(a);
                    var bIdx = preferred.indexOf(b);
                    if (aIdx === -1 && bIdx !== -1) {
                        return 1;
                    } else if (aIdx !== -1 && bIdx === -1) {
                        return -1;
                    } else {
                        var aCmp = aIdx === -1 ? a : aIdx;
                        var bCmp = bIdx === -1 ? b : bIdx;
                        if (aCmp > bCmp) {
                            return 1;
                        } else if (aCmp === bCmp) {
                            return 0;
                        } else {
                            return -1;
                        }
                    }
                }
                Object.keys(user).sort(preferredFirst).forEach(function (fld) {
                    if (typeof (user[fld]) !== 'function') {
                        printLdifField(fld, user[fld]);
                    }
                });
            } else {
                delete user.controls;
                p(JSON.stringify(user, null, 2));
            }
            callback();
        });
    });
};
示例#25
0
    function (t) {

    var file = path.join(TMPDIR, '01.txt');
    var argv = [MGET, '-O', sprintf('%s/%02d.txt', TESTDIR, 1)];

    /*
     * We expect "mget" to download the one file and store the contents in
     * the temporary file we nominated.
     */
    var expected = [
        'first',
        'file (01)'
    ].join('\n') + '\n';

    unlinkIfExists(file);

    process.chdir(TMPDIR);

    forkExecWait({
        argv: argv
    }, function (err, info) {
        t.ifError(err, err);
        t.equal(info.stdout, '', 'no stdout');
        t.equal(info.stderr, '', 'no stderr');

        var fileData = fs.readFileSync(file, 'utf8');
        t.equal(fileData, expected, 'file data from mget');

        unlinkIfExists(file);

        t.done();
    });
});
示例#26
0
function NoSourcesError() {
    ImgadmError.call(this, {
        message: sprintf('imgadm has no configured sources'),
        code: 'NoSources',
        exitStatus: 1
    });
}
示例#27
0
CLI.prototype.do_replace_attr = function (subcmd, opts, args, callback) {
    var self = this;
    if (opts.help) {
        this.do_help('help', {}, [subcmd], callback);
        return;
    } else if (args.length !== 3) {
        return callback(new errors.UsageError(sprintf(
            'incorrect number of arguments: "%s"', args.join(' '))));
    }
    var loginOrUuid = args[0];
    var attr = args[1];
    var value = args[2];

    vasync.pipeline({arg: {}, funcs: [
        /* @field ctx.client */
        function getClient(ctx, next) {
            self.getMasterUfdsClient(function (err, client) {
                if (err) {
                    return next(err);
                }
                ctx.client = client;
                next();
            });
        },
        /* @field ctx.user */
        function getUser(ctx, next) {
            ctx.client.getUser(loginOrUuid, function (err, user) {
                if (err) {
                    next(new errors.APIError(err));
                } else if (!user) {
                    next(new errors.NoSuchUser(user));
                } else {
                    ctx.user = user;
                    next();
                }
            });
        },
        function updateUser(ctx, next) {
            /*
             * <ufdsClient>.updateUser() doesn't support 'add' modification
             * type, so we are skipping using it for the '*-attr' commands.
             */
            var change = {
                type: 'replace',
                modification: {}
            };
            change.modification[attr] = value;
            ctx.client.modify(ctx.user.dn, [change], next);
        },
        function print(ctx, next) {
            p('Replaced attribute on user %s (%s): %s=%s', ctx.user.uuid,
                ctx.user.login, attr, value);
            next();
        },
        function closeClient(ctx, next) {
            ctx.client.close(next);
        }
    ]}, callback);
};
示例#28
0
 opts.probes.forEach(function (p) {
     console.log(sprintf(fmt,
                         // TODO: make sure we always have a role
                         p.role || '', // Role can be absent
                         p.agent.substr(0, 7),
                         p.uuid.substr(0, 7),
                         p.name));
 });
示例#29
0
handleRequest('/nonexistent', function (err) {
	if (err) {
		console.log(err.message);
		console.log(extsprintf.sprintf('%r', err));
	}

    /* ... */
});
示例#30
0
CLI.prototype.do_add_key = function (subcmd, opts, args, callback) {
    var self = this;
    if (opts.help) {
        this.do_help('help', {}, [subcmd], callback);
        return;
    } else if (args.length !== 2) {
        return callback(new errors.UsageError(sprintf(
            'incorrect number of arguments: "%s"', args.join(' '))));
    }
    var loginOrUuid = args[0];
    var pubkeyPath = args[1];

    var client;
    var key;
    var pubkey;
    async.series([
        function readPubkey(next) {
            // Guard
            if (!opts.force && pubkeyPath.slice(-4) !== '.pub') {
                return next(new errors.UsageError(sprintf(
                    'pubkey file, "%s", does not end in ".pub": aborting in '
                    + 'case this is accidentally a private key file (use '
                    + '"--force" to override)', pubkeyPath)));
            }
            fs.readFile(pubkeyPath, 'ascii', function (err, content) {
                pubkey = content;
                next(err);
            });
        },
        function getClient(next) {
            self.getMasterUfdsClient(function (cErr, client_) {
                if (cErr)
                    return callback(cErr);
                client = client_;
                next();
            });
        },
        function addKey(next) {
            var keyData = {
                openssh: pubkey
            };
            if (opts.name) {
                keyData.name = opts.name;
            }
            client.addKey(loginOrUuid, keyData, function (err, key_) {
                key = key_;
                next(err);
            });
        },
        function print(next) {
            p('Key "%s" added to user "%s"', key.name, loginOrUuid);
            next();
        },
        function closeClient(next) {
            client.close(next);
        }
    ], callback);
};