package config import ( "context" "errors" "flag" "os" "path/filepath" "github.com/peterbourgon/ff/v3" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "k8s.io/client-go/util/homedir" "sigs.k8s.io/controller-runtime/pkg/client" "edge-infra.dev/pkg/lib/gcp/cloudsql" ) // Config represents configuration for the lighthouse system. type Config struct { WatchClient client.WithWatch DatabaseCfg *cloudsql.EdgePostgres ProjectID string TopicID string } // New returns a new system config instance. func New() *Config { return &Config{} } // Init fetches the environment variables and sets the db config fields func Init(ctx context.Context, cl client.WithWatch) (*Config, error) { s := New() fs := flag.NewFlagSet("lighthouse", flag.ContinueOnError) connectionName := "" user := "" name := "" fs.StringVar(&connectionName, "sql-connection-name", "", "SQL Connection Name") fs.StringVar(&user, "sql-user", "", "SQL Connection Username") fs.StringVar(&name, "sql-db-name", "", "SQL Connection Database Name") fs.StringVar(&s.ProjectID, "project-id", "", "GCP Project ID") fs.StringVar(&s.TopicID, "topic-id", "", "GCP Pubsub Topic") if err := ff.Parse(fs, os.Args[1:], ff.WithEnvVarNoPrefix()); err != nil { return nil, err } dbCfg, err := cloudsql.GCPPostgresConnection(connectionName).Username(user).DBName(name).AttachDialer(ctx) if err != nil { return nil, err } s.DatabaseCfg = dbCfg client := cl if cl == nil { client, err = InitWatchClient() if err != nil { return nil, err } } s.WatchClient = client return s, nil } // InitWatchClient creates a new kubernetes watch client. func InitWatchClient() (client.WithWatch, error) { config, err := rest.InClusterConfig() if errors.Is(err, rest.ErrNotInCluster) { config, err = clientcmd.BuildConfigFromFlags("", filepath.Join(homedir.HomeDir(), ".kube", "config")) if err != nil { return nil, err } } ctrlClient, err := client.NewWithWatch(config, client.Options{}) if err != nil { return nil, err } return ctrlClient, nil }