@ossy/deployment-tools 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,23 @@
1
+ node-fetch
2
+ MIT
3
+ The MIT License (MIT)
4
+
5
+ Copyright (c) 2016 - 2020 Node Fetch Team
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
package/package.json ADDED
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "@ossy/deployment-tools",
3
+ "version": "0.0.1",
4
+ "description": "Collection of scripts and tools to aid deployment of containers and static files",
5
+ "main": "dist/index.js",
6
+ "type": "module",
7
+ "scripts": {
8
+ "test": "echo \"Error: no test specified\" && exit 1",
9
+ "build": "npx --yes @vercel/ncc build src/index.js --out dist --license licenses.txt"
10
+ },
11
+ "author": "Ossy",
12
+ "license": "ISC",
13
+ "bin": "dist/index.js",
14
+ "dependencies": {
15
+ "arg": "^5.0.2",
16
+ "express": "^4.18.1",
17
+ "nanoid": "^4.0.0",
18
+ "node-fetch": "^3.2.6"
19
+ }
20
+ }
package/src/Caddyfile ADDED
@@ -0,0 +1,22 @@
1
+ localhost {
2
+ reverse_proxy /api/* {
3
+ to localhost:3001
4
+ }
5
+
6
+ reverse_proxy * {
7
+ to localhost:3000
8
+ }
9
+
10
+ }
11
+
12
+ cms.localhost {
13
+ reverse_proxy * {
14
+ to localhost:3005
15
+ }
16
+ }
17
+
18
+ admin.localhost {
19
+ reverse_proxy * {
20
+ to localhost:3000
21
+ }
22
+ }
@@ -0,0 +1,118 @@
1
+ import fetch from 'node-fetch'
2
+
3
+ const Matchers = {
4
+ host: host => ({ host: [host] }),
5
+ path: path => ({ path: [path] })
6
+ }
7
+
8
+ const Handlers = {
9
+ reverseProxy: upstreamPort => ({
10
+ handler: 'reverse_proxy',
11
+ upstreams: [{ dial: `localhost:${upstreamPort}` }]
12
+ }),
13
+ subroute: routes => ( {
14
+ handler: 'subroute',
15
+ routes
16
+ })
17
+ }
18
+
19
+ const createRouteConfig = ({ domain, path, upstreamPort }) => ({
20
+ match: [Matchers.host(domain)],
21
+ handle: [
22
+ {
23
+ handler: 'subroute',
24
+ routes: [
25
+ { handle: [Handlers.reverseProxy(upstreamPort)]}
26
+ ]
27
+ }
28
+ ],
29
+ terminal: true
30
+ })
31
+
32
+ const multipleDomansAndSubroutes = () => ({
33
+ apps: {
34
+ http: {
35
+ servers: {
36
+ 'ci-client': {
37
+ listen: [
38
+ ':443'
39
+ ],
40
+ routes: [
41
+ {
42
+ match: [Matchers.host('admin.localhost')],
43
+ handle: [
44
+ Handlers.subroute([{ handle: [Handlers.reverseProxy(3000)] }])
45
+ ],
46
+ terminal: true
47
+ },
48
+ {
49
+ match: [Matchers.host('cms.localhost')],
50
+ handle: [
51
+ Handlers.subroute([{ handle: [Handlers.reverseProxy(3005)] }])
52
+ ],
53
+ terminal: true
54
+ },
55
+ {
56
+ match: [Matchers.host('localhost')],
57
+ handle: [
58
+ Handlers.subroute([
59
+ {
60
+ handle: [Handlers.reverseProxy(3001)],
61
+ match: [Matchers.path('/api/*')]
62
+ },
63
+ { handle: [Handlers.reverseProxy(3000)] }
64
+ ])
65
+ ],
66
+ terminal: true
67
+ }
68
+ ]
69
+ }
70
+ }
71
+ }
72
+ }
73
+ })
74
+
75
+ // curl localhost:2019/id/msg
76
+
77
+ class CaddyClient {
78
+
79
+ constructor(serverName = 'ci-client') {
80
+ this.serverName = serverName
81
+ }
82
+
83
+ deploy({ domain, targetPort }) {
84
+ return fetch(`http://localhost:2019/config/apps/http/servers/${this.serverName}/routes`, {
85
+ method: 'POST',
86
+ headers: { 'Content-Type': 'application/json' },
87
+ body: JSON.stringify({
88
+ match: [Matchers.host(domain)],
89
+ handle: [
90
+ Handlers.subroute([{ handle: [Handlers.reverseProxy(targetPort)] }])
91
+ ],
92
+ terminal: true
93
+ })
94
+ })
95
+ }
96
+
97
+ applyDefaultServerConfig() {
98
+ return fetch('http://localhost:2019/load', {
99
+ method: 'POST',
100
+ headers: { 'Content-Type': 'application/json' },
101
+ body: JSON.stringify({
102
+ apps: {
103
+ http: {
104
+ servers: {
105
+ [this.serverName]: {
106
+ listen: [':443'],
107
+ routes: []
108
+ }
109
+ }
110
+ }
111
+ }
112
+ })
113
+ })
114
+ }
115
+
116
+ }
117
+
118
+ export const createCaddyClient = serverName => new CaddyClient(serverName)
package/src/config.js ADDED
@@ -0,0 +1,3 @@
1
+ export const domain = process.env.DEPLOYMENT_TOOLS_DOMAIN || 'localhost'
2
+ export const subdomain = process.env.DEPLOYMENT_TOOLS_SUBDOMAIN || 'local-dev.ci'
3
+ export const port = process.env.DEPLOYMENT_TOOLS_PORT || 3000
@@ -0,0 +1,114 @@
1
+ import { resolve } from 'path'
2
+ import { readFileSync } from 'fs'
3
+ import fetch from 'node-fetch'
4
+
5
+ const username = 'oskarssylwan'
6
+ const authentication = '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'
7
+
8
+ export class ContainerManagerCommands {
9
+
10
+ static deploy(
11
+ targetEnvironment = 'local-dev',
12
+ pathToDeploymentPlatforms,
13
+ pathToOssyFile
14
+ ) {
15
+ const webApiCommands = new ContainerManagerCommands()
16
+ return webApiCommands.deploy(
17
+ targetEnvironment,
18
+ pathToDeploymentPlatforms,
19
+ pathToOssyFile
20
+ )
21
+ }
22
+
23
+ constructor() {
24
+
25
+ }
26
+
27
+ getDeployments(pathToOssyFile) {
28
+ const ossyfile = JSON.parse(readFileSync(resolve(pathToOssyFile), 'utf8'))
29
+ return Promise.resolve(ossyfile.deployments || [])
30
+ }
31
+
32
+ async getDeploymentPlatforms(pathToDeploymentPlatforms) {
33
+
34
+ const localDevPlatform = {
35
+ name: 'local-dev',
36
+ domain: 'localhost',
37
+ supportedDeploymentTypes: ['CONTAINER']
38
+ }
39
+
40
+ if (!pathToDeploymentPlatforms) return [localDevPlatform]
41
+
42
+ const imports = await import(resolve(pathToDeploymentPlatforms))
43
+ const deploymentPlatforms = Object.values(imports)
44
+ return deploymentPlatforms || [localDevPlatform]
45
+ }
46
+
47
+ getDeploymentTargetURL(targetEnvironment, deploymentPlatform, deployment) {
48
+ let domain = targetEnvironment !== 'prod'
49
+ ? `${targetEnvironment}.`
50
+ : ''
51
+
52
+ domain = deployment.subdomain
53
+ ? `${domain}${deployment.subdomain}.${deploymentPlatform.domain}`
54
+ : `${domain}${deploymentPlatform.domain}`
55
+
56
+ return domain
57
+ }
58
+
59
+ getEnvironmentVariables(targetEnvironment, deployment) {
60
+ const envs = deployment.env || {}
61
+ return {
62
+ ...(envs.shared || {}),
63
+ ...(envs[targetEnvironment] || {})
64
+ }
65
+ }
66
+
67
+ deploy(
68
+ targetEnvironment = 'local-dev',
69
+ pathToDeploymentPlatforms,
70
+ pathToOssyFile
71
+ ) {
72
+ console.log('pathToDeploymentPlatforms', pathToDeploymentPlatforms)
73
+ console.log('pathToOssyFile', pathToOssyFile)
74
+ console.log('pathToOssyFile resolved', resolve(pathToOssyFile))
75
+ return Promise.all([
76
+ this.getDeploymentPlatforms(pathToDeploymentPlatforms),
77
+ this.getDeployments(pathToOssyFile)
78
+ ])
79
+ .then(([platforms, deployments]) => {
80
+ deployments.map(deployment => {
81
+ const platform = platforms.find(platform => platform.name === deployment.targetDeploymentPlatform)
82
+
83
+ if (!platform) {
84
+ return Promise.reject(
85
+ `Could not find a deployment platform with the name ${deployment.targetDeploymentPlatform}`
86
+ )
87
+ }
88
+
89
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0
90
+
91
+ const body = {
92
+ image: deployment.image,
93
+ hostPort: deployment.hostPort,
94
+ containerPort: deployment.containerPort,
95
+ domain: this.getDeploymentTargetURL(targetEnvironment, platform, deployment),
96
+ env: this.getEnvironmentVariables(targetEnvironment, deployment),
97
+ registry: deployment.registry,
98
+ username: username,
99
+ authentication: authentication
100
+ }
101
+
102
+ console.log('body', body)
103
+
104
+ fetch(`http://${targetEnvironment}.ci.${platform.domain}/deploy`, {
105
+ method: 'POST',
106
+ headers: { 'Content-Type': 'application/json' },
107
+ body: JSON.stringify(body)
108
+ })
109
+ })
110
+ })
111
+ .catch(error => console.log(error))
112
+ }
113
+
114
+ }
@@ -0,0 +1,73 @@
1
+ import express from 'express'
2
+ import { createCaddyClient } from './caddy-client.js'
3
+ import { createDockerClient } from './docker-client.js'
4
+ import * as config from './config.js'
5
+
6
+ export class ContainerManagerServer {
7
+
8
+ static start() {
9
+ return new ContainerManagerServer()
10
+ }
11
+
12
+ constructor() {
13
+ this.dockerClient = createDockerClient()
14
+ this.caddyClient = createCaddyClient()
15
+ this.server = express()
16
+
17
+ this.server.use(express.json())
18
+
19
+ this.caddyClient.applyDefaultServerConfig()
20
+ .then(() => this.caddyClient.deploy({
21
+ domain: `${config.subdomain}.${config.domain}`,
22
+ targetPort: config.port
23
+ }))
24
+
25
+ this.server.get('/', (req, res) => {
26
+ res.redirect('/status')
27
+ })
28
+
29
+ this.server.get('/status', (req, res) => {
30
+ res.json('Server is live')
31
+ })
32
+
33
+ this.server.post('/deploy', (req, res) => {
34
+ console.log('/deploy body', req.body)
35
+ this.deploy(req, res)
36
+ })
37
+
38
+ this.server.listen(config.port, () => {
39
+ console.log(`Web API is live on port ${config.port}`)
40
+ })
41
+ }
42
+
43
+ deploy(req, res) {
44
+
45
+ console.log('req.body: ', req.body)
46
+
47
+ const {
48
+ registry,
49
+ username,
50
+ authentication,
51
+ containerPort,
52
+ hostPort,
53
+ image,
54
+ domain,
55
+ env
56
+ } = req.body
57
+
58
+ this.dockerClient.deploy({
59
+ image,
60
+ registry,
61
+ username,
62
+ authentication,
63
+ containerPort,
64
+ hostPort,
65
+ env
66
+ })
67
+
68
+ domain && this.caddyClient.deploy({ domain, targetPort: hostPort })
69
+
70
+ res.json('Recieved deployment request')
71
+ }
72
+
73
+ }
@@ -0,0 +1,78 @@
1
+ import { exec } from 'child_process'
2
+ import fs from 'fs'
3
+ import { nanoid } from 'nanoid'
4
+ import path from 'path'
5
+ import { fileURLToPath } from 'url'
6
+
7
+ const __filename = fileURLToPath(import.meta.url)
8
+ const __dirname = path.dirname(__filename)
9
+
10
+ class DockerClient {
11
+
12
+ constructor() {
13
+ this.networkName = 'deployment-tools'
14
+ exec(`docker network create ${this.networkName}`)
15
+ }
16
+
17
+ stopContainer({ image }) {
18
+ const name = image.replaceAll('/', '_')
19
+ return `sudo docker stop ${name} ||`
20
+ }
21
+
22
+ startContainer({ image, containerPort, hostPort, registry, env }) {
23
+ const name = image.replaceAll('/', '_')
24
+ const imageUrl = !!registry ? `${registry}/${image}` : image
25
+ const envsAsString = Object.entries(env || {}).reduce((envs, [name, value]) => `${envs} --env ${name}=${value}`, '')
26
+ return `sudo docker run -d -p ${hostPort}:${containerPort} --name=${name} --network=${this.networkName} --network-alias=${name} --rm ${envsAsString} ${imageUrl}`
27
+ }
28
+
29
+ resolveCredentials({ registry, username, authentication }) {
30
+ return (username || authentication)
31
+ ? `sudo docker login ${registry} -u ${username} -p ${authentication}`
32
+ : 'echo No credentials provided, assuming image is publicly hosted'
33
+ }
34
+
35
+ deploy({
36
+ image,
37
+ registry,
38
+ username,
39
+ authentication,
40
+ containerPort,
41
+ hostPort,
42
+ env
43
+ }) {
44
+ return new Promise(resolve => {
45
+ const dockerCommandScript = `'#!/bin/bash'
46
+ ${this.stopContainer({ image })}
47
+ ${this.resolveCredentials({ registry, username, authentication })}
48
+ ${this.startContainer({ image, containerPort, hostPort, registry, env })}`
49
+
50
+ const deploymentId = nanoid()
51
+
52
+ const FilePaths = {
53
+ DeploymentScript: `${__dirname}/${deploymentId}.sh`
54
+ }
55
+
56
+ fs.writeFileSync(FilePaths.DeploymentScript, dockerCommandScript)
57
+ const command = exec(`bash ${FilePaths.DeploymentScript}`)
58
+
59
+ command.stdout.on('data', (data) => {
60
+ console.log(`[DockerClient]: ${data}`)
61
+ })
62
+
63
+ command.stderr.on('data', (data) => {
64
+ console.error(`[DockerClient]: ${data}`)
65
+ })
66
+
67
+ command.on('close', (code) => {
68
+ console.log(`[DockerClient] command exited with code ${code}`)
69
+ fs.unlinkSync(FilePaths.DeploymentScript)
70
+ resolve()
71
+ })
72
+ })
73
+
74
+ }
75
+
76
+ }
77
+
78
+ export const createDockerClient = () => new DockerClient()
package/src/index.js ADDED
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ import { platform } from 'os'
3
+ import { writeFileSync } from 'fs'
4
+ import { exec } from 'child_process'
5
+ import arg from 'arg'
6
+ import { ContainerManagerServer } from './container-manager-server.js'
7
+ import { ContainerManagerCommands } from './container-manager-commands.js'
8
+
9
+ const [_, __, command, ...restArgs] = process.argv
10
+
11
+ const startHandler = () => {
12
+ console.log('Running start command')
13
+
14
+ const Platforms = {
15
+ windows: 'win32',
16
+ mac: 'darwin'
17
+ }
18
+
19
+ if ([Platforms.windows].includes(platform())) {
20
+ return console.error('Deployment tools do not support this os')
21
+ }
22
+
23
+ writeFileSync('/etc/systemd/system/deployment-tools.service', `
24
+ [Unit]
25
+ Description=D
26
+ After=network.target
27
+
28
+ [Service]
29
+ Environment=DEPLOYMENT_TOOLS_PORT=3000
30
+ User=root
31
+ WorkingDirectory=/%h/deployment-tools
32
+ ExecStart=/usr/bin/node /%h/deployment-tools/index.js start-container-manager
33
+ Restart=on-failure
34
+
35
+ [Install]
36
+ WantedBy=multi-user.target
37
+ `)
38
+
39
+ exec('systemctl daemon-reload')
40
+ exec('systemctl start deployment-tools.service')
41
+
42
+ }
43
+
44
+ const startContainerManagerHandler = () => {
45
+ console.log('Running start-container-manager command')
46
+ ContainerManagerServer.start()
47
+ }
48
+
49
+ const stopHandler = () => {
50
+ console.log('Running stop command')
51
+ exec('systemctl stop deployment-tools.service')
52
+ }
53
+
54
+ const statusHandler = () => {
55
+ console.log('Running status command')
56
+ exec('systemctl status deployment-tools.service')
57
+ }
58
+
59
+ const deployHandler = () => {
60
+ console.log('Running deploy command')
61
+
62
+ const args = arg({
63
+ '--target-env': String,
64
+ '-t': '--target-env',
65
+
66
+ '--ossyfile': String,
67
+ '-o': '--ossyfile',
68
+
69
+ '--platforms': String,
70
+ '-p': '--platforms'
71
+ }, { argv: restArgs })
72
+
73
+ console.log('args', args)
74
+
75
+ ContainerManagerCommands.deploy(
76
+ args['--target-env'],
77
+ args['--platforms'],
78
+ args['--ossyfile']
79
+ )
80
+ }
81
+
82
+ const Commands = {
83
+ start: startHandler,
84
+ stop: stopHandler,
85
+ status: statusHandler,
86
+ deploy: deployHandler,
87
+ // internal commands
88
+ 'start-container-manager': startContainerManagerHandler
89
+ }
90
+
91
+ const commandHandler = Commands[command]
92
+
93
+ if (!commandHandler) {
94
+ console.log('Command not implemented, did you spell it correctly?')
95
+ }
96
+
97
+ commandHandler()