webhook_deploy_gogs.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. /**
  2. * A server that listens on a port for Gogs's webhooks.
  3. * It will check for a push event on the master branch, then deploy the project on the machine.
  4. * The webhook's secret is check to ensure no malicious request from unknown sources.
  5. *
  6. * Usage :
  7. * Set the "WEBHOOK_SECRET" environment variable with the webhook's secret.
  8. *
  9. * @see https://gogs.io/docs/features/webhook
  10. *
  11. *
  12. * @author Antoine Sauvage <contact@asauvage.fr>
  13. * @license MIT 2019 - https://opensource.org/licenses/MIT
  14. * @see https://gist.github.com/rigwild/4238a13cb3501c6e85065b403a71b475
  15. */
  16. 'use strict'
  17. const fs = require('fs')
  18. const http = require('http')
  19. const path = require('path')
  20. const { promisify } = require('util')
  21. const exec = promisify(require('child_process').exec)
  22. // The port which this script will listen on
  23. const port = parseInt(process.env.WEBHOOK_PORT, 10)
  24. // Check the "WEBHOOK_PORT" environment variable is set to a valid integer
  25. if (!process.env.WEBHOOK_PORT || !parseInt(process.env.WEBHOOK_PORT, 10)) {
  26. console.error(`${new Date().toLocaleString()} - The "WEBHOOK_PORT" environment variable is not set or is not an integer.`)
  27. process.exit(1)
  28. }
  29. // The path to the project directory
  30. const projectPath = path.resolve('.')
  31. // The webhook secret to check the origin of the webhook event
  32. // Check the "WEBHOOK_SECRET" environment variable is set
  33. if (!process.env.WEBHOOK_SECRET && process.env.WEBHOOK_SECRET !== '') {
  34. console.error(`${new Date().toLocaleString()} - The "WEBHOOK_SECRET" environment variable is not set.`)
  35. process.exit(1)
  36. }
  37. const webhookSecret = process.env.WEBHOOK_SECRET
  38. // Check whether the project path exists and script has read access
  39. console.log(`${new Date().toLocaleString()} - Configured project path : ${projectPath}\n`)
  40. try {
  41. fs.accessSync(projectPath, fs.constants.W_OK)
  42. console.log(`${new Date().toLocaleString()} - The project's directory exists and script has write permission.`)
  43. }
  44. catch (err) {
  45. console.error(`${new Date().toLocaleString()} - The project's directory does not exist or script has not write permission.`, err)
  46. process.exit(1)
  47. }
  48. // Check the "PORT" environment variable is set to a valid integer
  49. if (!process.env.PORT || !parseInt(process.env.PORT, 10)) {
  50. console.error(`${new Date().toLocaleString()} - The "PORT" environment variable is not set or is not an integer.`)
  51. process.exit(1)
  52. }
  53. // Check the "SERVE_CLIENT" environment variable is set to 'true' or 'false'
  54. if (!process.env.SERVE_CLIENT || !['true', 'false'].some(x => x === process.env.SERVE_CLIENT)) {
  55. console.error(`${new Date().toLocaleString()} - The "SERVE_CLIENT" environment variable is not set or is not 'true' or 'false'`)
  56. process.exit(1)
  57. }
  58. let env = {
  59. PORT: parseInt(process.env.PORT, 10),
  60. SERVE_CLIENT: process.env.SERVE_CLIENT,
  61. IMAGES_PATH: process.env.IMAGES_PATH
  62. }
  63. env = Object.assign(process.env, env)
  64. if (!env.IMAGES_PATH) env.IMAGES_PATH = ''
  65. // Recap used environment variables
  66. Object.keys(env).forEach(x => console.log(`${x}=${env[x]}`))
  67. // The script that will be executed by the machine
  68. const deployScript = `cd ${projectPath}` +
  69. // ' && git reset --hard HEAD' +
  70. ' && git pull origin master' +
  71. ' && docker-compose down' +
  72. ' && docker-compose build' +
  73. ' && docker-compose up -d'
  74. console.log('\nConfiguration is valid. Starting the webhook-listener server ...')
  75. const deploy = async () => {
  76. try {
  77. console.log(`${new Date().toLocaleString()} - Deploying project ...`)
  78. const startTime = process.hrtime()
  79. const { stdout, stderr } = await exec(
  80. deployScript,
  81. {
  82. cwd: projectPath,
  83. env
  84. }
  85. )
  86. const endTime = process.hrtime(startTime)
  87. // Logs received from the deploy script are sent in stdout :
  88. // git fetch and docker-compose build/up are writing their success logs in stderr...
  89. // A deploy fail will be printed in stderr (in the catch)
  90. console.log('stdout :\n', stdout)
  91. console.log('stderr :\n', stderr)
  92. console.log(`\n${new Date().toLocaleString()} - Project successfully deployed with Docker.`)
  93. console.log(`Total deploy time : ${endTime[0]}s and ${endTime[1] / 1000000}ms.`)
  94. }
  95. catch (err) {
  96. console.error(`\n${new Date().toLocaleString()} - Error deploying project.\n`, err)
  97. }
  98. }
  99. // Configuration is fine, start the server
  100. http.createServer((req, res) => {
  101. // Check the method is POST
  102. if (req.method !== 'POST') {
  103. res.statusCode = 400
  104. res.write('Wrong HTTP method.')
  105. res.end()
  106. return
  107. }
  108. // Check the event is a push
  109. if (req.headers['x-gogs-event'] !== 'push') {
  110. res.statusCode = 200
  111. res.write('OK. Not a push event.')
  112. res.end()
  113. return
  114. }
  115. // Answer OK and close the connection
  116. res.statusCode = 200
  117. res.write('OK')
  118. res.end()
  119. let body = []
  120. req.on('data', chunk => body.push(chunk))
  121. req.on('end', () => {
  122. try {
  123. body = JSON.parse(Buffer.concat(body).toString())
  124. // Check if the event was on master
  125. if (!body.ref || body.ref !== 'refs/heads/master') return
  126. // Check if secret matches
  127. if (!body.secret || body.secret !== webhookSecret) return
  128. console.log(`${new Date()} - Valid webhook event. Push on master was sent. Deployement process starts.`)
  129. deploy()
  130. }
  131. catch (err) {
  132. console.error(`${new Date()} - Invalid JSON was received`)
  133. }
  134. })
  135. }).listen(port)
  136. console.log(`${new Date().toLocaleString()} - Server is listening on http://localhost:${port}/`)