-
Notifications
You must be signed in to change notification settings - Fork 175
Expand file tree
/
Copy pathserver.go
More file actions
193 lines (161 loc) · 5.7 KB
/
Copy pathserver.go
File metadata and controls
193 lines (161 loc) · 5.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
// Copyright 2025 BoxLite AI (originally Daytona Platforms Inc.
// Modified by BoxLite AI, 2025-2026
// SPDX-License-Identifier: AGPL-3.0
// @title BoxLite Runner API
// @version v0.0.0-dev
// @description BoxLite Runner API
// @securityDefinitions.apikey Bearer
// @in header
// @name Authorization
// @description Type "Bearer" followed by a space and an API token.
// @Security Bearer
package api
import (
"context"
"fmt"
"log/slog"
"net"
"net/http"
"time"
"github.com/boxlite-ai/runner/cmd/runner/config"
"github.com/boxlite-ai/runner/internal"
"github.com/boxlite-ai/runner/pkg/api/controllers"
"github.com/boxlite-ai/runner/pkg/api/docs"
"github.com/boxlite-ai/runner/pkg/api/middlewares"
"github.com/boxlite-ai/runner/pkg/common"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
common_errors "github.com/boxlite-ai/common-go/pkg/errors"
"github.com/boxlite-ai/common-go/pkg/log"
sloggin "github.com/samber/slog-gin"
swaggerfiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
)
type ApiServerConfig struct {
Logger *slog.Logger
ApiPort int
ApiToken string
TLSCertFile string
TLSKeyFile string
EnableTLS bool
LogRequests bool
}
func NewApiServer(config ApiServerConfig) *ApiServer {
return &ApiServer{
logger: config.Logger.With(slog.String("component", "server")),
apiPort: config.ApiPort,
apiToken: config.ApiToken,
tlsCertFile: config.TLSCertFile,
tlsKeyFile: config.TLSKeyFile,
enableTLS: config.EnableTLS,
logRequests: config.LogRequests,
}
}
type ApiServer struct {
logger *slog.Logger
apiPort int
apiToken string
tlsCertFile string
tlsKeyFile string
enableTLS bool
httpServer *http.Server
router *gin.Engine
logRequests bool
}
func (a *ApiServer) Start(ctx context.Context) error {
docs.SwaggerInfo.Description = "BoxLite Runner API"
docs.SwaggerInfo.Title = "BoxLite Runner API"
docs.SwaggerInfo.BasePath = "/"
docs.SwaggerInfo.Version = internal.Version
_, err := net.Dial("tcp", fmt.Sprintf(":%d", a.apiPort))
if err == nil {
return fmt.Errorf("cannot start API server, port %d is already in use", a.apiPort)
}
binding.Validator = new(DefaultValidator)
gin.DefaultWriter = &log.InfoLogWriter{}
gin.DefaultErrorWriter = &log.ErrorLogWriter{}
a.router = gin.New()
a.router.Use(common_errors.Recovery())
gin.SetMode(gin.ReleaseMode)
if config.GetEnvironment() == "development" {
gin.SetMode(gin.DebugMode)
}
if a.logRequests {
a.router.Use(sloggin.New(a.logger))
}
a.router.Use(otelgin.Middleware("boxlite-runner"))
a.router.Use(common_errors.NewErrorMiddleware(common.HandlePossibleDockerError))
a.router.Use(middlewares.RecoverableErrorsMiddleware())
public := a.router.Group("/")
public.GET("", controllers.HealthCheck)
if config.GetEnvironment() == "development" {
public.GET("/api/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
}
protected := a.router.Group("/")
protected.Use(middlewares.AuthMiddleware(a.apiToken))
metricsController := protected.Group("/metrics")
{
metricsController.GET("", gin.WrapH(promhttp.Handler()))
}
infoController := protected.Group("/info")
{
infoController.GET("", controllers.RunnerInfo)
}
boxControllerLogger := a.logger.With(slog.String("component", "box_controller"))
boxController := protected.Group("/boxes")
{
boxController.POST("", controllers.Create)
boxController.GET("/:boxId", controllers.Info)
boxController.POST("/:boxId/destroy", controllers.Destroy)
boxController.POST("/:boxId/start", controllers.Start)
boxController.POST("/:boxId/stop", controllers.Stop)
boxController.POST("/:boxId/recover", controllers.Recover)
boxController.POST("/:boxId/is-recoverable", controllers.IsRecoverable)
boxController.POST("/:boxId/network-settings", controllers.UpdateNetworkSettings)
// Add proxy endpoint within the box controller for toolbox
// Using Any() to handle all HTTP methods for the toolbox proxy
boxController.Any("/:boxId/toolbox/*path", controllers.ProxyRequest(boxControllerLogger))
}
// BoxLite REST API — exec, files, metrics
boxliteApi := protected.Group("/v1/boxes")
{
boxliteApi.POST("/:boxId/exec", controllers.BoxliteExec)
boxliteApi.GET("/:boxId/executions/:execId", controllers.BoxliteGetExecution)
boxliteApi.DELETE("/:boxId/executions/:execId", controllers.BoxliteExecKill)
boxliteApi.GET("/:boxId/executions/:execId/attach", controllers.BoxliteExecAttach)
boxliteApi.POST("/:boxId/executions/:execId/signal", controllers.BoxliteExecSignal)
boxliteApi.POST("/:boxId/executions/:execId/resize", controllers.BoxliteExecResize)
boxliteApi.PUT("/:boxId/files", controllers.BoxliteFileUpload)
boxliteApi.GET("/:boxId/files", controllers.BoxliteFileDownload)
boxliteApi.GET("/:boxId/metrics", controllers.BoxliteMetrics)
boxliteApi.Handle(http.MethodConnect, "/:boxId/network/tunnel", controllers.BoxliteNetworkTunnel(boxControllerLogger))
}
a.httpServer = &http.Server{
Addr: fmt.Sprintf(":%d", a.apiPort),
Handler: a.router,
}
listener, err := net.Listen("tcp", a.httpServer.Addr)
if err != nil {
return err
}
errChan := make(chan error)
go func() {
if a.enableTLS {
// Start HTTPS server
errChan <- a.httpServer.ServeTLS(listener, a.tlsCertFile, a.tlsKeyFile)
} else {
// Start HTTP server
errChan <- a.httpServer.Serve(listener)
}
}()
return <-errChan
}
func (a *ApiServer) Stop() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := a.httpServer.Shutdown(ctx); err != nil {
a.logger.Error("Failed to shutdown API server", "error", err)
}
}