forked from yunionio/cloudpods
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllm.go
More file actions
933 lines (845 loc) · 30.4 KB
/
Copy pathllm.go
File metadata and controls
933 lines (845 loc) · 30.4 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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
package models
import (
"context"
"database/sql"
"fmt"
"strings"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/utils"
"yunion.io/x/sqlchemy"
commonapi "yunion.io/x/onecloud/pkg/apis"
computeapi "yunion.io/x/onecloud/pkg/apis/compute"
api "yunion.io/x/onecloud/pkg/apis/llm"
"yunion.io/x/onecloud/pkg/apis/notify"
notifyapi "yunion.io/x/onecloud/pkg/apis/notify"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
"yunion.io/x/onecloud/pkg/cloudcommon/notifyclient"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/llm/options"
llmutils "yunion.io/x/onecloud/pkg/llm/utils"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/mcclient/auth"
"yunion.io/x/onecloud/pkg/mcclient/modules/compute"
baseoptions "yunion.io/x/onecloud/pkg/mcclient/options"
computeoptions "yunion.io/x/onecloud/pkg/mcclient/options/compute"
"yunion.io/x/onecloud/pkg/util/stringutils2"
)
var llmManager *SLLMManager
func init() {
GetLLMManager()
}
func GetLLMManager() *SLLMManager {
if llmManager != nil {
return llmManager
}
llmManager = &SLLMManager{
SLLMBaseManager: NewSLLMBaseManager(
SLLM{},
"llms_tbl",
"llm",
"llms",
),
}
llmManager.SetVirtualObject(llmManager)
return llmManager
}
type SLLMManager struct {
SLLMBaseManager
}
type SLLM struct {
SLLMBase
LLMSkuId string `width:"128" charset:"ascii" nullable:"false" list:"user" create:"required"`
LLMImageId string `width:"128" charset:"ascii" nullable:"false" list:"user" create:"required"`
// 秒装应用配额(可安装的总容量限制)
InstantModelQuotaGb int `list:"user" update:"user" create:"optional" default:"0" nullable:"false"`
// LLMSpec overrides/extends sku LLMSpec when building container; merged with sku.LLMSpec (llm priority).
LLMSpec *api.LLMSpec `json:"llm_spec,omitempty" length:"long" list:"user" create:"optional" update:"user"`
}
// CustomizeCreate saves Dify customized envs from create input when present.
func (llm *SLLM) CustomizeCreate(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data jsonutils.JSONObject) error {
if err := llm.SLLMBase.CustomizeCreate(ctx, userCred, ownerId, query, data); err != nil {
return err
}
return nil
}
func (man *SLLMManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, input *api.LLMCreateInput) (*api.LLMCreateInput, error) {
var err error
input.LLMBaseCreateInput, err = man.SLLMBaseManager.ValidateCreateData(ctx, userCred, ownerId, query, input.LLMBaseCreateInput)
if err != nil {
return input, errors.Wrap(err, "validate LLMBaseCreateInput")
}
sku, err := GetLLMSkuManager().FetchByIdOrName(ctx, userCred, input.LLMSkuId)
if err != nil {
return input, errors.Wrap(err, "fetch LLMSku")
}
lSku := sku.(*SLLMSku)
input.LLMSkuId = lSku.Id
input.LLMImageId = lSku.GetLLMImageId()
if input.LLMSpec != nil {
drv := lSku.GetLLMContainerDriver()
spec, err := drv.ValidateLLMCreateSpec(ctx, userCred, lSku, input.LLMSpec)
if err != nil {
return input, errors.Wrap(err, "validate LLM create spec")
}
input.LLMSpec = spec
}
return input, nil
}
func (man *SLLMManager) BatchCreateValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, input api.LLMCreateInput) (*jsonutils.JSONDict, error) {
data, err := man.ValidateCreateData(ctx, userCred, ownerId, query, &input)
if err != nil {
return nil, err
}
return data.JSON(data), nil
}
func (man *SLLMManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, input api.LLMListInput) (*sqlchemy.SQuery, error) {
q, err := man.SLLMBaseManager.ListItemFilter(ctx, q, userCred, input.LLMBaseListInput)
if err != nil {
return q, errors.Wrap(err, "VirtualResourceBaseManager.ListItemFilter")
}
if len(input.LLMSku) > 0 {
skuObj, err := GetLLMSkuManager().FetchByIdOrName(ctx, userCred, input.LLMSku)
if err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, httperrors.NewResourceNotFoundError2(GetLLMSkuManager().KeywordPlural(), input.LLMSku)
} else {
return nil, errors.Wrap(err, "GetLLMSkuManager.FetchByIdOrName")
}
}
q = q.Equals("llm_sku_id", skuObj.GetId())
}
if len(input.LLMImage) > 0 {
imgObj, err := GetLLMImageManager().FetchByIdOrName(ctx, userCred, input.LLMImage)
if err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, httperrors.NewResourceNotFoundError2(GetLLMImageManager().KeywordPlural(), input.LLMImage)
} else {
return nil, errors.Wrap(err, "LLMImageManager.FetchByIdOrName")
}
}
q = q.Equals("llm_image_id", imgObj.GetId())
}
if len(input.LLMType) > 0 {
skuQ := GetLLMSkuManager().Query().SubQuery()
q = q.Join(skuQ, sqlchemy.Equals(q.Field("llm_sku_id"), skuQ.Field("id")))
q = q.Filter(sqlchemy.Equals(skuQ.Field("llm_type"), input.LLMType))
}
if len(input.LLMTypes) > 0 {
skuQ := GetLLMSkuManager().Query().SubQuery()
q = q.Join(skuQ, sqlchemy.Equals(q.Field("llm_sku_id"), skuQ.Field("id")))
q = q.Filter(sqlchemy.In(skuQ.Field("llm_type"), input.LLMTypes))
}
return q, nil
}
func (man *SLLMManager) FetchCustomizeColumns(
ctx context.Context,
userCred mcclient.TokenCredential,
query jsonutils.JSONObject,
objs []interface{},
fields stringutils2.SSortedStrings,
isList bool,
) []api.LLMListDetails {
virtRows := man.SVirtualResourceBaseManager.FetchCustomizeColumns(ctx, userCred, query, objs, fields, isList)
llms := []SLLM{}
jsonutils.Update(&llms, objs)
res := make([]api.LLMListDetails, len(objs))
for i := 0; i < len(res); i++ {
res[i].VirtualResourceDetails = virtRows[i]
}
ids := make([]string, len(llms))
skuIds := make([]string, len(llms))
imgIds := make([]string, len(llms))
serverIds := []string{}
networkIds := []string{}
for idx, llm := range llms {
ids[idx] = llm.Id
skuIds[idx] = llm.LLMSkuId
imgIds[idx] = llm.LLMImageId
if !utils.IsInArray(llm.CmpId, serverIds) {
serverIds = append(serverIds, llm.CmpId)
}
if len(llm.NetworkId) > 0 {
networkIds = append(networkIds, llm.NetworkId)
}
mountedModelInfo, _ := llm.FetchMountedModelInfo()
res[idx].MountedModels = mountedModelInfo
res[idx].NetworkType = llm.NetworkType
res[idx].NetworkId = llm.NetworkId
}
// fetch volume
volumeQ := GetVolumeManager().Query().In("llm_Id", ids)
volumes := []SVolume{}
db.FetchModelObjects(GetVolumeManager(), volumeQ, &volumes)
for _, volume := range volumes {
for i, id := range ids {
if id == volume.LLMId {
res[i].Volume = api.Volume{
Id: volume.CmpId,
Name: volume.Name,
TemplateId: volume.TemplateId,
StorageType: volume.StorageType,
SizeMB: volume.SizeMB,
}
}
}
}
// fetch sku
skus := make(map[string]SLLMSku)
err := db.FetchModelObjectsByIds(GetLLMSkuManager(), "id", skuIds, &skus)
if err == nil {
for i := range llms {
if sku, ok := skus[llms[i].LLMSkuId]; ok {
res[i].LLMSku = sku.Name
res[i].LLMType = sku.LLMType
res[i].VcpuCount = sku.Cpu
res[i].VmemSizeMb = sku.Memory
res[i].Devices = sku.Devices
if llms[i].BandwidthMb != 0 {
res[i].EffectBandwidthMbps = llms[i].BandwidthMb
} else {
res[i].EffectBandwidthMbps = sku.Bandwidth
}
}
}
} else {
log.Errorf("FetchModelObjectsByIds LLMSkuManager fail %s", err)
}
// fetch image
images := make(map[string]SLLMImage)
err = db.FetchModelObjectsByIds(GetLLMImageManager(), "id", imgIds, &images)
if err == nil {
for i := range llms {
if image, ok := images[llms[i].LLMImageId]; ok {
res[i].LLMImage = image.Name
res[i].LLMImageLable = image.ImageLabel
res[i].LLMImageName = image.ImageName
}
}
} else {
log.Errorf("FetchModelObjectsByIds GetLLMImageManager fail %s", err)
}
// fetch network
if len(networkIds) > 0 {
networks, err := fetchNetworks(ctx, userCred, networkIds)
if err == nil {
for i, llm := range llms {
if net, ok := networks[llm.NetworkId]; ok {
res[i].Network = net.Name
}
}
} else {
log.Errorf("fail to retrieve network info %s", err)
}
}
// fetch host
if len(serverIds) > 0 {
// allow query cmp server
serverMap := make(map[string]computeapi.ServerDetails)
s := auth.GetAdminSession(ctx, options.Options.Region)
params := computeoptions.ServerListOptions{}
limit := 1000
params.Limit = &limit
details := true
params.Details = &details
params.Scope = "maxallowed"
offset := 0
for offset < len(serverIds) {
lastIdx := offset + limit
if lastIdx > len(serverIds) {
lastIdx = len(serverIds)
}
params.Id = serverIds[offset:lastIdx]
results, err := compute.Servers.List(s, jsonutils.Marshal(params))
if err != nil {
log.Errorf("query servers fails %s", err)
break
} else {
offset = lastIdx
for i := range results.Data {
guest := computeapi.ServerDetails{}
err := results.Data[i].Unmarshal(&guest)
if err == nil {
serverMap[guest.Id] = guest
}
}
}
}
for i := range llms {
llmStatus := api.LLM_STATUS_UNKNOWN
llm := llms[i]
if guest, ok := serverMap[llm.CmpId]; ok {
// find guest
if len(guest.Containers) == 0 {
llmStatus = api.LLM_LLM_STATUS_NO_CONTAINER
} else {
llmCtr := guest.Containers[0]
if llmCtr == nil {
llmStatus = api.LLM_LLM_STATUS_NO_CONTAINER
} else {
llmStatus = llmCtr.Status
}
}
res[i].Server = guest.Name
res[i].StartTime = guest.LastStartAt
res[i].Host = guest.Host
res[i].HostId = guest.HostId
res[i].HostAccessIp = guest.HostAccessIp
res[i].HostEIP = guest.HostEIP
res[i].Zone = guest.Zone
res[i].ZoneId = guest.ZoneId
adbMappedPort := -1
// for j := range res[i].AccessInfo {
// res[i].AccessInfo[j].DesktopIp = guest.IPs
// res[i].AccessInfo[j].ServerIp = guest.HostAccessIp
// res[i].AccessInfo[j].PublicIp = guest.HostEIP
// /*if res[i].AccessInfo[j].ListenPort == api.DESKTOP_ADB_PORT {
// adbMappedPort = res[i].AccessInfo[j].AccessPort
// }*/
// }
if adbMappedPort >= 0 {
res[i].AdbAccess = fmt.Sprintf("%s:%d", guest.HostAccessIp, adbMappedPort)
if len(res[i].HostEIP) > 0 {
res[i].AdbPublic = fmt.Sprintf("%s:%d", guest.HostEIP, adbMappedPort)
}
}
} else {
llmStatus = api.LLM_LLM_STATUS_NO_SERVER
}
res[i].LLMStatus = llmStatus
}
}
return res
}
func (lm *SLLMManager) OnCreateComplete(ctx context.Context, items []db.IModel, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data []jsonutils.JSONObject) {
parentTaskId, _ := data[0].GetString("parent_task_id")
err := runBatchCreateTask(ctx, items, userCred, data, "LLMBatchCreateTask", parentTaskId)
if err != nil {
for i := range items {
llm := items[i].(*SLLM)
llm.SetStatus(ctx, userCred, api.LLM_STATUS_CREATE_FAIL, err.Error())
}
}
}
func runBatchCreateTask(
ctx context.Context,
items []db.IModel,
userCred mcclient.TokenCredential,
data []jsonutils.JSONObject,
taskName string,
parentTaskId string,
) error {
taskItems := make([]db.IStandaloneModel, len(items))
for i, t := range items {
taskItems[i] = t.(db.IStandaloneModel)
}
params := jsonutils.NewDict()
params.Set("data", jsonutils.NewArray(data...))
task, err := taskman.TaskManager.NewParallelTask(ctx, taskName, taskItems, userCred, params, parentTaskId, "")
if err != nil {
return errors.Wrapf(err, "NewParallelTask %s", taskName)
}
return task.ScheduleRun(nil)
}
func (llm *SLLM) CustomizeDelete(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) error {
return llm.StartDeleteTask(ctx, userCred, "")
}
func (llm *SLLM) GetLLMSku(skuId string) (*SLLMSku, error) {
if len(skuId) == 0 {
skuId = llm.LLMSkuId
}
sku, err := GetLLMSkuManager().FetchById(skuId)
if err != nil {
return nil, errors.Wrap(err, "fetch LLMSku")
}
return sku.(*SLLMSku), nil
}
func (llm *SLLM) ValidateUpdateData(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input api.LLMUpdateInput) (api.LLMUpdateInput, error) {
var err error
input.VirtualResourceBaseUpdateInput, err = llm.SLLMBase.SVirtualResourceBase.ValidateUpdateData(ctx, userCred, query, input.VirtualResourceBaseUpdateInput)
if err != nil {
return input, errors.Wrap(err, "validate VirtualResourceBaseUpdateInput")
}
if input.LLMSpec == nil {
return input, nil
}
sku, err := llm.GetLLMSku(llm.LLMSkuId)
if err != nil {
return input, errors.Wrap(err, "fetch LLMSku")
}
drv := sku.GetLLMContainerDriver()
spec, err := drv.ValidateLLMUpdateSpec(ctx, userCred, llm, input.LLMSpec)
if err != nil {
return input, errors.Wrap(err, "validate LLM update spec")
}
input.LLMSpec = spec
return input, nil
}
func (llm *SLLM) GetLargeLanguageModelName(name string) (modelName string, modelTag string, err error) {
if name == "" {
return "", "", errors.Wrap(errors.ErrInvalidStatus, "model name is empty")
}
parts := strings.Split(name, ":")
modelName = parts[0]
modelTag = "latest"
if len(parts) == 2 {
modelTag = parts[1]
}
return
}
func (llm *SLLM) GetLLMImage() (*SLLMImage, error) {
return llm.getImage(llm.LLMImageId)
}
func (llm *SLLM) GetLLMSContainer(ctx context.Context) (*computeapi.SContainer, error) {
llmCtr, err := llm.GetLLMContainer()
if err != nil {
return nil, errors.Wrap(err, "GetLLMContainer")
}
return llmCtr.GetSContainer(ctx)
}
func (llm *SLLM) GetLLMContainer() (*SLLMContainer, error) {
return GetLLMContainerManager().FetchByLLMId(llm.Id)
}
func (llm *SLLM) SyncLLMContainer(ctx context.Context, userCred mcclient.TokenCredential, server *computeapi.ServerDetails) (*SLLMContainer, error) {
curCtr, _ := llm.GetLLMContainer()
if curCtr != nil {
return curCtr, nil
}
drv := llm.GetLLMContainerDriver()
ctr, err := drv.GetPrimaryContainer(ctx, llm, server.Containers)
if err != nil {
return nil, errors.Wrap(err, "GetPrimaryContainer")
}
llmCtr, err := GetLLMContainerManager().CreateOnLLM(ctx, userCred, llm.GetOwnerId(), llm, ctr.Id, ctr.Name)
if nil != err {
return nil, errors.Wrapf(err, "create llm container on llm %s", ctr.Id)
}
return llmCtr, nil
}
func (llm *SLLM) GetLLMContainerDriver() ILLMContainerDriver {
sku, _ := llm.GetLLMSku(llm.LLMSkuId)
return sku.GetLLMContainerDriver()
}
func (llm *SLLM) StartCreateTask(ctx context.Context, userCred mcclient.TokenCredential, input api.LLMCreateInput, parentTaskId string) error {
llm.SetStatus(ctx, userCred, commonapi.STATUS_CREATING, "")
params := jsonutils.Marshal(input).(*jsonutils.JSONDict)
var err = func() error {
task, err := taskman.TaskManager.NewTask(ctx, "LLMCreateTask", llm, userCred, params, parentTaskId, "", nil)
if err != nil {
return errors.Wrapf(err, "NewTask")
}
return task.ScheduleRun(params)
}()
if err != nil {
llm.SetStatus(ctx, userCred, api.LLM_STATUS_CREATE_FAIL, err.Error())
return err
}
return nil
}
func (llm *SLLM) StartPullModelTask(ctx context.Context, userCred mcclient.TokenCredential, input *jsonutils.JSONDict, parentTaskId string) error {
task, err := taskman.TaskManager.NewTask(ctx, "LLMPullModelTask", llm, userCred, input, parentTaskId, "", nil)
if err != nil {
return errors.Wrapf(err, "NewTask")
}
return task.ScheduleRun(nil)
}
func (llm *SLLM) StartDeleteTask(ctx context.Context, userCred mcclient.TokenCredential, parentTaskId string) error {
llm.SetStatus(ctx, userCred, api.LLM_STATUS_START_DELETE, "StartDeleteTask")
task, err := taskman.TaskManager.NewTask(ctx, "LLMDeleteTask", llm, userCred, nil, parentTaskId, "", nil)
if err != nil {
return err
}
return task.ScheduleRun(nil)
}
func (llm *SLLM) ServerCreate(ctx context.Context, userCred mcclient.TokenCredential, s *mcclient.ClientSession, input *api.LLMCreateInput) (string, error) {
sku, err := llm.GetLLMSku(llm.LLMSkuId)
if nil != err {
return "", errors.Wrap(err, "GetLLMSku")
}
llmImage, err := llm.GetLLMImage()
if nil != err {
return "", errors.Wrap(err, "GetLLMImage")
}
data, err := GetLLMPodCreateInput(ctx, userCred, input, llm, sku, llmImage, "")
if nil != err {
return "", errors.Wrap(err, "GetPodCreateInput")
}
log.Infoln("PodCreateInput Data: ", jsonutils.Marshal(data).String())
resp, err := compute.Servers.Create(s, jsonutils.Marshal(data))
if nil != err {
return "", errors.Wrap(err, "Servers.Create")
}
id, err := resp.GetString("id")
if nil != err {
return "", errors.Wrap(err, "resp.GetString")
}
return id, nil
}
func (llm *SLLM) PerformStart(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) (jsonutils.JSONObject, error) {
// can't start while it's already running
if utils.IsInStringArray(llm.Status, computeapi.VM_RUNNING_STATUS) {
return nil, errors.Wrapf(errors.ErrInvalidStatus, "llm id: %s status: %s", llm.Id, llm.Status)
}
_, err := llm.GetVolume()
if err != nil {
if errors.Cause(err) == sql.ErrNoRows {
return nil, errors.Wrapf(errors.ErrNotSupported, "llm id: %s missing volume", llm.Id)
}
return nil, errors.Wrap(err, "GetVolume")
}
taskinput := &api.LLMRestartTaskInput{
LLMId: llm.Id,
LLMStatus: api.LLM_STATUS_READY,
}
_, err = llm.StartRestartTask(ctx, userCred, taskinput, "")
if err != nil {
return nil, errors.Wrap(err, "StartRestartTask")
}
return nil, nil
}
func (d *SLLM) StartStartTaskInternal(ctx context.Context, userCred mcclient.TokenCredential, parentTaskId string) error {
d.SetStatus(ctx, userCred, computeapi.VM_STARTING, "")
task, err := taskman.TaskManager.NewTask(ctx, "LLMStartTask", d, userCred, nil, parentTaskId, "", nil)
if err != nil {
return errors.Wrapf(err, "NewTask")
}
return task.ScheduleRun(nil)
}
func (llm *SLLM) StartStartTask(ctx context.Context, userCred mcclient.TokenCredential, parentTaskId string) error {
task, err := taskman.TaskManager.NewTask(ctx, "LLMStartTask", llm, userCred, nil, parentTaskId, "", nil)
if err != nil {
return errors.Wrap(err, "NewTask")
}
return task.ScheduleRun(nil)
}
func (llm *SLLM) PerformStop(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) (jsonutils.JSONObject, error) {
if llm.Status == computeapi.VM_READY {
return nil, errors.Wrapf(errors.ErrInvalidStatus, "llm id: %s status: %s", llm.Id, llm.Status)
}
llm.SetStatus(ctx, userCred, computeapi.VM_START_STOP, "perform stop")
err := llm.StartLLMStopTask(ctx, userCred, "")
if err != nil {
return nil, errors.Wrap(err, "StartStopTask")
}
return nil, nil
}
func (llm *SLLM) ValidateRestartInput(ctx context.Context, userCred mcclient.TokenCredential, input *api.LLMRestartInput) (*api.LLMRestartTaskInput, error) {
if len(llm.CmpId) == 0 {
return nil, errors.Wrap(errors.ErrInvalidStatus, "empty cmp_id")
}
srv, err := llm.GetServer(ctx)
if err != nil {
return nil, errors.Wrap(err, "GetServer")
}
if (llm.Status != api.LLM_STATUS_READY && llm.Status != api.LLM_STATUS_RUNNING) || (srv.Status != computeapi.VM_READY && !utils.IsInArray(srv.Status, computeapi.VM_RUNNING_STATUS)) {
return nil, errors.Wrapf(errors.ErrInvalidStatus, "invalid llm status %s", llm.Status)
}
return &api.LLMRestartTaskInput{}, nil
}
func (llm *SLLM) PerformRestart(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input *api.LLMRestartInput) (jsonutils.JSONObject, error) {
taskInput, err := llm.ValidateRestartInput(ctx, userCred, input)
if err != nil {
return nil, errors.Wrap(err, "ValidateRestartInput")
}
_, err = llm.StartRestartTask(ctx, userCred, taskInput, "")
if err != nil {
return nil, errors.Wrap(err, "StartRestartTask")
}
return nil, nil
}
func (llm *SLLM) StartRestartTask(ctx context.Context, userCred mcclient.TokenCredential, params *api.LLMRestartTaskInput, parentTaskId string) (*taskman.STask, error) {
key := "perform_restart"
if params.ResetDataDisk {
key = "perform_reset"
}
llm.SetStatus(ctx, userCred, api.LLM_STATUS_START_RESTART, key)
taskName := "LLMRestartTask"
if params.ResetDataDisk {
taskName = "LLMResetTask"
}
params.LLMId = llm.Id
task, err := taskman.TaskManager.NewTask(ctx, taskName, llm, userCred, jsonutils.Marshal(params).(*jsonutils.JSONDict), parentTaskId, "", nil)
if err != nil {
return nil, errors.Wrap(err, "NewTask")
}
if err := task.ScheduleRun(nil); err != nil {
return nil, errors.Wrap(err, "ScheduleRun")
}
return task, nil
}
func (llm *SLLM) PerformReset(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, input *api.LLMRestartInput) (jsonutils.JSONObject, error) {
taskInput, err := llm.ValidateRestartInput(ctx, userCred, input)
if err != nil {
return nil, errors.Wrap(err, "ValidateRestartInput")
}
_, err = llm.StartResetTask(ctx, userCred, taskInput, "")
if err != nil {
return nil, errors.Wrap(err, "StartRestartTask")
}
return nil, nil
}
func (llm *SLLM) StartResetTask(ctx context.Context, userCred mcclient.TokenCredential, params *api.LLMRestartTaskInput, parentTaskId string) (*taskman.STask, error) {
llm.SetStatus(ctx, userCred, api.LLM_STATUS_START_RESTART, "perform_reset")
task, err := taskman.TaskManager.NewTask(ctx, "LLMResetTask", llm, userCred, jsonutils.Marshal(params).(*jsonutils.JSONDict), parentTaskId, "", nil)
if err != nil {
return nil, errors.Wrapf(err, "NewTask")
}
if err := task.ScheduleRun(nil); err != nil {
return nil, errors.Wrap(err, "ScheduleRun")
}
return task, nil
}
func (llm *SLLM) NotifyRequest(ctx context.Context, userCred mcclient.TokenCredential, action notify.SAction, model jsonutils.JSONObject, success bool) {
obj := func(ctx context.Context, details *jsonutils.JSONDict) {}
if model != nil {
obj = func(ctx context.Context, details *jsonutils.JSONDict) {
details.Set("customize_details", model)
}
}
notifyclient.EventNotify(ctx, userCred, notifyclient.SEventNotifyParam{
Obj: llm,
Action: action,
ObjDetailsDecorator: obj,
IsFail: !success,
ResourceType: notifyapi.TOPIC_RESOURCE_LLM,
})
}
func (llm *SLLM) StartLLMStopTask(ctx context.Context, userCred mcclient.TokenCredential, parentTaskId string) error {
task, err := taskman.TaskManager.NewTask(ctx, "LLMStopTask", llm, userCred, nil, parentTaskId, "", nil)
if err != nil {
return errors.Wrap(err, "NewTask")
}
err = task.ScheduleRun(nil)
if err != nil {
return errors.Wrap(err, "ScheduleRun")
}
return nil
}
func (llm *SLLM) ValidateDeleteCondition(ctx context.Context, info jsonutils.JSONObject) error {
if err := llm.SLLMBase.ValidateDeleteCondition(ctx, info); err != nil {
return err
}
// Check for associated MCPAgents
cnt, err := GetMCPAgentManager().Query().Equals("llm_id", llm.Id).CountWithError()
if err != nil {
return errors.Wrap(err, "GetMCPAgentManager().Query().CountWithError")
}
if cnt > 0 {
return httperrors.NewConflictError("LLM is being used by %d MCPAgents", cnt)
}
return nil
}
func (llm *SLLM) WaitContainerStatus(ctx context.Context, userCred mcclient.TokenCredential, targetStatus []string, timeoutSecs int) (*computeapi.SContainer, error) {
llmCtr, err := llm.GetLLMContainer()
if err != nil {
return nil, errors.Wrap(err, "GetLLMContainer")
}
return llmutils.WaitContainerStatus(ctx, llmCtr.CmpId, targetStatus, timeoutSecs)
}
func (llm *SLLM) PerformSyncstatus(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data api.LLMSyncStatusInput) (jsonutils.JSONObject, error) {
llm.SetStatus(ctx, userCred, api.LLM_STATUS_START_SYNCSTATUS, "perform syncstatus")
err := llm.StartSyncStatusTask(ctx, userCred, "")
if err != nil {
return nil, errors.Wrap(err, "StartSyncStatusTask")
}
return nil, nil
}
func (llm *SLLM) StartSyncStatusTask(ctx context.Context, userCred mcclient.TokenCredential, parentTaskId string) error {
task, err := taskman.TaskManager.NewTask(ctx, "LLMSyncStatusTask", llm, userCred, nil, parentTaskId, "")
if err != nil {
return errors.Wrap(err, "NewTask")
}
err = task.ScheduleRun(nil)
if err != nil {
return errors.Wrap(err, "ScheduleRun")
}
return nil
}
func (llm *SLLM) GetLLMUrl(ctx context.Context, userCred mcclient.TokenCredential) (string, error) {
if llm.CmpId == "" {
return "", nil
}
return llm.GetLLMContainerDriver().GetLLMUrl(ctx, userCred, llm)
}
func (llm *SLLM) GetDetailsUrl(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (jsonutils.JSONObject, error) {
accessUrl, err := llm.GetLLMUrl(ctx, userCred)
if err != nil {
return nil, errors.Wrap(err, "GetLLMUrl")
}
output := jsonutils.NewDict()
output.Set("access_url", jsonutils.NewString(accessUrl))
return output, nil
}
func (llm *SLLM) GetDetailsLoginInfo(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (*api.LLMLoginInfo, error) {
if llm.CmpId == "" {
return nil, nil
}
output := new(api.LLMLoginInfo)
loginUrl, err := llm.GetLLMUrl(ctx, userCred)
if err != nil {
return nil, errors.Wrap(err, "GetLLMUrl")
}
output.LoginUrl = loginUrl
drv := llm.GetLLMContainerDriver()
if loginInfoDrv, ok := drv.(ILLMContainerLoginInfo); ok {
info, err := loginInfoDrv.GetLoginInfo(ctx, userCred, llm)
if err != nil {
return nil, errors.Wrap(err, "GetLoginInfo")
}
if info != nil {
if info.Username != "" {
output.Username = info.Username
}
if info.Password != "" {
output.Password = info.Password
}
if len(info.Extra) > 0 {
output.Extra = info.Extra
}
}
}
return output, nil
}
func fetchNetworks(ctx context.Context, userCred mcclient.TokenCredential, networkIds []string) (map[string]computeapi.NetworkDetails, error) {
s := auth.GetSession(ctx, userCred, "")
params := computeoptions.ServerListOptions{}
params.Id = networkIds
limit := len(networkIds)
params.Limit = &limit
params.Scope = "maxallowed"
results, err := compute.Networks.List(s, jsonutils.Marshal(params))
if err != nil {
return nil, errors.Wrap(err, "Networks.List")
}
networks := make(map[string]computeapi.NetworkDetails)
for i := range results.Data {
net := computeapi.NetworkDetails{}
err := results.Data[i].Unmarshal(&net)
if err == nil {
networks[net.Id] = net
}
}
return networks, nil
}
func (man *SLLMManager) GetAvailableNetwork(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (jsonutils.JSONObject, error) {
s := auth.GetSession(ctx, userCred, "")
ret := jsonutils.NewDict()
q := jsonutils.NewDict()
if query != nil {
q.Update(query)
}
q.Set("server_type", jsonutils.NewString(string(computeapi.NETWORK_TYPE_HOSTLOCAL)))
q.Set("is_auto_alloc", jsonutils.NewBool(true))
q.Set("status", jsonutils.NewString(computeapi.NETWORK_STATUS_AVAILABLE))
q.Set("limit", jsonutils.NewInt(1))
result, err := compute.Networks.List(s, q)
if err == nil && result.Total > 0 {
ret.Add(jsonutils.NewInt(int64(result.Total)), "auto_alloc_network_hostlocal_count")
}
q.Set("server_type", jsonutils.NewString(string(computeapi.NETWORK_TYPE_GUEST)))
q.Set("vpc_id", jsonutils.NewString(computeapi.DEFAULT_VPC_ID))
resultGuest, err := compute.Networks.List(s, q)
if err == nil && resultGuest.Total > 0 {
ret.Add(jsonutils.NewInt(int64(resultGuest.Total)), "auto_alloc_network_guest_count")
}
return ret, nil
}
func (llm *SLLM) StartBindVolumeTask(ctx context.Context, userCred mcclient.TokenCredential, volumeId string, autoStart bool, parenentTaskId string) (*taskman.STask, error) {
llm.SetStatus(ctx, userCred, api.LLM_STATUS_START_BIND, "perform bind volume")
params := api.LLMVolumeInput{
LLMId: llm.Id,
VolumeId: volumeId,
AutoStart: autoStart,
}
task, err := taskman.TaskManager.NewTask(ctx, "LLMAttachTask", llm, userCred, jsonutils.Marshal(params).(*jsonutils.JSONDict), parenentTaskId, "", nil)
if err != nil {
return nil, errors.Wrap(err, "NewTask")
}
err = task.ScheduleRun(nil)
if err != nil {
return nil, errors.Wrap(err, "ScheduleRun")
}
return task, nil
}
func (llm *SLLM) ChangeServerNetworkConfig(ctx context.Context, bandwidth int, whitePrefixes []string, noSync bool) error {
s := auth.GetAdminSession(ctx, options.Options.Region)
params := baseoptions.BaseListOptions{}
params.Scope = "max"
limit := 0
params.Limit = &limit
serverNicObjs, err := compute.Servernetworks.ListDescendent(s, llm.CmpId, jsonutils.Marshal(params))
if err != nil {
return errors.Wrap(err, "compute.Servernetworks.ListDescendent")
} else if len(serverNicObjs.Data) == 0 {
return errors.Wrap(httperrors.ErrEmptyRequest, "compute.Servernetworks.ListDescendent")
}
gns := computeapi.GuestnetworkDetails{}
err = serverNicObjs.Data[0].Unmarshal(&gns)
if err != nil {
return errors.Wrap(err, "Unmarshal GuestnetworkDetails")
}
if gns.BwLimit != bandwidth {
// need to change bandwidth
params := computeapi.ServerChangeBandwidthInput{}
params.Mac = gns.MacAddr
params.Index = 0
params.Bandwidth = bandwidth
params.NoSync = &noSync
_, err := compute.Servers.PerformAction(s, llm.CmpId, "change-bandwidth", jsonutils.Marshal(params))
if err != nil {
return errors.Wrap(err, "compute.Servers.PerformAction change-bandwidth")
}
}
/*if len(adbWhitePrefixes) > 0 {
for _, pm := range gns.PortMappings {
if pm.Port == apis.PHONE_ADB_PORT {
// verify adb port remote ips
remoteIps := stringutils2.NewSortedStrings(pm.RemoteIps)
remoteIps2 := stringutils2.NewSortedStrings(adbWhitePrefixes)
if !stringutils2.Equals(remoteIps, remoteIps2) {
// need to update remote Ips
params := computeapi.GuestnetworkUpdateInput{}
for i := range gns.PortMappings {
npm := gns.PortMappings[i]
if gns.PortMappings[i].Port == apis.PHONE_ADB_PORT {
npm.RemoteIps = adbWhitePrefixes
}
params.PortMappings = append(params.PortMappings, npm)
}
_, err := compute.Servernetworks.Update(s, gns.GuestId, gns.NetworkId, nil, jsonutils.Marshal(params))
if err != nil {
return errors.Wrap(err, "Servernetworks.Update")
}
}
break
}
}
}*/
return nil
}
func (llm *SLLM) PerformNetConfig(
ctx context.Context,
userCred mcclient.TokenCredential,
query jsonutils.JSONObject,
input api.LLMChangeNetworkInput,
) (jsonutils.JSONObject, error) {
err := llm.ChangeServerNetworkConfig(ctx, input.BandwidthMb, input.WhitePrefxies, false)
if err != nil {
return nil, errors.Wrap(err, "changeServerNetworkConfig")
}
if llm.BandwidthMb != input.BandwidthMb {
_, err := db.Update(llm, func() error {
llm.BandwidthMb = input.BandwidthMb
return nil
})
if err != nil {
return nil, errors.Wrap(err, "update")
}
}
return nil, nil
}
func (llm *SLLM) purgeModelList() error {
return GetLLMInstantModelManager().purgeModelList(llm.Id)
}