balena-cli/lib/actions/logs.coffee

53 lines
1.4 KiB
CoffeeScript
Raw Normal View History

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