common.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. "fmt"
  17. "sort"
  18. "strings"
  19. "github.com/LocoStack/loco-operator/api/v1alpha1"
  20. corev1 "k8s.io/api/core/v1"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. "k8s.io/apimachinery/pkg/util/intstr"
  23. "sigs.k8s.io/controller-runtime/pkg/client"
  24. )
  25. type ComponentReconciler interface {
  26. // create all resources for the component, and return the list of dependencies
  27. ReconcileComponent(ctx context.Context, tmpl *v1alpha1.Template, variables map[string]string) ([]client.Object, error)
  28. ComponentAvailable(ctx context.Context) bool
  29. ResourceName(name string) string
  30. }
  31. func ResourceLabels(stack, component, name, namespace string) map[string]string {
  32. labels := map[string]string{
  33. "app.kubernetes.io/managed-by": "loco-operator",
  34. "locostack.com/stack": stack,
  35. "locostack.com/component": component,
  36. "locostack.com/name": name,
  37. }
  38. if namespace != "" {
  39. labels["locostack.com/namespace"] = namespace
  40. }
  41. return labels
  42. }
  43. // substituteVariables replaces placeholders in the input string with actual values from the variables map.
  44. // Placeholders are in the format $(placeholder).
  45. func substituteVariables(variables map[string]string, input string) (bool, string) {
  46. for placeholder, value := range variables {
  47. if !strings.Contains(input, "$(") {
  48. return true, input
  49. }
  50. if strings.Contains(input, fmt.Sprintf("$(%s)", placeholder)) {
  51. input = strings.ReplaceAll(input, fmt.Sprintf("$(%s)", placeholder), value)
  52. }
  53. }
  54. return false, input
  55. }
  56. func mustSubstituteVariables(variables map[string]string, input string) string {
  57. _, substituted := substituteVariables(variables, input)
  58. return substituted
  59. }
  60. func buildVolumes(variables map[string]string, tmpl *v1alpha1.Template) []corev1.Volume {
  61. volumes := make([]corev1.Volume, len(tmpl.Spec.Volumes))
  62. if len(volumes) == 0 {
  63. volumes = nil
  64. } else {
  65. for i, vol := range tmpl.Spec.Volumes {
  66. volumes[i] = vol
  67. if vol.VolumeSource.ConfigMap != nil {
  68. volumes[i].VolumeSource.ConfigMap.LocalObjectReference.Name = mustSubstituteVariables(variables, vol.VolumeSource.ConfigMap.LocalObjectReference.Name)
  69. }
  70. if vol.VolumeSource.Secret != nil {
  71. volumes[i].VolumeSource.Secret.SecretName = mustSubstituteVariables(variables, vol.VolumeSource.Secret.SecretName)
  72. }
  73. if vol.VolumeSource.PersistentVolumeClaim != nil {
  74. volumes[i].VolumeSource.PersistentVolumeClaim.ClaimName = mustSubstituteVariables(variables, vol.VolumeSource.PersistentVolumeClaim.ClaimName)
  75. }
  76. }
  77. }
  78. return volumes
  79. }
  80. func buildContainerSpec(variables map[string]string, tmpl *v1alpha1.Template) corev1.Container {
  81. command := make([]string, len(tmpl.Spec.Runtime.Command))
  82. if len(command) == 0 {
  83. command = nil
  84. } else {
  85. for i, cmd := range tmpl.Spec.Runtime.Command {
  86. command[i] = mustSubstituteVariables(variables, cmd)
  87. }
  88. }
  89. args := make([]string, len(tmpl.Spec.Runtime.Args))
  90. if len(args) == 0 {
  91. args = nil
  92. } else {
  93. for i, arg := range tmpl.Spec.Runtime.Args {
  94. args[i] = mustSubstituteVariables(variables, arg)
  95. }
  96. for _, arg := range tmpl.Spec.Runtime.ExtraArgs {
  97. args = append(args, mustSubstituteVariables(variables, arg))
  98. }
  99. for _, arg := range tmpl.Spec.Runtime.ConditionalArgs {
  100. complete, substituted := substituteVariables(variables, arg.When)
  101. if complete && substituted != "" {
  102. for _, a := range arg.Args {
  103. args = append(args, mustSubstituteVariables(variables, a))
  104. }
  105. }
  106. }
  107. }
  108. env := make([]corev1.EnvVar, len(tmpl.Spec.Runtime.Env))
  109. if len(env) == 0 {
  110. env = nil
  111. } else {
  112. for i, envVar := range tmpl.Spec.Runtime.Env {
  113. env[i] = envVar
  114. env[i].Value = mustSubstituteVariables(variables, envVar.Value)
  115. if envVar.ValueFrom != nil && envVar.ValueFrom.SecretKeyRef != nil {
  116. env[i].ValueFrom.SecretKeyRef.LocalObjectReference.Name = mustSubstituteVariables(variables, envVar.ValueFrom.SecretKeyRef.LocalObjectReference.Name)
  117. env[i].ValueFrom.SecretKeyRef.Key = mustSubstituteVariables(variables, envVar.ValueFrom.SecretKeyRef.Key)
  118. }
  119. }
  120. }
  121. envFrom := make([]corev1.EnvFromSource, len(tmpl.Spec.Runtime.EnvFrom))
  122. if len(envFrom) == 0 {
  123. envFrom = nil
  124. } else {
  125. for i, envFromSource := range tmpl.Spec.Runtime.EnvFrom {
  126. envFrom[i] = envFromSource
  127. if envFromSource.ConfigMapRef != nil {
  128. envFrom[i].ConfigMapRef.LocalObjectReference.Name = mustSubstituteVariables(variables, envFromSource.ConfigMapRef.LocalObjectReference.Name)
  129. }
  130. if envFromSource.SecretRef != nil {
  131. envFrom[i].SecretRef.LocalObjectReference.Name = mustSubstituteVariables(variables, envFromSource.SecretRef.LocalObjectReference.Name)
  132. }
  133. }
  134. }
  135. ports := make([]corev1.ContainerPort, 0)
  136. if tmpl.Spec.Runtime.Port != 0 {
  137. ports = append(ports, corev1.ContainerPort{
  138. ContainerPort: tmpl.Spec.Runtime.Port,
  139. Protocol: corev1.ProtocolTCP,
  140. })
  141. }
  142. container := corev1.Container{
  143. Name: "main",
  144. Image: tmpl.Spec.Runtime.Image,
  145. ImagePullPolicy: corev1.PullIfNotPresent,
  146. Command: command,
  147. Args: args,
  148. Env: env,
  149. EnvFrom: envFrom,
  150. VolumeMounts: tmpl.Spec.Runtime.VolumeMounts,
  151. Ports: ports,
  152. Resources: tmpl.Spec.Resources,
  153. }
  154. if tmpl.Spec.Runtime.Name == "lambdagent" && tmpl.Spec.Runtime.Port != 0 {
  155. container.ReadinessProbe = &corev1.Probe{
  156. ProbeHandler: corev1.ProbeHandler{HTTPGet: &corev1.HTTPGetAction{
  157. Path: "/health",
  158. Port: intstr.FromInt32(tmpl.Spec.Runtime.Port),
  159. }},
  160. InitialDelaySeconds: 5,
  161. PeriodSeconds: 10,
  162. TimeoutSeconds: 3,
  163. FailureThreshold: 3,
  164. }
  165. container.LivenessProbe = &corev1.Probe{
  166. ProbeHandler: corev1.ProbeHandler{HTTPGet: &corev1.HTTPGetAction{
  167. Path: "/health",
  168. Port: intstr.FromInt32(tmpl.Spec.Runtime.Port),
  169. }},
  170. InitialDelaySeconds: 15,
  171. PeriodSeconds: 20,
  172. TimeoutSeconds: 3,
  173. FailureThreshold: 3,
  174. }
  175. }
  176. return container
  177. }
  178. func buildPodSpec(variables map[string]string, tmpl *v1alpha1.Template) (corev1.PodSpec, error) {
  179. return corev1.PodSpec{
  180. NodeSelector: tmpl.Spec.NodeSelector,
  181. Affinity: tmpl.Spec.Affinity,
  182. Tolerations: tmpl.Spec.Tolerations,
  183. TopologySpreadConstraints: tmpl.Spec.TopologySpreadConstraints,
  184. Containers: []corev1.Container{buildContainerSpec(variables, tmpl)},
  185. SecurityContext: tmpl.Spec.SecurityContext,
  186. Volumes: buildVolumes(variables, tmpl),
  187. }, nil
  188. }
  189. type EndpointResolver struct {
  190. client client.Client
  191. scheme *runtime.Scheme
  192. namespace string
  193. }
  194. func NewEndpointResolver(client client.Client, scheme *runtime.Scheme, namespace string) *EndpointResolver {
  195. return &EndpointResolver{
  196. client: client,
  197. scheme: scheme,
  198. namespace: namespace,
  199. }
  200. }
  201. func (r *EndpointResolver) ResolveEndpoint(ctx context.Context, stack *v1alpha1.Stack, ref corev1.ObjectReference) (client.Object, string, error) {
  202. switch ref.Kind {
  203. case "ExternalModel":
  204. return r.resolveExternalModelEndpoint(ctx, stack, ref.Name)
  205. case "ManagedModel":
  206. return r.resolveManagedModelEndpoint(ctx, stack, ref.Name)
  207. case "Skill":
  208. return nil, "", nil
  209. case "ExternalTool":
  210. return r.resolveExternalToolEndpoint(ctx, stack, ref.Name)
  211. case "ManagedTool":
  212. return r.resolveManagedToolEndpoint(ctx, stack, ref.Name)
  213. case "ExternalKnowledgeBase":
  214. return r.resolveExternalKnowledgeBaseEndpoint(ctx, ref.Name)
  215. case "ManagedKnowledgeBase":
  216. return r.resolveManagedKnowledgeBaseEndpoint(ctx, ref.Name)
  217. case "Component":
  218. return r.resolveComponentEndpoint(ctx, ref.Name)
  219. default:
  220. return nil, "", fmt.Errorf("unsupported reference kind: %s", ref.Kind)
  221. }
  222. }
  223. func (r *EndpointResolver) resolveGatewayEndpoint(ctx context.Context, stack *v1alpha1.Stack) (*v1alpha1.Component, error) {
  224. gatewayEnabled := true
  225. if stack.Spec.Gateway != nil {
  226. gatewayEnabled = stack.Spec.Gateway.Enabled
  227. }
  228. if !gatewayEnabled {
  229. return nil, nil
  230. }
  231. gwList := &v1alpha1.ComponentList{}
  232. err := r.client.List(ctx, gwList, client.InNamespace(stack.Namespace), client.MatchingLabels{"locostack.com/component": "Gateway", "stack.locostack.com/default": "true"})
  233. if err != nil {
  234. return nil, fmt.Errorf("Failed to list gateway components: %v", err)
  235. }
  236. if len(gwList.Items) == 0 {
  237. return nil, fmt.Errorf("No gateway component found for stack %s", stack.Name)
  238. } else if len(gwList.Items) > 1 {
  239. return nil, fmt.Errorf("Multiple gateway components found for stack %s", stack.Name)
  240. }
  241. gatewayComp := &gwList.Items[0]
  242. if gatewayComp.Status.Endpoint == "" {
  243. return nil, fmt.Errorf("Gateway component for stack %s not ready", stack.Name)
  244. }
  245. return gatewayComp, nil
  246. }
  247. func (r *EndpointResolver) resolveExternalModelEndpoint(ctx context.Context, stack *v1alpha1.Stack, name string) (client.Object, string, error) {
  248. var model v1alpha1.ExternalModel
  249. if err := r.client.Get(ctx, client.ObjectKey{Namespace: r.namespace, Name: name}, &model); err != nil {
  250. return nil, "", fmt.Errorf("Failed to get ExternalModel %s: %w", name, err)
  251. }
  252. gatewayComp, err := r.resolveGatewayEndpoint(ctx, stack)
  253. if err != nil {
  254. return nil, "", fmt.Errorf("Failed to resolve gateway endpoint for ExternalModel %s: %w", name, err)
  255. }
  256. if gatewayComp != nil {
  257. return &model, gatewayComp.Status.Endpoint, nil
  258. }
  259. return &model, model.Spec.APIBase, nil
  260. }
  261. func (r *EndpointResolver) resolveManagedModelEndpoint(ctx context.Context, stack *v1alpha1.Stack, name string) (client.Object, string, error) {
  262. var model v1alpha1.ManagedModel
  263. if err := r.client.Get(ctx, client.ObjectKey{Namespace: r.namespace, Name: name}, &model); err != nil {
  264. return nil, "", fmt.Errorf("Failed to get ManagedModel %s: %w", name, err)
  265. }
  266. gatewayComp, err := r.resolveGatewayEndpoint(ctx, stack)
  267. if err != nil {
  268. return nil, "", fmt.Errorf("Failed to resolve gateway endpoint for ManagedModel %s: %w", name, err)
  269. }
  270. if gatewayComp != nil {
  271. return &model, gatewayComp.Status.Endpoint + "/v1", nil
  272. }
  273. return &model, model.Status.Endpoint, nil
  274. }
  275. func (r *EndpointResolver) resolveExternalToolEndpoint(ctx context.Context, stack *v1alpha1.Stack, name string) (client.Object, string, error) {
  276. var tool v1alpha1.ExternalTool
  277. if err := r.client.Get(ctx, client.ObjectKey{Namespace: r.namespace, Name: name}, &tool); err != nil {
  278. return nil, "", fmt.Errorf("Failed to get ExternalTool %s: %w", name, err)
  279. }
  280. gatewayComp, err := r.resolveGatewayEndpoint(ctx, stack)
  281. if err != nil {
  282. return nil, "", fmt.Errorf("Failed to resolve gateway endpoint for ExternalTool %s: %w", name, err)
  283. }
  284. if gatewayComp != nil {
  285. return &tool, gatewayComp.Status.Endpoint + "/mcp", nil
  286. }
  287. return &tool, tool.Spec.Endpoint, nil
  288. }
  289. func (r *EndpointResolver) resolveManagedToolEndpoint(ctx context.Context, stack *v1alpha1.Stack, name string) (client.Object, string, error) {
  290. var tool v1alpha1.ManagedTool
  291. if err := r.client.Get(ctx, client.ObjectKey{Namespace: r.namespace, Name: name}, &tool); err != nil {
  292. return nil, "", fmt.Errorf("Failed to get ManagedTool %s: %w", name, err)
  293. }
  294. gatewayComp, err := r.resolveGatewayEndpoint(ctx, stack)
  295. if err != nil {
  296. return nil, "", fmt.Errorf("Failed to resolve gateway endpoint for ManagedTool %s: %w", name, err)
  297. }
  298. if gatewayComp != nil {
  299. return &tool, gatewayComp.Status.Endpoint, nil
  300. }
  301. return &tool, tool.Status.Endpoint, nil
  302. }
  303. func (r *EndpointResolver) resolveExternalKnowledgeBaseEndpoint(ctx context.Context, name string) (client.Object, string, error) {
  304. var kb v1alpha1.ExternalKnowledgeBase
  305. if err := r.client.Get(ctx, client.ObjectKey{Namespace: r.namespace, Name: name}, &kb); err != nil {
  306. return nil, "", fmt.Errorf("Failed to get ExternalKnowledgeBase %s: %w", name, err)
  307. }
  308. // TODO: use gateway endpoint
  309. return &kb, "", nil
  310. }
  311. func (r *EndpointResolver) resolveManagedKnowledgeBaseEndpoint(ctx context.Context, name string) (client.Object, string, error) {
  312. var kb v1alpha1.ManagedKnowledgeBase
  313. if err := r.client.Get(ctx, client.ObjectKey{Namespace: r.namespace, Name: name}, &kb); err != nil {
  314. return nil, "", fmt.Errorf("Failed to get ManagedKnowledgeBase %s: %w", name, err)
  315. }
  316. return &kb, kb.Status.Endpoint, nil
  317. }
  318. func (r *EndpointResolver) resolveComponentEndpoint(ctx context.Context, name string) (client.Object, string, error) {
  319. comp := &v1alpha1.Component{}
  320. if err := r.client.Get(ctx, client.ObjectKey{Namespace: r.namespace, Name: name}, comp); err != nil {
  321. return nil, "", fmt.Errorf("Failed to get Component %s: %w", name, err)
  322. }
  323. return comp, comp.Status.Endpoint, nil
  324. }
  325. func sortedKeys[V any](m map[string]V) []string {
  326. keys := make([]string, 0, len(m))
  327. for key := range m {
  328. keys = append(keys, key)
  329. }
  330. sort.Strings(keys)
  331. return keys
  332. }