Compare commits

..

No commits in common. "main" and "v0.0.4" have entirely different histories.
main ... v0.0.4

35 changed files with 111 additions and 1132 deletions

View file

@ -1,41 +0,0 @@
name: Pull-Request
on: [pull_request]
jobs:
static-analysis:
runs-on: runner-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 1.23
- name: Validate Yaml
run: pipx run pre-commit run check-yaml -a
- name: Validate shell scripts
run: pipx run pre-commit run shellcheck -a
- name: Check formatting
run: pipx run pre-commit run go-fmt -a
- name: Check code patterns
run: pipx run pre-commit run go-vet-mod -a
tests:
runs-on: runner-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 1.23
- name: Tests
run: pipx run pre-commit run go-test-mod -a
post-run:
runs-on: runner-latest
needs: [static-analysis,tests]
if: ${{ always() }}
steps:
- name: Export trace
uses: https://forge.karnov.club/marc/opentelemetry-trace-export-forgejo-action@main
with:
otlp-endpoint: "http://otel.home.karnov.club:4318"
forgejo-token: ${{ secrets.GITHUB_TOKEN }}
forgejo-base-url: ${{ env.GITHUB_SERVER_URL }}
run-id: ${{ env.GITHUB_RUN_NUMBER }}
repo-name: ${{ env.GITHUB_REPOSITORY }}

View file

@ -1,67 +0,0 @@
name: Push
on:
push:
branches: [main]
jobs:
pre-run:
runs-on: runner-latest
steps:
- uses: https://forge.karnov.club/marc/push-status-to-discord-action@main
with:
webhook-url: ${{secrets.DISCORD_WEBHOOK_URL}}
status: "Started"
init: true
static-analysis:
runs-on: runner-latest
needs: [pre-run]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 1.23
- name: Validate Yaml
run: pipx run pre-commit run check-yaml -a
- name: Validate shell scripts
run: pipx run pre-commit run shellcheck -a
- name: Check formatting
run: pipx run pre-commit run go-fmt -a
- name: Check code patterns
run: pipx run pre-commit run go-vet-mod -a
tests:
runs-on: runner-latest
needs: [pre-run]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: 1.23
- name: Tests
run: pipx run pre-commit run go-test-mod -a
post-run:
runs-on: runner-latest
needs: [static-analysis,tests]
steps:
- name: Export trace
uses: https://forge.karnov.club/marc/opentelemetry-trace-export-forgejo-action@main
with:
otlp-endpoint: "http://otel.home.karnov.club:4318"
forgejo-token: ${{ secrets.GITHUB_TOKEN }}
forgejo-base-url: ${{ env.GITHUB_SERVER_URL }}
run-id: ${{ env.GITHUB_RUN_NUMBER }}
repo-name: ${{ env.GITHUB_REPOSITORY }}
- name: Notify success
uses: https://forge.karnov.club/marc/push-status-to-discord-action@main
if: ${{always() && success()}}
with:
webhook-url: ${{secrets.DISCORD_WEBHOOK_URL}}
status: "Success"
variant: "success"
- name: Notify failure
uses: https://forge.karnov.club/marc/push-status-to-discord-action@main
if: ${{always() && failure()}}
with:
webhook-url: ${{secrets.DISCORD_WEBHOOK_URL}}
status: "Failure"
variant: "failure"

View file

@ -5,7 +5,7 @@ on:
jobs:
build:
runs-on: runner-latest
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5

View file

@ -1,16 +0,0 @@
---
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.6.0
hooks:
- id: check-yaml
- repo: https://github.com/shellcheck-py/shellcheck-py
rev: v0.10.0.1
hooks:
- id: shellcheck
- repo: https://github.com/tekwizely/pre-commit-golang
rev: master
hooks:
- id: go-test-mod
- id: go-fmt
- id: go-vet-mod

View file

@ -22,7 +22,3 @@ curl https://forge.karnov.club/spadinastan/spud/raw/branch/main/install.sh | bas
To pull a specific version, supply a `$SPUD_VERSION` that corresponds to an existing release tag, and to control where
the binary is unpacked and installed, supply `$SPUD_ROOT`.
## Development
The `bootstrap.sh` script should be run to prepare any pre-commit hooks and other required tooling for local development. Checks can be run manually via `pipx run pre-commit run -a`.

View file

@ -1,8 +0,0 @@
#!/bin/bash
if [[ -z "$(command -v pipx)" ]]; then
echo "ERROR: Pre-commit tooling requires pipx to be available."
exit 1
fi
pipx run pre-commit install

