servers.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. /* eslint-disable @typescript-eslint/no-unused-expressions,@typescript-eslint/no-floating-promises */
  2. import { expect } from 'chai'
  3. import { ChildProcess, exec, fork } from 'child_process'
  4. import { copy, ensureDir, pathExists, readdir, readFile, remove } from 'fs-extra'
  5. import { join } from 'path'
  6. import { randomInt } from '../../core-utils/miscs/miscs'
  7. import { VideoChannel } from '../../models/videos'
  8. import { buildServerDirectory, getFileSize, isGithubCI, root, wait } from '../miscs/miscs'
  9. import { makeGetRequest } from '../requests/requests'
  10. interface ServerInfo {
  11. app: ChildProcess
  12. url: string
  13. host: string
  14. hostname: string
  15. port: number
  16. rtmpPort: number
  17. parallel: boolean
  18. internalServerNumber: number
  19. serverNumber: number
  20. client: {
  21. id: string
  22. secret: string
  23. }
  24. user: {
  25. username: string
  26. password: string
  27. email?: string
  28. }
  29. customConfigFile?: string
  30. accessToken?: string
  31. videoChannel?: VideoChannel
  32. video?: {
  33. id: number
  34. uuid: string
  35. name?: string
  36. url?: string
  37. account?: {
  38. name: string
  39. }
  40. }
  41. remoteVideo?: {
  42. id: number
  43. uuid: string
  44. }
  45. videos?: { id: number, uuid: string }[]
  46. }
  47. function parallelTests () {
  48. return process.env.MOCHA_PARALLEL === 'true'
  49. }
  50. function flushAndRunMultipleServers (totalServers: number, configOverride?: Object) {
  51. const apps = []
  52. let i = 0
  53. return new Promise<ServerInfo[]>(res => {
  54. function anotherServerDone (serverNumber, app) {
  55. apps[serverNumber - 1] = app
  56. i++
  57. if (i === totalServers) {
  58. return res(apps)
  59. }
  60. }
  61. for (let j = 1; j <= totalServers; j++) {
  62. flushAndRunServer(j, configOverride).then(app => anotherServerDone(j, app))
  63. }
  64. })
  65. }
  66. function flushTests (serverNumber?: number) {
  67. return new Promise<void>((res, rej) => {
  68. const suffix = serverNumber ? ` -- ${serverNumber}` : ''
  69. return exec('npm run clean:server:test' + suffix, (err, _stdout, stderr) => {
  70. if (err || stderr) return rej(err || new Error(stderr))
  71. return res()
  72. })
  73. })
  74. }
  75. function randomServer () {
  76. const low = 10
  77. const high = 10000
  78. return randomInt(low, high)
  79. }
  80. function randomRTMP () {
  81. const low = 1900
  82. const high = 2100
  83. return randomInt(low, high)
  84. }
  85. type RunServerOptions = {
  86. hideLogs?: boolean
  87. execArgv?: string[]
  88. }
  89. async function flushAndRunServer (serverNumber: number, configOverride?: Object, args = [], options: RunServerOptions = {}) {
  90. const parallel = parallelTests()
  91. const internalServerNumber = parallel ? randomServer() : serverNumber
  92. const rtmpPort = parallel ? randomRTMP() : 1936
  93. const port = 9000 + internalServerNumber
  94. await flushTests(internalServerNumber)
  95. const server: ServerInfo = {
  96. app: null,
  97. port,
  98. internalServerNumber,
  99. rtmpPort,
  100. parallel,
  101. serverNumber,
  102. url: `http://localhost:${port}`,
  103. host: `localhost:${port}`,
  104. hostname: 'localhost',
  105. client: {
  106. id: null,
  107. secret: null
  108. },
  109. user: {
  110. username: null,
  111. password: null
  112. }
  113. }
  114. return runServer(server, configOverride, args, options)
  115. }
  116. async function runServer (server: ServerInfo, configOverrideArg?: any, args = [], options: RunServerOptions = {}) {
  117. // These actions are async so we need to be sure that they have both been done
  118. const serverRunString = {
  119. 'HTTP server listening': false
  120. }
  121. const key = 'Database peertube_test' + server.internalServerNumber + ' is ready'
  122. serverRunString[key] = false
  123. const regexps = {
  124. client_id: 'Client id: (.+)',
  125. client_secret: 'Client secret: (.+)',
  126. user_username: 'Username: (.+)',
  127. user_password: 'User password: (.+)'
  128. }
  129. if (server.internalServerNumber !== server.serverNumber) {
  130. const basePath = join(root(), 'config')
  131. const tmpConfigFile = join(basePath, `test-${server.internalServerNumber}.yaml`)
  132. await copy(join(basePath, `test-${server.serverNumber}.yaml`), tmpConfigFile)
  133. server.customConfigFile = tmpConfigFile
  134. }
  135. const configOverride: any = {}
  136. if (server.parallel) {
  137. Object.assign(configOverride, {
  138. listen: {
  139. port: server.port
  140. },
  141. webserver: {
  142. port: server.port
  143. },
  144. database: {
  145. suffix: '_test' + server.internalServerNumber
  146. },
  147. storage: {
  148. tmp: `test${server.internalServerNumber}/tmp/`,
  149. avatars: `test${server.internalServerNumber}/avatars/`,
  150. videos: `test${server.internalServerNumber}/videos/`,
  151. streaming_playlists: `test${server.internalServerNumber}/streaming-playlists/`,
  152. redundancy: `test${server.internalServerNumber}/redundancy/`,
  153. logs: `test${server.internalServerNumber}/logs/`,
  154. previews: `test${server.internalServerNumber}/previews/`,
  155. thumbnails: `test${server.internalServerNumber}/thumbnails/`,
  156. torrents: `test${server.internalServerNumber}/torrents/`,
  157. captions: `test${server.internalServerNumber}/captions/`,
  158. cache: `test${server.internalServerNumber}/cache/`,
  159. plugins: `test${server.internalServerNumber}/plugins/`
  160. },
  161. admin: {
  162. email: `admin${server.internalServerNumber}@example.com`
  163. },
  164. live: {
  165. rtmp: {
  166. port: server.rtmpPort
  167. }
  168. }
  169. })
  170. }
  171. if (configOverrideArg !== undefined) {
  172. Object.assign(configOverride, configOverrideArg)
  173. }
  174. // Share the environment
  175. const env = Object.create(process.env)
  176. env['NODE_ENV'] = 'test'
  177. env['NODE_APP_INSTANCE'] = server.internalServerNumber.toString()
  178. env['NODE_CONFIG'] = JSON.stringify(configOverride)
  179. const forkOptions = {
  180. silent: true,
  181. env,
  182. detached: true,
  183. execArgv: options.execArgv || []
  184. }
  185. return new Promise<ServerInfo>(res => {
  186. server.app = fork(join(root(), 'dist', 'server.js'), args, forkOptions)
  187. server.app.stdout.on('data', function onStdout (data) {
  188. let dontContinue = false
  189. // Capture things if we want to
  190. for (const key of Object.keys(regexps)) {
  191. const regexp = regexps[key]
  192. const matches = data.toString().match(regexp)
  193. if (matches !== null) {
  194. if (key === 'client_id') server.client.id = matches[1]
  195. else if (key === 'client_secret') server.client.secret = matches[1]
  196. else if (key === 'user_username') server.user.username = matches[1]
  197. else if (key === 'user_password') server.user.password = matches[1]
  198. }
  199. }
  200. // Check if all required sentences are here
  201. for (const key of Object.keys(serverRunString)) {
  202. if (data.toString().indexOf(key) !== -1) serverRunString[key] = true
  203. if (serverRunString[key] === false) dontContinue = true
  204. }
  205. // If no, there is maybe one thing not already initialized (client/user credentials generation...)
  206. if (dontContinue === true) return
  207. if (options.hideLogs === false) {
  208. console.log(data.toString())
  209. } else {
  210. server.app.stdout.removeListener('data', onStdout)
  211. }
  212. process.on('exit', () => {
  213. try {
  214. process.kill(server.app.pid)
  215. } catch { /* empty */ }
  216. })
  217. res(server)
  218. })
  219. })
  220. }
  221. async function reRunServer (server: ServerInfo, configOverride?: any) {
  222. const newServer = await runServer(server, configOverride)
  223. server.app = newServer.app
  224. return server
  225. }
  226. function checkTmpIsEmpty (server: ServerInfo) {
  227. return checkDirectoryIsEmpty(server, 'tmp', [ 'plugins-global.css' ])
  228. }
  229. async function checkDirectoryIsEmpty (server: ServerInfo, directory: string, exceptions: string[] = []) {
  230. const testDirectory = 'test' + server.internalServerNumber
  231. const directoryPath = join(root(), testDirectory, directory)
  232. const directoryExists = await pathExists(directoryPath)
  233. expect(directoryExists).to.be.true
  234. const files = await readdir(directoryPath)
  235. const filtered = files.filter(f => exceptions.includes(f) === false)
  236. expect(filtered).to.have.lengthOf(0)
  237. }
  238. function killallServers (servers: ServerInfo[]) {
  239. for (const server of servers) {
  240. if (!server.app) continue
  241. process.kill(-server.app.pid)
  242. server.app = null
  243. }
  244. }
  245. async function cleanupTests (servers: ServerInfo[]) {
  246. killallServers(servers)
  247. if (isGithubCI()) {
  248. await ensureDir('artifacts')
  249. }
  250. const p: Promise<any>[] = []
  251. for (const server of servers) {
  252. if (isGithubCI()) {
  253. const origin = await buildServerDirectory(server, 'logs/peertube.log')
  254. const destname = `peertube-${server.internalServerNumber}.log`
  255. console.log('Saving logs %s.', destname)
  256. await copy(origin, join('artifacts', destname))
  257. }
  258. if (server.parallel) {
  259. p.push(flushTests(server.internalServerNumber))
  260. }
  261. if (server.customConfigFile) {
  262. p.push(remove(server.customConfigFile))
  263. }
  264. }
  265. return Promise.all(p)
  266. }
  267. async function waitUntilLog (server: ServerInfo, str: string, count = 1, strictCount = true) {
  268. const logfile = buildServerDirectory(server, 'logs/peertube.log')
  269. while (true) {
  270. const buf = await readFile(logfile)
  271. const matches = buf.toString().match(new RegExp(str, 'g'))
  272. if (matches && matches.length === count) return
  273. if (matches && strictCount === false && matches.length >= count) return
  274. await wait(1000)
  275. }
  276. }
  277. async function getServerFileSize (server: ServerInfo, subPath: string) {
  278. const path = buildServerDirectory(server, subPath)
  279. return getFileSize(path)
  280. }
  281. function makePingRequest (server: ServerInfo) {
  282. return makeGetRequest({
  283. url: server.url,
  284. path: '/api/v1/ping',
  285. statusCodeExpected: 200
  286. })
  287. }
  288. // ---------------------------------------------------------------------------
  289. export {
  290. checkDirectoryIsEmpty,
  291. checkTmpIsEmpty,
  292. getServerFileSize,
  293. ServerInfo,
  294. parallelTests,
  295. cleanupTests,
  296. flushAndRunMultipleServers,
  297. flushTests,
  298. makePingRequest,
  299. flushAndRunServer,
  300. killallServers,
  301. reRunServer,
  302. waitUntilLog
  303. }