balena-cli/lib/actions/logs.coffee

53 lines
1.4 KiB
CoffeeScript
Raw Normal View History

2014-11-28 12:46:24 -04:00
_ = require('lodash')
PubNub = require('pubnub')
2015-01-08 09:04:37 -03:00
resin = require('resin-sdk')
2014-11-28 15:36:03 -04:00
helpers = require('../helpers/helpers')
permissions = require('../permissions/permissions')
2014-12-22 12:41:14 -04:00
log = require('../log/log')
2014-12-22 12:47:12 -04:00
errors = require('../errors/errors')
2014-11-28 12:46:24 -04:00
LOGS_HISTORY_COUNT = 200
2014-11-28 20:51:03 -04:00
getLogData = (logs) ->
return logs[0] if _.isArray(logs)
return logs
printLogs = (logs, number) ->
logs = getLogData(logs)
logs = _.last(logs, number) if _.isNumber(number)
2014-12-22 12:41:14 -04:00
log.array(logs, log.out)
2014-11-28 20:51:03 -04:00
exports.logs = permissions.user (params, options) ->
numberOfLines = options.num
tailOutput = options.tail or false
2014-11-28 20:51:03 -04:00
if numberOfLines? and not _.isNumber(numberOfLines)
2014-12-22 12:47:12 -04:00
errors.handle(new Error('n/num should be a number'))
2014-11-28 20:51:03 -04:00
helpers.isDeviceUUIDValid params.uuid, (error, isValidUUID) ->
2014-12-22 12:47:12 -04:00
errors.handle(error) if error?
2014-11-28 12:46:24 -04:00
2014-11-28 15:36:03 -04:00
if not isValidUUID
2014-12-22 12:47:12 -04:00
return errors.handle(new Error('Invalid UUID'))
2014-11-28 12:46:24 -04:00
# PubNub needs to be initialised after logs
# action was called, otherwise it prevents
# all other actions from exiting on completion
2014-12-05 10:53:59 -04:00
pubnub = PubNub.init(resin.settings.get('pubnub'))
2014-11-28 12:46:24 -04:00
channel = _.template(resin.settings.get('events.deviceLogs'), uuid: params.uuid)
2014-11-28 12:46:24 -04:00
pubnub.history
count: LOGS_HISTORY_COUNT
channel: channel
2014-11-28 20:51:03 -04:00
callback: (logs) ->
printLogs(logs, numberOfLines)
if not tailOutput or numberOfLines?
process.exit(0)
2014-11-28 12:46:24 -04:00
2014-11-28 20:51:03 -04:00
if tailOutput
2014-11-28 20:18:59 -04:00
pubnub.subscribe
channel: channel
callback: printLogs