cli.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #!/usr/bin/env node
  2. /* es-lint disable*/
  3. 'use strict'
  4. // Node requires
  5. const path = require('path')
  6. // npm requires
  7. const meow = require('meow')
  8. const chalk = require('chalk')
  9. const figlet = require('figlet')
  10. const _ = require('lodash')
  11. const debug = require('debug')('joystream:colossus')
  12. // Project root
  13. const PROJECT_ROOT = path.resolve(__dirname, '..')
  14. // Number of milliseconds to wait between synchronization runs.
  15. const SYNC_PERIOD_MS = 300000 // 5min
  16. // Parse CLI
  17. const FLAG_DEFINITIONS = {
  18. port: {
  19. type: 'number',
  20. alias: 'p',
  21. default: 3000
  22. },
  23. keyFile: {
  24. type: 'string',
  25. isRequired: (flags, input) => {
  26. return !flags.dev
  27. }
  28. },
  29. publicUrl: {
  30. type: 'string',
  31. alias: 'u',
  32. isRequired: (flags, input) => {
  33. return !flags.dev
  34. }
  35. },
  36. passphrase: {
  37. type: 'string'
  38. },
  39. wsProvider: {
  40. type: 'string',
  41. default: 'ws://localhost:9944'
  42. },
  43. providerId: {
  44. type: 'number',
  45. alias: 'i',
  46. isRequired: (flags, input) => {
  47. return !flags.dev
  48. }
  49. }
  50. }
  51. const cli = meow(`
  52. Usage:
  53. $ colossus [command] [arguments]
  54. Commands:
  55. server Runs a production server instance. (discovery and storage services)
  56. This is the default command if not specified.
  57. discovery Run the discovery service only.
  58. Arguments (required for server. Ignored if running server with --dev option):
  59. --provider-id ID, -i ID StorageProviderId assigned to you in working group.
  60. --key-file FILE JSON key export file to use as the storage provider (role account).
  61. --public-url=URL, -u URL API Public URL to announce.
  62. Arguments (optional):
  63. --dev Runs server with developer settings.
  64. --passphrase Optional passphrase to use to decrypt the key-file.
  65. --port=PORT, -p PORT Port number to listen on, defaults to 3000.
  66. --ws-provider WS_URL Joystream-node websocket provider, defaults to ws://localhost:9944
  67. `,
  68. { flags: FLAG_DEFINITIONS })
  69. // All-important banner!
  70. function banner () {
  71. console.log(chalk.blue(figlet.textSync('joystream', 'Speed')))
  72. }
  73. function start_express_app(app, port) {
  74. const http = require('http')
  75. const server = http.createServer(app)
  76. return new Promise((resolve, reject) => {
  77. server.on('error', reject)
  78. server.on('close', (...args) => {
  79. console.log('Server closed, shutting down...')
  80. resolve(...args)
  81. })
  82. server.on('listening', () => {
  83. console.log('API server started.', server.address())
  84. })
  85. server.listen(port, '::')
  86. console.log('Starting API server...')
  87. })
  88. }
  89. // Start app
  90. function start_all_services ({ store, api, port }) {
  91. const app = require('../lib/app')(PROJECT_ROOT, store, api) // reduce falgs to only needed values
  92. return start_express_app(app, port)
  93. }
  94. // Start discovery service app only
  95. function start_discovery_service ({ api, port }) {
  96. const app = require('../lib/discovery')(PROJECT_ROOT, api) // reduce flags to only needed values
  97. return start_express_app(app, port)
  98. }
  99. // Get an initialized storage instance
  100. function get_storage (runtime_api) {
  101. // TODO at some point, we can figure out what backend-specific connection
  102. // options make sense. For now, just don't use any configuration.
  103. const { Storage } = require('@joystream/storage-node-backend')
  104. const options = {
  105. resolve_content_id: async (content_id) => {
  106. // Resolve via API
  107. const obj = await runtime_api.assets.getDataObject(content_id)
  108. if (!obj || obj.isNone) {
  109. return
  110. }
  111. // if obj.liaison_judgement !== Accepted .. throw ?
  112. return obj.unwrap().ipfs_content_id.toString()
  113. }
  114. }
  115. return Storage.create(options)
  116. }
  117. async function init_api_production ({ wsProvider, providerId, keyFile, passphrase }) {
  118. // Load key information
  119. const { RuntimeApi } = require('@joystream/storage-runtime-api')
  120. if (!keyFile) {
  121. throw new Error('Must specify a --key-file argument for running a storage node.')
  122. }
  123. if (providerId === undefined) {
  124. throw new Error('Must specify a --provider-id argument for running a storage node')
  125. }
  126. const api = await RuntimeApi.create({
  127. account_file: keyFile,
  128. passphrase,
  129. provider_url: wsProvider,
  130. storageProviderId: providerId
  131. })
  132. if (!api.identities.key) {
  133. throw new Error('Failed to unlock storage provider account')
  134. }
  135. if (!await api.workers.isRoleAccountOfStorageProvider(api.storageProviderId, api.identities.key.address)) {
  136. throw new Error('storage provider role account and storageProviderId are not associated with a worker')
  137. }
  138. return api
  139. }
  140. async function init_api_development () {
  141. // Load key information
  142. const { RuntimeApi } = require('@joystream/storage-runtime-api')
  143. const wsProvider = 'ws://localhost:9944'
  144. const api = await RuntimeApi.create({
  145. provider_url: wsProvider
  146. })
  147. const dev = require('../../cli/bin/dev')
  148. api.identities.useKeyPair(dev.roleKeyPair(api))
  149. api.storageProviderId = await dev.check(api)
  150. return api
  151. }
  152. function get_service_information (publicUrl) {
  153. // For now assume we run all services on the same endpoint
  154. return({
  155. asset: {
  156. version: 1, // spec version
  157. endpoint: publicUrl
  158. },
  159. discover: {
  160. version: 1, // spec version
  161. endpoint: publicUrl
  162. }
  163. })
  164. }
  165. async function announce_public_url (api, publicUrl) {
  166. // re-announce in future
  167. const reannounce = function (timeoutMs) {
  168. setTimeout(announce_public_url, timeoutMs, api, publicUrl)
  169. }
  170. debug('announcing public url')
  171. const { publish } = require('@joystream/service-discovery')
  172. try {
  173. const serviceInformation = get_service_information(publicUrl)
  174. let keyId = await publish.publish(serviceInformation)
  175. await api.discovery.setAccountInfo(keyId)
  176. debug('publishing complete, scheduling next update')
  177. // >> sometimes after tx is finalized.. we are not reaching here!
  178. // Reannounce before expiery. Here we are concerned primarily
  179. // with keeping the account information refreshed and 'available' in
  180. // the ipfs network. our record on chain is valid for 24hr
  181. reannounce(50 * 60 * 1000) // in 50 minutes
  182. } catch (err) {
  183. debug(`announcing public url failed: ${err.stack}`)
  184. // On failure retry sooner
  185. debug(`announcing failed, retrying in: 2 minutes`)
  186. reannounce(120 * 1000)
  187. }
  188. }
  189. function go_offline (api) {
  190. return api.discovery.unsetAccountInfo()
  191. }
  192. // Simple CLI commands
  193. var command = cli.input[0]
  194. if (!command) {
  195. command = 'server'
  196. }
  197. async function start_colossus ({ api, publicUrl, port, flags }) {
  198. // TODO: check valid url, and valid port number
  199. const store = get_storage(api)
  200. banner()
  201. const { start_syncing } = require('../lib/sync')
  202. start_syncing(api, { syncPeriod: SYNC_PERIOD_MS }, store)
  203. announce_public_url(api, publicUrl)
  204. return start_all_services({ store, api, port, flags }) // dont pass all flags only required values
  205. }
  206. const commands = {
  207. 'server': async () => {
  208. let publicUrl, port, api
  209. if (cli.flags.dev) {
  210. const dev = require('../../cli/bin/dev')
  211. api = await init_api_development()
  212. port = dev.developmentPort()
  213. publicUrl = `http://localhost:${port}/`
  214. } else {
  215. api = await init_api_production(cli.flags)
  216. publicUrl = cli.flags.publicUrl
  217. port = cli.flags.port
  218. }
  219. return start_colossus({ api, publicUrl, port })
  220. },
  221. 'discovery': async () => {
  222. debug('Starting Joystream Discovery Service')
  223. const { RuntimeApi } = require('@joystream/storage-runtime-api')
  224. const wsProvider = cli.flags.wsProvider
  225. const api = await RuntimeApi.create({ provider_url: wsProvider })
  226. const port = cli.flags.port
  227. await start_discovery_service({ api, port })
  228. }
  229. }
  230. async function main () {
  231. // Simple CLI commands
  232. var command = cli.input[0]
  233. if (!command) {
  234. command = 'server'
  235. }
  236. if (commands.hasOwnProperty(command)) {
  237. // Command recognized
  238. const args = _.clone(cli.input).slice(1)
  239. await commands[command](...args)
  240. } else {
  241. throw new Error(`Command '${command}' not recognized, aborting!`)
  242. }
  243. }
  244. main()
  245. .then(() => {
  246. process.exit(0)
  247. })
  248. .catch((err) => {
  249. console.error(chalk.red(err.stack))
  250. process.exit(-1)
  251. })