Skip to content

Commit

Permalink
add slog,goreleaser,github workflow
Browse files Browse the repository at this point in the history
  • Loading branch information
martinhny committed Oct 17, 2023
1 parent af774eb commit 106af82
Show file tree
Hide file tree
Showing 12 changed files with 206 additions and 24 deletions.
17 changes: 17 additions & 0 deletions .github/dependabot.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
version: 2
updates:
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "12:30"
timezone: "Europe/Oslo"

- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "12:30"
timezone: "Europe/Oslo"
54 changes: 54 additions & 0 deletions .github/workflows/publish.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
name: Create and publish a Docker image

on:
push:
tags:
- '[0-9]+.[0-9]+.[0-9]+'

env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}

jobs:
build-and-push-image:
runs-on: ubuntu-latest
permissions:
contents: write
packages: write
id-token: write

steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Golang environment
uses: actions/setup-go@v4
with:
go-version: "1.21"
- name: Log in to the Container registry
uses: docker/login-action@b4bedf8053341df3b5a9f9e0f2cf4e79e27360c6
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Release with Goreleaser
uses: goreleaser/goreleaser-action@v5
with:
distribution: goreleaser
version: latest
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
pharos-job:
name: Run Pharos with Required Permissions
needs: build-and-push-image
permissions:
actions: read
packages: read
contents: read
security-events: write
runs-on: ubuntu-latest
steps:
- name: "Run Pharos"
uses: kartverket/[email protected]
with:
image_url: ${{env.REGISTRY}}/${{env.IMAGE_NAME}}:${{ github.ref_name }}
35 changes: 35 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
name: Build and test PR

on:
pull_request:
branches: [main]

push:
branches: [main]

jobs:
mod:
runs-on: ubuntu-latest
name: Check modules
steps:
- uses: actions/setup-go@v4
with:
go-version: '>=1.21.0'
check-latest: true
- uses: actions/checkout@v3
- run: go mod tidy && git diff --exit-code go.mod go.sum
build:
runs-on: ubuntu-latest
strategy:
matrix:
version: [ '1.21' ]
name: Go ${{ matrix.version }}
steps:
- uses: actions/setup-go@v4
with:
go-version: ${{ matrix.version }}
- uses: actions/checkout@v3
- run: go vet ./...
- run: go run github.com/onsi/ginkgo/v2/ginkgo -r --randomize-suites --race --trace --fail-on-pending --keep-going


5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,6 @@
go.work

.idea
config.yaml
smseagle-proxy
cmd/config.yaml
smseagle-proxy
cmd/dist
43 changes: 43 additions & 0 deletions .gorealeser.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
project_name: smseagle-proxy

builds:
- binary: smseagle-proxy
env:
- CGO_ENABLED=0
goos:
- linux
goarch:
- amd64
- arm64
ldflags:
- -extldflags "-static"
tags:
- timetzdata
dir: cmd
dockers:
- dockerfile: 'Dockerfile'
image_templates:
- "ghcr.io/kartverket/{{ .ProjectName }}:{{ .Version }}"


archives:
- format: tar.gz
# this name template makes the OS and Arch compatible with the results of `uname`.
name_template: >-
{{ .ProjectName }}_
{{- title .Os }}_
{{- if eq .Arch "amd64" }}x86_64
{{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }}
{{- if .Arm }}v{{ .Arm }}{{ end }}
# use zip for windows archives
format_overrides:
- goos: windows
format: zip

changelog:
sort: asc
filters:
exclude:
- "^docs:"
- "^test:"
9 changes: 9 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
FROM golang:1.21 as builder
RUN adduser -u 10001 scratchuser

FROM scratch
COPY smseagle-proxy /
COPY --from=builder /etc/passwd /etc/passwd
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
USER scratchuser
ENTRYPOINT ["/smseagle-proxy"]
22 changes: 18 additions & 4 deletions main.go → cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,42 @@ package main

import (
"errors"
"fmt"
"kartverket.no/smseagle-proxy/pkg/alerter"
"kartverket.no/smseagle-proxy/pkg/config"
"kartverket.no/smseagle-proxy/pkg/smseagle"
"log/slog"
"net/http"
"os"
)

func init() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
Level: slog.LevelInfo,
}))
slog.SetDefault(logger)
}

func main() {
cfg := config.Read()
if cfg.Debug {
logLevel := &slog.LevelVar{}
logLevel.Set(slog.LevelDebug)
}

smseagle := smseagle.NewSMSEagle(cfg)
grafana := alerter.NewGrafana(smseagle, cfg)

http.HandleFunc("/webhook/sms", grafana.HandleSMS)
http.HandleFunc("/webhook/call", grafana.HandleCall)

err := http.ListenAndServe(":8080", nil)
port := ":10393"
slog.Info("Starting smseagle-proxy", "port", port)
err := http.ListenAndServe(port, nil)

if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("server closed\n")
slog.Info("server closed\n")
} else if err != nil {
fmt.Printf("error starting server: %s\n", err)
slog.Error("error starting server:", "error", err)
os.Exit(1)
}
}
6 changes: 2 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,6 @@ github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyua
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/onsi/ginkgo/v2 v2.12.1 h1:uHNEO1RP2SpuZApSkel9nEh1/Mu+hmQe7Q+Pepg5OYA=
github.com/onsi/ginkgo/v2 v2.12.1/go.mod h1:TE309ZR8s5FsKKpuB1YAQYBzCaAfUgatB/xlT/ETL/o=
github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI=
github.com/onsi/gomega v1.27.10/go.mod h1:RsS8tutOdbdgzbPtzzATp12yT7kM5I5aElG3evPbQ0M=
github.com/onsi/gomega v1.28.0 h1:i2rg/p9n/UqIDAMFUJ6qIUUMcsqOuUHgbpbu235Vr1c=
github.com/onsi/gomega v1.28.0/go.mod h1:A1H2JE76sI14WIP57LMKj7FVfCHx3g3BcZVjJG8bjX8=
github.com/pelletier/go-toml/v2 v2.0.8 h1:0ctb6s9mE31h0/lhu+J6OPmVeDxJn+kYnJc2jZR9tGQ=
Expand Down Expand Up @@ -254,6 +252,8 @@ golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
Expand Down Expand Up @@ -343,8 +343,6 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM=
golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o=
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
Expand Down
8 changes: 6 additions & 2 deletions pkg/alerter/grafana.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io"
"kartverket.no/smseagle-proxy/pkg/config"
. "kartverket.no/smseagle-proxy/pkg/smseagle"
"log/slog"
"net/http"
)

