github.com/deemoprobe/k8s-first-commit@v0.0.0-20230430165612-a541f1982be3/pkg/registry/endpoints.go (about) 1 /* 2 Copyright 2014 Google Inc. All rights reserved. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 package registry 17 18 import ( 19 "fmt" 20 "log" 21 22 . "github.com/GoogleCloudPlatform/kubernetes/pkg/api" 23 ) 24 25 func MakeEndpointController(serviceRegistry ServiceRegistry, taskRegistry TaskRegistry) *EndpointController { 26 return &EndpointController{ 27 serviceRegistry: serviceRegistry, 28 taskRegistry: taskRegistry, 29 } 30 } 31 32 type EndpointController struct { 33 serviceRegistry ServiceRegistry 34 taskRegistry TaskRegistry 35 } 36 37 func (e *EndpointController) SyncServiceEndpoints() error { 38 services, err := e.serviceRegistry.ListServices() 39 if err != nil { 40 return err 41 } 42 var resultErr error 43 for _, service := range services.Items { 44 tasks, err := e.taskRegistry.ListTasks(&service.Labels) 45 if err != nil { 46 log.Printf("Error syncing service: %#v, skipping.", service) 47 resultErr = err 48 continue 49 } 50 endpoints := make([]string, len(tasks)) 51 for ix, task := range tasks { 52 // TODO: Use port names in the service object, don't just use port #0 53 endpoints[ix] = fmt.Sprintf("%s:%d", task.CurrentState.Host, task.DesiredState.Manifest.Containers[0].Ports[0].HostPort) 54 } 55 err = e.serviceRegistry.UpdateEndpoints(Endpoints{ 56 Name: service.ID, 57 Endpoints: endpoints, 58 }) 59 if err != nil { 60 log.Printf("Error updating endpoints: %#v", err) 61 continue 62 } 63 } 64 return resultErr 65 }