|
| 1 | +// npm packages |
| 2 | +const fs = require('fs'); |
| 3 | +const path = require('path'); |
| 4 | + |
| 5 | +const javaDockerfile = () => |
| 6 | + `FROM openjdk |
| 7 | +COPY . /usr/src/myapp |
| 8 | +WORKDIR /usr/src/myapp |
| 9 | +EXPOSE 80 |
| 10 | +CMD java -jar app.jar`; |
| 11 | + |
| 12 | +// template name |
| 13 | +exports.name = 'java'; |
| 14 | + |
| 15 | +// function to check if the template fits this recipe |
| 16 | +exports.checkTemplate = async ({tempDockerDir}) => { |
| 17 | + // if project already has dockerfile - just exit |
| 18 | + try { |
| 19 | + const filesList = fs.readdirSync(tempDockerDir); |
| 20 | + return filesList.filter(file => file.includes('.jar')).length > 0; |
| 21 | + } catch (e) { |
| 22 | + return false; |
| 23 | + } |
| 24 | +}; |
| 25 | + |
| 26 | +// function to execute current template |
| 27 | +exports.executeTemplate = async ({username, tempDockerDir, resultStream, util, docker}) => { |
| 28 | + try { |
| 29 | + // generate dockerfile |
| 30 | + const dockerfile = javaDockerfile(); |
| 31 | + const dfPath = path.join(tempDockerDir, 'Dockerfile'); |
| 32 | + fs.writeFileSync(dfPath, dockerfile, 'utf-8'); |
| 33 | + util.writeStatus(resultStream, {message: 'Deploying Java project..', level: 'info'}); |
| 34 | + |
| 35 | + // build docker image |
| 36 | + const buildRes = await docker.build({username, resultStream}); |
| 37 | + util.logger.debug('Build result:', buildRes); |
| 38 | + |
| 39 | + // check for errors in build log |
| 40 | + if ( |
| 41 | + buildRes.log |
| 42 | + .map(it => it.toLowerCase()) |
| 43 | + .some(it => it.includes('error') || (it.includes('failed') && !it.includes('optional'))) |
| 44 | + ) { |
| 45 | + util.logger.debug('Build log conains error!'); |
| 46 | + util.writeStatus(resultStream, {message: 'Build log contains errors!', level: 'error'}); |
| 47 | + resultStream.end(''); |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + // start image |
| 52 | + const containerInfo = await docker.start(Object.assign({}, buildRes, {username, resultStream})); |
| 53 | + util.logger.debug(containerInfo.Name); |
| 54 | + |
| 55 | + // clean temp folder |
| 56 | + await util.cleanTemp(); |
| 57 | + |
| 58 | + const containerData = docker.daemon.getContainer(containerInfo.Id); |
| 59 | + const container = await containerData.inspect(); |
| 60 | + // return new deployments |
| 61 | + util.writeStatus(resultStream, {message: 'Deployment success!', deployments: [container], level: 'info'}); |
| 62 | + resultStream.end(''); |
| 63 | + } catch (e) { |
| 64 | + util.logger.debug('build failed!', e); |
| 65 | + util.writeStatus(resultStream, {message: e.error, error: e.error, log: e.log, level: 'error'}); |
| 66 | + resultStream.end(''); |
| 67 | + } |
| 68 | +}; |
0 commit comments