You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dockerNode.ts 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. await runExec(container, ['php', 'occ', 'config:system:set', 'versions_retention_obligation', '--value', '0, 0'], true)
  114. console.log('└─ Nextcloud is now ready to use 🎉')
  115. }
  116. /**
  117. * Applying local changes to the container
  118. * Only triggered if we're not in CI. Otherwise the
  119. * continuous-integration-shallow-server image will
  120. * already fetch the proper branch.
  121. */
  122. export const applyChangesToNextcloud = async function() {
  123. console.log('\nApply local changes to nextcloud...')
  124. const container = docker.getContainer(CONTAINER_NAME)
  125. const htmlPath = '/var/www/html'
  126. const folderPaths = [
  127. './apps',
  128. './core',
  129. './dist',
  130. './lib',
  131. './ocs',
  132. ]
  133. // Tar-streaming the above folders into the container
  134. const serverTar = tar.c({ gzip: false }, folderPaths)
  135. await container.putArchive(serverTar, {
  136. path: htmlPath,
  137. })
  138. // Making sure we have the proper permissions
  139. await runExec(container, ['chown', '-R', 'www-data:www-data', htmlPath], false, 'root')
  140. console.log('└─ Changes applied successfully 🎉')
  141. }
  142. /**
  143. * Force stop the testing container
  144. */
  145. export const stopNextcloud = async function() {
  146. try {
  147. const container = docker.getContainer(CONTAINER_NAME)
  148. console.log('Stopping Nextcloud container...')
  149. container.remove({ force: true })
  150. console.log('└─ Nextcloud container removed 🥀')
  151. } catch (err) {
  152. console.log(err)
  153. }
  154. }
  155. /**
  156. * Get the testing container's IP
  157. *
  158. * @param {Docker.Container} container the container to get the IP from
  159. */
  160. export const getContainerIP = async function(
  161. container = docker.getContainer(CONTAINER_NAME)
  162. ): Promise<string> {
  163. let ip = ''
  164. let tries = 0
  165. while (ip === '' && tries < 10) {
  166. tries++
  167. await container.inspect(function(err, data) {
  168. if (err) {
  169. throw err
  170. }
  171. ip = data?.NetworkSettings?.IPAddress || ''
  172. })
  173. if (ip !== '') {
  174. break
  175. }
  176. await sleep(1000 * tries)
  177. }
  178. return ip
  179. }
  180. // Would be simpler to start the container from cypress.config.ts,
  181. // but when checking out different branches, it can take a few seconds
  182. // Until we can properly configure the baseUrl retry intervals,
  183. // We need to make sure the server is already running before cypress
  184. // https://github.com/cypress-io/cypress/issues/22676
  185. export const waitOnNextcloud = async function(ip: string) {
  186. console.log('├─ Waiting for Nextcloud to be ready... ⏳')
  187. await waitOn({ resources: [`http://${ip}/index.php`] })
  188. console.log('└─ Done')
  189. }
  190. const runExec = async function(
  191. container: Docker.Container,
  192. command: string[],
  193. verbose = false,
  194. user = 'www-data'
  195. ) {
  196. const exec = await container.exec({
  197. Cmd: command,
  198. AttachStdout: true,
  199. AttachStderr: true,
  200. User: user,
  201. })
  202. return new Promise((resolve, reject) => {
  203. exec.start({}, (err, stream) => {
  204. if (err) {
  205. reject(err)
  206. }
  207. if (stream) {
  208. stream.setEncoding('utf-8')
  209. stream.on('data', str => {
  210. if (verbose && str.trim() !== '') {
  211. console.log(`├─ ${str.trim().replace(/\n/gi, '\n├─ ')}`)
  212. }
  213. })
  214. stream.on('end', resolve)
  215. }
  216. })
  217. })
  218. }
  219. const sleep = function(milliseconds: number) {
  220. return new Promise((resolve) => setTimeout(resolve, milliseconds))
  221. }
  222. const getCurrentGitBranch = function() {
  223. return execSync('git rev-parse --abbrev-ref HEAD').toString().trim() || 'master'
  224. }