function startRestify(next) { var server = restify.createServer({ name: 'Todo', version: '0.0.1' }); // ------------------------------------ // Middleware // ------------------------------------ server.use(restify.CORS()); server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser()); server.use(restify.bodyParser()); // ------------------------------------ // Routes // ------------------------------------ var todos = require('./controllers/todos'); server.get('/todos', todos.list); server.get('/todos/:id', todos.show); server.post('/todos', todos.create); server.put('/todos/:id', todos.update); server.put('/todos/:id/completed', todos.completed); server.del('/todos/:id', todos.destroy); // Logging of requests server.on('after', restify.auditLogger({ log: Logger })); // Start server server.listen(8080, function () { next(server); }); }
function main() { var server; if (process.argv.length > 2) { baseport = parseInt(process.argv[2], 10); if (isNaN(baseport)) { throw (new Error('bad base port')); } } log = new bunyan({ 'name': 'testproxy', 'level': 'trace' }); server = restify.createServer({ 'name': 'testproxy', 'noWriteContinue': true, 'version': [ '1.0.0' ], 'log': log.child({ 'serializers': restify.bunyan.serializers }) }); server.pre(restify.pre.sanitizePath()); server.use(restify.requestLogger()); server.use(restify.queryParser()); server.on('after', restify.auditLogger({ 'log': log })); /* JSSTYLED */ server.get(/.*/, proxy); server.listen(baseport + 1, function () { console.log('%s listening at %s', server.name, server.url); }); }
server.on('after', function _auditAfter(req, res, route, err) { var auditLogger = restify.auditLogger({ log: req.log.child({route: route && route.name}, true) }); auditLogger(req, res, route, err); });
function bootstrap(options, callback) { var server = restify.createServer() server.use(restify.queryParser({mapParams : false})) server.use(restify.bodyParser({mapParams : false})) restify.defaultResponseHeaders = function () { // LOL -- the collector *always* leaves the content-type set to text/plain this.header('Content-Type', 'text/plain') } server.on('after', restify.auditLogger({log : logger})) server.post('/agent_listener/invoke_raw_method', function (req, res, next) { var validations = {} validators.queryString(req.query, validations) validators.httpHeaders(req, validations) if (!methods[req.query.method]) { validations.query_errors.push("unfamiliar method invoked; bailing out") res.send(404, validations) next() } else { methods[req.query.method](req, res, validations, next) } }) server.listen(options.port, function () { callback(null, server) }) }
/* * Set up server * @return the created server */ function createServer (logger) { var settings = { name: (config.has('server.name') && config.get('server.name')) ? config.get('server.name') : require(path.join(__dirname, 'package')).name }; if (logger) settings.log = logger; var server = restify.createServer(settings); server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(restify.jsonp()); server.use(restify.gzipResponse()); server.use(restify.CORS()); server.on('NotFound', function (req, res, next) { if (logger) { logger.debug('404', 'No route that matches request for ' + req.url); } res.send(404, req.url + ' was not found'); }); if (logger) server.on('after', restify.auditLogger({ log: logger })); routes(server, logger); return server; }
(function main() { var server = restify.createServer({ name: "HelloWorld", log: LOG }); server.get('/', function root(req, res, next) { var routes = [ 'GET /', 'POST /todo', 'GET /todo', 'DELETE /todo', 'PUT /todo/:name', 'GET /todo/:name', 'DELETE /todo/:name' ]; res.send(200, routes); return next(false); }); server.on('after', restify.auditLogger({ body: true, log: bunyan.createLogger({ level: 'info', name: 'todoapp-audit', stream: process.stdout }) })); // At last, let's rock and roll server.listen(3000, function onListening() { LOG.info('listening at %s', "3000"); }); })();
server.on('after', function (req, res, route, err) { var method = req.method; var path = req.path(); if (method === 'GET' || method === 'HEAD') { if (path === '/ping') { return; } } // Successful GET res bodies are uninteresting and big. var body = !(method === 'GET' && Math.floor(res.statusCode / 100) === 2); var timers = {}; (req.timers || []).forEach(function (time) { var t = time.time; var _t = Math.floor((1000000 * t[0]) + (t[1] / 1000)); timers[time.name] = _t; }); restify.auditLogger({ log: req.log.child({ route: route }, true), body: body, timers: timers })(req, res, route, err); });
server.on('after', function restifyAuditCb (req, res, route, err) { if (route && route.spec.path === 'health') { // Skip auditor logging if its health request return } var auditer = restify.auditLogger({ log: logger }) auditer(req, res, route, err) })
server.on('after', function _filteredAuditLog(req, res, route, err) { restify.auditLogger({ log: req.log.child({ component: 'audit', route: route && route.name }, true), // Successful GET res bodies are uninteresting and *big*. body: !((req.method === 'GET') && Math.floor(res.statusCode/100) === 2) })(req, res, route, err); });
server.on('after', function (req, res, route, err) { restify.auditLogger({ log: log.child( { route: route && route.name, action: req.query.action }, true), body: true })(req, res, route, err); });
/* * Set up server * @return the created server */ function createServer (logger) { var settings = { name: (config.has('server.name') && config.get('server.name')) ? config.get('server.name') : require(path.join(__dirname, 'package')).name }; if (logger) settings.log = logger; var server = restify.createServer(settings); server.use(restify.CORS()); server.use(restify.acceptParser(server.acceptable)); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.use(jwt({ secret: config.get('server.secret'), credentialsRequired: false, getToken: function fromHeaderOrQuerystring (req) { if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'JWT') { return req.headers.authorization.split(' ')[1]; } else if (req.query && req.query.token) { return req.query.token; } return null; } })); server.on('NotFound', function (req, res, next) { if (logger) { logger.debug('404', 'No route that matches request for ' + req.url); } res.send(404, req.url + ' was not found'); }); if (logger) server.on('after', restify.auditLogger({ log: logger })); var mongoUrl = config.get("server.mongoUrl"); logger.info("Connecting to MongDB " + mongoUrl); var db = mongojs(mongoUrl); db.on('error', function (err) { logger.error(err); }); db.on('connect', function() { logger.info("Connected to MongoDB"); }); routes(server, logger, db); return server; }
cnapi.on('after', function (req, res, route, err) { if (req.route && AUDIT_SKIP_ROUTES[req.route.name]) { return; } // Successful GET res bodies are uninteresting and *big*. var body = req.method !== 'GET' && res.statusCode !== 404 && Math.floor(res.statusCode/100) !== 2; restify.auditLogger({ log: req.log.child({ route: route && route.name }, true), body: body })(req, res, route, err); });
this.server.on('after', function (req, res, route, err) { if (req.path() === '/ping') { return; } // Successful GET res bodies are uninteresting and *big*. var method = req.method; var body = !((method === 'GET' || req.route.name === 'putvms') && Math.floor(res.statusCode/100) === 2); restify.auditLogger({ log: req.log.child({ route: route && route.name }, true), body: body })(req, res, route, err); });
server.on('after', function _filteredAuditLog(req, res, route, err) { // Don't log ping requests, to avoid filling up the log if (route && (route.name == 'getping' || route.name == 'headping')) { return; } restify.auditLogger({ log: req.log.child({ component: 'audit', route: route && route.name }, true), // Successful GET res bodies are uninteresting and *big*. body: !((req.method === 'GET') && Math.floor(res.statusCode/100) === 2) })(req, res, route, err); });
server.on('after', function (req, res, route, err) { var method = req.method; var path = req.path(); if (method === 'GET' || method === 'HEAD') { if (path === '/ping') { return; } } // Successful GET res bodies are uninteresting and big. var body = !(method === 'GET' && Math.floor(res.statusCode / 100) === 2); restify.auditLogger({ log: req.log.child({ route: route }, true), body: body })(req, res, route, err); });
server.on('after', function (req, res, route, err) { // Skip logging some high frequency or unimportant endpoints to // keep log noise down. var method = req.method; var pth = req.path(); if (pth === '/ping') { return; } // Successful GET res bodies are uninteresting and *big*. var body = !(method === 'GET' && Math.floor(res.statusCode / 100) === 2); restify.auditLogger({ log: req.log.child( { route: route && route.name || route }, true), body: body })(req, res, route, err); });
self.server.on('after', function auditReq(req, res, route, err) { var method = req.method; var reqpath = req.path(); if (method === 'GET' || method === 'HEAD') { if (reqpath === '/ping') { return; } } // Successful GET res bodies are uninteresting and *big*. var body = method !== 'GET' && res.statusCode !== 404 && Math.floor(res.statusCode/100) !== 2; restify.auditLogger({ log: req.log.child({ route: route && route.name }, true), body: body })(req, res, route, err); });
constructor(connection) { this.Room = connection.model('Room', schemas.Room) this.Message = connection.model('Message', schemas.Message); this.User = connection.model('User', schemas.User); this.server = restify.createServer({ name: 'Battle chat RESTify server', }); this.server.on('after', restify.auditLogger({ log: bunyan.createLogger({ name: 'Battle chat RESTify server', streams: [ { level: "warn", stream: process.stdout }, { level: "trace", path: 'server.log', type: "rotating-file", period: "1d", count: 1 }] }), body: true, })); this.server.use(restify.acceptParser(this.server.acceptable)) .use(restify.authorizationParser()) .use(restify.dateParser()) .use(restify.queryParser({ mapParams: false })) .use(restify.bodyParser({ mapParams: false })) .use(cookieParser.parse) .use(restify.throttle({ burst: 100, rate: 10, ip: false, xff: true, })); this.server.get('/user/', this.authorize.bind(this), this.populateUser.bind(this), this.get_user.bind(this)); this.server.post('/room/', this.authorize.bind(this), this.post_room.bind(this)); this.server.get('/room/', this.authorize.bind(this), this.populateUser.bind(this), this.get_rooms.bind(this)); this.server.get('/room/:_id', this.authorize.bind(this), this.populateUser.bind(this), this.get_room.bind(this)); this.server.post('/room/:room_id/message', this.authorize.bind(this), this.populateUser.bind(this), this.post_room_message.bind(this)); //this.server.post('/room/:room_id/user/', this.authorize.bind(this), post_room_user); return this; };
var init_restify = function (_, next) { server.use(mod_restify.acceptParser(server.acceptable)); server.use(mod_restify.queryParser()); server.use(mod_restify.bodyParser({ 'mapParams': false })); server.on('after', mod_restify.auditLogger({ log: log.child({ component: 'AuditLog' }) })); server.on('uncaughtException', mod_common.restifyPanic); server.get('/status', self.handle_status.bind(self)); server.get('/attach/:id/master', self.handle_master.bind(self)); server.get('/attach/:id/slave', self.handle_slave.bind(self)); server.listen(port, bind_ip, function () { log.info({ port: port }, 'server listening'); next(); }); };
module.exports = function (app, config, restLogger) { app.use(restify.acceptParser(app.acceptable)); app.use(restify.authorizationParser()); app.use(restify.dateParser()); app.use(restify.queryParser()); app.use(restify.jsonp()); app.use(restify.gzipResponse()); app.use(restify.bodyParser()); // Validating rest calls app.use(node_restify_validator.validationPlugin( { errorsAsArray: false })); // Cross domain? Need to verify if this is required for this app // http://stackoverflow.com/questions/14338683/how-can-i-support-cors-when-using-restify app.use(restify.CORS()); app.use(restify.fullResponse()); //new Buffer("Hello World").toString('base64') //findOne SessionKey // if not found create one and use it's key app.use(clientSessions(config.cookieSetting)); app.use(restify.throttle({ burst: 100, rate: 50, ip: true, overrides: { '192.168.1.1': { rate: 0, // unlimited burst: 0 } } })); app.use(restify.conditionalRequest()); // Enabling auditing app.on('after', restify.auditLogger({ log:restLogger })); }
module.exports.createServer = function createServer(cb) { var confObj = loadConf(appRoot + '/test/fixture/testConf.json'); var port = process.env.UNIT_TEST_PORT || confObj.restify.port; var dtra = getDtrace(); var server = restify.createServer({ dtrace: dtra, log: LOG }); server.on('after', restify.auditLogger({ log: LOG.child({ component: 'audit' }) })); server.listen(port, confObj.restify.host, function (err) { if (err) { cb(err); } cb(); }); return server; };
this.server.on('after', function (req, res, route, err) { if (req.path() === '/ping') { return; } var method = req.method; var requestSuccessful = responseIndicatesSuccess(res); // For debugging purposes, include the response's body in the audit log // by default. var includeBodyInAuditLog = true; if (requestSuccessful) { // When the request is succesful, include the body of the response // in the audit log, unless in the following cases: // // 1. A GET request: the response's body is not particularly // interesting and is usually big. // // 2. A HEAD request: even if a body is set in this case, it's only // so that the Content-Length header is properly set in the custom // JSON restify formatter according to RFC 2616. Having it in the // audit log is not relevant since it's actually not sent to the // client sending the request. // // 3. A PutVms request: the response's body would be equivalent to // the request's data and is usually big. if (method === 'GET' || method === 'HEAD' || (route && route.name === 'putvms')) { includeBodyInAuditLog = false; } } restify.auditLogger({ log: req.log.child({ route: route && route.name }, true), body: includeBodyInAuditLog })(req, res, route, err); });
function MockAgentStartHttpServeruuid() { var server; var self = this; self.agentServer = new CnAgentHttpServer({ bindip: '0.0.0.0', log: log }); self.agentServer.start(); server = restify.createServer(); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.on('after', restify.auditLogger({ log: log })); server.get('/servers', self.getServers.bind(self)); server.get('/servers/:uuid', self.getServer.bind(self)); server.post('/servers', self.createServer.bind(self)); server.del('/servers/:uuid', self.deleteServer.bind(self)); server.listen(HTTP_LISTEN_PORT, HTTP_LISTEN_IP, function () { console.log('%s listening at %s', server.name, server.url); }); };
var logger = function (server, config) { // Check if not enable if (!config.audit.enable) { return function (req, res, next) { next(); }; } // Create conecction var redisClient = require('./Redis.js')(config); // Check if ther is some redis stream for (var stream in config.audit.streams) { var item = config.audit.streams[stream]; if (item.type === 'redis') { item.type = 'raw'; item.stream = redisClient; } // Prettyprint if show in console if (item.stream === process.stdout) { var prettyStdOut = new PrettyStream(); prettyStdOut.pipe(process.stdout); item.stream = prettyStdOut; } } // Create auditLogger return restify.auditLogger({ log: bunyan.createLogger({ name: config.audit.name, src: config.audit.src, streams: config.audit.streams }) }); };
MongoClient.connect(config.mongo.connectionString, (err, db) => { var server = restify.createServer({ log: log, name: 'nrod-api' }) server.on('after', restify.auditLogger({ log: log })); server.get( '/test', function (req, resp, next) { var collection = db.collection('TRAINS') collection.find({'movementActive':true, 'tdActive': true, 'lastSeen.location.TIPLOC': 'LEWISHM'}).toArray( (error, doc) => { log.debug(doc) resp.end(JSON.stringify(doc)) next() }) }) server.listen(3000, () => { log.info('%s listening at %s', server.name, server.url) }) })
credentials: nconf.get('CORS:Credentials'), headers: nconf.get('CORS:Headers'), }; server.pre( restify.CORS(corsOptions) ); if ( corsOptions.headers.length ) { server.on('MethodNotAllowed', require( path.join(__dirname, 'helpers', 'corsHelper.js') )() ); } /** * Request / Response Logging */ server.on('after', restify.auditLogger({ log: Logger })); /** * Server routes */ var middlewareList = [ 'root' ].map(function ( middlewareName ) { var middleware; middleware = require( path.join(__dirname, 'middleware', middlewareName) ); return middleware.setup( server ); }); /**
server.on('uncaughtException', function uncaughtExceptionCb (req, res, route, err) { var auditer = restify.auditLogger({ log: logger.child({component: 'audit'}) }) auditer(req, res, route, err) res.send(500, 'Unexpected error occured') })
///--- API /** * Returns a server with all routes defined on it */ function createServer(options) { assert.object(options, 'options'); assert.string(options.directory, 'options.directory'); assert.object(options.log, 'options.log'); // Create a server with our logger and custom formatter // Note that 'version' means all routes will default to // 1.0.0 var server = restify.createServer({ formatters: { 'application/todo; q=0.9': formatTodo }, log: options.log, name: 'todoapp', version: '1.0.0' }); // Ensure we don't drop data on uploads server.pre(restify.pre.pause()); // Clean up sloppy paths like //todo//////1// server.pre(restify.pre.sanitizePath()); // Handles annoying user agents (curl) server.pre(restify.pre.userAgentConnection()); // Set a per request bunyan logger (with requestid filled in) server.use(restify.requestLogger()); // Allow 5 requests/second by IP, and burst to 10 server.use(restify.throttle({ burst: 10, rate: 5, ip: true, })); // Use the common stuff you probably want server.use(restify.acceptParser(server.acceptable)); server.use(restify.dateParser()); server.use(restify.authorizationParser()); server.use(restify.queryParser()); server.use(restify.gzipResponse()); server.use(restify.bodyParser()); // Now our own handlers for authentication/authorization // Here we only use basic auth, but really you should look // at https://github.com/joyent/node-http-signature server.use(function setup(req, res, next) { req.dir = options.directory; if (options.user && options.password) { req.allow = { user: options.user, password: options.password }; } next(); }); server.use(authenticate); /// Now the real handlers. Here we just CRUD on TODO blobs server.use(loadTodos); server.post('/todo', createTodo); server.get('/todo', listTodos); server.head('/todo', listTodos); // everything else requires that the TODO exist server.use(ensureTodo); // Return a TODO by name server.get('/todo/:name', getTodo); server.head('/todo/:name', getTodo); // Overwrite a complete TODO - here we require that the body // be JSON - otherwise the caller will get a 415 if they try // to send a different type // With the body parser, req.body will be the fully JSON // parsed document, so we just need to serialize and save server.put({ path: '/todo/:name', contentType: 'application/json' }, putTodo); // Delete a TODO by name server.del('/todo/:name', deleteTodo); // Destroy everything server.del('/todo', deleteAll, function respond(req, res, next) { res.send(204); next(); }); // Register a default '/' handler server.get('/', function root(req, res, next) { var routes = [ 'GET /', 'POST /todo', 'GET /todo', 'DELETE /todo', 'PUT /todo/:name', 'GET /todo/:name', 'DELETE /todo/:name' ]; res.send(200, routes); next(); }); // Setup an audit logger if (!options.noAudit) { server.on('after', restify.auditLogger({ body: true, log: bunyan.createLogger({ level: 'info', name: 'todoapp-audit', stream: process.stdout }) })); } return (server); }
{ level : 'info', // path : 'logs/api-debug.log' // log ERROR and above to a file stream: process.stdout // log INFO and above to stdout }, { level: 'error', path : 'logs/api-error.log' // log ERROR and above to a file }, { level: 'debug', path : 'logs/debug.log' // log ERROR and above to a file } ] }); // Server // ---------------------------------------------------------------------------- global.server = require('./src/server'); server.on('after', restify.auditLogger({ log: Logger.createLogger({ name: 'audit', stream: process.stdout }) })); server.listen( 8000, function() { console.log( '%s listening at %s', server.name, server.url ); });
function main() { mazLog = new mod_bunyan({ 'name': mazServerName, 'level': 'debug' }); if (process.argv.length < 3) usage(); mod_panic.enablePanicOnCrash({ 'skipDump': true, 'abortOnPanic': true }); /* * Set up connection to our parent, the global zone agent. */ mazUdsPath = process.argv[2]; mazLog.info('using client url "%s"', mazUdsPath); mazClient = mod_restify.createJsonClient({ 'socketPath': mazUdsPath, 'log': mazLog, 'retry': false }); mazClient.agent = false; mazClientRequests = {}; mazMantaClient = mod_manta.createClient({ 'socketPath': mazUdsPath, 'log': mazLog, 'retry': false, 'sign': mod_mautil.mantaSignNull }); /* * Set up the process contract template. */ mod_contract.set_template(mazContractTemplate); /* * Construct default path. */ var base = mod_path.normalize(mod_path.join(__dirname, '../..')); mazTaskPath = [ mod_path.join(base, 'ubin'), '/opt/local/bin', '/opt/local/sbin', process.env['PATH'] ].join(':'); /* * Set up restify server for the in-zone Task Control API. */ mazServer = mod_restify.createServer({ 'name': mazServerName, 'noWriteContinue': true, 'log': mazLog.child({ 'component': 'LackeyHttpServer', 'serializers': mod_restify.bunyan.serializers }), 'version': ['1.0.0'] }); mod_http.globalAgent.maxSockets = mazHttpSockets; mazServerRequests = {}; mazServer.pre(mod_restify.pre.sanitizePath()); mazServer.use(mod_restify.requestLogger()); mazServer.use(function trackRequest(request, response, next) { mazServerRequests[request['id']] = request; next(); }); mazServer.use(mod_restify.queryParser()); mazServer.on('uncaughtException', mod_mautil.maRestifyPanic); mazServer.on('after', mod_restify.auditLogger({ 'log': mazLog })); mazServer.on('after', function (request, response) { delete (mazServerRequests[request['id']]); }); mazServer.on('error', function (err) { mazLog.fatal(err, 'failed to start server: %s', err.mesage); process.exit(1); }); /* * All incoming requests are just proxied directly to our parent agent. */ /* BEGIN JSSTYLED */ mazServer.get(/.*/, mazApiProxy); mazServer.put(/.*/, mazApiProxy); mazServer.post(/.*/, mazApiProxy); mazServer.del(/.*/, mazApiProxy); mazServer.head(/.*/, mazApiProxy); /* END JSSTYLED */ /* * Figure out whether we've executed the zone initialization script yet. * There are three possibilities: * * - the "done" file exists, in which we don't need to do anything * * - the "running" file exists, in which case we crashed while the * script was running, and the zone is in an undefined state * * - neither exists, in which case we just need to make sure to run * the "init" script when we pick up our first task */ if (mod_fs.existsSync(mazInitStarted)) mazInitUndefined = true; else if (mod_fs.existsSync(mazInitDone)) mazInitHasRun = true; /* * Create our output directory, start up the in-zone HTTP server, then * ask our parent for work to do. */ mod_vasync.pipeline({ 'funcs': [ function cleanupCores(_, callback) { mazCleanupCores(callback); }, function mkOutputDir(_, callback) { mod_fs.mkdir(mazOutputDir, function (err) { if (err && err['code'] == 'EEXIST') err = null; callback(err); }); }, function mkCoreDir(_, callback) { mod_fs.mkdir(mazCoreDir, function (err) { if (err && err['code'] == 'EEXIST') err = null; callback(err); }); }, function runCoreadm(_, callback) { mod_child.execFile('coreadm', [ '-p', mod_path.join(mazCoreDir, mazCorePattern), process.pid ], function (err, stdout, stderr) { if (err) err = new VError(err, 'coreadm failed: stderr = "%s"', stderr); callback(err); }); }, function startListening(_, callback) { mazServer.listen(mazPort, function () { mazLog.info('server listening on port %d', mazPort); callback(); }); } ] }, function (err) { if (err) { mazLog.fatal(err, 'initialization failed (dumping core)'); process.abort(); } mazTaskFetch(); }); }