litellm.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. /*
  2. Copyright 2026 LocoStack.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package reconciler
  14. import (
  15. "context"
  16. "crypto/rand"
  17. "crypto/sha256"
  18. "encoding/hex"
  19. "fmt"
  20. "maps"
  21. "github.com/LocoStack/loco-operator/api/v1alpha1"
  22. "github.com/LocoStack/loco-operator/pkg/templates/litellm"
  23. "go.yaml.in/yaml/v2"
  24. corev1 "k8s.io/api/core/v1"
  25. apierrors "k8s.io/apimachinery/pkg/api/errors"
  26. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  27. "k8s.io/apimachinery/pkg/runtime"
  28. "sigs.k8s.io/controller-runtime/pkg/client"
  29. "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
  30. )
  31. type LiteLLMReconciler struct {
  32. *DefaultComponentReconciler
  33. client client.Client
  34. scheme *runtime.Scheme
  35. stack *v1alpha1.Stack
  36. component *v1alpha1.Component
  37. }
  38. func NewLiteLLMReconciler(client client.Client, scheme *runtime.Scheme, stack *v1alpha1.Stack, component *v1alpha1.Component) *LiteLLMReconciler {
  39. return &LiteLLMReconciler{
  40. DefaultComponentReconciler: NewDefaultComponentReconciler(client, scheme, stack, component),
  41. client: client,
  42. scheme: scheme,
  43. stack: stack,
  44. component: component,
  45. }
  46. }
  47. func (r *LiteLLMReconciler) ReconcileComponent(ctx context.Context, tmpl *v1alpha1.Template, variables map[string]string) ([]client.Object, error) {
  48. if err := r.ReconcileKey(ctx, "litellm", litellm.LITELLM_AUTH_SECRET_KEY, generateKey); err != nil {
  49. return nil, fmt.Errorf("Failed to reconcile LiteLLM master key: %w", err)
  50. }
  51. deps := make([]client.Object, 0)
  52. emList := make([]*v1alpha1.ExternalModel, 0)
  53. mmList := make([]*v1alpha1.ManagedModel, 0)
  54. etList := make([]*v1alpha1.ExternalTool, 0)
  55. mtList := make([]*v1alpha1.ManagedTool, 0)
  56. for _, dep := range r.component.Spec.Dependencies {
  57. switch dep.Kind {
  58. case "ExternalModel":
  59. em := &v1alpha1.ExternalModel{}
  60. if err := r.client.Get(ctx, client.ObjectKey{Name: dep.Name, Namespace: dep.Namespace}, em); err != nil {
  61. return nil, fmt.Errorf("Failed to get ExternalModel %s/%s: %w", dep.Namespace, dep.Name, err)
  62. }
  63. emList = append(emList, em)
  64. deps = append(deps, em)
  65. case "ManagedModel":
  66. mm := &v1alpha1.ManagedModel{}
  67. if err := r.client.Get(ctx, client.ObjectKey{Name: dep.Name, Namespace: dep.Namespace}, mm); err != nil {
  68. return nil, fmt.Errorf("Failed to get ManagedModel %s/%s: %w", dep.Namespace, dep.Name, err)
  69. }
  70. mmList = append(mmList, mm)
  71. deps = append(deps, mm)
  72. case "ExternalTool":
  73. et := &v1alpha1.ExternalTool{}
  74. if err := r.client.Get(ctx, client.ObjectKey{Name: dep.Name, Namespace: dep.Namespace}, et); err != nil {
  75. return nil, fmt.Errorf("Failed to get ExternalTool %s/%s: %w", dep.Namespace, dep.Name, err)
  76. }
  77. etList = append(etList, et)
  78. deps = append(deps, et)
  79. case "ManagedTool":
  80. mt := &v1alpha1.ManagedTool{}
  81. if err := r.client.Get(ctx, client.ObjectKey{Name: dep.Name, Namespace: dep.Namespace}, mt); err != nil {
  82. return nil, fmt.Errorf("Failed to get ManagedTool %s/%s: %w", dep.Namespace, dep.Name, err)
  83. }
  84. mtList = append(mtList, mt)
  85. deps = append(deps, mt)
  86. }
  87. }
  88. configHash, err := r.reconcileConfigMap(ctx, emList, mmList, etList, mtList)
  89. if err != nil {
  90. return nil, fmt.Errorf("Failed to reconcile LiteLLM config: %w", err)
  91. }
  92. authSpecs := make(map[string]map[string]*v1alpha1.AuthSpec)
  93. for _, em := range emList {
  94. if em.Spec.Auth != nil {
  95. if _, ok := authSpecs["ExternalModel"]; !ok {
  96. authSpecs["ExternalModel"] = make(map[string]*v1alpha1.AuthSpec)
  97. }
  98. authSpecs["ExternalModel"][em.Name] = em.Spec.Auth
  99. }
  100. }
  101. for _, et := range etList {
  102. if et.Spec.Auth != nil {
  103. if _, ok := authSpecs["ExternalTool"]; !ok {
  104. authSpecs["ExternalTool"] = make(map[string]*v1alpha1.AuthSpec)
  105. }
  106. authSpecs["ExternalTool"][et.Name] = et.Spec.Auth
  107. }
  108. }
  109. for _, mt := range mtList {
  110. if mt.Spec.Auth != nil {
  111. if _, ok := authSpecs["ManagedTool"]; !ok {
  112. authSpecs["ManagedTool"] = make(map[string]*v1alpha1.AuthSpec)
  113. }
  114. authSpecs["ManagedTool"][mt.Name] = mt.Spec.Auth
  115. }
  116. }
  117. credentialsHash, err := r.credentialsHash(ctx, authSpecs)
  118. if err != nil {
  119. return nil, fmt.Errorf("Failed to hash LiteLLM credentials: %w", err)
  120. }
  121. injectSecrets(tmpl, authSpecs)
  122. if tmpl.Metadata.Annotations == nil {
  123. tmpl.Metadata.Annotations = make(map[string]string)
  124. }
  125. // the credential values reach the Pod as env vars, which are snapshotted when it
  126. // starts, so the rendered config alone does not decide whether the gateway is current:
  127. // a key rotated in place has to roll it out as well
  128. h := sha256.Sum256([]byte(configHash + credentialsHash))
  129. maps.Copy(tmpl.Metadata.Annotations, map[string]string{
  130. "locostack.com/configHash": hex.EncodeToString(h[:]),
  131. })
  132. if _, err := r.DefaultComponentReconciler.ReconcileComponent(ctx, tmpl, variables); err != nil {
  133. return nil, err
  134. }
  135. return deps, nil
  136. }
  137. func (r *LiteLLMReconciler) reconcileConfigMap(ctx context.Context, emList []*v1alpha1.ExternalModel, mmList []*v1alpha1.ManagedModel, etList []*v1alpha1.ExternalTool, mtList []*v1alpha1.ManagedTool) (string, error) {
  138. var o11yComp *v1alpha1.Component
  139. if r.stack.Spec.Observability != nil && r.stack.Spec.Observability.Enabled {
  140. o11yComp = &v1alpha1.Component{}
  141. if err := r.client.Get(ctx, client.ObjectKey{Name: fmt.Sprintf("observability-%s", r.stack.Name), Namespace: r.stack.Namespace}, o11yComp); err != nil {
  142. return "", fmt.Errorf("Failed to get Observability component: %w", err)
  143. }
  144. }
  145. configBuilder := litellm.LiteLLMConfigBuilder{
  146. MasterKeyEnvName: litellm.LITELLM_MASTER_KEY_ENV_NAME,
  147. Stack: r.stack,
  148. ObservabilityComponent: o11yComp,
  149. ExternalModels: emList,
  150. ManagedModels: mmList,
  151. ExternalTools: etList,
  152. ManagedTools: mtList,
  153. }
  154. config, err := configBuilder.BuildLiteLLMConfig()
  155. if err != nil {
  156. return "", fmt.Errorf("Failed to build LiteLLM config: %w", err)
  157. }
  158. configData, err := yaml.Marshal(config)
  159. if err != nil {
  160. return "", fmt.Errorf("Failed to marshal LiteLLM config: %w", err)
  161. }
  162. configDataStr := string(configData)
  163. h := sha256.Sum256([]byte(configDataStr))
  164. configHash := hex.EncodeToString(h[:])
  165. cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Name: r.ResourceName("config"), Namespace: r.component.GetNamespace()}}
  166. if _, err := controllerutil.CreateOrUpdate(ctx, r.client, cm, func() error {
  167. if cm.Labels == nil {
  168. cm.Labels = map[string]string{}
  169. }
  170. maps.Copy(cm.Labels, r.ResourceLabels())
  171. if cm.Annotations == nil {
  172. cm.Annotations = make(map[string]string)
  173. }
  174. cm.Annotations["hash"] = configHash
  175. cm.Data = map[string]string{litellm.LITELLM_CONFIG_KEY: configDataStr}
  176. return controllerutil.SetControllerReference(r.component, cm, r.scheme)
  177. }); err != nil {
  178. return "", err
  179. }
  180. return configHash, nil
  181. }
  182. // credentialsHash digests the credential values that the gateway Pod reads from Secrets,
  183. // keyed by the dependency and Secret key they belong to. A Secret or key that does not
  184. // resolve hashes as empty rather than failing the reconcile: the rest of the config still
  185. // has to be written, and it is the dependency's own CredentialsResolved condition that
  186. // reports the dangling reference.
  187. func (r *LiteLLMReconciler) credentialsHash(ctx context.Context, authSpecs map[string]map[string]*v1alpha1.AuthSpec) (string, error) {
  188. h := sha256.New()
  189. for _, kind := range sortedKeys(authSpecs) {
  190. for _, name := range sortedKeys(authSpecs[kind]) {
  191. for _, ref := range AuthSecretRefs(authSpecs[kind][name]) {
  192. secret := &corev1.Secret{}
  193. if err := r.client.Get(ctx, client.ObjectKey{Name: ref.Name, Namespace: r.component.GetNamespace()}, secret); err != nil && !apierrors.IsNotFound(err) {
  194. return "", fmt.Errorf("Failed to get Secret %s: %w", ref.Name, err)
  195. }
  196. _, _ = fmt.Fprintf(h, "%s/%s/%s/%s=%s\n", kind, name, ref.Name, ref.Key, secret.Data[ref.Key])
  197. }
  198. }
  199. }
  200. return hex.EncodeToString(h.Sum(nil)), nil
  201. }
  202. func generateKey() (string, error) {
  203. b := make([]byte, 24)
  204. if _, err := rand.Read(b); err != nil {
  205. return "", err
  206. }
  207. return "sk-" + hex.EncodeToString(b), nil
  208. }
  209. func injectSecrets(tmpl *v1alpha1.Template, authSpecs map[string]map[string]*v1alpha1.AuthSpec) {
  210. envVars := []corev1.EnvVar{}
  211. for _, kind := range sortedKeys(authSpecs) {
  212. kindAuthSpecs := authSpecs[kind]
  213. for _, name := range sortedKeys(kindAuthSpecs) {
  214. auth := kindAuthSpecs[name]
  215. var refName string
  216. var refKey string
  217. if auth.APIKey != nil {
  218. refName = auth.APIKey.SecretRef.Name
  219. refKey = auth.APIKey.SecretRef.Key
  220. } else if auth.BearerToken != nil {
  221. refName = auth.BearerToken.Name
  222. refKey = auth.BearerToken.Key
  223. }
  224. if refName != "" && refKey != "" {
  225. envVars = append(envVars, corev1.EnvVar{
  226. Name: litellm.AuthEnvVarName(kind, name),
  227. ValueFrom: &corev1.EnvVarSource{
  228. SecretKeyRef: &corev1.SecretKeySelector{
  229. LocalObjectReference: corev1.LocalObjectReference{Name: refName},
  230. Key: refKey,
  231. },
  232. },
  233. })
  234. }
  235. if auth.Headers != nil {
  236. for _, header := range auth.Headers {
  237. if header.ValueFrom.SecretKeyRef != nil {
  238. envVars = append(envVars, corev1.EnvVar{
  239. Name: litellm.AuthEnvVarName(kind, name+"_"+header.Name),
  240. ValueFrom: &corev1.EnvVarSource{
  241. SecretKeyRef: &corev1.SecretKeySelector{
  242. LocalObjectReference: header.ValueFrom.SecretKeyRef.LocalObjectReference,
  243. Key: header.ValueFrom.SecretKeyRef.Key,
  244. },
  245. },
  246. })
  247. }
  248. }
  249. }
  250. }
  251. }
  252. tmpl.Spec.Runtime.Env = append(tmpl.Spec.Runtime.Env, envVars...)
  253. }