...

Source file src/edge-infra.dev/pkg/edge/lighthouse/config/config.go

Documentation: edge-infra.dev/pkg/edge/lighthouse/config

     1  package config
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"flag"
     7  	"os"
     8  	"path/filepath"
     9  
    10  	"github.com/peterbourgon/ff/v3"
    11  	"k8s.io/client-go/rest"
    12  	"k8s.io/client-go/tools/clientcmd"
    13  	"k8s.io/client-go/util/homedir"
    14  	"sigs.k8s.io/controller-runtime/pkg/client"
    15  
    16  	"edge-infra.dev/pkg/lib/gcp/cloudsql"
    17  )
    18  
    19  // Config represents configuration for the lighthouse system.
    20  type Config struct {
    21  	WatchClient client.WithWatch
    22  	DatabaseCfg *cloudsql.EdgePostgres
    23  	ProjectID   string
    24  	TopicID     string
    25  }
    26  
    27  // New returns a new system config instance.
    28  func New() *Config {
    29  	return &Config{}
    30  }
    31  
    32  // Init fetches the environment variables and sets the db config fields
    33  func Init(ctx context.Context, cl client.WithWatch) (*Config, error) {
    34  	s := New()
    35  	fs := flag.NewFlagSet("lighthouse", flag.ContinueOnError)
    36  	connectionName := ""
    37  	user := ""
    38  	name := ""
    39  	fs.StringVar(&connectionName, "sql-connection-name", "", "SQL Connection Name")
    40  	fs.StringVar(&user, "sql-user", "", "SQL Connection Username")
    41  	fs.StringVar(&name, "sql-db-name", "", "SQL Connection Database Name")
    42  	fs.StringVar(&s.ProjectID, "project-id", "", "GCP Project ID")
    43  	fs.StringVar(&s.TopicID, "topic-id", "", "GCP Pubsub Topic")
    44  	if err := ff.Parse(fs, os.Args[1:], ff.WithEnvVarNoPrefix()); err != nil {
    45  		return nil, err
    46  	}
    47  	dbCfg, err := cloudsql.GCPPostgresConnection(connectionName).Username(user).DBName(name).AttachDialer(ctx)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  	s.DatabaseCfg = dbCfg
    52  	client := cl
    53  	if cl == nil {
    54  		client, err = InitWatchClient()
    55  		if err != nil {
    56  			return nil, err
    57  		}
    58  	}
    59  	s.WatchClient = client
    60  	return s, nil
    61  }
    62  
    63  // InitWatchClient creates a new kubernetes watch client.
    64  func InitWatchClient() (client.WithWatch, error) {
    65  	config, err := rest.InClusterConfig()
    66  	if errors.Is(err, rest.ErrNotInCluster) {
    67  		config, err = clientcmd.BuildConfigFromFlags("", filepath.Join(homedir.HomeDir(), ".kube", "config"))
    68  		if err != nil {
    69  			return nil, err
    70  		}
    71  	}
    72  	ctrlClient, err := client.NewWithWatch(config, client.Options{})
    73  	if err != nil {
    74  		return nil, err
    75  	}
    76  	return ctrlClient, nil
    77  }
    78  

View as plain text