View file

@ -1,35 +1,21 @@
package cli
import (
"fmt"
"github.com/spf13/cobra"
"log"
podman "spud/podman"
service_definition "spud/service_definition"
)
func getBuildCommand() *cobra.Command {
build := &cobra.Command{
var build = &cobra.Command{
Use: "build",
Short: "Build service images.",
RunE: func(cmd *cobra.Command, args []string) error {
var pathProvided string
var fetcher service_definition.DefinitionFetcher
var def service_definition.ServiceDefinition
var err error
Run: func(cmd *cobra.Command, args []string) {
pathProvided := args[0]
def, err := service_definition.GetServiceDefinitionFromFile(pathProvided)
if pathProvided, err = cmd.PersistentFlags().GetString("definition"); err != nil {
return fmt.Errorf("%+v", err)
}
defPathType := service_definition.GetPathType(pathProvided)
if fetcher, err = service_definition.NewDefinitionFetcher(defPathType); err != nil {
return fmt.Errorf("Couldn't set up fetcher from the path provided.")
}
if def, err = fetcher.GetDefinition(pathProvided); err != nil {
return fmt.Errorf("Failed to read service definition from file: %+v", err)
if err != nil {
log.Fatal(err)
}
imagesToBuild := def.Build.Images
@ -41,11 +27,5 @@ func getBuildCommand() *cobra.Command {
for _, imageDef := range imagesToBuild {
podman.Build(imageDef)
}
return nil
},
}
build.PersistentFlags().StringP("definition", "d", "./service.yml", "Path to the service definition to use.")
return build
}

View file

@ -1,37 +0,0 @@
package cli
import (
"github.com/spf13/cobra"
"testing"
)
func TestCliBuildServiceDefinitionPathMustExist(t *testing.T) {
cli := GetCli()
cli.SetArgs([]string{"build", "-d", "./not-a-file.yml"})
outcome := cli.Execute()
if outcome == nil {
t.Errorf("Expected error, got nil.")
}
}
func TestCliBuildDefaultsServiceDefinitionPath(t *testing.T) {
cli := GetCli()
cli.SetArgs([]string{"build"})
startCommand, _, _ := cli.Find([]string{"build"})
startCommand.RunE = func(cmd *cobra.Command, args []string) error {
actual, _ := cmd.PersistentFlags().GetString("definition")
if actual != "./service.yml" {
t.Errorf("Unexpected default value for 'definition' / 'd' arg: %s", actual)
}
return nil
}
cli.Execute()
}

View file

@ -5,6 +5,15 @@ import (
"github.com/spf13/cobra"
)
var allCommands = []*cobra.Command{
// cli/start_service.go
start,
// cli/stop_service.go
stop,
// cli/build.go
build,
}
// Creates the root of the CLI, with all available commands
// added to it.
func GetCli() *cobra.Command {
@ -13,17 +22,6 @@ func GetCli() *cobra.Command {
Short: "A not-entirely-terrible-way to manage self-hosted services.",
}
allCommands := []*cobra.Command{
// cli/start_service.go
getStartCommand(),
// cli/stop_service.go
getStopCommand(),
// cli/build.go
getBuildCommand(),
// cli/daemon.go
getDaemonCommand(),
}
for _, command := range allCommands {
cli.AddCommand(command)
}

View file

@ -1,21 +0,0 @@
package cli
import (
"github.com/spf13/cobra"
daemon "spud/daemon"
)
func getDaemonCommand() *cobra.Command {
startDaemon := &cobra.Command{
Use: "daemon",
Short: "Starts a daemon instance.",
RunE: func(cmd *cobra.Command, args []string) error {
d := daemon.NewDaemon("", 8000, nil)
d.Start()
return nil
},
}
return startDaemon
}

View file

@ -5,78 +5,23 @@
package cli
import (
"context"
"fmt"
"github.com/spf13/cobra"
"log"
service "spud/service"
service_definition "spud/service_definition"
webclient "spud/webclient"
)
func getStartCommand() *cobra.Command {
type ParsedFlags struct {
definitionPath string
daemonHost string
daemonPort int
}
start := &cobra.Command{
var start = &cobra.Command{
Use: "start",
Short: "Creates or updates a service based on the provided definition.",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
var pathProvided, host string
var port int
var err error
Run: func(cmd *cobra.Command, args []string) {
pathProvided := args[0]
def, err := service_definition.GetServiceDefinitionFromFile(pathProvided)
if pathProvided, err = cmd.PersistentFlags().GetString("definition"); err != nil {
return err
if err != nil {
log.Fatal(err)
}
if host, err = cmd.PersistentFlags().GetString("host"); err != nil {
return err
}
if port, err = cmd.PersistentFlags().GetInt("port"); err != nil {
return err
}
if host != "" && port == 0 || host == "" && port != 0 {
return fmt.Errorf("Invalid flags: host and port must be defined together or not at all.")
}
cmd.SetContext(context.WithValue(cmd.Context(), "flags", ParsedFlags{definitionPath: pathProvided, daemonHost: host, daemonPort: port}))
return nil
service.CreateService(def)
},
RunE: func(cmd *cobra.Command, args []string) error {
var fetcher service_definition.DefinitionFetcher
var def service_definition.ServiceDefinition
var err error
ctx := cmd.Context()
flags := ctx.Value("flags").(ParsedFlags)
defPath := flags.definitionPath
defPathType := service_definition.GetPathType(defPath)
if fetcher, err = service_definition.NewDefinitionFetcher(defPathType); err != nil {
return fmt.Errorf("Couldn't set up fetcher from the path provided.")
}
if def, err = fetcher.GetDefinition(defPath); err != nil {
return fmt.Errorf("Failed to read service definition: %+v", err)
}
if flags.daemonHost != "" && flags.daemonPort != 0 {
webclient.NewWebClient(flags.daemonHost, flags.daemonPort).CreateService(def)
return nil
}
return service.NewPodmanServiceManager().Create(def)
},
}
start.PersistentFlags().StringP("definition", "d", "./service.yml", "Path to the service definition to use.")
start.PersistentFlags().StringP("host", "H", "", "If specified, host where the daemon lives.")
start.PersistentFlags().IntP("port", "p", 0, "Port on the daemon host.")
return start
}

View file

@ -1,71 +0,0 @@
package cli
import (
"fmt"
"github.com/spf13/cobra"
"testing"
)
func Test_StartServiceCli_StartServiceDefinitionPathMustExist(t *testing.T) {
cli := GetCli()
cli.SetArgs([]string{"start", "-d", "./not-a-file.yml"})
outcome := cli.Execute()
if outcome == nil {
t.Errorf("Expected error, got nil.")
}
}
func Test_StartServiceCli_StartDefaultsServiceDefinitionPath(t *testing.T) {
cli := GetCli()
cli.SetArgs([]string{"start"})
startCommand, _, _ := cli.Find([]string{"start"})
startCommand.RunE = func(cmd *cobra.Command, args []string) error {
actual, _ := cmd.PersistentFlags().GetString("definition")
if actual != "./service.yml" {
t.Errorf("Unexpected default value for 'definition' / 'd' arg: %s", actual)
}
return nil
}
cli.Execute()
}
func Test_StartServiceCli_ErrorIfHostAndPortNotProvidedTogether(t *testing.T) {
inputs := [][]string{
{"start", "-H", "host"},
{"start", "-p", "9999"},
}
for _, input := range inputs {
t.Run(fmt.Sprintf("%+v", input), func(t *testing.T) {
cli := GetCli()
cli.SetArgs(input)
startCommand, _, _ := cli.Find([]string{"start"})
previousPreRun := startCommand.PersistentPreRunE
startCommand.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
if err := previousPreRun(cmd, args); err == nil {
t.Errorf("Expected error, got nil.")
}
return nil
}
startCommand.RunE = func(cmd *cobra.Command, args []string) error {
return nil
}
cli.Execute()
})
}
}

View file

@ -4,63 +4,15 @@
package cli
import (
"context"
"fmt"
"github.com/spf13/cobra"
service "spud/service"
webclient "spud/webclient"
)
func getStopCommand() *cobra.Command {
type ParsedFlags struct {
serviceName string
daemonHost string
daemonPort int
}
stop := &cobra.Command{
Use: "stop [service-name]",
var stop = &cobra.Command{
Use: "stop",
Short: "Stops a running service and all of its containers.",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
var serviceName, host string
var port int
var err error
if host, err = cmd.PersistentFlags().GetString("host"); err != nil {
return err
}
if port, err = cmd.PersistentFlags().GetInt("port"); err != nil {
return err
}
if host != "" && port == 0 || host == "" && port != 0 {
return fmt.Errorf("Invalid flags: host and port must be defined together or not at all.")
}
if len(args) == 0 {
return fmt.Errorf("Must provide a service name.")
}
serviceName = args[0]
cmd.SetContext(context.WithValue(cmd.Context(), "flags", ParsedFlags{serviceName: serviceName, daemonHost: host, daemonPort: port}))
return nil
Run: func(cmd *cobra.Command, args []string) {
serviceName := args[0]
service.StopService(serviceName)
},
RunE: func(cmd *cobra.Command, args []string) error {
flags := cmd.Context().Value("flags").(ParsedFlags)
if flags.daemonHost != "" && flags.daemonPort != 0 {
webclient.NewWebClient(flags.daemonHost, flags.daemonPort).StopService(flags.serviceName)
return nil
}
return service.NewPodmanServiceManager().Stop(flags.serviceName)
},
}
stop.PersistentFlags().StringP("host", "H", "", "If specified, host where the daemon lives.")
stop.PersistentFlags().IntP("port", "p", 0, "Port on the daemon host.")
return stop
}

View file

@ -1,52 +0,0 @@
package cli
import (
"fmt"
"github.com/spf13/cobra"
"testing"
)
func Test_StopServiceCli_StopRequiresAServiceName(t *testing.T) {
cli := GetCli()
cli.SetArgs([]string{"stop"})
outcome := cli.Execute()
if outcome == nil {
t.Error("Expected error, got nil.")
}
}
func Test_StopServiceCli_ErrorIfHostAndPortNotProvidedTogether(t *testing.T) {
inputs := [][]string{
{"stop", "-H", "host"},
{"stop", "-p", "9999"},
}
for _, input := range inputs {
t.Run(fmt.Sprintf("%+v", input), func(t *testing.T) {
cli := GetCli()
cli.SetArgs(input)
stopCommand, _, _ := cli.Find([]string{"stop"})
previousPreRun := stopCommand.PersistentPreRunE
stopCommand.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
if err := previousPreRun(cmd, args); err == nil {
t.Errorf("Expected error, got nil.")
}
return nil
}
stopCommand.RunE = func(cmd *cobra.Command, args []string) error {
return nil
}
cli.Execute()
})
}
}

View file

@ -1,59 +0,0 @@
package daemon
import (
"context"
"encoding/json"
"net/http"
service "spud/service"
service_definition "spud/service_definition"
)
func GetApiRoutes() map[string]HandlerFuncWithContext {
return map[string]HandlerFuncWithContext{
"/service/": ServiceList,
"/service/{serviceName}/": ServiceDetails,
}
}
type ServiceListPayload struct {
Definition service_definition.ServiceDefinition `json:"definition"`
}
func handleServiceListPost(w http.ResponseWriter, r *http.Request, c context.Context) {
client := c.Value("client").(service.ServiceClient)
var p ServiceListPayload
json.NewDecoder(r.Body).Decode(&p)
client.Create(p.Definition)
w.WriteHeader(201)
json.NewEncoder(w).Encode(p.Definition)
}
func handleServiceDetailDelete(w http.ResponseWriter, r *http.Request, c context.Context) {
client := c.Value("client").(service.ServiceClient)
serviceName := r.PathValue("serviceName")
client.Stop(serviceName)
w.WriteHeader(204)
}
func handleNotImplemented(w http.ResponseWriter) {
w.WriteHeader(501)
}
func ServiceList(w http.ResponseWriter, r *http.Request, c context.Context) {
switch r.Method {
case http.MethodPost:
handleServiceListPost(w, r, c)
default:
handleNotImplemented(w)
}
}
func ServiceDetails(w http.ResponseWriter, r *http.Request, c context.Context) {
switch r.Method {
case http.MethodDelete:
handleServiceDetailDelete(w, r, c)
default:
handleNotImplemented(w)
}
}

View file

@ -1,100 +0,0 @@
package daemon
import (
"context"
"net/http"
"net/http/httptest"
service_definition "spud/service_definition"
"testing"
)
type MockClient struct {
calls struct {
Create []service_definition.ServiceDefinition
Stop []string
}
}
func (c *MockClient) Create(s service_definition.ServiceDefinition) error {
c.calls.Create = append(c.calls.Create, s)
return nil
}
func (c *MockClient) Stop(n string) error {
c.calls.Stop = append(c.calls.Stop, n)
return nil
}
func TestServiceListPostCreatesService(t *testing.T) {
mockClient := &MockClient{}
daemonContext := context.WithValue(context.Background(), "client", mockClient)
req := httptest.NewRequest(http.MethodPost, "/service/", nil)
resp := httptest.NewRecorder()
ServiceList(resp, req, daemonContext)
response := resp.Result()
if response.StatusCode != 201 {
t.Errorf("Expected status 201, got %d", response.StatusCode)
}
if len(mockClient.calls.Create) != 1 {
t.Error("Expected a call to Create")
}
}
func TestServiceListUnsupportedMethods(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodHead, http.MethodDelete} {
t.Run(method, func(t *testing.T) {
req := httptest.NewRequest(method, "/service/", nil)
resp := httptest.NewRecorder()
ServiceList(resp, req, context.Background())
response := resp.Result()
if response.StatusCode != 501 {
t.Errorf("Expected status 501, got %d.", response.StatusCode)
}
})
}
}
func TestServiceDetailsDeleteStopsService(t *testing.T) {
mockClient := &MockClient{}
daemonContext := context.WithValue(context.Background(), "client", mockClient)
req := httptest.NewRequest(http.MethodDelete, "/service/service-name/", nil)
resp := httptest.NewRecorder()
ServiceDetails(resp, req, daemonContext)
response := resp.Result()
if response.StatusCode != 204 {
t.Errorf("Expected status 204, got %d", response.StatusCode)
}
if len(mockClient.calls.Stop) != 1 {
t.Error("Expected a call to Stop")
}
}
func TestServiceDetailUnsupportedMethods(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodHead} {
t.Run(method, func(t *testing.T) {
req := httptest.NewRequest(method, "/service/service-name/", nil)
resp := httptest.NewRecorder()
ServiceDetails(resp, req, context.Background())
response := resp.Result()
if response.StatusCode != 501 {
t.Errorf("Expected status 501, got %d.", response.StatusCode)
}
})
}
}

View file

@ -1,71 +0,0 @@
package daemon
import (
"context"
"fmt"
"log/slog"
"net/http"
service "spud/service"
"strconv"
)
type Daemon struct {
Host string
Port int
Services service.ServiceClient
Routes map[string]http.HandlerFunc
}
type HandlerFuncWithContext = func(w http.ResponseWriter, r *http.Request, c context.Context)
type RecordingResponseWriter struct {
responseWriter http.ResponseWriter
StatusCode int
}
func (r *RecordingResponseWriter) WriteHeader(statusCode int) {
r.StatusCode = statusCode
r.responseWriter.WriteHeader(statusCode)
}
func (r RecordingResponseWriter) Write(b []byte) (int, error) {
return r.responseWriter.Write(b)
}
func (r RecordingResponseWriter) Header() http.Header {
return r.responseWriter.Header()
}
func handleFuncWithContext(h HandlerFuncWithContext, c context.Context) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
respWriter := &RecordingResponseWriter{responseWriter: w}
h(respWriter, r, c)
slog.Info("Request", "Method", r.Method, "Path", r.URL.Path, "Status", strconv.Itoa(respWriter.StatusCode))
}
}
func NewDaemon(host string, port int, serviceClient service.ServiceClient) *Daemon {
d := &Daemon{Host: host, Port: port}
if serviceClient == nil {
d.Services = service.NewPodmanServiceManager()
} else {
d.Services = serviceClient
}
return d
}
func (d Daemon) GetListenAddress() string {
return fmt.Sprintf("%s:%d", d.Host, d.Port)
}
func (d Daemon) Start() {
daemonContext := context.WithValue(context.Background(), "client", d.Services)
for route, handler := range GetApiRoutes() {
http.HandleFunc(route, handleFuncWithContext(handler, daemonContext))
}
http.ListenAndServe(d.GetListenAddress(), nil)
}

View file

@ -1,31 +0,0 @@
package daemon
import (
"reflect"
service "spud/service"
service_definition "spud/service_definition"
"testing"
)
type DummyClient struct{}
func (c DummyClient) Create(d service_definition.ServiceDefinition) error { return nil }
func (c DummyClient) Stop(d string) error { return nil }
func TestDaemonDefaultsToPodmanClient(t *testing.T) {
d := NewDaemon("host", 0, nil)
clientType := reflect.TypeOf(d.Services).String()
if clientType != reflect.TypeOf(service.NewPodmanServiceManager()).String() {
t.Errorf("Expected podman client, got %s instead.", clientType)
}
}
func TestDaemonUsesInjectedClientIfProvided(t *testing.T) {
d := NewDaemon("host", 0, DummyClient{})
clientType := reflect.TypeOf(d.Services).String()
if clientType != reflect.TypeOf(DummyClient{}).String() {
t.Errorf("Expected dummy client, got %s instead.", clientType)
}
}

View file

@ -1,26 +0,0 @@
// Git wrapper
//
// Facilitates the usage of `git` commands when dealing with
// data living in repositories.
package git
import (
"os/exec"
)
type GitClient interface {
Clone(path string, destination string) (string, error)
}
type Git struct{}
func (g Git) Clone(path string, destination string) (string, error) {
cloneCmd := exec.Command("git", "clone", path, destination)
if err := cloneCmd.Run(); err != nil {
return "", err
}
return path, nil
}

2
go.mod
View file

@ -1,6 +1,6 @@
module spud
go 1.23.1
go 1.22.2
require (
github.com/goccy/go-yaml v1.11.3

View file

@ -1,12 +1,9 @@
package main
import (
"os"
cli "spud/cli"
)
func main() {
if err := cli.GetCli().Execute(); err != nil {
os.Exit(1)
}
cli.GetCli().Execute()
}

View file

@ -96,14 +96,6 @@ func CreateContainer(definition service_definition.ContainerDefinition, knownVol
"--replace",
}
if definition.Network != "" {
args = append(args, []string{"--network", definition.Network}...)
}
if definition.PIDNamespace != "" {
args = append(args, []string{"--pid", definition.PIDNamespace}...)
}
if definition.EnvFile != "" {
args = append(args, []string{"--env-file", definition.EnvFile}...)
}

View file

@ -1,10 +0,0 @@
package service
import (
service_definition "spud/service_definition"
)
type ServiceClient interface {
Create(service_definition.ServiceDefinition) error
Stop(string) error
}

View file

@ -1,28 +1,19 @@
package service
import (
"log"
podman "spud/podman"
service_definition "spud/service_definition"
)
type ServiceManager interface {
Create(definition service_definition.ServiceDefinition)
Stop(name string)
}
type PodmanServiceManager struct{}
func NewPodmanServiceManager() *PodmanServiceManager {
return &PodmanServiceManager{}
}
func (c PodmanServiceManager) Create(definition service_definition.ServiceDefinition) error {
func CreateService(definition service_definition.ServiceDefinition) {
var err error
err = podman.CreatePod(definition.Name, definition.Ports)
if err != nil {
return err
log.Fatalf("%s", err)
}
knownVolumes := map[string]string{}
@ -35,11 +26,9 @@ func (c PodmanServiceManager) Create(definition service_definition.ServiceDefini
for _, container := range definition.Containers {
if err = podman.CreateContainer(container, knownVolumes, definition.Name); err != nil {
return err
log.Fatalf("%s", err)
}
}
return nil
}
/*
@ -47,6 +36,10 @@ func (c PodmanServiceManager) Create(definition service_definition.ServiceDefini
*
* The service and all its containers are stopped but not deleted.
*/
func (c PodmanServiceManager) Stop(name string) error {
return podman.StopPod(name)
func StopService(name string) {
err := podman.StopPod(name)
if err != nil {
log.Fatalf("%s", err)
}
}

View file

@ -0,0 +1,24 @@
package service_definition
type FileDoesNotExistError struct {
Message string
ExpectedPath string
}
func (r *FileDoesNotExistError) Error() string {
prefix := "File not found"
if r.Message != "" {
prefix = r.Message
}
return prefix + ": " + r.ExpectedPath
}
type InvalidServiceDefinitionError struct {
Path string
}
func (r *InvalidServiceDefinitionError) Error() string {
return "Service definition does not satisfy expected schema: " + r.Path
}

View file

@ -1,26 +0,0 @@
// Definition fetcher
//
// Handles fetching and building ServiceDefinition structs from different
// data sources.
package service_definition
import (
"fmt"
)
type DefinitionFetcher interface {
GetDefinition(path string) (ServiceDefinition, error)
}
func NewDefinitionFetcher(fetcher_type string) (DefinitionFetcher, error) {
if fetcher_type == "git" {
return NewGitDefinitionFetcher(), nil
}
if fetcher_type == "file" {
return NewFileDefinitionFetcher(), nil
}
return nil, fmt.Errorf("Unrecognized fetcher type: %s", fetcher_type)
}

View file

@ -1,19 +0,0 @@
package service_definition
import (
"testing"
)
func TestGetPathTypeDetectsGitPathPrefix(t *testing.T) {
actual := GetPathType("git+https://test.com")
if actual != "git" {
t.Errorf("Expected 'git' type, got %s", actual)
}
}
func TestGetPathTypeDetectsFileNoPrefix(t *testing.T) {
actual := GetPathType("file/path.yml")
if actual != "file" {
t.Errorf("Expected 'file' type, got %s", actual)
}
}

View file

@ -1,34 +0,0 @@
// File Definition fetcher
//
// Handles extracting service definitions from local files.
package service_definition
import (
"fmt"
"github.com/goccy/go-yaml"
"os"
)
type FileDefinitionFetcher struct{}
func NewFileDefinitionFetcher() *FileDefinitionFetcher {
return &FileDefinitionFetcher{}
}
// Retrieves a service definition from the given filepath.
func (f FileDefinitionFetcher) GetDefinition(path string) (ServiceDefinition, error) {
var definition ServiceDefinition
defData, err := os.ReadFile(path)
if err != nil {
return ServiceDefinition{}, fmt.Errorf("Could not find service configuration file: %s", path)
}
if err = yaml.Unmarshal(defData, &definition); err != nil {
return ServiceDefinition{}, fmt.Errorf("Service definition does not satisfy expected schema: %s", path)
}
return definition, nil
}

View file

@ -1,38 +0,0 @@
// Git Definition fetcher
//
// Handles fetching and building ServiceDefinition structs from git
// repositories.
package service_definition
import (
"os"
git "spud/git"
"strings"
)
type GitDefinitionFetcher struct {
Git git.GitClient
}
func NewGitDefinitionFetcher() *GitDefinitionFetcher {
return &GitDefinitionFetcher{
Git: git.Git{},
}
}
// Clones the target git repository and uses it as a basis to extract
// a service definition.
func (f GitDefinitionFetcher) GetDefinition(path string) (ServiceDefinition, error) {
dir, err := os.MkdirTemp("/tmp", "spud-service-")
if err != nil {
return ServiceDefinition{}, err
}
if _, err := f.Git.Clone(strings.TrimPrefix(path, "git+"), dir); err != nil {
return ServiceDefinition{}, err
}
return NewFileDefinitionFetcher().GetDefinition((dir + "/service.yml"))
}

View file

@ -1,34 +0,0 @@
package service_definition
import (
"strings"
"testing"
)
type MockGit struct {
calls []string
}
func (g *MockGit) Clone(path string, destination string) (string, error) {
g.calls = append(g.calls, path+":"+destination)
return path, nil
}
func TestGetDefinitionGetDefinitionFromGit(t *testing.T) {
var gitFetcher GitDefinitionFetcher
fetcher, _ := NewDefinitionFetcher("git")
gitFetcher, _ = fetcher.(GitDefinitionFetcher)
mockGit := MockGit{}
gitFetcher.Git = &mockGit
mockUrl := "https://git.com/owner/repo.git"
gitFetcher.GetDefinition("git+" + mockUrl)
if !strings.HasPrefix(mockGit.calls[0], mockUrl) {
t.Errorf("Expected git cloning for %s, got %s instead.", mockUrl, mockGit.calls[0])
}
}

View file

@ -1,5 +1,11 @@
package service_definition
import (
"os"
"github.com/goccy/go-yaml"
)
type BuildImage struct {
Path string `yaml:"path"`
TagPrefix string `yaml:"tag"`
@ -31,8 +37,6 @@ type ContainerDefinition struct {
Image string `yaml:"image"`
Volumes []VolumeConfiguration `yaml:"volumes"`
EnvFile string `yaml:"env-file"`
Network string `yaml:"network"`
PIDNamespace string `yaml:"pid-namespace"`
ExtraArgs []string `yaml:"extra-args"`
}
@ -43,3 +47,19 @@ type ServiceDefinition struct {
Containers []ContainerDefinition `yaml:"containers"`
Ports []PortMapping `yaml:"ports"`
}
func GetServiceDefinitionFromFile(path string) (ServiceDefinition, error) {
var definition ServiceDefinition
defData, err := os.ReadFile(path)
if err != nil {
return ServiceDefinition{}, &FileDoesNotExistError{Message: "Could not find service configuration file", ExpectedPath: path}
}
if err = yaml.Unmarshal(defData, &definition); err != nil {
return ServiceDefinition{}, &InvalidServiceDefinitionError{Path: path}
}
return definition, nil
}

View file

@ -1,13 +0,0 @@
package service_definition
import (
"strings"
)
func GetPathType(path string) string {
if strings.HasPrefix(path, "git+") {
return "git"
}
return "file"
}

View file

@ -5,8 +5,7 @@ import (
)
func TestGetServiceDefinitionFromFileDoesNotExist(t *testing.T) {
fetcher, _ := NewDefinitionFetcher("file")
_, err := fetcher.GetDefinition(t.TempDir() + "/not-a-file.yml")
_, err := GetServiceDefinitionFromFile(t.TempDir() + "/not-a-file.yml")
if err == nil {
t.Errorf("Expected error, got nil.")

View file

@ -1,91 +0,0 @@
package webclient
import (
"bytes"
"encoding/json"
"io"
"net/http"
daemon "spud/daemon"
service_definition "spud/service_definition"
"testing"
)
type RecordedRequest struct {
method string
url string
contentType string
data io.Reader
}
type DummyHttpClient struct {
requests []RecordedRequest
}
func (d *DummyHttpClient) Do(request *http.Request) (*http.Response, error) {
d.requests = append(d.requests, RecordedRequest{method: request.Method, url: request.URL.String(), contentType: "", data: request.Body})
return nil, nil
}
func Test_WebClient_GetBaseUrlGetsUrlFromHostPort(t *testing.T) {
c := NewWebClient("http://host", 9999)
actual := c.getBaseUrl()
expected := "http://host:9999"
if actual != expected {
t.Errorf("Expected %s, got %s.", expected, actual)
}
}
func Test_WebClient_CreateServicePostsToDaemon(t *testing.T) {
c := NewWebClient("http://host", 9999)
httpClient := &DummyHttpClient{}
c.httpClient = httpClient
def := service_definition.ServiceDefinition{Name: "test-service"}
c.CreateService(def)
if len(httpClient.requests) != 1 || httpClient.requests[0].method != http.MethodPost {
t.Errorf("Expected one POST requests, got none.")
}
}
func Test_WebClient_CreateServiceSendsDefinition(t *testing.T) {
c := NewWebClient("http://host", 9999)
httpClient := &DummyHttpClient{}
c.httpClient = httpClient
payload := daemon.ServiceListPayload{
Definition: service_definition.ServiceDefinition{Name: "test-service"},
}
c.CreateService(payload.Definition)
req := httpClient.requests[0]
actualDef := bytes.NewBuffer([]byte{})
actualDef.ReadFrom(req.data)
expectedDef, _ := json.Marshal(payload)
if actualDef.String() != string(expectedDef) {
t.Errorf("Unexpected data: %s != %s", actualDef.String(), string(expectedDef))
}
}
func Test_WebClient_StopServiceDeletesToDaemon(t *testing.T) {
c := NewWebClient("http://host", 9999)
httpClient := &DummyHttpClient{}
c.httpClient = httpClient
serviceName := "test-service"
c.StopService(serviceName)
if len(httpClient.requests) != 1 || httpClient.requests[0].method != http.MethodDelete {
t.Errorf("Expected one DELETE request, got none.")
}
expected := c.getBaseUrl() + "/service/" + serviceName + "/"
if httpClient.requests[0].url != expected {
t.Errorf("Expected url to be %s, got %s.", expected, httpClient.requests[0].url)
}
}

View file

@ -1,52 +0,0 @@
package webclient
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
daemon "spud/daemon"
service_definition "spud/service_definition"
)
type HttpClient interface {
Do(*http.Request) (*http.Response, error)
}
type WebClient struct {
httpClient HttpClient
Host string
Port int
}
func NewWebClient(host string, port int) *WebClient {
return &WebClient{
httpClient: &http.Client{},
Host: host,
Port: port,
}
}
func (c WebClient) getBaseUrl() string {
return fmt.Sprintf("%s:%d", c.Host, c.Port)
}
func (c WebClient) CreateService(def service_definition.ServiceDefinition) error {
payload := daemon.ServiceListPayload{
Definition: def,
}
serializedPayload, _ := json.Marshal(payload)
req, _ := http.NewRequest(http.MethodPost, c.getBaseUrl()+"/service/", bytes.NewBuffer(serializedPayload))
_, e := c.httpClient.Do(req)
return e
}
func (c WebClient) StopService(name string) error {
req, _ := http.NewRequest(http.MethodDelete, c.getBaseUrl()+"/service/"+name+"/", nil)
_, e := c.httpClient.Do(req)
return e
}