// Package agent holds the Docker Compose files of the agents and the // script that installs them, which the API serves at /install.sh. package agent import ( "bytes" "embed" "fmt" "net/url" "regexp" "strings" "text/template" ) //go:embed compose.checker.yaml compose.statuspage.yaml compose.docker-socket.yaml install.sh.tmpl var files embed.FS // Compose returns the Compose file of an agent kind (checker, statuspage) // or of the docker-socket addition. func Compose(name string) ([]byte, error) { return files.ReadFile("compose." + name + ".yaml") } // Install is what the platform fills into the install script. type Install struct { // APIURL is the platform's public address. APIURL string // Image is the image name; -checker or -statuspage is appended. Image string // Tag is the channel the platform runs: latest, beta or edge. Tag string } var ( safeImage = regexp.MustCompile(`^[a-z0-9.:/_-]+$`) stable = regexp.MustCompile(`^v\d+\.\d+\.\d+$`) beta = regexp.MustCompile(`^v\d+\.\d+\.\d+-beta\.\d+$`) ) // Script renders the install script. func Script(in Install) ([]byte, error) { u, err := url.Parse(in.APIURL) if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Host == "" || strings.ContainsAny(in.APIURL, "'\n") { return nil, fmt.Errorf("agent: %q is not a usable platform address", in.APIURL) } if !safeImage.MatchString(in.Image) || !safeImage.MatchString(in.Tag) { return nil, fmt.Errorf("agent: unusable image %q or tag %q", in.Image, in.Tag) } tmpl, err := template.ParseFS(files, "install.sh.tmpl") if err != nil { return nil, err } data := map[string]string{"APIURL": strings.TrimSuffix(in.APIURL, "/"), "Image": in.Image, "Tag": in.Tag} for key, name := range map[string]string{"Checker": "checker", "StatusPage": "statuspage", "DockerSocket": "docker-socket"} { c, err := Compose(name) if err != nil { return nil, err } data[key] = string(c) } var b bytes.Buffer if err := tmpl.Execute(&b, data); err != nil { return nil, err } return b.Bytes(), nil } // Channel is the image tag that follows a platform release: latest for // releases, beta for prereleases, edge for everything else. func Channel(version string) string { switch { case stable.MatchString(version): return "latest" case beta.MatchString(version): return "beta" } return "edge" }