jynx/scaler/scaler.go

85 lines
2.2 KiB
Go
Raw Normal View History

2023-05-29 21:21:50 +00:00
package scaler
import (
"fmt"
2023-07-15 19:51:31 +00:00
"os"
2023-05-29 21:21:50 +00:00
"git.stinnesbeck.com/go/jynx/backend/hetzner"
"git.stinnesbeck.com/go/jynx/ci/woodpecker"
"git.stinnesbeck.com/go/log"
)
func Start(w *woodpecker.Server) error {
stats, err := w.GetStats()
if err != nil {
return err
}
2023-07-15 19:51:31 +00:00
// get the prefix for jynx managed servers
prefix := os.Getenv("HCLOUD_PREFIX")
// get a list of all servers from hetzner (from jynx)
servers, err := hetzner.ListJynxServers(prefix)
2023-05-29 21:21:50 +00:00
if err != nil {
return err
}
2023-07-15 19:51:31 +00:00
newServers := stats.PendingJobs - len(servers) + stats.RunningJobs
startingUp := len(servers) - stats.RunningJobs - stats.IdlingWorkers
// check if the result is negative, if so set starting servers as 0
// happens when servers are queued for deletion and api is polled in the
// meantime
if startingUp < 0 {
startingUp = 0
}
log.PrintInfo(stats.RunningJobs, "running jobs,", stats.PendingJobs, "pending jobs,", stats.IdlingWorkers, "idling workers,", startingUp, "servers starting up")
2023-07-15 19:51:31 +00:00
// check if there are servers to be removed
if stats.PendingJobs == 0 && stats.RunningJobs == 0 {
// we need to remove servers
if err := hetzner.CheckServerDeletions(servers); err != nil {
return err
}
}
2023-05-29 21:21:50 +00:00
2023-07-15 19:51:31 +00:00
// check if we need to create new servers
// if stats.PendingJobs < 1 || len(servers)-stats.RunningJobs >= stats.PendingJobs {
if stats.PendingJobs < 1 || newServers < 1 {
// if stats.PendingJobs == 0 || stats.IdlingWorkers+stats.RunningJobs >= stats.PendingJobs {
// skip rest of this run
2023-05-29 21:21:50 +00:00
return nil
}
2023-07-15 19:51:31 +00:00
// there are servers to be created
if newServers < 1 {
return nil
}
2023-05-29 21:21:50 +00:00
2023-07-15 19:51:31 +00:00
var ScaleUpServers []string
2023-05-29 21:21:50 +00:00
2023-07-15 19:51:31 +00:00
// get the suffix for the starting server
suffix, err := hetzner.GetNewSuffix(servers)
2023-05-29 21:21:50 +00:00
for i := 0; i < newServers; i++ {
2023-07-15 19:51:31 +00:00
if err != nil {
2023-05-29 21:21:50 +00:00
return err
}
2023-07-15 19:51:31 +00:00
// assemble server name and add it to the list of servers to scale up
serverName := fmt.Sprintf("%s-worker-%d", prefix, suffix)
ScaleUpServers = append(ScaleUpServers, serverName)
// add 1 to the suffix for the next server
suffix++
2023-05-29 21:21:50 +00:00
}
2023-07-15 19:51:31 +00:00
log.PrintInfo("starting", newServers, "workers:", ScaleUpServers)
// create servers on hetzner cloud
if err := hetzner.CreateServers(ScaleUpServers); err != nil {
2023-05-29 21:21:50 +00:00
return err
}
return nil
}