/
common.go
278 lines (248 loc) · 7.6 KB
/
common.go
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
/*
Copyright 2023 KubeAGI.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package common
import (
"context"
"errors"
"fmt"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/kubeagi/arcadia/api/base/v1alpha1"
"github.com/kubeagi/arcadia/apiserver/graph/generated"
"github.com/kubeagi/arcadia/apiserver/pkg/auth"
"github.com/kubeagi/arcadia/pkg/config"
)
var (
DefaultNamespace = "default"
ErrNoResourceKind = errors.New("must provide resource kind")
// Common status
StatusTrue = "True"
StatusFalse = "False"
)
// ModelType
var (
ModelTypeAll = "llm,embedding"
ModelTypeLLM = "llm"
ModelTypeEmbedding = "embedding"
)
// ModelSource
var (
ModelSourceLocal = "local"
ModelSourceModelscope = "modelscope"
ModelSourceHuggingface = "huggingface"
)
// GetAPIServer returns the api server url to access arcadia's worker
// if external is true,then this func will return the external api server
func GetAPIServer(ctx context.Context, cli client.Client, external bool) (string, error) {
gateway, err := config.GetGateway(ctx)
if err != nil {
return "", err
}
api := gateway.APIServer
if external {
api = gateway.ExternalAPIServer
}
return api, nil
}
// GetGPTsURL returns the gpts url to access arcadia's gpt store
func GetGPTStoreConfig(ctx context.Context, cli client.Client) (*config.GPTsConfig, error) {
return config.GetGPTsConfig(ctx, cli)
}
// GetObjStatus is used to calculate the state of the resource, unified management,
// in general, a resource will only record its own state,
// then the state calculation of this resource, should be written to this function.
// But for some special resources. For example, VersionedDataset,
// he needs to calculate multiple states, it is not suitable for this function.
func GetObjStatus(obj client.Object) string {
if obj == nil {
return ""
}
if obj.GetDeletionTimestamp() != nil {
return "Deleting"
}
var (
condition v1alpha1.Condition
)
switch v := obj.(type) {
case *v1alpha1.Datasource:
condition = v.Status.GetCondition(v1alpha1.TypeReady)
case *v1alpha1.Embedder:
condition = v.Status.GetCondition(v1alpha1.TypeReady)
case *v1alpha1.KnowledgeBase:
condition = v.Status.GetCondition(v1alpha1.TypeReady)
case *v1alpha1.LLM:
condition = v.Status.GetCondition(v1alpha1.TypeReady)
case *v1alpha1.Model:
condition = v.Status.GetCondition(v1alpha1.TypeReady)
case *v1alpha1.Worker:
condition = v.Status.GetCondition(v1alpha1.TypeReady)
// Worker can better represent the state of resources through Reason.
status := string(condition.Reason)
// When replicas is zero but status is not `Offline`, it must be in `OfflineInProgress`
if v.Spec.Replicas == nil || *v.Spec.Replicas == 0 {
if status != "Offline" {
status = "OfflineInProgress"
}
}
return status
case *v1alpha1.Application:
condition = v.Status.GetCondition(v1alpha1.TypeReady)
default:
return ""
}
return string(condition.Status)
}
// PageNodeConvertFunc convert `any` to a `PageNode`
type PageNodeConvertFunc func(any) generated.PageNode
var (
DefaultPageNodeConvertFunc = func(node any) generated.PageNode {
pageNode, ok := node.(generated.PageNode)
if !ok {
return nil
}
return pageNode
}
)
var (
// UnlimitedPageSize which means all
UnlimitedPageSize = -1
)
// ListOptions for graphql list
type ListOptions struct {
ConvertFunc PageNodeConvertFunc
}
// DefaultListOptions initialize a ListOptions with default settings
func DefaultListOptions() *ListOptions {
return &ListOptions{
ConvertFunc: DefaultPageNodeConvertFunc,
}
}
type ListOptionsFunc func(options *ListOptions)
// WithPageNodeConvertFunc update the PageNodeConvertFunc
func WithPageNodeConvertFunc(convertFunc PageNodeConvertFunc) ListOptionsFunc {
return func(option *ListOptions) {
option.ConvertFunc = convertFunc
}
}
func SetCreator(ctx context.Context, common *v1alpha1.CommonSpec) {
currentUser, _ := ctx.Value(auth.UserNameContextKey).(string)
common.Creator = currentUser
}
func PagePosition(page, size, total int) (int, int) {
// if pageSize is -1 which means unlimited pageSize,return all
if size == UnlimitedPageSize {
page = 1
size = total
}
if page <= 0 {
page = 1
}
if size <= 0 {
size = 10
}
start := (page - 1) * size
if start > total {
start = total
}
end := page * size
if end > total {
end = total
}
return start, end
}
func TypedObjectReferenceToInput(ref generated.TypedObjectReference) generated.TypedObjectReferenceInput {
return generated.TypedObjectReferenceInput{
APIGroup: ref.APIGroup,
Kind: ref.Kind,
Namespace: ref.Namespace,
Name: ref.Name,
}
}
func GetAppCategory(app *v1alpha1.Application) []*string {
category := make([]*string, 0)
categoryStr, ok := app.GetLabels()[v1alpha1.AppCategoryLabelKey]
if ok && len(categoryStr) > 0 {
for _, v := range strings.Split(categoryStr, ",") {
v := v
category = append(category, pointer.String(strings.TrimSpace(v)))
}
}
return category
}
func DeleteAllOptions(input *generated.DeleteCommonInput) ([]client.DeleteAllOfOption, error) {
if input.Namespace == "" {
return nil, errors.New("namespace is empty, please check your request args")
}
if pointer.StringDeref(input.Name, "") == "" && pointer.StringDeref(input.LabelSelector, "") == "" && pointer.StringDeref(input.FieldSelector, "") == "" {
return nil, errors.New("no name, no LabelSelector, no FieldSelector, please check your request args")
}
opts := []client.DeleteAllOfOption{
client.InNamespace(input.Namespace),
}
fieldsSelector := ""
if pointer.StringDeref(input.Name, "") != "" {
fieldsSelector = fmt.Sprintf("metadata.name=%s", *input.Name)
}
if pointer.StringDeref(input.FieldSelector, "") != "" {
fieldsSelector = *input.FieldSelector
}
if fieldsSelector != "" {
f, err := fields.ParseSelector(fieldsSelector)
if err != nil {
return nil, err
}
opts = append(opts, client.MatchingFieldsSelector{Selector: f})
}
if pointer.StringDeref(input.LabelSelector, "") != "" {
l, err := labels.Parse(*input.LabelSelector)
if err != nil {
return nil, err
}
opts = append(opts, client.MatchingLabelsSelector{Selector: l})
}
return opts, nil
}
func NewListOptions(input generated.ListCommonInput) ([]client.ListOption, error) {
if input.Namespace == "" {
input.Namespace = metav1.NamespaceDefault
}
opts := []client.ListOption{
client.InNamespace(input.Namespace),
}
if pointer.StringDeref(input.LabelSelector, "") != "" {
l, err := labels.Parse(*input.LabelSelector)
if err != nil {
return nil, err
}
opts = append(opts, client.MatchingLabelsSelector{Selector: l})
}
if pointer.StringDeref(input.FieldSelector, "") != "" {
f, err := fields.ParseSelector(*input.FieldSelector)
if err != nil {
return nil, err
}
opts = append(opts, client.MatchingFieldsSelector{Selector: f})
}
return opts, nil
}
func AppIconLink(app *v1alpha1.Application, endpointPrefix string) string {
base := fmt.Sprintf("/bff/icon?namespace=%s&application=%s", app.Namespace, app.Name)
if endpointPrefix != "" {
base = "/" + endpointPrefix + base
}
return base
}