Skip to content

Commit

Permalink
Fix use of environment variables
Browse files Browse the repository at this point in the history
  • Loading branch information
bahner committed Mar 3, 2024
1 parent 4b02d78 commit 3ea48ef
Show file tree
Hide file tree
Showing 24 changed files with 435 additions and 252 deletions.
23 changes: 15 additions & 8 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/actor/main.go",
"program": "${workspaceFolder}/cmd/actor/",
"console": "integratedTerminal",
"env": {
"GOLOG_FILE": "debug.log",
Expand All @@ -38,32 +38,39 @@
"args": [
"--generate",
"--nick",
"bahner",
"--publish"
"FUBAR",
]
},
{
"name": "Launch Foo",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/actor/main.go",
"program": "${workspaceFolder}/cmd/actor/",
"args": [
"-c",
"~/.ma/foo.yaml"
],
"console": "integratedTerminal"
},
{
"name": "Show config",
"name": "show-config",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/cmd/actor/main.go",
"program": "${workspaceFolder}/cmd/actor/",
"console": "integratedTerminal",
"args": [
"--show_config",
"--show-config"
],
"console": "integratedTerminal"
"env": {
"GO_MA_ACTOR_ACTOR_NICK": "jonatan",
"GO_MA_ACTOR_LOG_FILE": "/dev/null",
"GOLOG_FILE": "debug.log",
"GOLOG_LOG_LEVEL": "debug",
"GOLOG_STDOUT": "false",
"GOLOG_OUTPUT": "file"
}
}

]
Expand Down
6 changes: 3 additions & 3 deletions cmd/actor/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,11 @@ func startWebServer(p *p2p.P2P, a *actor.Actor) {
mux.HandleFunc("/", h.WebHandler)
}

log.Infof("Listening on %s", config.GetHttpSocket())
log.Infof("Listening on %s", config.HttpSocket())

// IN relay mode we want to stop here.
fmt.Print("Web server starting on http://" + config.GetHttpSocket() + "/")
err := http.ListenAndServe(config.GetHttpSocket(), mux)
fmt.Print("Web server starting on http://" + config.HttpSocket() + "/")
err := http.ListenAndServe(config.HttpSocket(), mux)
if err != nil {
log.Fatalf("Web server failed: %v", err)
}
Expand Down
80 changes: 60 additions & 20 deletions config/actor.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,37 +14,41 @@ import (
)

const (
defaultActor string = "actor"
defaultActor string = "actor"
defaultLocation string = "did:ma:k2k4r8kzkhamrqz9m5yy0tihj1fso3t6znnuidu00dbtnh3plazatrfw#pong"
fakeActorIdentity string = "NO_DEFAULT_ACTOR_IDENITY"
)

var keyset set.Keyset
var (
keyset set.Keyset
ErrEmptyIdentity = fmt.Errorf("config: Identity is empty")
ErrFakeIdentity = fmt.Errorf("config: Your identity is fake. You need to define actorKeyset or generate a new one")
)

func init() {
// Keyset
pflag.BoolP("generate", "g", false, "Generates a new keyset")

pflag.BoolP("publish", "p", false, "Publishes keyset to IPFS")

// Nick used for keyset generation (fragment)
pflag.StringP("nick", "n", defaultActor, "Nickname to use in character creation")
viper.BindPFlag("actor.nick", pflag.Lookup("nick"))

pflag.StringP("location", "l", "", "DID of the initial location.")
viper.BindPFlag("actor.home", pflag.Lookup("home"))
pflag.StringP("location", "l", defaultLocation, "DID of the location to visit")

}

