Skip to content

Commit

Permalink
Refactor config handling to avoid race conditions
Browse files Browse the repository at this point in the history
  • Loading branch information
bahner committed Mar 17, 2024
1 parent 41c895b commit 9e8e244
Show file tree
Hide file tree
Showing 13 changed files with 89 additions and 36 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,6 @@ go-ma-*
releases
*.tar
go.work
actor
pong
relay
13 changes: 11 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ ARM64=android-arm64 darwin-arm64 netbsd-arm64 openbsd-arm64
ALL = $(FETCH) $(KEYSET) $(NAME) $(DEBUG)
BINDIR = $(PREFIX)/bin
RELEASES = releases
CMDS = actor relay pong

ifneq (,$(wildcard ./.env))
include .env
Expand All @@ -39,8 +40,8 @@ local: clean tidy install
$(BINDIR):
test -d $(BINDIR)

install: $(BINDIR) $(NAME)
sudo install -m755 -T $(NAME) $(DESTDIR)$(BINDIR)/ma
install: $(BINDIR) $(CMDS)
sudo install -m755 $(CMDS) $(DESTDIR)$(BINDIR)/

$(DEBUG): BUILDFLAGS = -tags=debug
$(DEBUG): tidy
Expand Down Expand Up @@ -78,6 +79,14 @@ release: VERSION = $(shell ./.version)
release: clean $(RELEASES) $(PLATFORMS)
git tag -a $(VERSION) -m "Release $(VERSION)"

actor: tidy
$(GO) build $(BUILDFLAGS) ./cmd/actor

pong: tidy
$(GO) build $(BUILDFLAGS) ./cmd/pong

relay: tidy
$(GO) build $(BUILDFLAGS) ./cmd/relay

$(RELEASES):
mkdir -p $(RELEASES)
Expand Down
17 changes: 16 additions & 1 deletion cmd/actor/config.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package main

import (
"errors"
"os"

"github.com/bahner/go-ma-actor/config"
"github.com/bahner/go-ma/did/doc"
log "github.com/sirupsen/logrus"
"github.com/spf13/pflag"
)
Expand All @@ -20,12 +22,13 @@ func initConfig() {
// Reinit logging to STDOUT
log.SetOutput(os.Stdout)
log.Info("Generating new actor and node identity")
actor, node := config.GenerateActorIdentitiesOrPanic()
actor, node := generateActorIdentitiesOrPanic(config.Profile())
actorConfig := configTemplate(actor, node)
config.Generate(actorConfig)
os.Exit(0)
}

// At this point an actor *must* be initialized
config.InitActor()

// This flag is dependent on the actor to be initialized to make sense.
Expand All @@ -35,3 +38,15 @@ func initConfig() {
}

}

