added automagical detection of woodpecker server version
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful

This commit is contained in:
Nils Stinnesbeck 2023-07-30 21:55:05 +02:00
parent f359f0fb1f
commit 3d6d7b738f
Signed by: nils
GPG Key ID: C52E07422A136076

View File

@ -2,7 +2,10 @@ package hetzner
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"regexp"
"strconv"
@ -13,6 +16,11 @@ import (
"github.com/hetznercloud/hcloud-go/hcloud"
)
type VersionInfo struct {
Source string `json:"source"`
Version string `json:"version"`
}
func connect() *hcloud.Client {
token := os.Getenv("HCLOUD_API_TOKEN")
if token == "" {
@ -130,9 +138,10 @@ func CreateServers(servers []string) error {
// read in some environment variables
agentSecret := os.Getenv("WOODPECKER_AGENT_SECRET")
r := regexp.MustCompile(`http[s]*:\/\/(.*)`)
woodpeckerHostname := os.Getenv("WOODPECKER_HOSTNAME")
hasPort := regexp.MustCompile(`^.*(:\d+)`)
withoutPort := regexp.MustCompile(`^https?:\/\/(.*):`)
woodpeckerHost := r.FindStringSubmatch(os.Getenv("WOODPECKER_HOSTNAME"))[1]
woodpeckerHost := r.FindStringSubmatch(woodpeckerHostname)[1]
if hasPort.MatchString(woodpeckerHost) {
woodpeckerHost = withoutPort.FindStringSubmatch(woodpeckerHost)[1]
}
@ -146,10 +155,36 @@ func CreateServers(servers []string) error {
}
woodpeckerHost += ":" + statsPort
// get woodpecker server version
// prepare request
req, err := http.NewRequest(http.MethodGet, woodpeckerHostname+"/version", nil)
if err != nil {
return err
}
c := http.DefaultClient
response, err := c.Do(req)
if err != nil {
return err
}
b, err := io.ReadAll(response.Body)
if err != nil {
return err
}
var version VersionInfo
err = json.Unmarshal(b, &version)
if err != nil {
return err
}
// loop through each server
for _, server := range servers {
// create unique AgentCMD for cloud init
AgentCMD := fmt.Sprintf("docker run -d -v /var/run/docker.sock:/var/run/docker.sock -e WOODPECKER_GRPC_SECURE=false -e WOODPECKER_SERVER=%s -e WOODPECKER_AGENT_SECRET=%s -e WOODPECKER_MAX_PROCS=%d -e WOODPECKER_HOSTNAME=%s woodpeckerci/woodpecker-agent", woodpeckerHost, agentSecret, 1, server)
AgentCMD := fmt.Sprintf("docker run -d -v /var/run/docker.sock:/var/run/docker.sock -e WOODPECKER_GRPC_SECURE=false -e WOODPECKER_SERVER=%s -e WOODPECKER_AGENT_SECRET=%s -e WOODPECKER_MAX_PROCS=%d -e WOODPECKER_HOSTNAME=%s woodpeckerci/woodpecker-agent:v"+version.Version, woodpeckerHost, agentSecret, 1, server)
userdata := fmt.Sprintf("#cloud-config\nruncmd:\n - %s", AgentCMD)
labels := make(map[string]string)