Expand Down Expand Up @@ -50,11 +51,13 @@ func NewGrafana(notifier Notifier, cfg *config.ProxyConfig) *Grafana {
}

func parseGrafanaWebhook(r *http.Request) (*GrafanaWebhook, error) {
slog.Debug("Parsing", "request", r)
var webhook OncallWebhook
err := json.NewDecoder(r.Body).Decode(&webhook)
if err != nil {
return nil, err
}
slog.Debug("Parsed %w", "webhook", &webhook)
return &webhook.GrafanaWebhook, nil
}

Expand All @@ -75,13 +78,14 @@ func (g *Grafana) handleRequest(w http.ResponseWriter, r *http.Request, c Contac

webhook, err := parseGrafanaWebhook(r)
if err != nil {
slog.Error("decoding webhook failed", "error", err)
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, "Invalid request body")
return
}

receiver := getReceiver(r.Header.Get("team"))

slog.Debug("Checking header for receiver", "receiver", receiver)
if receiver == Invalid {
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, "Missing or invalid team header")
Expand All @@ -96,7 +100,7 @@ func (g *Grafana) handleRequest(w http.ResponseWriter, r *http.Request, c Contac

err = g.notifier.Notify(&message)
if err != nil {
panic("something")
slog.Error("Failure to notify", "error", err)
}
}

Expand Down
13 changes: 9 additions & 4 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
package config

import (
"fmt"
"github.com/go-playground/validator/v10"
"github.com/spf13/viper"
"log/slog"
"os"
)

type ProxyConfig struct {
AppdriftPhoneNumber string `mapstructure:"app-drift-phone-number"`
InfraPhoneNumber string `mapstructure:"infra-drift-phone-number"`
Call SMSEagleConfig `mapstructure:"call"`
SMS SMSEagleConfig `mapstructure:"sms"`
Debug bool `mapstructure:"debug"`
}

type SMSEagleConfig struct {
Expand All @@ -25,17 +27,20 @@ func Read() *ProxyConfig {
viper.AddConfigPath(".")
err := viper.ReadInConfig()
if err != nil {
fmt.Errorf("fatal error config file: %w", err)
slog.Error("fatal error config file: %w", err)
os.Exit(1)
}
err = viper.Unmarshal(&cfg)

if err != nil {
fmt.Errorf("something went wrong unmarshaling config: %w", err)
slog.Error("something went wrong unmarshaling config: %w", err)
os.Exit(1)
}

validate := validator.New()
if err := validate.Struct(&cfg); err != nil {
fmt.Errorf("missing config: %w", err)
slog.Error("missing config: %w", err)
os.Exit(1)
}

return &cfg
Expand Down
15 changes: 7 additions & 8 deletions pkg/smseagle/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,29 +3,28 @@ package smseagle
import (
"fmt"
"kartverket.no/smseagle-proxy/pkg/config"
"log/slog"
"net/http"
)

func sendSMS(cfg *config.ProxyConfig, phoneNumber string, message string) error {
requestUrl := fmt.Sprintf("%s/http_api/send_sms?access_token=%s&to=%s&message=%s", cfg.SMS.Url, cfg.SMS.AccessToken, phoneNumber, message)
slog.Debug("Sending sms", "url", requestUrl)
res, err := http.Get(requestUrl)
if err != nil {
fmt.Printf("error making http request: %s\n", err)
return err
}

fmt.Printf("client: got response!\n")
fmt.Printf("client: status code: %d\n", res.StatusCode)
slog.Debug("sms request succesfull", "response", res)
return nil
}

func call(cfg *config.ProxyConfig, phoneNumber string) error {
requestUrl := fmt.Sprintf("%s/http_api/call_with_termination?access_token=%s&to=%s", cfg.Call.Url, cfg.Call.AccessToken, phoneNumber)
slog.Debug("Sending call request", "url", requestUrl)
res, err := http.Get(requestUrl)
if err != nil {
fmt.Printf("error making http request: %s\n", err)
return err
}

fmt.Printf("client: got response!\n")
fmt.Printf("client: status code: %d\n", res.StatusCode)
slog.Debug("Call request successful", "response", res)
return nil
}
3 changes: 3 additions & 0 deletions pkg/smseagle/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package smseagle

import (
"kartverket.no/smseagle-proxy/pkg/config"
"log/slog"
)

type SMSEagleMessage struct {
Expand Down Expand Up @@ -46,11 +47,13 @@ func (s *SMSEagle) Notify(message *SMSEagleMessage) error {

err := sendSMS(s.cfg, phoneNumber, message.Message)
if err != nil {
slog.Error("Error sending sms", "error", err)
return err
}

err = call(s.cfg, phoneNumber)
if err != nil {
slog.Error("Error sending call request", "error", err)
return err
}

Expand Down

0 comments on commit 106af82

Please sign in to comment.