Skip to content

Commit

Permalink
refactor: some clean ups mentioned in 2do.md
Browse files Browse the repository at this point in the history
  • Loading branch information
arshamalh committed Oct 24, 2023
1 parent b3e5935 commit b30e02f
Show file tree
Hide file tree
Showing 18 changed files with 255 additions and 152 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/main.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: main

on:
push:
branches: [main]

jobs:
build-and-release:
runs-on: ubuntu-20.04
steps:
- name: Checkout code
uses: actions/checkout@v2

- name: Login to Docker
uses: docker/login-action@v1
with:
registry: docker.io
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}

- name: Build and push Docker image
uses: docker/build-push-action@v2
with:
context: .
push: true
tags: arshamalh/dockeroller:latest
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
.env
log.json
15 changes: 8 additions & 7 deletions 2do.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
- [ ] Use Cobra as explained in Readme.
- [x] Add logging
- [x] Dockerize, Makefile, Basic CI/CD
- [x] Telegram is at the presentation layer, it doesn't need to be abstracted behind an interface.
- [x] What is tools/get_token.go? there is no need for that. (UPDATE: Removed)
- [x] Use Cobra as explained in Readme.
- [x] ChatID whitelisting (has a TODO, middleware whitelisting) for security concerns
- [ ] Remove session which is used as a one size fits all!
- [ ] Should we replace docker by contract and use it directly as we will never replace it? Not actually, as we may want to plug a mock instead or wrap its functions
- [ ] Load yaml config
- [ ] Add logging
- [ ] Define semi-hardcoded buttons! (button unique identifiers all totally hard coded in two places which lead to confusion, one when defining and one when putting in the handler, it's better to define button somehow else)
- [ ] What is tools/get_token.go? there is no need for that.
- [ ] Implement web hook and let the user decide for it.
- [ ] Dockerize, Makefile and make it ready to be installed using go install, apt install, etc.
- [ ] ChatID whitelisting for security concerns
- [ ] Telegram is at the presentation layer, it doesn't need to be abstracted behind an interface.
- [ ] Make it ready to be installed using go install, apt install, etc.
- [ ] Should we replace docker by contract and use it directly as we will never replace it? Not actually, as we may want to plug a mock instead or wrap its functions
10 changes: 10 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM golang:1.21-alpine3.18 AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . ./
RUN CGO_ENABLED=0 GOOS=linux go build -a -o dclr .

FROM alpine:3.18 AS production
COPY --from=builder /app/dclr .
ENTRYPOINT [ "./dclr" ]
15 changes: 15 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Default values, but should be overriden like `make run File=data/another.json
version=latest
name=dockeroller

help: # Generate list of targets with descriptions
@grep '^.*\:\s#.*' Makefile | sed 's/\(.*\) # \(.*\)/\1 \2/' | column -t -s ":"

build: # Build the binary for current local system
go build -o dockeroller .

build-docker: # Build the docker image
docker build -t ${name}:${version} .

sample-docker: # Run docker with sample start command
docker run --rm ${name}:${version} start --token="something"
18 changes: 18 additions & 0 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package cmd

import (
"github.com/arshamalh/dockeroller/log"
"github.com/spf13/cobra"
)

func Execute() {
var root = &cobra.Command{
Use: "dockeroller",
Short: "ChatOps application for controlling docker daemon through messengers such as Telegram",
}

registerStart(root)
if err := root.Execute(); err != nil {
log.Gl.Fatal(err.Error())
}
}
21 changes: 0 additions & 21 deletions cmd/dockeroller/main.go

This file was deleted.

72 changes: 72 additions & 0 deletions cmd/start.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package cmd

import (
"os"
"time"

"github.com/arshamalh/dockeroller/contracts"
"github.com/arshamalh/dockeroller/docker"
"github.com/arshamalh/dockeroller/log"
"github.com/arshamalh/dockeroller/pkg/session"
tpkg "github.com/arshamalh/dockeroller/telegram"
"github.com/arshamalh/dockeroller/telegram/handlers"
"github.com/joho/godotenv"
"github.com/spf13/cobra"
"gopkg.in/telebot.v3"
"gopkg.in/telebot.v3/middleware"
)

func registerStart(root *cobra.Command) {
var token string
whitelistedIDS := make([]int64, 0)

cmd := &cobra.Command{
Use: "start",
Short: "starting telegram bot",
Run: func(cmd *cobra.Command, args []string) {
start(token, whitelistedIDS)
},
}

cmd.Flags().StringVarP(&token, "token", "t", "", "input your telegram token")
cmd.Flags().Int64SliceVarP(&whitelistedIDS, "whitelisted-ids", "w", whitelistedIDS, "a comma separated list of ids which are allowed to use this bot")
root.AddCommand(cmd)
}

func start(token string, whitelistedIDs []int64) {
if err := godotenv.Load(); err != nil {
log.Gl.Error(err.Error())
}

docker := docker.New()

// apiSrv := api.New(docker)
if token == "" {
if os.Getenv("TOKEN") != "" {
token = os.Getenv("TOKEN")
} else {
log.Gl.Error("telegram can't start because no token is provided")
}
}
startTelegram(docker, token, whitelistedIDs)
}

func startTelegram(docker contracts.Docker, token string, whitelistedIDs []int64) {
bot, err := telebot.NewBot(telebot.Settings{
Token: token,
Poller: &telebot.LongPoller{Timeout: 10 * time.Second},
})
if err != nil {
log.Gl.Error(err.Error())
}
session := session.New()
handlers.Register(bot, docker, session)
// Middlewares
bot.Use(middleware.Whitelist(whitelistedIDs...))
// TODO: Disabled logger middleware for now.
// bot.Use(LoggerMiddleware(log.Gl))
if err := bot.SetCommands(tpkg.Commands); err != nil {
log.Gl.Error(err.Error())
}
bot.Start()
}
5 changes: 2 additions & 3 deletions docker/docker.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
package docker

import (
"fmt"

"github.com/arshamalh/dockeroller/log"
"github.com/moby/moby/client"
)

func New() *docker {
cli, err := client.NewClientWithOpts(client.FromEnv)
if err != nil {
fmt.Println(err)
log.Gl.Error(err.Error())
}
return &docker{
cli: cli,
Expand Down
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@ require (
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-playground/validator/v10 v10.10.0 // indirect
github.com/goccy/go-json v0.9.7 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/mattn/go-isatty v0.0.14 // indirect
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/ugorji/go/codec v1.2.7 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97 // indirect
golang.org/x/text v0.3.6 // indirect
google.golang.org/protobuf v1.28.0 // indirect
Expand All @@ -39,6 +42,8 @@ require (
github.com/opencontainers/image-spec v1.0.2 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/sirupsen/logrus v1.9.0 // indirect
github.com/spf13/cobra v1.7.0
go.uber.org/zap v1.26.0
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 // indirect
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect
)
13 changes: 13 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
github.com/Microsoft/go-winio v0.5.2 h1:a9IhgEQBCUEk6QCdml9CiJGhAws+YwffDHEMp1VMrpA=
github.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand Down Expand Up @@ -35,6 +36,8 @@ github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/joho/godotenv v1.4.0 h1:3l4+N6zfMWnkbPEXKng2o2/MR5mSwTrBih4ZEkkz1lg=
github.com/joho/godotenv v1.4.0/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
Expand Down Expand Up @@ -74,10 +77,15 @@ github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0=
github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cobra v1.7.0 h1:hyqWnYt1ZQShIddO5kBpj3vu05/++x6tJ6dg8EC572I=
github.com/spf13/cobra v1.7.0/go.mod h1:uLxZILRyS/50WlhOIKD7W6V5bgeIt+4sICxh6uRMrb0=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
Expand All @@ -90,6 +98,10 @@ github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0
github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo=
go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
Expand Down Expand Up @@ -150,3 +162,4 @@ gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
30 changes: 30 additions & 0 deletions log/log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package log

import (
"fmt"
"os"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

// Gl is the global logger
var Gl *zap.Logger

func init() {
config := zap.NewProductionEncoderConfig()
config.EncodeTime = zapcore.ISO8601TimeEncoder
fileEncoder := zapcore.NewJSONEncoder(config)
consoleEncoder := zapcore.NewConsoleEncoder(config)
logFile, err := os.OpenFile("log.json", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
fmt.Println(err)
}
writer := zapcore.AddSync(logFile)
defaultLogLevel := zapcore.DebugLevel
core := zapcore.NewTee(
zapcore.NewCore(fileEncoder, writer, defaultLogLevel),
zapcore.NewCore(consoleEncoder, zapcore.AddSync(os.Stdout), defaultLogLevel),
)
Gl = zap.New(core, zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel))
}
9 changes: 9 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package main

import (
"github.com/arshamalh/dockeroller/cmd"
)

func main() {
cmd.Execute()
}
4 changes: 2 additions & 2 deletions telegram/commands.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package telegram

import tele "gopkg.in/telebot.v3"
import "gopkg.in/telebot.v3"

var commands = []tele.Command{
var Commands = []telebot.Command{
{
Text: "containers",
Description: "list all existing containers",
Expand Down
Loading

0 comments on commit b30e02f

Please sign in to comment.