talos
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5package cluster6
7import (8"context"9"strings"10
11"github.com/siderolabs/talos/pkg/machinery/client"12clientconfig "github.com/siderolabs/talos/pkg/machinery/client/config"13)
14
15// ConfigClientProvider builds Talos client from client config.
16type ConfigClientProvider struct {17// DefaultClient to be used when using default endpoints.18//19// Not required, if missing client will be constructed from the config.20DefaultClient *client.Client21
22// TalosConfig is a client Talos configuration.23TalosConfig *clientconfig.Config24
25clients map[string]*client.Client26}
27
28// Client returns Talos client instance for default (if no endpoints are given) or
29// specific endpoints.
30//
31// Client implements ClientProvider interface.
32func (c *ConfigClientProvider) Client(endpoints ...string) (*client.Client, error) {33key := strings.Join(endpoints, ",")34
35if c.clients == nil {36c.clients = make(map[string]*client.Client)37}38
39if cli := c.clients[key]; cli != nil {40return cli, nil41}42
43if len(endpoints) == 0 && c.DefaultClient != nil {44return c.DefaultClient, nil45}46
47opts := []client.OptionFunc{48client.WithConfig(c.TalosConfig),49}50
51if len(endpoints) > 0 {52opts = append(opts, client.WithEndpoints(endpoints...))53}54
55return client.New(context.TODO(), opts...)56}
57
58// Close all the client connections.
59func (c *ConfigClientProvider) Close() error {60for _, cli := range c.clients {61if err := cli.Close(); err != nil {62return err63}64}65
66c.clients = nil67
68return nil69}
70