endpoints.go
1 // Copyright 2025 Alibaba Group Holding Ltd. 2 // 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 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package utils 16 17 import ( 18 "encoding/json" 19 "fmt" 20 21 sandboxv1alpha1 "github.com/alibaba/OpenSandbox/sandbox-k8s/apis/sandbox/v1alpha1" 22 ) 23 24 const ( 25 // AnnotationEndpoints is the annotation key for storing BatchSandbox endpoints 26 AnnotationEndpoints = "sandbox.opensandbox.io/endpoints" 27 ) 28 29 // GetEndpoints extracts endpoint IPs from BatchSandbox annotations 30 // Returns a slice of IP addresses parsed from the endpoints annotation 31 // The annotation format is a JSON array: ["10.244.1.5", "10.244.1.6"] 32 func GetEndpoints(bs *sandboxv1alpha1.BatchSandbox) ([]string, error) { 33 if bs == nil { 34 return nil, fmt.Errorf("BatchSandbox is nil") 35 } 36 37 if bs.Annotations == nil { 38 return nil, fmt.Errorf("BatchSandbox has no annotations") 39 } 40 41 endpointsAnnotation := bs.Annotations[AnnotationEndpoints] 42 if endpointsAnnotation == "" { 43 return nil, fmt.Errorf("missing %s annotation", AnnotationEndpoints) 44 } 45 46 var endpoints []string 47 if err := json.Unmarshal([]byte(endpointsAnnotation), &endpoints); err != nil { 48 return nil, fmt.Errorf("failed to parse endpoints annotation: %w", err) 49 } 50 51 if len(endpoints) == 0 { 52 return nil, fmt.Errorf("endpoints annotation contains no IPs") 53 } 54 55 return endpoints, nil 56 }