@omer-x/buttler 0.1.0
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.
- package/LICENSE +21 -0
- package/bin/api.js +36 -0
- package/bin/database.js +23 -0
- package/bin/docker.js +60 -0
- package/bin/git.js +13 -0
- package/bin/github.js +14 -0
- package/bin/index.js +38 -0
- package/bin/object.js +9 -0
- package/bin/services.js +67 -0
- package/package.json +68 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Omer Mecitoglu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/bin/api.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import bodyParser from "body-parser";
|
|
2
|
+
import express from "express";
|
|
3
|
+
import { cancelBuild, removeContainer, removeImage } from "./docker.js";
|
|
4
|
+
import { verifySignature } from "./github.js";
|
|
5
|
+
import { omit } from "./object.js";
|
|
6
|
+
import { getAllServices, prepareService } from "./services.js";
|
|
7
|
+
const app = express();
|
|
8
|
+
app.use(bodyParser.json());
|
|
9
|
+
app.post("/webhook", bodyParser.json({ verify: verifySignature }), (req, res) => {
|
|
10
|
+
handleWebhookEvent(req.body);
|
|
11
|
+
res.status(200).send("Webhook received");
|
|
12
|
+
});
|
|
13
|
+
async function handleWebhookEvent(event) {
|
|
14
|
+
const savedServices = await getAllServices();
|
|
15
|
+
for (const [serviceId, service] of Object.entries(savedServices)) {
|
|
16
|
+
if (service.repo !== event.repository.ssh_url)
|
|
17
|
+
continue;
|
|
18
|
+
console.log(serviceId + " needs update");
|
|
19
|
+
if (service.containerId) {
|
|
20
|
+
await removeContainer(service.containerId);
|
|
21
|
+
}
|
|
22
|
+
if (service.imageId) {
|
|
23
|
+
if (service.state === "building") {
|
|
24
|
+
await cancelBuild(serviceId, service.imageId);
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
await removeImage(service.imageId);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
await prepareService(serviceId, {
|
|
31
|
+
...omit(service, "state", "containerId", "imageId"),
|
|
32
|
+
state: "cloned",
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export default app;
|
package/bin/database.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
export async function saveNode(collectionName, id, data) {
|
|
4
|
+
const dirPath = path.resolve(process.cwd(), "storage/db", collectionName);
|
|
5
|
+
await fs.mkdir(dirPath, { recursive: true });
|
|
6
|
+
const filePath = path.resolve(dirPath, `${id}.json`);
|
|
7
|
+
return fs.writeFile(filePath, JSON.stringify(data), "utf8");
|
|
8
|
+
}
|
|
9
|
+
export async function readNode(collectionName, id) {
|
|
10
|
+
const dirPath = path.resolve(process.cwd(), "storage/db", collectionName);
|
|
11
|
+
await fs.mkdir(dirPath, { recursive: true });
|
|
12
|
+
const filePath = path.resolve(dirPath, `${id}.json`);
|
|
13
|
+
const content = await fs.readFile(filePath, "utf-8");
|
|
14
|
+
return JSON.parse(content);
|
|
15
|
+
}
|
|
16
|
+
export async function findNodes(collectionName) {
|
|
17
|
+
const dirPath = path.resolve(process.cwd(), "storage/db", collectionName);
|
|
18
|
+
await fs.mkdir(dirPath, { recursive: true });
|
|
19
|
+
const items = await fs.readdir(dirPath, { withFileTypes: true });
|
|
20
|
+
const files = items.filter(i => i.isFile() && i.name.endsWith(".json"));
|
|
21
|
+
const records = await Promise.all(files.map(f => readNode(collectionName, f.name.slice(0, -5))));
|
|
22
|
+
return Object.fromEntries(files.map((file, index) => [file.name.slice(0, -5), records[index]]));
|
|
23
|
+
}
|
package/bin/docker.js
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import Docker from "dockerode";
|
|
3
|
+
import tar from "tar-fs";
|
|
4
|
+
import { deleteRepo } from "./services.js";
|
|
5
|
+
const docker = new Docker();
|
|
6
|
+
const streams = {};
|
|
7
|
+
export function buildImage(imageId, repoPath) {
|
|
8
|
+
const dockerfilePath = path.join(repoPath, "Dockerfile");
|
|
9
|
+
// Create a tar stream of the directory containing the Dockerfile
|
|
10
|
+
const tarStream = tar.pack(path.dirname(dockerfilePath));
|
|
11
|
+
return new Promise((resolve, reject) => {
|
|
12
|
+
docker.buildImage(tarStream, { t: `${imageId}:latest` }, (err, stream) => {
|
|
13
|
+
if (err)
|
|
14
|
+
return reject(err);
|
|
15
|
+
if (!stream)
|
|
16
|
+
return reject(new Error("no stream"));
|
|
17
|
+
// stream.pipe(process.stdout, { end: true });
|
|
18
|
+
stream.on("data", () => null);
|
|
19
|
+
stream.on("end", () => {
|
|
20
|
+
resolve(true);
|
|
21
|
+
});
|
|
22
|
+
stream.on("error", reason => {
|
|
23
|
+
if (reason === "UPDATE") {
|
|
24
|
+
resolve(false);
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
reject(reason);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
streams[imageId] = stream;
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
export async function cancelBuild(serviceId, imageId) {
|
|
35
|
+
const stream = streams[imageId];
|
|
36
|
+
await stream.destroy("UPDATE");
|
|
37
|
+
delete streams[imageId];
|
|
38
|
+
await deleteRepo(serviceId);
|
|
39
|
+
}
|
|
40
|
+
export async function removeImage(imageId) {
|
|
41
|
+
const image = docker.getImage(imageId);
|
|
42
|
+
await image.remove();
|
|
43
|
+
}
|
|
44
|
+
export async function createContainer(service) {
|
|
45
|
+
const container = await docker.createContainer({
|
|
46
|
+
name: service.name,
|
|
47
|
+
Image: service.imageId,
|
|
48
|
+
Env: Object.entries(service.env).map(([key, value]) => `${key}=${value}`),
|
|
49
|
+
HostConfig: {
|
|
50
|
+
PortBindings: Object.fromEntries(Object.entries(service.ports).map(([internal, external]) => {
|
|
51
|
+
return [`${internal}/tcp`, [{ HostPort: external }]];
|
|
52
|
+
})),
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
await container.start();
|
|
56
|
+
return container.id;
|
|
57
|
+
}
|
|
58
|
+
export async function removeContainer(containerId) {
|
|
59
|
+
await docker.getContainer(containerId).remove({ force: true });
|
|
60
|
+
}
|
package/bin/git.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import nodegit from "@figma/nodegit";
|
|
2
|
+
export function cloneRepo(repoUrl, targetPath) {
|
|
3
|
+
return nodegit.Clone(repoUrl, targetPath, {
|
|
4
|
+
fetchOpts: {
|
|
5
|
+
callbacks: {
|
|
6
|
+
certificateCheck: () => 0,
|
|
7
|
+
credentials: (_url, userName) => {
|
|
8
|
+
return nodegit.Credential.sshKeyFromAgent(userName);
|
|
9
|
+
},
|
|
10
|
+
},
|
|
11
|
+
},
|
|
12
|
+
});
|
|
13
|
+
}
|
package/bin/github.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import crypto from "crypto";
|
|
2
|
+
const app = {
|
|
3
|
+
secret: "",
|
|
4
|
+
};
|
|
5
|
+
export function setSecret(secret) {
|
|
6
|
+
app.secret = secret;
|
|
7
|
+
}
|
|
8
|
+
export function verifySignature(req, res, buf, _encoding) {
|
|
9
|
+
const sha1 = crypto.createHmac("sha1", app.secret).update(buf).digest("hex");
|
|
10
|
+
const signature = `sha1=${sha1}`;
|
|
11
|
+
if (req.headers["x-hub-signature"] !== signature) {
|
|
12
|
+
throw new Error("Invalid signature");
|
|
13
|
+
}
|
|
14
|
+
}
|
package/bin/index.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import http from "node:http";
|
|
3
|
+
import readline from "node:readline";
|
|
4
|
+
import dotenv from "dotenv";
|
|
5
|
+
import api from "./api.js";
|
|
6
|
+
import { setSecret } from "./github.js";
|
|
7
|
+
import { getAllServices, getPredefinedServices, prepareService, saveService } from "./services.js";
|
|
8
|
+
const server = http.createServer(api);
|
|
9
|
+
dotenv.config({ path: [".env.local", ".env"] });
|
|
10
|
+
const rl = readline.createInterface({
|
|
11
|
+
input: process.stdin,
|
|
12
|
+
output: process.stdout,
|
|
13
|
+
});
|
|
14
|
+
function askQuestion(query) {
|
|
15
|
+
return new Promise(resolve => rl.question(query, resolve));
|
|
16
|
+
}
|
|
17
|
+
(async () => {
|
|
18
|
+
const port = parseInt(process.env.PORT || await askQuestion("Port: "));
|
|
19
|
+
const secret = process.env.WEBHOOK_SECRET || await askQuestion("Secret: ");
|
|
20
|
+
setSecret(secret);
|
|
21
|
+
console.clear();
|
|
22
|
+
server.listen(port, () => {
|
|
23
|
+
console.log(`Server running at http://127.0.0.1:${port}/`);
|
|
24
|
+
});
|
|
25
|
+
// init services
|
|
26
|
+
const savedServices = await getAllServices();
|
|
27
|
+
const predefinedServices = await getPredefinedServices();
|
|
28
|
+
const unsavedServices = predefinedServices
|
|
29
|
+
.filter(s => !Object.keys(savedServices).includes(s.name));
|
|
30
|
+
await Promise.all(unsavedServices.map(s => saveService(s.name, {
|
|
31
|
+
...s,
|
|
32
|
+
state: "idle",
|
|
33
|
+
})));
|
|
34
|
+
const services = await getAllServices();
|
|
35
|
+
for (const [serviceId, service] of Object.entries(services)) {
|
|
36
|
+
await prepareService(serviceId, service);
|
|
37
|
+
}
|
|
38
|
+
})();
|
package/bin/object.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/* export function pick<T extends object, K extends keyof T>(object: T, ...keys: K[]) {
|
|
2
|
+
return Object.fromEntries(Object.entries(object).filter(([key]) => keys.includes(key as K))) as Pick<T, K>;
|
|
3
|
+
} */
|
|
4
|
+
export function omit(object, ...keys) {
|
|
5
|
+
return Object.fromEntries(Object.entries(object).filter(([key]) => !keys.includes(key)));
|
|
6
|
+
}
|
|
7
|
+
/* export function pluck<T, K extends keyof T>(collection: T[], key: K) {
|
|
8
|
+
return collection.map(item => item[key]) as T[K][];
|
|
9
|
+
} */
|
package/bin/services.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { findNodes, readNode, saveNode } from "./database.js";
|
|
4
|
+
import { buildImage, createContainer } from "./docker.js";
|
|
5
|
+
import { cloneRepo } from "./git.js";
|
|
6
|
+
export function getAllServices() {
|
|
7
|
+
return findNodes("services");
|
|
8
|
+
}
|
|
9
|
+
function getService(id) {
|
|
10
|
+
return readNode("services", id);
|
|
11
|
+
}
|
|
12
|
+
export function saveService(id, data) {
|
|
13
|
+
return saveNode("services", id, data);
|
|
14
|
+
}
|
|
15
|
+
async function getRepoPath(serviceId) {
|
|
16
|
+
const repoPath = path.resolve(process.cwd(), "storage/repos", serviceId);
|
|
17
|
+
await fs.mkdir(repoPath, { recursive: true });
|
|
18
|
+
return repoPath;
|
|
19
|
+
}
|
|
20
|
+
export async function deleteRepo(serviceId) {
|
|
21
|
+
const repoPath = await getRepoPath(serviceId);
|
|
22
|
+
await fs.rm(repoPath, { recursive: true, force: true });
|
|
23
|
+
}
|
|
24
|
+
export async function prepareService(id, data) {
|
|
25
|
+
console.log("service", `"${id}"`, "is", data.state);
|
|
26
|
+
await saveService(id, data);
|
|
27
|
+
switch (data.state) {
|
|
28
|
+
case "idle": {
|
|
29
|
+
const repoPath = await getRepoPath(id);
|
|
30
|
+
console.log("service", `"${id}"`, "is", "cloning");
|
|
31
|
+
await cloneRepo(data.repo, repoPath);
|
|
32
|
+
await prepareService(id, { ...data, state: "cloned" });
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
case "cloned": {
|
|
36
|
+
const imageId = crypto.randomUUID();
|
|
37
|
+
await saveService(id, { ...data, state: "building", imageId });
|
|
38
|
+
console.log("service", `"${id}"`, "is", "building");
|
|
39
|
+
const repoPath = await getRepoPath(id);
|
|
40
|
+
const success = await buildImage(imageId, repoPath);
|
|
41
|
+
if (success) {
|
|
42
|
+
await deleteRepo(id);
|
|
43
|
+
await prepareService(id, { ...data, state: "built", imageId });
|
|
44
|
+
}
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
case "building": {
|
|
48
|
+
await prepareService(id, { ...data, state: "cloned" });
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
case "built": {
|
|
52
|
+
if (!data.imageId)
|
|
53
|
+
throw new Error("image ID of the service is not defined");
|
|
54
|
+
const containerId = await createContainer(data);
|
|
55
|
+
await prepareService(id, { ...data, state: "ready", containerId });
|
|
56
|
+
break;
|
|
57
|
+
}
|
|
58
|
+
case "ready": {
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export async function getPredefinedServices() {
|
|
64
|
+
const filePath = path.resolve(process.cwd(), "services.json");
|
|
65
|
+
const content = await fs.readFile(filePath, "utf-8");
|
|
66
|
+
return JSON.parse(content);
|
|
67
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@omer-x/buttler",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "automates CI/CD workflows using Docker and GitHub webhooks",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"automation",
|
|
7
|
+
"continuous-delivery",
|
|
8
|
+
"continous-integration",
|
|
9
|
+
"continous-deployment",
|
|
10
|
+
"docker",
|
|
11
|
+
"github-webhooks",
|
|
12
|
+
"cli"
|
|
13
|
+
],
|
|
14
|
+
"repository": {
|
|
15
|
+
"type": "git",
|
|
16
|
+
"url": "git+https://github.com/omermecitoglu/buttler.git"
|
|
17
|
+
},
|
|
18
|
+
"bugs": {
|
|
19
|
+
"url": "https://github.com/omermecitoglu/buttler/issues"
|
|
20
|
+
},
|
|
21
|
+
"homepage": "https://github.com/omermecitoglu/buttler#readme",
|
|
22
|
+
"private": false,
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"author": {
|
|
27
|
+
"name": "Omer Mecitoglu",
|
|
28
|
+
"email": "omer.mecitoglu@gmail.com",
|
|
29
|
+
"url": "https://omermecitoglu.github.io"
|
|
30
|
+
},
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"main": "bin/index.js",
|
|
33
|
+
"bin": {
|
|
34
|
+
"buttler": "./bin/index.js"
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"bin/"
|
|
38
|
+
],
|
|
39
|
+
"type": "module",
|
|
40
|
+
"engines": {
|
|
41
|
+
"node": "^20.0.0"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"test": "echo \"Error: no test specified\" && exit 1",
|
|
45
|
+
"dev": "tsx src/index.ts",
|
|
46
|
+
"prebuild": "ts-unused-exports tsconfig.json",
|
|
47
|
+
"build": "tsc"
|
|
48
|
+
},
|
|
49
|
+
"dependencies": {
|
|
50
|
+
"@figma/nodegit": "^0.28.0-figma.6",
|
|
51
|
+
"dockerode": "^4.0.2",
|
|
52
|
+
"dotenv": "^16.4.5",
|
|
53
|
+
"express": "^4.19.2",
|
|
54
|
+
"tar-fs": "^3.0.6"
|
|
55
|
+
},
|
|
56
|
+
"devDependencies": {
|
|
57
|
+
"@omer-x/eslint-config": "^1.0.7",
|
|
58
|
+
"@types/dockerode": "^3.3.31",
|
|
59
|
+
"@types/express": "^4.17.21",
|
|
60
|
+
"@types/node": "^22.0.0",
|
|
61
|
+
"@types/nodegit": "^0.28.7",
|
|
62
|
+
"@types/tar-fs": "^2.0.4",
|
|
63
|
+
"eslint": "^8.57.0",
|
|
64
|
+
"ts-unused-exports": "^10.1.0",
|
|
65
|
+
"tsx": "^4.16.2",
|
|
66
|
+
"typescript": "^5.5.4"
|
|
67
|
+
}
|
|
68
|
+
}
|