108 lines
2.3 KiB
Go
108 lines
2.3 KiB
Go
package node
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/moby/moby/api/types/container"
|
|
"github.com/moby/moby/client"
|
|
log "gitlab.com/gdulai/simpleloglvl"
|
|
)
|
|
|
|
type BuildCommand struct {
|
|
Repository string `json:"repository"`
|
|
Branch string `json:"branch"`
|
|
Descriptor string `json:"descriptor"`
|
|
}
|
|
|
|
func HandleBuild(w http.ResponseWriter, r *http.Request) {
|
|
|
|
}
|
|
|
|
func build(command BuildCommand) {
|
|
|
|
}
|
|
|
|
func HandleStart(w http.ResponseWriter, r *http.Request) {
|
|
|
|
}
|
|
|
|
func start() {
|
|
|
|
}
|
|
|
|
func HandleStop(w http.ResponseWriter, r *http.Request) {
|
|
decoder := json.NewDecoder(r.Body)
|
|
var containerId string
|
|
err := decoder.Decode(&containerId)
|
|
if err != nil {
|
|
log.LogError("Failed to decode node/stop request body!")
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
if containerId == "" {
|
|
log.LogError("Container id mus be specified for node/stop!")
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if stop(containerId) {
|
|
w.WriteHeader(http.StatusOK)
|
|
} else {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
}
|
|
}
|
|
|
|
func stop(containerId string) bool {
|
|
cli := openDockerClient()
|
|
_, err := cli.ContainerStop(context.Background(), containerId, client.ContainerStopOptions{})
|
|
if err != nil {
|
|
log.LogError("Failed to stop container: %s\n%s", containerId, err)
|
|
return false
|
|
}
|
|
log.LogInfo("Successfully stopped container: %s", containerId)
|
|
return true
|
|
}
|
|
|
|
func HandleInfo(w http.ResponseWriter, r *http.Request) {
|
|
json.NewEncoder(w).Encode(info())
|
|
}
|
|
|
|
func info() []container.Summary {
|
|
cli := openDockerClient()
|
|
// List all containers (running and stopped)
|
|
containers, err := cli.ContainerList(context.Background(), client.ContainerListOptions{
|
|
All: true,
|
|
})
|
|
if err != nil {
|
|
log.LogFatalError("Failed to list containers: %v", err)
|
|
}
|
|
|
|
var summaries []container.Summary
|
|
// Print container info
|
|
for _, c := range containers.Items {
|
|
summaries = append(summaries, c)
|
|
name := ""
|
|
if len(c.Names) > 0 {
|
|
name = c.Names[0]
|
|
}
|
|
log.LogInfo("ID: %s Name: %s Image: %s Status: %s\n",
|
|
c.ID[:12], name, c.Image, c.Status)
|
|
}
|
|
|
|
return summaries
|
|
|
|
}
|
|
|
|
func openDockerClient() *client.Client {
|
|
cli, err := client.New(
|
|
client.FromEnv,
|
|
client.WithAPIVersionFromEnv(),
|
|
)
|
|
if err != nil {
|
|
log.LogFatalError("Failed to create Docker client: %v", err)
|
|
}
|
|
return cli
|
|
}
|