server/listen/listen.go

79 lines
1.8 KiB
Go
Raw Normal View History

2022-09-16 04:02:25 +00:00
package listen
import (
"fmt"
"net/http"
2023-01-14 13:02:17 +00:00
"git.ohea.xyz/cursorius/server/admin_api"
"git.ohea.xyz/cursorius/server/config"
2023-01-14 13:02:17 +00:00
"git.ohea.xyz/cursorius/server/database"
"git.ohea.xyz/cursorius/server/pipeline_api"
"git.ohea.xyz/cursorius/server/runnermanager"
"git.ohea.xyz/cursorius/server/webhook"
"github.com/google/uuid"
2022-09-16 04:02:25 +00:00
"github.com/op/go-logging"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"nhooyr.io/websocket"
2022-09-16 04:02:25 +00:00
)
var log = logging.MustGetLogger("cursorius-server")
func setupHTTPServer(
mux *http.ServeMux,
conf config.PipelineConf,
2023-01-14 13:02:17 +00:00
db database.Database,
runnerManagerChans runnermanager.RunnerManagerChans,
pollChan chan uuid.UUID,
2023-01-14 13:02:17 +00:00
) error {
webhook.CreateWebhookHandler(db, conf, mux)
pipeline_api.CreateHandler(runnerManagerChans.Allocation, runnerManagerChans.Release, mux)
err := admin_api.CreateHandler(db, pollChan, mux)
2023-01-14 13:02:17 +00:00
if err != nil {
return fmt.Errorf("Could not create admin api handler: %w", err)
}
mux.HandleFunc("/runner", func(w http.ResponseWriter, r *http.Request) {
conn, err := websocket.Accept(w, r, nil)
if err != nil {
log.Errorf("Could not upgrade runner connection to websocket: %v", err)
return
}
go runnermanager.RegisterRunner(conn, runnerManagerChans.Registration)
})
2023-01-14 13:02:17 +00:00
return nil
2022-09-16 04:02:25 +00:00
}
func Listen(
mux *http.ServeMux,
address string,
port int,
conf config.PipelineConf,
2023-01-14 13:02:17 +00:00
db database.Database,
runnerManagerChans runnermanager.RunnerManagerChans,
pollChan chan uuid.UUID,
2023-01-14 13:02:17 +00:00
) error {
2023-01-14 13:02:17 +00:00
err := setupHTTPServer(
mux,
conf,
2023-01-14 13:02:17 +00:00
db,
runnerManagerChans,
pollChan,
)
2023-01-14 13:02:17 +00:00
if err != nil {
return fmt.Errorf("Could not setup http endpoints: %w", err)
}
2022-09-16 04:02:25 +00:00
connect_string := fmt.Sprintf("%v:%v", address, port)
log.Noticef("Launching HTTP server on %v\n", connect_string)
2023-01-14 13:02:17 +00:00
return http.ListenAndServe(
connect_string,
h2c.NewHandler(mux, &http2.Server{}),
2023-01-14 13:02:17 +00:00
)
2022-09-16 04:02:25 +00:00
}