1
0
mirror of https://github.com/containrrr/watchtower.git synced 2024-12-12 09:04:17 +02:00
watchtower/pkg/api/api.go

64 lines
1.2 KiB
Go
Raw Normal View History

package api
import (
"errors"
"io"
2020-04-24 13:45:24 +02:00
"net/http"
"os"
log "github.com/sirupsen/logrus"
)
var (
2020-04-24 13:45:24 +02:00
lock chan bool
)
func init() {
lock = make(chan bool, 1)
lock <- true
}
2020-04-24 13:45:24 +02:00
// SetupHTTPUpdates configures the endopint needed for triggering updates via http
func SetupHTTPUpdates(apiToken string, updateFunction func()) error {
if apiToken == "" {
2020-04-24 13:45:24 +02:00
return errors.New("api token is empty or has not been set. not starting api")
}
2020-04-24 13:45:24 +02:00
log.Println("Watchtower HTTP API started.")
2020-04-24 13:45:24 +02:00
http.HandleFunc("/v1/update", func(w http.ResponseWriter, r *http.Request) {
log.Info("Updates triggered by HTTP API request.")
2020-04-24 13:45:24 +02:00
_, err := io.Copy(os.Stdout, r.Body)
if err != nil {
log.Println(err)
return
}
if r.Header.Get("Token") != apiToken {
log.Println("Invalid token. Not updating.")
return
}
log.Println("Valid token found. Attempting to update.")
2020-04-24 13:45:24 +02:00
select {
2020-04-24 13:45:24 +02:00
case chanValue := <-lock:
defer func() { lock <- chanValue }()
updateFunction()
default:
log.Debug("Skipped. Another update already running.")
}
})
2020-04-24 13:45:24 +02:00
return nil
}
2020-04-24 13:45:24 +02:00
// WaitForHTTPUpdates starts the http server and listens for requests.
func WaitForHTTPUpdates() error {
log.Fatal(http.ListenAndServe(":8080", nil))
os.Exit(0)
return nil
2020-04-24 13:45:24 +02:00
}