cli.js 7.9 KB

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