func generateActorIdentitiesOrPanic(name string) (string, string) {
actor, node, err := config.GenerateActorIdentities(name)
if err != nil {
if errors.Is(err, doc.ErrAlreadyPublished) {
log.Warnf("Actor document already published: %v", err)
} else {
log.Fatal(err)
}
}
return actor, node
}
10 changes: 5 additions & 5 deletions cmd/create_keyset/create_keyset.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,35 +26,35 @@ func main() {
flag.Parse()
_level, err := log.ParseLevel(*logLevel)
if err != nil {
panic(err)
log.Fatal(err)
}
log.SetLevel(_level)
log.Debugf("main: log level set to %v", _level)

// Create a new keyset for the entity
keyset, err := keyset.GetOrCreate(*name)
if err != nil {
panic(err)
log.Fatal(err)
}
log.Debugf("main: keyset: %v", keyset)

if *publish {
d, err := doc.NewFromKeyset(keyset)
if err != nil {
panic(err)
log.Fatal(err)
}

c, err := d.Publish()
if err != nil {
panic(err)
log.Fatal(err)
}

log.Debugf("main: published document: %v to %v", d, c)
}

packedKeyset, err := keyset.Pack()
if err != nil {
panic(err)
log.Fatal(err)
}
fmt.Println(packedKeyset)

Expand Down
2 changes: 1 addition & 1 deletion cmd/fetch_document/fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func main() {
flag.Parse()
_level, err := log.ParseLevel(*logLevel)
if err != nil {
panic(err)
log.Fatal(err)
}
log.SetLevel(_level)
log.Debugf("main: log level set to %v", _level)
Expand Down
16 changes: 15 additions & 1 deletion cmd/pong/config.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package main

import (
"errors"
"os"

"github.com/bahner/go-ma-actor/config"
"github.com/bahner/go-ma/did/doc"
log "github.com/sirupsen/logrus"
"github.com/spf13/pflag"
"github.com/spf13/viper"
Expand Down Expand Up @@ -54,7 +56,7 @@ func initConfig(profile string) {
// Reinit logging to STDOUT
log.SetOutput(os.Stdout)
log.Info("Generating new actor and node identity")
actor, node := config.GenerateActorIdentitiesOrPanic()
actor, node := generateActorIdentitiesOrPanic(pong)
actorConfig := configTemplate(actor, node)
config.Generate(actorConfig)
os.Exit(0)
Expand All @@ -69,3 +71,15 @@ func initConfig(profile string) {
}

}

func generateActorIdentitiesOrPanic(name string) (string, string) {
actor, node, err := config.GenerateActorIdentities(name)
if err != nil {
if errors.Is(err, doc.ErrAlreadyPublished) {
log.Warnf("Actor document already published: %v", err)
} else {
log.Fatal(err)
}
}
return actor, node
}
13 changes: 11 additions & 2 deletions config/actor.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ const (
)

var (
defaultNick string = os.Getenv("USER")
keyset set.Keyset
ErrEmptyIdentity = fmt.Errorf("identity is empty")
ErrFakeIdentity = fmt.Errorf("your identity is fake. You need to define actorKeyset or generate a new one")
Expand All @@ -33,10 +32,20 @@ func InitActorFlags() {
viper.BindPFlag("actor.location", pflag.Lookup("location"))

viper.SetDefault("actor.location", defaultLocation)
viper.SetDefault("actor.nick", defaultNick)
viper.SetDefault("actor.nick", defaultNick())

}

// Set the default nick to the user's username, unless a profile is set.
func defaultNick() string {

if Profile() == defaultProfile {
return os.Getenv("USER")
}

return Profile()
}

// 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() {
Expand Down
8 changes: 4 additions & 4 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func Init() error {
// Make sure the XDG directories exist before we start writing to them.
err = createXDGDirectories()
if err != nil {
panic(err)
log.Fatal(err)
}

return nil
Expand All @@ -95,7 +95,7 @@ func Print() (int, error) {

configYAML, err := yaml.Marshal(configMap)
if err != nil {
panic(err)
log.Fatal(err)
}

fmt.Println("# " + ActorKeyset().DID.Id)
Expand Down Expand Up @@ -129,14 +129,14 @@ func File() string {

config, err := pflag.CommandLine.GetString("config")
if err != nil {
panic(err)
log.Fatal(err)
}

// Prefer explicitly requested config. If not, use the name of the profile name.
if config != defaultConfigFile && config != "" {
filename, err = homedir.Expand(config)
if err != nil {
panic(err)
log.Fatal(err)
}
} else {
filename = configHome + Profile() + ".yaml"
Expand Down
33 changes: 16 additions & 17 deletions config/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func Generate(configMap map[string]interface{}) {
// Convert the config map to YAML
configYAML, err := yaml.Marshal(configMap)
if err != nil {
panic(err)
log.Fatalf("Failed to marshal config to YAML: %v", err)
}

if GenerateFlag() {
Expand Down Expand Up @@ -54,51 +54,50 @@ func writeGeneratedConfigFile(content []byte) {
} else {
errMsg = fmt.Sprintf("Failed to open file: %v", err)
}
panic(errMsg)
log.Fatalf(errMsg)
}
defer file.Close()

// Write content to file.
if _, err := file.Write(content); err != nil {
panic(fmt.Sprintf("Failed to write to file: %v", err))
log.Fatalf("Failed to write to file: %v", err)
}

log.Printf("Generated config file %s", filePath)
}

// Genreates a libp2p and actor identity and returns the keyset and the actor identity
// These are imperative, so failure to generate them is a fatal error.
func GenerateActorIdentitiesOrPanic() (string, string) {
func GenerateActorIdentities(name string) (string, string, error) {

keyset_string, err := GenerateActorIdentity()
keyset_string, err := GenerateActorIdentity(name)
if err != nil {
panic(err)
return "", "", fmt.Errorf("failed to generate actor identity: %w", err)
}

ni, err := GenerateNodeIdentity()
if err != nil {
panic(err)
return "", "", fmt.Errorf("failed to generate node identity: %w", err)
}

return keyset_string, ni
return keyset_string, ni, nil
}
func GenerateActorIdentity() (string, error) {
func GenerateActorIdentity(nick string) (string, error) {

// Generate a new keysets if requested
nick := ActorNick()
log.Debugf("Generating new keyset for %s", nick)
keyset_string, err := generateKeysetString(nick)
if err != nil {
log.Errorf("handleGenerateOrExit: %v", err)
return "", err
log.Errorf("Failed to generate new keyset: %s", err)
return "", fmt.Errorf("failed to generate new keyset: %w", err)
}

if PublishFlag() {
err = publishActorIdentityFromString(keyset_string)
if err != nil {
log.Warnf("handleGenerateOrExit: %v", err)
return "", err

for err != nil {
return "", fmt.Errorf("failed to publish actor identity: %w", err)
}

}

return keyset_string, nil
Expand Down Expand Up @@ -154,7 +153,7 @@ func publishActorIdentityFromString(keyset_string string) error {

err = PublishIdentityFromKeyset(keyset)
if err != nil {
return fmt.Errorf("publishActorIdentityFromString: Failed to publish keyset: %v", err)
return fmt.Errorf("publishActorIdentityFromString: Failed to publish keyset: %w", err)
}

return nil
Expand Down
2 changes: 1 addition & 1 deletion config/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const (
logFilePerm os.FileMode = 0640
)

var defaultLogfile string = NormalisePath(dataHome + defaultNick + ".log")
var defaultLogfile string = NormalisePath(dataHome + Profile() + ".log")

func InitLogFlags() {

Expand Down
2 changes: 1 addition & 1 deletion config/publish.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ func PublishIdentityFromKeyset(k set.Keyset) error {

d, err := doc.NewFromKeyset(k)
if err != nil {
return fmt.Errorf("config.publishIdentityFromKeyset: failed to create DOC: %v", err)
return fmt.Errorf("config.publishIdentityFromKeyset: failed to create DOC: %w", err)
}

assertionMethod, err := d.GetAssertionMethod()
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ go 1.22

require (
github.com/adrg/xdg v0.4.0
github.com/bahner/go-ma v0.7.5
github.com/bahner/go-ma v0.7.6-0.20240317212356-a93a3105fcf2
github.com/gdamore/tcell/v2 v2.7.4
github.com/ipfs/boxo v0.18.0
github.com/libp2p/go-libp2p v0.32.2
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ github.com/aliyun/credentials-go v1.1.2/go.mod h1:ozcZaMR5kLM7pwtCMEpVmQ242suV6q
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c=
github.com/bahner/go-ma v0.7.5 h1:m6Q1R/qPhVOIzc2IA+B2cbXiQfZMIAFaLGNgKZ9RHXo=
github.com/bahner/go-ma v0.7.5/go.mod h1:IgMPcdPzH1GkP5mMz2PhJh8831hGi4TzhYbOV8UFzZ0=
github.com/bahner/go-ma v0.7.6-0.20240317205324-524cb616bc19 h1:3vKhTBj60I8rtCa61xrdsUp8pvOq0Eq9yrhjqM9oyQs=
github.com/bahner/go-ma v0.7.6-0.20240317205324-524cb616bc19/go.mod h1:IgMPcdPzH1GkP5mMz2PhJh8831hGi4TzhYbOV8UFzZ0=
github.com/bahner/go-ma v0.7.6-0.20240317212356-a93a3105fcf2 h1:x16IMBvjaN9uafXPZEhnHUtchax94P+fx++ucXu+m3g=
github.com/bahner/go-ma v0.7.6-0.20240317212356-a93a3105fcf2/go.mod h1:IgMPcdPzH1GkP5mMz2PhJh8831hGi4TzhYbOV8UFzZ0=
github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/benbjohnson/clock v1.3.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/benbjohnson/clock v1.3.5 h1:VvXlSJBzZpA/zum6Sj74hxwYI2DIxRWuNIoXAzHZz5o=
Expand Down

0 comments on commit 9e8e244

Please sign in to comment.