mirror of
https://github.com/hanzoai/ai.git
synced 2026-11-20 14:13:23 +00:00
The Go-Linter job runs only after go-tests passes, and go-tests has been red on main, so gofumpt has not actually checked this tree in a while. With the boot panic fixed the job ran again and found eight files whose imports sit in the wrong group — five in cluster, three in object, one of them arriving with the ZAP telemetry change. gofumpt -w, nothing else. Every changed line is identical on both sides of the diff; only the grouping moved. Build is clean and object's tests pass. Co-authored-by: Hanzo Dev <[email protected]>
267 lines
8.2 KiB
Go
267 lines
8.2 KiB
Go
// Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.
|
|
// Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.
|
|
//
|
|
// 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 cluster
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/hanzoai/ai/object"
|
|
|
|
"github.com/hanzoai/ai/i18n"
|
|
"k8s.io/apimachinery/pkg/api/errors"
|
|
"k8s.io/apimachinery/pkg/api/meta"
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
|
"k8s.io/apimachinery/pkg/runtime/schema"
|
|
"k8s.io/apimachinery/pkg/util/yaml"
|
|
"k8s.io/client-go/discovery"
|
|
"k8s.io/client-go/dynamic"
|
|
"k8s.io/client-go/kubernetes"
|
|
"k8s.io/client-go/rest"
|
|
"k8s.io/client-go/restmapper"
|
|
"k8s.io/client-go/tools/clientcmd"
|
|
)
|
|
|
|
type Client struct {
|
|
clientSet *kubernetes.Clientset
|
|
dynamicClient dynamic.Interface
|
|
restMapper meta.RESTMapper
|
|
config *rest.Config
|
|
connected bool
|
|
configText string
|
|
}
|
|
|
|
var (
|
|
client *Client
|
|
clientMutex sync.Mutex
|
|
)
|
|
|
|
func init() {
|
|
client = nil
|
|
}
|
|
|
|
// Create K8s client from provider's ConfigText
|
|
func clientFromProvider(provider *object.Provider, lang string) (*Client, error) {
|
|
if provider.ConfigText == "" {
|
|
return nil, fmt.Errorf("%s", i18n.Translate(lang, "object:provider kubeconfig content is empty"))
|
|
}
|
|
// Parse kubeconfig from provider.ConfigText
|
|
config, err := clientcmd.RESTConfigFromKubeConfig([]byte(provider.ConfigText))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to parse kubeconfig from provider: %v"), err))
|
|
}
|
|
return newClient(config, provider.ConfigText, lang)
|
|
}
|
|
|
|
func newClient(config *rest.Config, configText string, lang string) (*Client, error) {
|
|
config.Timeout = 30 * time.Second // Default timeout
|
|
clientset, err := kubernetes.NewForConfig(config)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to create kubernetes clientSet: %v"), err))
|
|
}
|
|
dynamicClient, err := dynamic.NewForConfig(config)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to create dynamic client: %v"), err))
|
|
}
|
|
discoveryClient, err := discovery.NewDiscoveryClientForConfig(config)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to create discovery client: %v"), err))
|
|
}
|
|
groupResources, err := restmapper.GetAPIGroupResources(discoveryClient)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to get API group resources: %v"), err))
|
|
}
|
|
restMapper := restmapper.NewDiscoveryRESTMapper(groupResources)
|
|
client := &Client{
|
|
clientSet: clientset,
|
|
dynamicClient: dynamicClient,
|
|
restMapper: restMapper,
|
|
config: config,
|
|
connected: false,
|
|
configText: configText,
|
|
}
|
|
if err := client.testConnection(); err != nil {
|
|
return nil, fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to connect to kubernetes cluster: %v"), err))
|
|
}
|
|
client.connected = true
|
|
return client, nil
|
|
}
|
|
|
|
func (k *Client) testConnection() error {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
_, err := k.clientSet.CoreV1().Namespaces().List(ctx, metav1.ListOptions{Limit: 1})
|
|
return err
|
|
}
|
|
|
|
// Ensure k8s client is initialized, try to initialize if not
|
|
func ensure(lang string) error {
|
|
// Quick check if client is already ready
|
|
if client != nil && client.connected {
|
|
return nil
|
|
}
|
|
clientMutex.Lock()
|
|
defer clientMutex.Unlock()
|
|
if client != nil && client.connected {
|
|
return nil
|
|
}
|
|
provider, err := object.GetDefaultKubernetesProvider(lang)
|
|
if err != nil {
|
|
return fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to get default Kubernetes provider: %v"), err))
|
|
}
|
|
// Only recreate if config changed or client doesn't exist
|
|
if client == nil || client.configText != provider.ConfigText {
|
|
if mirror != nil {
|
|
mirror.Stop()
|
|
mirror = nil
|
|
}
|
|
c, err := clientFromProvider(provider, lang)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
client = c
|
|
host, parseErr := parseHost(provider.ConfigText, lang)
|
|
if parseErr != nil {
|
|
cachedHost = ""
|
|
} else {
|
|
cachedHost = host
|
|
}
|
|
// Initialize cache manager
|
|
if err := initMirror(); err != nil {
|
|
return fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to initialize cache manager: %v"), err))
|
|
}
|
|
if err := startMirror(lang); err != nil {
|
|
return fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to start cache manager: %v"), err))
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func Status(lang string) (string, error) {
|
|
if err := ensure(lang); err != nil {
|
|
return "Disconnected", err
|
|
}
|
|
err := client.testConnection()
|
|
if err != nil {
|
|
client.connected = false
|
|
return "Disconnected", err
|
|
}
|
|
client.connected = true
|
|
return "Connected", nil
|
|
}
|
|
|
|
func (k *Client) createNamespaceIfNotExists(name string) error {
|
|
_, err := k.clientSet.CoreV1().Namespaces().Get(
|
|
context.TODO(),
|
|
name,
|
|
metav1.GetOptions{},
|
|
)
|
|
if err != nil {
|
|
if errors.IsNotFound(err) {
|
|
// Create namespace
|
|
namespace := &unstructured.Unstructured{
|
|
Object: map[string]interface{}{
|
|
"apiVersion": "v1",
|
|
"kind": "Namespace",
|
|
"metadata": map[string]interface{}{
|
|
"name": name,
|
|
"labels": map[string]interface{}{
|
|
"managed-by": "hanzo-cloud",
|
|
},
|
|
},
|
|
},
|
|
}
|
|
gvr := schema.GroupVersionResource{
|
|
Group: "",
|
|
Version: "v1",
|
|
Resource: "namespaces",
|
|
}
|
|
_, err = k.dynamicClient.Resource(gvr).Create(
|
|
context.TODO(),
|
|
namespace,
|
|
metav1.CreateOptions{},
|
|
)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (k *Client) deployResource(yamlContent, namespace string, lang string) error {
|
|
// Parse YAML to unstructured object
|
|
decoder := yaml.NewYAMLToJSONDecoder(strings.NewReader(yamlContent))
|
|
var obj unstructured.Unstructured
|
|
err := decoder.Decode(&obj)
|
|
if err != nil {
|
|
return fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to decode YAML: %v"), err))
|
|
}
|
|
// Skip empty objects
|
|
if obj.GetKind() == "" {
|
|
return nil
|
|
}
|
|
// Set namespace if not specified and resource is namespaced
|
|
if obj.GetNamespace() == "" && obj.GetKind() != "Namespace" {
|
|
obj.SetNamespace(namespace)
|
|
}
|
|
// Add labels for management
|
|
labels := obj.GetLabels()
|
|
if labels == nil {
|
|
labels = make(map[string]string)
|
|
}
|
|
labels["managed-by"] = "hanzo-cloud"
|
|
obj.SetLabels(labels)
|
|
// Get GVR for the resource
|
|
gvk := obj.GetObjectKind().GroupVersionKind()
|
|
mapping, err := k.restMapper.RESTMapping(gvk.GroupKind(), gvk.Version)
|
|
if err != nil {
|
|
return fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to get REST mapping for %s: %v"), gvk, err))
|
|
}
|
|
var dr dynamic.ResourceInterface
|
|
if mapping.Scope.Name() == meta.RESTScopeNameNamespace {
|
|
dr = k.dynamicClient.Resource(mapping.Resource).Namespace(obj.GetNamespace())
|
|
} else {
|
|
dr = k.dynamicClient.Resource(mapping.Resource)
|
|
}
|
|
// Try to get existing resource
|
|
existing, err := dr.Get(context.TODO(), obj.GetName(), metav1.GetOptions{})
|
|
if err != nil {
|
|
if errors.IsNotFound(err) {
|
|
// Create new resource
|
|
_, err = dr.Create(context.TODO(), &obj, metav1.CreateOptions{})
|
|
if err != nil {
|
|
return fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to create resource %s/%s: %v"), obj.GetKind(), obj.GetName(), err))
|
|
}
|
|
} else {
|
|
return fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to get existing resource %s/%s: %v"), obj.GetKind(), obj.GetName(), err))
|
|
}
|
|
} else {
|
|
// Update existing resource
|
|
obj.SetResourceVersion(existing.GetResourceVersion())
|
|
_, err = dr.Update(context.TODO(), &obj, metav1.UpdateOptions{})
|
|
if err != nil {
|
|
return fmt.Errorf("%s", fmt.Sprintf(i18n.Translate(lang, "object:failed to update resource %s/%s: %v"), obj.GetKind(), obj.GetName(), err))
|
|
}
|
|
}
|
|
return nil
|
|
}
|