dockerNode.ts 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /**
  2. * @copyright Copyright (c) 2022 John Molakvoæ <skjnldsv@protonmail.com>
  3. *
  4. * @author John Molakvoæ <skjnldsv@protonmail.com>
  5. *
  6. * @license AGPL-3.0-or-later
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License as
  10. * published by the Free Software Foundation, either version 3 of the
  11. * License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /* eslint-disable no-console */
  23. /* eslint-disable n/no-unpublished-import */
  24. /* eslint-disable n/no-extraneous-import */
  25. import Docker from 'dockerode'
  26. import waitOn from 'wait-on'
  27. import tar from 'tar'
  28. import { execSync } from 'child_process'
  29. export const docker = new Docker()
  30. const CONTAINER_NAME = 'nextcloud-cypress-tests-server'
  31. const SERVER_IMAGE = 'ghcr.io/nextcloud/continuous-integration-shallow-server'
  32. /**
  33. * Start the testing container
  34. *
  35. * @param {string} branch the branch of your current work
  36. */
  37. export const startNextcloud = async function(branch: string = getCurrentGitBranch()): Promise<any> {
  38. try {
  39. // Pulling images
  40. console.log('\nPulling images... ⏳')
  41. await new Promise((resolve, reject): any => docker.pull(SERVER_IMAGE, (err, stream) => {
  42. if (err) {
  43. reject(err)
  44. }
  45. // https://github.com/apocas/dockerode/issues/357
  46. docker.modem.followProgress(stream, onFinished)
  47. /**
  48. *
  49. * @param err
  50. */
  51. function onFinished(err) {
  52. if (!err) {
  53. resolve(true)
  54. return
  55. }
  56. reject(err)
  57. }
  58. }))
  59. console.log('└─ Done')
  60. // Remove old container if exists
  61. console.log('\nChecking running containers... 🔍')
  62. try {
  63. const oldContainer = docker.getContainer(CONTAINER_NAME)
  64. const oldContainerData = await oldContainer.inspect()
  65. if (oldContainerData) {
  66. console.log('├─ Existing running container found')
  67. console.log('├─ Removing... ⏳')
  68. // Forcing any remnants to be removed just in case
  69. await oldContainer.remove({ force: true })
  70. console.log('└─ Done')
  71. }
  72. } catch (error) {
  73. console.log('└─ None found!')
  74. }
  75. // Starting container
  76. console.log('\nStarting Nextcloud container... 🚀')
  77. console.log(`├─ Using branch '${branch}'`)
  78. const container = await docker.createContainer({
  79. Image: SERVER_IMAGE,
  80. name: CONTAINER_NAME,
  81. HostConfig: {
  82. Binds: [],
  83. },
  84. Env: [
  85. `BRANCH=${branch}`,
  86. ],
  87. })
  88. await container.start()
  89. // Get container's IP
  90. const ip = await getContainerIP(container)
  91. console.log(`├─ Nextcloud container's IP is ${ip} 🌏`)
  92. return ip
  93. } catch (err) {
  94. console.log('└─ Unable to start the container 🛑')
  95. console.log(err)
  96. stopNextcloud()
  97. throw new Error('Unable to start the container')
  98. }
  99. }
  100. /**
  101. * Configure Nextcloud
  102. */
  103. export const configureNextcloud = async function() {
  104. console.log('\nConfiguring nextcloud...')
  105. const container = docker.getContainer(CONTAINER_NAME)
  106. await runExec(container, ['php', 'occ', '--version'], true)
  107. // Be consistent for screenshots
  108. await runExec(container, ['php', 'occ', 'config:system:set', 'default_language', '--value', 'en'], true)
  109. await runExec(container, ['php', 'occ', 'config:system:set', 'force_language', '--value', 'en'], true)
  110. await runExec(container, ['php', 'occ', 'config:system:set', 'default_locale', '--value', 'en_US'], true)
  111. await runExec(container, ['php', 'occ', 'config:system:set', 'force_locale', '--value', 'en_US'], true)
  112. await runExec(container, ['php', 'occ', 'config:system:set', 'enforce_theme', '--value', 'light'], true)
  113. console.log('└─ Nextcloud is now ready to use 🎉')
  114. }
  115. /**
  116. * Applying local changes to the container
  117. * Only triggered if we're not in CI. Otherwise the
  118. * continuous-integration-shallow-server image will
  119. * already fetch the proper branch.
  120. */
  121. export const applyChangesToNextcloud = async function() {
  122. console.log('\nApply local changes to nextcloud...')
  123. const container = docker.getContainer(CONTAINER_NAME)
  124. const htmlPath = '/var/www/html'
  125. const folderPaths = [
  126. './apps',
  127. './core',
  128. './dist',
  129. './lib',
  130. './ocs',
  131. ]
  132. // Tar-streaming the above folders into the container
  133. const serverTar = tar.c({ gzip: false }, folderPaths)
  134. await container.putArchive(serverTar, {
  135. path: htmlPath,
  136. })
  137. // Making sure we have the proper permissions
  138. await runExec(container, ['chown', '-R', 'www-data:www-data', htmlPath], false, 'root')
  139. console.log('└─ Changes applied successfully 🎉')
  140. }
  141. /**
  142. * Force stop the testing container
  143. */
  144. export const stopNextcloud = async function() {
  145. try {
  146. const container = docker.getContainer(CONTAINER_NAME)
  147. console.log('Stopping Nextcloud container...')
  148. container.remove({ force: true })
  149. console.log('└─ Nextcloud container removed 🥀')
  150. } catch (err) {
  151. console.log(err)
  152. }
  153. }
  154. /**
  155. * Get the testing container's IP
  156. *
  157. * @param {Docker.Container} container the container to get the IP from
  158. */
  159. export const getContainerIP = async function(
  160. container = docker.getContainer(CONTAINER_NAME)
  161. ): Promise<string> {
  162. let ip = ''
  163. let tries = 0
  164. while (ip === '' && tries < 10) {
  165. tries++
  166. await container.inspect(function(err, data) {
  167. if (err) {
  168. throw err
  169. }
  170. ip = data?.NetworkSettings?.IPAddress || ''
  171. })
  172. if (ip !== '') {
  173. break
  174. }
  175. await sleep(1000 * tries)
  176. }
  177. return ip
  178. }
  179. // Would be simpler to start the container from cypress.config.ts,
  180. // but when checking out different branches, it can take a few seconds
  181. // Until we can properly configure the baseUrl retry intervals,
  182. // We need to make sure the server is already running before cypress
  183. // https://github.com/cypress-io/cypress/issues/22676
  184. export const waitOnNextcloud = async function(ip: string) {
  185. console.log('├─ Waiting for Nextcloud to be ready... ⏳')
  186. await waitOn({ resources: [`http://${ip}/index.php`] })
  187. console.log('└─ Done')
  188. }
  189. const runExec = async function(
  190. container: Docker.Container,
  191. command: string[],
  192. verbose = false,
  193. user = 'www-data'
  194. ) {
  195. const exec = await container.exec({
  196. Cmd: command,
  197. AttachStdout: true,
  198. AttachStderr: true,
  199. User: user,
  200. })
  201. return new Promise((resolve, reject) => {
  202. exec.start({}, (err, stream) => {
  203. if (err) {
  204. reject(err)
  205. }
  206. if (stream) {
  207. stream.setEncoding('utf-8')
  208. stream.on('data', str => {
  209. if (verbose && str.trim() !== '') {
  210. console.log(`├─ ${str.trim().replace(/\n/gi, '\n├─ ')}`)
  211. }
  212. })
  213. stream.on('end', resolve)
  214. }
  215. })
  216. })
  217. }
  218. const sleep = function(milliseconds: number) {
  219. return new Promise((resolve) => setTimeout(resolve, milliseconds))
  220. }
  221. const getCurrentGitBranch = function() {
  222. return execSync('git rev-parse --abbrev-ref HEAD').toString().trim() || 'master'
  223. }