aboutsummaryrefslogtreecommitdiffhomepage
path: root/packages/peertube-runner/shared/ipc/ipc-client.ts
blob: f8e72f97f965818b6c680e3e3703ed3af582902f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import CliTable3 from 'cli-table3'
import { ensureDir } from 'fs-extra'
import { Client as NetIPC } from 'net-ipc'
import { ConfigManager } from '../config-manager'
import { IPCReponse, IPCReponseData, IPCRequest } from './shared'

export class IPCClient {
  private netIPC: NetIPC

  async run () {
    await ensureDir(ConfigManager.Instance.getSocketDirectory())

    const socketPath = ConfigManager.Instance.getSocketPath()

    this.netIPC = new NetIPC({ path: socketPath })

    try {
      await this.netIPC.connect()
    } catch (err) {
      if (err.code === 'ECONNREFUSED') {
        throw new Error(
          'This runner is not currently running in server mode on this system. ' +
          'Please run it using the `server` command first (in another terminal for example) and then retry your command.'
        )
      }

      throw err
    }
  }

  async askRegister (options: {
    url: string
    registrationToken: string
    runnerName: string
    runnerDescription?: string
  }) {
    const req: IPCRequest = {
      type: 'register',
      ...options
    }

    const { success, error } = await this.netIPC.request(req) as IPCReponse

    if (success) console.log('PeerTube instance registered')
    else console.error('Could not register PeerTube instance on runner server side', error)
  }

  async askUnregister (options: {
    url: string
    runnerName: string
  }) {
    const req: IPCRequest = {
      type: 'unregister',
      ...options
    }

    const { success, error } = await this.netIPC.request(req) as IPCReponse

    if (success) console.log('PeerTube instance unregistered')
    else console.error('Could not unregister PeerTube instance on runner server side', error)
  }

  async askListRegistered () {
    const req: IPCRequest = {
      type: 'list-registered'
    }

    const { success, error, data } = await this.netIPC.request(req) as IPCReponse<IPCReponseData>
    if (!success) {
      console.error('Could not list registered PeerTube instances', error)
      return
    }

    const table = new CliTable3({
      head: [ 'instance', 'runner name', 'runner description' ]
    })

    for (const server of data.servers) {
      table.push([ server.url, server.runnerName, server.runnerDescription ])
    }

    console.log(table.toString())
  }

  stop () {
    this.netIPC.destroy()
  }
}