github.com/kubewharf/katalyst-core@v0.5.3/pkg/util/service-discovery/interface.go (about)

     1  /*
     2  Copyright 2022 The Katalyst Authors.
     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  
    17  package service_discovery
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"sync"
    23  
    24  	katalystbase "github.com/kubewharf/katalyst-core/cmd/base"
    25  	"github.com/kubewharf/katalyst-core/pkg/config/generic"
    26  )
    27  
    28  // ServiceDiscoveryManager is used to discover all available endpoints.
    29  type ServiceDiscoveryManager interface {
    30  	Name() string
    31  	Run() error
    32  
    33  	// GetEndpoints get all endpoints list in the format `host:port`,
    34  	// different implementations may have each individual explanations
    35  	// for what the returned value represents for.
    36  	GetEndpoints() ([]string, error)
    37  }
    38  
    39  type InitFunc func(ctx context.Context, agentCtx *katalystbase.GenericContext,
    40  	conf *generic.ServiceDiscoveryConf) (ServiceDiscoveryManager, error)
    41  
    42  var sdManagerInitializers sync.Map
    43  
    44  func RegisterSDManagerInitializers(name string, initFunc InitFunc) {
    45  	sdManagerInitializers.Store(name, initFunc)
    46  }
    47  
    48  // GetSDManager return an implementation for ServiceDiscoveryManager based on the given parameters
    49  func GetSDManager(ctx context.Context, agentCtx *katalystbase.GenericContext,
    50  	conf *generic.ServiceDiscoveryConf,
    51  ) (ServiceDiscoveryManager, error) {
    52  	name := conf.Name
    53  	if len(name) == 0 {
    54  		name = ServiceDiscoveryPodSinglePort
    55  	}
    56  
    57  	val, ok := sdManagerInitializers.Load(name)
    58  	if !ok {
    59  		return DummyServiceDiscoveryManager{}, fmt.Errorf("failed to get sd-manager %v", name)
    60  	}
    61  	f, ok := val.(InitFunc)
    62  	if !ok {
    63  		return DummyServiceDiscoveryManager{}, fmt.Errorf("failed to init sd-manager %v", conf.Name)
    64  	}
    65  	return f(ctx, agentCtx, conf)
    66  }