// Load a keyset from string and initiate an Actor.
// This is optional, but if you want to use the actor package, you need to call this.
func InitActor() {

keyset_string := viper.GetString("actor.identity")
viper.BindPFlag("actor.location", pflag.Lookup("location"))
viper.SetDefault("actor.location", defaultLocation)

keyset_string := ActorIdentity()
if keyset_string == fakeActorIdentity {
log.Fatalf(ErrFakeIdentity.Error())
}

log.Debugf("config.initActor: %s", keyset_string)
// Create the actor keyset
if keyset_string == "" {
log.Errorf("config.initActor: You need to define actorKeyset or generate a new one.")
os.Exit(64) // EX_USAGE
log.Fatalf(ErrEmptyIdentity.Error())
}

// This function fails fatally, so no return value
Expand All @@ -61,16 +65,52 @@ func InitActor() {

}

// Fetches the actor nick from the config or the command line
// NB! This is a little more complex than the other config functions, as it
// needs to fetch the nick from the command line if it's not in the config.
// Due to being a required parameter when generating a new keyset.
func ActorNick() string {
return viper.GetString("actor.nick")

var err error
nick := viper.GetString("actor.nick")

if nick == "" {
nick, err = pflag.CommandLine.GetString("nick")
if err != nil {
log.Warnf("config.ActorNick: %v", err)
return defaultActor
}
}

return nick
}

func ActorHome() string {
return viper.GetString("actor.home")
func ActorLocation() string {

var err error
e := viper.GetString("actor.location")

if e == "" {
e, err = pflag.CommandLine.GetString("location")
if err != nil {
log.Warnf("config.ActorEntity: %v", err)
return defaultActor
}
}

return e
}

func ActorDid() string {
return viper.GetString("actor.did")
func ActorIdentity() string {

e := viper.GetString("actor.identity")

if e == "" {
log.Warnf("config.ActorIdentity: No identity set.")
return fakeActorIdentity
}

return e
}

func ActorKeyset() set.Keyset {
Expand All @@ -82,8 +122,8 @@ func ActorKeyset() set.Keyset {
func handleGenerateOrExit() (string, string) {

// Generate a new keysets if requested
nick := viper.GetString("actor.nick")

nick := ActorNick()
log.Debugf("Generating new keyset for %s", nick)
keyset_string, err := generateKeysetString(nick)
if err != nil {
log.Errorf("config.handleGenerateOrExit: %v", err)
Expand Down
85 changes: 58 additions & 27 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"

"github.com/adrg/xdg"
"github.com/bahner/go-ma"
Expand All @@ -15,11 +16,9 @@ import (
)

const (
NAME string = "go-ma-actor"
VERSION string = "v0.2.3"
ENV_PREFIX string = "GO_MA_ACTOR"
fakeActorIdentity string = "NO_DEFAULT_ACTOR_IDENITY"
fakeNodeIdentity string = "NO_DEFAULT_NODE_IDENITY"
NAME string = "go-ma-actor"
VERSION string = "v0.2.3"
ENV_PREFIX string = "GO_MA_ACTOR"

configFileMode os.FileMode = 0600
configDirMode os.FileMode = 0700
Expand All @@ -35,15 +34,6 @@ var (

func init() {

// Look in the current directory, the home directory and /etc for the config file.
// In that order.
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.AddConfigPath(configHome)

viper.SetEnvPrefix(ENV_PREFIX)
viper.AutomaticEnv()

// Allow to set config file via command line flag.
pflag.StringVarP(&config, "config", "c", defaultConfigFile, "Config file to use.")

Expand All @@ -58,49 +48,90 @@ func init() {
// The name parameter is the name of the config file to search for without the extension.
func Init(mode string) error {

// Read the config file and environment variables.
viper.SetEnvPrefix(ENV_PREFIX)
viper.AutomaticEnv()

// Handle nested values in environment variables.
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)

// We need the nick to be set before we can generate the config file correctly.
viper.BindPFlag("actor.nick", pflag.Lookup("nick"))

// Handle the easy flags first.
if versionFlag() {
fmt.Println(VERSION)
os.Exit(0)
}

if showDefaultsFlag() {
// Print the YAML to stdout or write it to a template file
generateConfigFile(fakeActorIdentity, fakeNodeIdentity)
generateActorConfigFile(fakeActorIdentity, fakeP2PIdentity)
os.Exit(0)
}

// Now we need logging to be set up, so we can see what's going on.
InitLogging()

// Make sure the XDG directories exist before we start writing to them.
err := createXDGDirectories()
if err != nil {
log.Fatalf("config.init: %v", err)
}

// These values initialised here are required for the generation of the config file.
InitP2P()
InitHttp()

if generateFlag() {
log.Info("Generating new keyset and node identity")
actor, node := handleGenerateOrExit()
generateConfigFile(actor, node)

// Reinit logging to STDOUT
viper.Set("log.file", "STDOUT")
InitLogging()

switch Mode() {
case "actor":
log.Info("Generating new actor and node identity")
actor, node := handleGenerateOrExit()
generateActorConfigFile(actor, node)
case "pong":
viper.Set("actor.nick", "pong")
log.Info("Generating new pong actor and node identity")
actor, node := handleGenerateOrExit()
generatePongConfigFile(actor, node)
case "relay":
viper.Set("actor.nick", "relay")
log.Info("Generating new relay node identity")
_, node := handleGenerateOrExit()
generateRelayConfigFile(node)
}
os.Exit(0)
}

// Look in the current directory, the home directory and /etc for the config file.
// In that order.
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.AddConfigPath(configHome)

// We *must* read the config file after we have generated the identity.
// Otherwise: Unforeseen consequences.
log.Infof("Using config file: %s", configFile())
viper.SetConfigFile(configFile())
err = viper.ReadInConfig()
if err != nil {
log.Fatalf("No config file found: %s", err)
log.Warnf("No config file found: %s", err)
}

if showConfigFlag() {
Print()
os.Exit(0)
}

InitLogging()
InitP2P()

if !RelayMode() {
InitActor()
}

if showConfigFlag() {
Print()
os.Exit(0)
}
return nil

}
Expand Down
8 changes: 4 additions & 4 deletions config/db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,20 @@ var (
func init() {

pflag.String("db-file", defaultDbFile, "File to *write* node peers and entities to. If the file does not exist, it will be created.")
viper.BindPFlag("db.file", pflag.Lookup("db-file"))
viper.SetDefault("db.file", defaultDbFile)

pflag.Int("db-timeout", defaultDbTimeout, "Timeout for serialized access to the database in milliseconds.")
viper.BindPFlag("db.timeout", pflag.Lookup("db-timeout"))
viper.SetDefault("db.timeout", defaultDbTimeout)
}

// Initiates the database connection and creates the tables if they do not exist
func Init() (*sql.DB, error) {

viper.BindPFlag("db.file", pflag.Lookup("db-file"))
viper.BindPFlag("db.timeout", pflag.Lookup("db-timeout"))

var onceErr error

once.Do(func() {

var err error
f, err := dbfile()
if err != nil {
Expand Down
Loading

0 comments on commit 3ea48ef

Please sign in to comment.