cli.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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 { sleep } = require('@joystream/storage-utils/sleep')
  12. const debug = require('debug')('joystream:colossus')
  13. // Project root
  14. const PROJECT_ROOT = path.resolve(__dirname, '..')
  15. // Number of milliseconds to wait between synchronization runs.
  16. const SYNC_PERIOD_MS = 120000 // 2min
  17. // Parse CLI
  18. const FLAG_DEFINITIONS = {
  19. port: {
  20. type: 'number',
  21. alias: 'p',
  22. default: 3000,
  23. },
  24. keyFile: {
  25. type: 'string',
  26. isRequired: (flags, input) => {
  27. // Only required if running server command and not in dev mode
  28. const serverCmd = input[0] === 'server'
  29. return !flags.dev && serverCmd
  30. },
  31. },
  32. publicUrl: {
  33. type: 'string',
  34. alias: 'u',
  35. isRequired: (flags, input) => {
  36. // Only required if running server command and not in dev mode
  37. const serverCmd = input[0] === 'server'
  38. return !flags.dev && serverCmd
  39. },
  40. },
  41. passphrase: {
  42. type: 'string',
  43. },
  44. wsProvider: {
  45. type: 'string',
  46. default: 'ws://localhost:9944',
  47. },
  48. providerId: {
  49. type: 'number',
  50. alias: 'i',
  51. isRequired: (flags, input) => {
  52. // Only required if running server command and not in dev mode
  53. const serverCmd = input[0] === 'server'
  54. return !flags.dev && serverCmd
  55. },
  56. },
  57. ipfsHost: {
  58. type: 'string',
  59. default: 'localhost',
  60. },
  61. }
  62. const cli = meow(
  63. `
  64. Usage:
  65. $ colossus [command] [arguments]
  66. Commands:
  67. server Runs a production server instance. (discovery and storage services)
  68. This is the default command if not specified.
  69. discovery Run the discovery service only.
  70. Arguments (required for server. Ignored if running server with --dev option):
  71. --provider-id ID, -i ID StorageProviderId assigned to you in working group.
  72. --key-file FILE JSON key export file to use as the storage provider (role account).
  73. --public-url=URL, -u URL API Public URL to announce.
  74. Arguments (optional):
  75. --dev Runs server with developer settings.
  76. --passphrase Optional passphrase to use to decrypt the key-file.
  77. --port=PORT, -p PORT Port number to listen on, defaults to 3000.
  78. --ws-provider WS_URL Joystream-node websocket provider, defaults to ws://localhost:9944
  79. --ipfs-host hostname ipfs host to use, default to 'localhost'. Default port 5001 is always used
  80. `,
  81. { flags: FLAG_DEFINITIONS }
  82. )
  83. // All-important banner!
  84. function banner() {
  85. console.log(chalk.blue(figlet.textSync('joystream', 'Speed')))
  86. }
  87. function startExpressApp(app, port) {
  88. const http = require('http')
  89. const server = http.createServer(app)
  90. return new Promise((resolve, reject) => {
  91. server.on('error', reject)
  92. server.on('close', (...args) => {
  93. console.log('Server closed, shutting down...')
  94. resolve(...args)
  95. })
  96. server.on('listening', () => {
  97. console.log('API server started.', server.address())
  98. })
  99. server.listen(port, '::')
  100. console.log('Starting API server...')
  101. })
  102. }
  103. // Start app
  104. function startAllServices({ store, api, port, discoveryClient, ipfsHttpGatewayUrl }) {
  105. const app = require('../lib/app')(PROJECT_ROOT, store, api, discoveryClient, ipfsHttpGatewayUrl)
  106. return startExpressApp(app, port)
  107. }
  108. // Start discovery service app only
  109. function startDiscoveryService({ port, discoveryClient }) {
  110. const app = require('../lib/discovery')(PROJECT_ROOT, discoveryClient)
  111. return startExpressApp(app, port)
  112. }
  113. // Get an initialized storage instance
  114. function getStorage(runtimeApi, { ipfsHost }) {
  115. // TODO at some point, we can figure out what backend-specific connection
  116. // options make sense. For now, just don't use any configuration.
  117. const { Storage } = require('@joystream/storage-node-backend')
  118. const options = {
  119. resolve_content_id: async (contentId) => {
  120. // Resolve via API
  121. const obj = await runtimeApi.assets.getDataObject(contentId)
  122. if (!obj || obj.isNone) {
  123. return
  124. }
  125. // if obj.liaison_judgement !== Accepted .. throw ?
  126. return obj.unwrap().ipfs_content_id.toString()
  127. },
  128. ipfsHost,
  129. }
  130. return Storage.create(options)
  131. }
  132. async function initApiProduction({ wsProvider, providerId, keyFile, passphrase }) {
  133. // Load key information
  134. const { RuntimeApi } = require('@joystream/storage-runtime-api')
  135. const api = await RuntimeApi.create({
  136. account_file: keyFile,
  137. passphrase,
  138. provider_url: wsProvider,
  139. storageProviderId: providerId,
  140. })
  141. if (!api.identities.key) {
  142. throw new Error('Failed to unlock storage provider account')
  143. }
  144. await api.untilChainIsSynced()
  145. // We allow the node to startup without correct provider id and account, but syncing and
  146. // publishing of identity will be skipped.
  147. if (!(await api.providerIsActiveWorker())) {
  148. debug('storage provider role account and storageProviderId are not associated with a worker')
  149. }
  150. return api
  151. }
  152. async function initApiDevelopment({ wsProvider }) {
  153. // Load key information
  154. const { RuntimeApi } = require('@joystream/storage-runtime-api')
  155. const api = await RuntimeApi.create({
  156. provider_url: wsProvider,
  157. })
  158. const dev = require('../../cli/dist/commands/dev')
  159. api.identities.useKeyPair(dev.roleKeyPair(api))
  160. // Wait until dev provider is added to role
  161. while (true) {
  162. try {
  163. api.storageProviderId = await dev.check(api)
  164. break
  165. } catch (err) {
  166. debug(err)
  167. }
  168. await sleep(10000)
  169. }
  170. return api
  171. }
  172. function getServiceInformation(publicUrl) {
  173. // For now assume we run all services on the same endpoint
  174. return {
  175. asset: {
  176. version: 1, // spec version
  177. endpoint: publicUrl,
  178. },
  179. discover: {
  180. version: 1, // spec version
  181. endpoint: publicUrl,
  182. },
  183. }
  184. }
  185. // TODO: instead of recursion use while/async-await and use promise/setTimout based sleep
  186. // or cleaner code with generators?
  187. async function announcePublicUrl(api, publicUrl, publisherClient) {
  188. // re-announce in future
  189. const reannounce = function (timeoutMs) {
  190. setTimeout(announcePublicUrl, timeoutMs, api, publicUrl, publisherClient)
  191. }
  192. const chainIsSyncing = await api.chainIsSyncing()
  193. if (chainIsSyncing) {
  194. debug('Chain is syncing. Postponing announcing public url.')
  195. return reannounce(10 * 60 * 1000)
  196. }
  197. // postpone if provider not active
  198. if (!(await api.providerIsActiveWorker())) {
  199. debug('storage provider role account and storageProviderId are not associated with a worker')
  200. return reannounce(10 * 60 * 1000)
  201. }
  202. const sufficientBalance = await api.providerHasMinimumBalance(1)
  203. if (!sufficientBalance) {
  204. debug('Provider role account does not have sufficient balance. Postponing announcing public url.')
  205. return reannounce(10 * 60 * 1000)
  206. }
  207. debug('announcing public url')
  208. try {
  209. const serviceInformation = getServiceInformation(publicUrl)
  210. const keyId = await publisherClient.publish(serviceInformation)
  211. await api.discovery.setAccountInfo(keyId)
  212. debug('publishing complete, scheduling next update')
  213. // >> sometimes after tx is finalized.. we are not reaching here!
  214. // Reannounce before expiery. Here we are concerned primarily
  215. // with keeping the account information refreshed and 'available' in
  216. // the ipfs network. our record on chain is valid for 24hr
  217. reannounce(50 * 60 * 1000) // in 50 minutes
  218. } catch (err) {
  219. debug(`announcing public url failed: ${err.stack}`)
  220. // On failure retry sooner
  221. debug(`announcing failed, retrying in: 2 minutes`)
  222. reannounce(120 * 1000)
  223. }
  224. }
  225. // Simple CLI commands
  226. let command = cli.input[0]
  227. if (!command) {
  228. command = 'server'
  229. }
  230. const commands = {
  231. server: async () => {
  232. banner()
  233. let publicUrl, port, api
  234. if (cli.flags.dev) {
  235. const dev = require('../../cli/dist/commands/dev')
  236. api = await initApiDevelopment(cli.flags)
  237. port = dev.developmentPort()
  238. publicUrl = `http://localhost:${port}/`
  239. } else {
  240. api = await initApiProduction(cli.flags)
  241. publicUrl = cli.flags.publicUrl
  242. port = cli.flags.port
  243. }
  244. // TODO: check valid url, and valid port number
  245. const store = getStorage(api, cli.flags)
  246. const ipfsHost = cli.flags.ipfsHost
  247. const ipfs = require('ipfs-http-client')(ipfsHost, '5001', { protocol: 'http' })
  248. const { PublisherClient, DiscoveryClient } = require('@joystream/service-discovery')
  249. const publisherClient = new PublisherClient(ipfs)
  250. const discoveryClient = new DiscoveryClient(ipfs, api)
  251. const ipfsHttpGatewayUrl = `http://${ipfsHost}:8080/`
  252. const { startSyncing } = require('../lib/sync')
  253. startSyncing(api, { syncPeriod: SYNC_PERIOD_MS }, store)
  254. announcePublicUrl(api, publicUrl, publisherClient)
  255. return startAllServices({ store, api, port, discoveryClient, ipfsHttpGatewayUrl })
  256. },
  257. discovery: async () => {
  258. banner()
  259. debug('Starting Joystream Discovery Service')
  260. const { RuntimeApi } = require('@joystream/storage-runtime-api')
  261. const wsProvider = cli.flags.wsProvider
  262. const api = await RuntimeApi.create({ provider_url: wsProvider })
  263. const port = cli.flags.port
  264. const ipfsHost = cli.flags.ipfsHost
  265. const ipfs = require('ipfs-http-client')(ipfsHost, '5001', { protocol: 'http' })
  266. const { DiscoveryClient } = require('@joystream/service-discovery')
  267. const discoveryClient = new DiscoveryClient(ipfs, api)
  268. await api.untilChainIsSynced()
  269. await startDiscoveryService({ api, port, discoveryClient })
  270. },
  271. }
  272. async function main() {
  273. // Simple CLI commands
  274. let command = cli.input[0]
  275. if (!command) {
  276. command = 'server'
  277. }
  278. if (Object.prototype.hasOwnProperty.call(commands, command)) {
  279. // Command recognized
  280. const args = _.clone(cli.input).slice(1)
  281. await commands[command](...args)
  282. } else {
  283. throw new Error(`Command '${command}' not recognized, aborting!`)
  284. }
  285. }
  286. main()
  287. .then(() => {
  288. process.exit(0)
  289. })
  290. .catch((err) => {
  291. console.error(chalk.red(err.stack))
  292. process.exit(-1)
  293. })