-
Notifications
You must be signed in to change notification settings - Fork 102
Expand file tree
/
Copy pathmanager.go
More file actions
660 lines (575 loc) · 19.7 KB
/
manager.go
File metadata and controls
660 lines (575 loc) · 19.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
package models
import (
"context"
"encoding/json"
"errors"
"fmt"
"html"
"net/http"
"path"
"strconv"
"strings"
"sync"
"github.com/docker/model-distribution/distribution"
"github.com/docker/model-distribution/registry"
"github.com/docker/model-distribution/types"
"github.com/docker/model-runner/pkg/diskusage"
"github.com/docker/model-runner/pkg/inference"
"github.com/docker/model-runner/pkg/logging"
"github.com/sirupsen/logrus"
)
const (
// maximumConcurrentModelPulls is the maximum number of concurrent model
// pulls that a model manager will allow.
maximumConcurrentModelPulls = 2
)
// Manager manages inference model pulls and storage.
type Manager struct {
// log is the associated logger.
log logging.Logger
// pullTokens is a semaphore used to restrict the maximum number of
// concurrent pull requests.
pullTokens chan struct{}
// router is the HTTP request router.
router *http.ServeMux
// distributionClient is the client for model distribution.
distributionClient *distribution.Client
// registryClient is the client for model registry.
registryClient *registry.Client
// lock is used to synchronize access to the models manager's router.
lock sync.Mutex
}
type ClientConfig struct {
// StoreRootPath is the root path for the model store.
StoreRootPath string
// Logger is the logger to use.
Logger *logrus.Entry
// Transport is the HTTP transport to use.
Transport http.RoundTripper
// UserAgent is the user agent to use.
UserAgent string
}
// NewManager creates a new model's manager.
func NewManager(log logging.Logger, c ClientConfig, allowedOrigins []string) *Manager {
// Create the model distribution client.
distributionClient, err := distribution.NewClient(
distribution.WithStoreRootPath(c.StoreRootPath),
distribution.WithLogger(c.Logger),
distribution.WithTransport(c.Transport),
distribution.WithUserAgent(c.UserAgent),
)
if err != nil {
log.Errorf("Failed to create distribution client: %v", err)
// Continue without distribution client. The model manager will still
// respond to requests, but may return errors if the client is required.
}
// Create the model registry client.
registryClient := registry.NewClient(
registry.WithTransport(c.Transport),
registry.WithUserAgent(c.UserAgent),
)
// Create the manager.
m := &Manager{
log: log,
pullTokens: make(chan struct{}, maximumConcurrentModelPulls),
router: http.NewServeMux(),
distributionClient: distributionClient,
registryClient: registryClient,
}
// Register routes.
m.router.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "not found", http.StatusNotFound)
})
for route, handler := range m.routeHandlers(allowedOrigins) {
m.router.HandleFunc(route, handler)
}
// Populate the pull concurrency semaphore.
for i := 0; i < maximumConcurrentModelPulls; i++ {
m.pullTokens <- struct{}{}
}
// Manager successfully initialized.
return m
}
func (m *Manager) RebuildRoutes(allowedOrigins []string) {
m.lock.Lock()
defer m.lock.Unlock()
// Clear existing routes and re-register them.
m.router = http.NewServeMux()
// Register routes.
m.router.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "not found", http.StatusNotFound)
})
for route, handler := range m.routeHandlers(allowedOrigins) {
m.router.HandleFunc(route, handler)
}
}
func (m *Manager) routeHandlers(allowedOrigins []string) map[string]http.HandlerFunc {
handlers := map[string]http.HandlerFunc{
"POST " + inference.ModelsPrefix + "/create": m.handleCreateModel,
"GET " + inference.ModelsPrefix: m.handleGetModels,
"GET " + inference.ModelsPrefix + "/{name...}": m.handleGetModel,
"DELETE " + inference.ModelsPrefix + "/{name...}": m.handleDeleteModel,
"POST " + inference.ModelsPrefix + "/{nameAndAction...}": m.handleModelAction,
"GET " + inference.InferencePrefix + "/{backend}/v1/models": m.handleOpenAIGetModels,
"GET " + inference.InferencePrefix + "/{backend}/v1/models/{name...}": m.handleOpenAIGetModel,
"GET " + inference.InferencePrefix + "/v1/models": m.handleOpenAIGetModels,
"GET " + inference.InferencePrefix + "/v1/models/{name...}": m.handleOpenAIGetModel,
}
for route, handler := range handlers {
if strings.HasPrefix(route, "GET ") {
handlers[route] = inference.CorsMiddleware(allowedOrigins, handler).ServeHTTP
}
}
return handlers
}
func (m *Manager) GetRoutes() []string {
routeHandlers := m.routeHandlers(nil)
routes := make([]string, 0, len(routeHandlers))
for route := range routeHandlers {
routes = append(routes, route)
}
return routes
}
// handleCreateModel handles POST <inference-prefix>/models/create requests.
func (m *Manager) handleCreateModel(w http.ResponseWriter, r *http.Request) {
if m.distributionClient == nil {
http.Error(w, "model distribution service unavailable", http.StatusServiceUnavailable)
return
}
// Decode the request.
var request ModelCreateRequest
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
// Pull the model. In the future, we may support additional operations here
// besides pulling (such as model building).
if err := m.PullModel(request.From, r, w); err != nil {
if errors.Is(err, registry.ErrInvalidReference) {
m.log.Warnf("Invalid model reference %q: %v", request.From, err)
http.Error(w, "Invalid model reference", http.StatusBadRequest)
return
}
if errors.Is(err, registry.ErrUnauthorized) {
m.log.Warnf("Unauthorized to pull model %q: %v", request.From, err)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
if errors.Is(err, registry.ErrModelNotFound) {
m.log.Warnf("Failed to pull model %q: %v", request.From, err)
http.Error(w, "Model not found", http.StatusNotFound)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// handleGetModels handles GET <inference-prefix>/models requests.
func (m *Manager) handleGetModels(w http.ResponseWriter, r *http.Request) {
if m.distributionClient == nil {
http.Error(w, "model distribution service unavailable", http.StatusServiceUnavailable)
return
}
// Query models.
models, err := m.distributionClient.ListModels()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
apiModels := make([]*Model, len(models))
for i, model := range models {
apiModels[i], err = ToModel(model)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// Write the response.
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(apiModels); err != nil {
m.log.Warnln("Error while encoding model listing response:", err)
}
}
// handleGetModel handles GET <inference-prefix>/models/{name} requests.
func (m *Manager) handleGetModel(w http.ResponseWriter, r *http.Request) {
// Parse remote query parameter
remote := false
if r.URL.Query().Has("remote") {
if val, err := strconv.ParseBool(r.URL.Query().Get("remote")); err != nil {
m.log.Warnln("Error while parsing remote query parameter:", err)
} else {
remote = val
}
}
if remote && m.registryClient == nil {
http.Error(w, "registry client unavailable", http.StatusServiceUnavailable)
return
}
var apiModel *Model
var err error
if remote {
apiModel, err = getRemoteModel(r.Context(), m, r.PathValue("name"))
} else {
apiModel, err = getLocalModel(m, r.PathValue("name"))
}
if err != nil {
if errors.Is(err, distribution.ErrModelNotFound) || errors.Is(err, registry.ErrModelNotFound) {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write the response.
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(apiModel); err != nil {
m.log.Warnln("Error while encoding model response:", err)
}
}
func getLocalModel(m *Manager, name string) (*Model, error) {
if m.distributionClient == nil {
return nil, errors.New("model distribution service unavailable")
}
// Query the model.
model, err := m.GetModel(name)
if err != nil {
return nil, err
}
return ToModel(model)
}
func getRemoteModel(ctx context.Context, m *Manager, name string) (*Model, error) {
if m.registryClient == nil {
return nil, errors.New("registry client unavailable")
}
m.log.Infoln("Getting remote model:", name)
model, err := m.registryClient.Model(ctx, name)
if err != nil {
return nil, err
}
id, err := model.ID()
if err != nil {
return nil, err
}
descriptor, err := model.Descriptor()
if err != nil {
return nil, err
}
config, err := model.Config()
if err != nil {
return nil, err
}
apiModel := &Model{
ID: id,
Tags: nil,
Created: descriptor.Created.Unix(),
Config: config,
}
return apiModel, nil
}
// handleDeleteModel handles DELETE <inference-prefix>/models/{name} requests.
// query params:
// - force: if true, delete the model even if it has multiple tags
func (m *Manager) handleDeleteModel(w http.ResponseWriter, r *http.Request) {
if m.distributionClient == nil {
http.Error(w, "model distribution service unavailable", http.StatusServiceUnavailable)
return
}
// TODO: We probably want the manager to have a lock / unlock mechanism for
// models so that active runners can retain / release a model, analogous to
// a container blocking the release of an image. However, unlike containers,
// runners are only evicted when idle or when memory is needed, so users
// won't be able to release the images manually. Perhaps we can unlink the
// corresponding GGUF files from disk and allow the OS to clean them up once
// the runner process exits (though this won't work for Windows, where we
// might need some separate cleanup process).
var force bool
if r.URL.Query().Has("force") {
if val, err := strconv.ParseBool(r.URL.Query().Get("force")); err != nil {
m.log.Warnln("Error while parsing force query parameter:", err)
} else {
force = val
}
}
if _, err := m.distributionClient.DeleteModel(r.PathValue("name"), force); err != nil {
if errors.Is(err, distribution.ErrModelNotFound) {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
if errors.Is(err, distribution.ErrConflict) {
http.Error(w, err.Error(), http.StatusConflict)
return
}
m.log.Warnln("Error while deleting model:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// handleOpenAIGetModels handles GET <inference-prefix>/<backend>/v1/models and
// GET /<inference-prefix>/v1/models requests.
func (m *Manager) handleOpenAIGetModels(w http.ResponseWriter, r *http.Request) {
if m.distributionClient == nil {
http.Error(w, "model distribution service unavailable", http.StatusServiceUnavailable)
return
}
// Query models.
available, err := m.distributionClient.ListModels()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
models, err := ToOpenAIList(available)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Write the response.
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(models); err != nil {
m.log.Warnln("Error while encoding OpenAI model listing response:", err)
}
}
// handleOpenAIGetModel handles GET <inference-prefix>/<backend>/v1/models/{name}
// and GET <inference-prefix>/v1/models/{name} requests.
func (m *Manager) handleOpenAIGetModel(w http.ResponseWriter, r *http.Request) {
if m.distributionClient == nil {
http.Error(w, "model distribution service unavailable", http.StatusServiceUnavailable)
return
}
// Query the model.
model, err := m.GetModel(r.PathValue("name"))
if err != nil {
if errors.Is(err, distribution.ErrModelNotFound) {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
// Write the response.
w.Header().Set("Content-Type", "application/json")
openaiModel, err := ToOpenAI(model)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := json.NewEncoder(w).Encode(openaiModel); err != nil {
m.log.Warnln("Error while encoding OpenAI model response:", err)
}
}
// handleTagModel handles POST <inference-prefix>/models/{nameAndAction} requests.
// Action is one of:
// - tag: tag the model with a repository and tag (e.g. POST <inference-prefix>/models/my-org/my-repo:latest/tag})
// - push: pushes a tagged model to the registry
func (m *Manager) handleModelAction(w http.ResponseWriter, r *http.Request) {
model, action := path.Split(r.PathValue("nameAndAction"))
model = strings.TrimRight(model, "/")
switch action {
case "tag":
m.handleTagModel(w, r, model)
case "push":
m.handlePushModel(w, r, model)
default:
http.Error(w, fmt.Sprintf("unknown action %q", action), http.StatusNotFound)
}
}
// handleTagModel handles POST <inference-prefix>/models/{name}/tag requests.
// The query parameters are:
// - repo: the repository to tag the model with (required)
// - tag: the tag to apply to the model (required)
func (m *Manager) handleTagModel(w http.ResponseWriter, r *http.Request, model string) {
if m.distributionClient == nil {
http.Error(w, "model distribution service unavailable", http.StatusServiceUnavailable)
return
}
// Extract query parameters.
repo := r.URL.Query().Get("repo")
tag := r.URL.Query().Get("tag")
// Validate query parameters.
if repo == "" || tag == "" {
http.Error(w, "missing repo or tag query parameter", http.StatusBadRequest)
return
}
// Construct the target string.
target := fmt.Sprintf("%s:%s", repo, tag)
// Call the Tag method on the distribution client with source and modelName.
if err := m.distributionClient.Tag(model, target); err != nil {
m.log.Warnf("Failed to apply tag %q to model %q: %v", target, model, err)
if errors.Is(err, distribution.ErrModelNotFound) {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Respond with success.
w.WriteHeader(http.StatusCreated)
w.Write([]byte(fmt.Sprintf("Model %q tagged successfully with %q", model, target)))
}
// handlePushModel handles POST <inference-prefix>/models/{name}/push requests.
func (m *Manager) handlePushModel(w http.ResponseWriter, r *http.Request, model string) {
if m.distributionClient == nil {
http.Error(w, "model distribution service unavailable", http.StatusServiceUnavailable)
return
}
// Call the PushModel method on the distribution client.
if err := m.PushModel(model, r, w); err != nil {
if errors.Is(err, distribution.ErrInvalidReference) {
m.log.Warnf("Invalid model reference %q: %v", model, err)
http.Error(w, "Invalid model reference", http.StatusBadRequest)
return
}
if errors.Is(err, distribution.ErrModelNotFound) {
m.log.Warnf("Failed to push model %q: %v", model, err)
http.Error(w, "Model not found", http.StatusNotFound)
return
}
if errors.Is(err, registry.ErrUnauthorized) {
m.log.Warnf("Unauthorized to push model %q: %v", model, err)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// GetDiskUsage returns the disk usage of the model store.
func (m *Manager) GetDiskUsage() (int64, error, int) {
if m.distributionClient == nil {
return 0, errors.New("model distribution service unavailable"), http.StatusServiceUnavailable
}
storePath := m.distributionClient.GetStorePath()
size, err := diskusage.Size(storePath)
if err != nil {
return 0, fmt.Errorf("error while getting store size: %v", err), http.StatusInternalServerError
}
return size, nil, http.StatusOK
}
// ServeHTTP implement net/http.Handler.ServeHTTP.
func (m *Manager) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.lock.Lock()
defer m.lock.Unlock()
m.router.ServeHTTP(w, r)
}
// GetModel returns a single model.
func (m *Manager) GetModel(ref string) (types.Model, error) {
model, err := m.distributionClient.GetModel(ref)
if err != nil {
return nil, fmt.Errorf("error while getting model: %w", err)
}
return model, err
}
// GetModelPath returns the path to a model's files.
func (m *Manager) GetModelPath(ref string) (string, error) {
model, err := m.GetModel(ref)
if err != nil {
return "", err
}
path, err := model.GGUFPath()
if err != nil {
return "", fmt.Errorf("error while getting model path: %w", err)
}
return path, nil
}
// PullModel pulls a model to local storage. Any error it returns is suitable
// for writing back to the client.
func (m *Manager) PullModel(model string, r *http.Request, w http.ResponseWriter) error {
// Restrict model pull concurrency.
select {
case <-m.pullTokens:
case <-r.Context().Done():
return context.Canceled
}
defer func() {
m.pullTokens <- struct{}{}
}()
// Set up response headers for streaming
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Transfer-Encoding", "chunked")
// Check Accept header to determine content type
acceptHeader := r.Header.Get("Accept")
isJSON := acceptHeader == "application/json"
if isJSON {
w.Header().Set("Content-Type", "application/json")
} else {
// Defaults to text/plain
w.Header().Set("Content-Type", "text/plain")
}
// Create a flusher to ensure chunks are sent immediately
flusher, ok := w.(http.Flusher)
if !ok {
return fmt.Errorf("streaming not supported")
}
// Create a progress writer that writes to the response
progressWriter := &progressResponseWriter{
writer: w,
flusher: flusher,
isJSON: isJSON,
}
// Pull the model using the Docker model distribution client
m.log.Infoln("Pulling model:", model)
err := m.distributionClient.PullModel(r.Context(), model, progressWriter)
if err != nil {
return fmt.Errorf("error while pulling model: %w", err)
}
return nil
}
// PushModel pushes a model from the store to the registry.
func (m *Manager) PushModel(model string, r *http.Request, w http.ResponseWriter) error {
// Set up response headers for streaming
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("Transfer-Encoding", "chunked")
// Check Accept header to determine content type
acceptHeader := r.Header.Get("Accept")
isJSON := acceptHeader == "application/json"
if isJSON {
w.Header().Set("Content-Type", "application/json")
} else {
w.Header().Set("Content-Type", "text/plain")
}
// Create a flusher to ensure chunks are sent immediately
flusher, ok := w.(http.Flusher)
if !ok {
return errors.New("streaming not supported")
}
// Create a progress writer that writes to the response
progressWriter := &progressResponseWriter{
writer: w,
flusher: flusher,
isJSON: isJSON,
}
// Pull the model using the Docker model distribution client
m.log.Infoln("Pushing model:", model)
err := m.distributionClient.PushModel(r.Context(), model, progressWriter)
if err != nil {
return fmt.Errorf("error while pushing model: %w", err)
}
return nil
}
// progressResponseWriter implements io.Writer to write progress updates to the HTTP response
type progressResponseWriter struct {
writer http.ResponseWriter
flusher http.Flusher
isJSON bool
}
func (w *progressResponseWriter) Write(p []byte) (n int, err error) {
var data []byte
if w.isJSON {
// For JSON, write the raw bytes without escaping
data = p
} else {
// For plain text, escape HTML
escapedData := html.EscapeString(string(p))
data = []byte(escapedData)
}
n, err = w.writer.Write(data)
if err != nil {
return 0, err
}
// Flush the response to ensure the chunk is sent immediately
if w.flusher != nil {
w.flusher.Flush()
}
return n, nil
}