Skip to content

Commit 173438e

Browse files
authored
Merge pull request #103 from fystack/improve-logs-code-cleanup
Improve logs code cleanup
2 parents f7ece22 + 12312b6 commit 173438e

12 files changed

Lines changed: 158 additions & 68 deletions

File tree

.gitignore

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,4 +20,5 @@ node0
2020
node1
2121
node2
2222
config.yaml
23-
.vscode
23+
.vscode
24+
.vagrant

cmd/mpcium-cli/main.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,10 @@ func main() {
5151
Action: registerPeers,
5252
Flags: []cli.Flag{
5353
&cli.StringFlag{
54-
Name: "input",
55-
Aliases: []string{"i"},
56-
Usage: "Input peers JSON file path (default: peers.json)",
57-
Value: peersFileName,
54+
Name: "peers",
55+
Aliases: []string{"p"},
56+
Usage: "Path to peers.json file (defaults to ./peers.json)",
57+
Required: false,
5858
},
5959
&cli.StringFlag{
6060
Name: "environment",

cmd/mpcium-cli/register-peers.go

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,14 @@ import (
1515
)
1616

1717
func registerPeers(ctx context.Context, c *cli.Command) error {
18-
inputPath := c.String("input")
18+
inputPath := c.String("peers")
1919
environment := c.String("environment")
2020

21+
// If no peers path specified, check for peers.json in current directory
22+
if inputPath == "" {
23+
inputPath = "peers.json"
24+
}
25+
2126
// Hardcoded prefix for MPC peers in Consul
2227
prefix := "mpc_peers/"
2328

@@ -28,6 +33,9 @@ func registerPeers(ctx context.Context, c *cli.Command) error {
2833

2934
// Check if input file exists
3035
if _, err := os.Stat(inputPath); os.IsNotExist(err) {
36+
if inputPath == "peers.json" {
37+
return fmt.Errorf("peers.json not found in current directory. Please specify the path using --peers flag or create peers.json in the current directory")
38+
}
3139
return fmt.Errorf("input file %s does not exist", inputPath)
3240
}
3341

@@ -58,10 +66,26 @@ func registerPeers(ctx context.Context, c *cli.Command) error {
5866
// Register peers in Consul
5967
for nodeName, nodeID := range peerMap {
6068
key := prefix + nodeName
69+
70+
// Check if the key already exists
71+
existing, _, err := kv.Get(key, nil)
72+
if err != nil {
73+
return fmt.Errorf("failed to check existing key %s: %w", key, err)
74+
}
75+
76+
if existing != nil {
77+
existingID := string(existing.Value)
78+
if existingID != nodeID {
79+
return fmt.Errorf("conflict detected: peer %s already exists with ID %s, but trying to register with different ID %s", nodeName, existingID, nodeID)
80+
}
81+
fmt.Printf("Peer %s already registered with same ID %s, skipping\n", nodeName, nodeID)
82+
continue
83+
}
84+
6185
p := &api.KVPair{Key: key, Value: []byte(nodeID)}
6286

6387
// Store the key-value pair
64-
_, err := kv.Put(p, nil)
88+
_, err = kv.Put(p, nil)
6589
if err != nil {
6690
return fmt.Errorf("failed to store key %s: %w", key, err)
6791
}

cmd/mpcium/main.go

Lines changed: 20 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,9 @@ func runNode(ctx context.Context, c *cli.Command) error {
113113

114114
viper.SetDefault("backup_enabled", true)
115115
config.InitViperConfig(configPath)
116-
environment := viper.GetString("environment")
116+
117+
appConfig := config.LoadConfig()
118+
environment := appConfig.Environment
117119
logger.Init(environment, debug)
118120

119121
// Handle password file if provided
@@ -127,15 +129,15 @@ func runNode(ctx context.Context, c *cli.Command) error {
127129
promptForSensitiveCredentials()
128130
} else {
129131
// Validate the config values
130-
checkRequiredConfigValues()
132+
checkRequiredConfigValues(appConfig)
131133
}
132134

133135
consulClient := infra.GetConsulClient(environment)
134136
keyinfoStore := keyinfo.NewStore(consulClient.KV())
135137
peers := LoadPeersFromConsul(consulClient)
136138
nodeID := GetIDFromName(nodeName, peers)
137139

138-
badgerKV := NewBadgerKV(nodeName, nodeID)
140+
badgerKV := NewBadgerKV(nodeName, nodeID, appConfig)
139141
defer badgerKV.Close()
140142

141143
// Start background backup job
@@ -151,7 +153,7 @@ func runNode(ctx context.Context, c *cli.Command) error {
151153
logger.Fatal("Failed to create identity store", err)
152154
}
153155

154-
natsConn, err := GetNATSConnection(environment)
156+
natsConn, err := GetNATSConnection(environment, appConfig)
155157
if err != nil {
156158
logger.Fatal("Failed to connect to NATS", err)
157159
}
@@ -388,9 +390,9 @@ func maskString(s string) string {
388390
}
389391

390392
// Check required configuration values are present
391-
func checkRequiredConfigValues() {
393+
func checkRequiredConfigValues(appConfig *config.AppConfig) {
392394
// Show warning if we're using file-based config but no password is set
393-
if viper.GetString("badger_password") == "" {
395+
if appConfig.BadgerPassword == "" {
394396
logger.Fatal("Badger password is required", nil)
395397
}
396398

@@ -441,7 +443,7 @@ func GetIDFromName(name string, peers []config.Peer) string {
441443
return nodeID
442444
}
443445

444-
func NewBadgerKV(nodeName, nodeID string) *kvstore.BadgerKVStore {
446+
func NewBadgerKV(nodeName, nodeID string, appConfig *config.AppConfig) *kvstore.BadgerKVStore {
445447
// Badger KV DB
446448
// Use configured db_path or default to current directory + "db"
447449
basePath := viper.GetString("db_path")
@@ -459,8 +461,8 @@ func NewBadgerKV(nodeName, nodeID string) *kvstore.BadgerKVStore {
459461
// Create BadgerConfig struct
460462
config := kvstore.BadgerConfig{
461463
NodeID: nodeName,
462-
EncryptionKey: []byte(viper.GetString("badger_password")),
463-
BackupEncryptionKey: []byte(viper.GetString("badger_password")), // Using same key for backup encryption
464+
EncryptionKey: []byte(appConfig.BadgerPassword),
465+
BackupEncryptionKey: []byte(appConfig.BadgerPassword), // Using same key for backup encryption
464466
BackupDir: backupDir,
465467
DBPath: dbPath,
466468
}
@@ -499,8 +501,8 @@ func StartPeriodicBackup(ctx context.Context, badgerKV *kvstore.BadgerKVStore, p
499501
return backupCancel
500502
}
501503

502-
func GetNATSConnection(environment string) (*nats.Conn, error) {
503-
url := viper.GetString("nats.url")
504+
func GetNATSConnection(environment string, appConfig *config.AppConfig) (*nats.Conn, error) {
505+
url := appConfig.NATs.URL
504506
opts := []nats.Option{
505507
nats.MaxReconnects(-1), // retry forever
506508
nats.ReconnectWait(2 * time.Second),
@@ -517,9 +519,12 @@ func GetNATSConnection(environment string) (*nats.Conn, error) {
517519

518520
if environment == constant.EnvProduction {
519521
// Load TLS config from configuration
520-
clientCert := viper.GetString("nats.tls.client_cert")
521-
clientKey := viper.GetString("nats.tls.client_key")
522-
caCert := viper.GetString("nats.tls.ca_cert")
522+
var clientCert, clientKey, caCert string
523+
if appConfig.NATs.TLS != nil {
524+
clientCert = appConfig.NATs.TLS.ClientCert
525+
clientKey = appConfig.NATs.TLS.ClientKey
526+
caCert = appConfig.NATs.TLS.CACert
527+
}
523528

524529
// Fallback to default paths if not configured
525530
if clientCert == "" {
@@ -535,7 +540,7 @@ func GetNATSConnection(environment string) (*nats.Conn, error) {
535540
opts = append(opts,
536541
nats.ClientCert(clientCert, clientKey),
537542
nats.RootCAs(caCert),
538-
nats.UserInfo(viper.GetString("nats.username"), viper.GetString("nats.password")),
543+
nats.UserInfo(appConfig.NATs.Username, appConfig.NATs.Password),
539544
)
540545
}
541546

deployments/systemd/setup-config.sh

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -109,29 +109,6 @@ check_root() {
109109
fi
110110
}
111111

112-
# Get environment from config.yaml
113-
get_environment_from_config() {
114-
log_step "Reading environment from config.yaml..."
115-
116-
local config_file="/etc/mpcium/config.yaml"
117-
118-
if [[ ! -f "$config_file" ]]; then
119-
log_error "Config file not found at $config_file"
120-
exit 1
121-
fi
122-
123-
# Extract environment from config.yaml
124-
local environment=$(grep "^environment:" "$config_file" | sed 's/environment: *//g' | sed 's/"//g' | sed "s/'//g")
125-
126-
if [[ -z "$environment" ]]; then
127-
environment="production" # default
128-
log_warn "Environment not specified in config.yaml, defaulting to production"
129-
fi
130-
131-
# Store the environment for later use
132-
MPCIUM_ENVIRONMENT="$environment"
133-
log_info "Environment from config.yaml: $MPCIUM_ENVIRONMENT"
134-
}
135112

136113
# Prompt for MPCIUM_NODE_NAME if not provided
137114
setup_node_name() {
@@ -559,7 +536,6 @@ setup_environment_file() {
559536
# Mpcium Environment Variables
560537
# Generated on $(date)
561538
# Note: All credentials are now configured in /etc/mpcium/config.yaml
562-
ENVIRONMENT=${MPCIUM_ENVIRONMENT}
563539
MPCIUM_NODE_NAME=${MPCIUM_NODE_NAME}
564540
EOF
565541

@@ -734,7 +710,6 @@ main() {
734710
log_info "Starting Mpcium configuration setup..."
735711

736712
check_root
737-
get_environment_from_config
738713
setup_node_name
739714
check_binaries
740715
ensure_configuration

go.mod

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
module github.com/fystack/mpcium
22

3-
go 1.23.0
3+
go 1.23.8
44

5-
toolchain go1.23.5
5+
toolchain go1.24.7
66

77
require (
88
filippo.io/age v1.2.1
99
github.com/avast/retry-go v3.0.0+incompatible
1010
github.com/aws/aws-sdk-go-v2/config v1.31.4
11+
github.com/aws/aws-sdk-go-v2/credentials v1.18.8
1112
github.com/aws/aws-sdk-go-v2/service/kms v1.45.0
1213
github.com/bnb-chain/tss-lib/v2 v2.0.2
1314
github.com/decred/dcrd/dcrec/edwards/v2 v2.0.3
1415
github.com/dgraph-io/badger/v4 v4.7.0
1516
github.com/google/uuid v1.6.0
16-
github.com/hashicorp/consul/api v1.26.1
17+
github.com/hashicorp/consul/api v1.32.1
1718
github.com/mitchellh/mapstructure v1.5.0
1819
github.com/nats-io/nats.go v1.31.0
1920
github.com/rs/zerolog v1.31.0
@@ -29,7 +30,6 @@ require (
2930
github.com/agl/ed25519 v0.0.0-20200225211852-fd4d107ace12 // indirect
3031
github.com/armon/go-metrics v0.4.1 // indirect
3132
github.com/aws/aws-sdk-go-v2 v1.38.2 // indirect
32-
github.com/aws/aws-sdk-go-v2/credentials v1.18.8 // indirect
3333
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.5 // indirect
3434
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.5 // indirect
3535
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.5 // indirect
@@ -96,7 +96,7 @@ require (
9696
go.uber.org/goleak v1.3.0 // indirect
9797
go.uber.org/multierr v1.9.0 // indirect
9898
go.uber.org/zap v1.21.0 // indirect
99-
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
99+
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 // indirect
100100
golang.org/x/net v0.39.0 // indirect
101101
golang.org/x/sys v0.33.0 // indirect
102102
golang.org/x/text v0.24.0 // indirect

go.sum

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,8 +160,11 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
160160
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
161161
github.com/hashicorp/consul/api v1.26.1 h1:5oSXOO5fboPZeW5SN+TdGFP/BILDgBm19OrPZ/pICIM=
162162
github.com/hashicorp/consul/api v1.26.1/go.mod h1:B4sQTeaSO16NtynqrAdwOlahJ7IUDZM9cj2420xYL8A=
163+
github.com/hashicorp/consul/api v1.32.1 h1:0+osr/3t/aZNAdJX558crU3PEjVrG4x6715aZHRgceE=
164+
github.com/hashicorp/consul/api v1.32.1/go.mod h1:mXUWLnxftwTmDv4W3lzxYCPD199iNLLUyLfLGFJbtl4=
163165
github.com/hashicorp/consul/sdk v0.15.0 h1:2qK9nDrr4tiJKRoxPGhm6B7xJjLVIQqkjiab2M4aKjU=
164166
github.com/hashicorp/consul/sdk v0.15.0/go.mod h1:r/OmRRPbHOe0yxNahLw7G9x5WG17E1BIECMtCjcPSNo=
167+
github.com/hashicorp/consul/sdk v0.16.1 h1:V8TxTnImoPD5cj0U9Spl0TUxcytjcbbJeADFF07KdHg=
165168
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
166169
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
167170
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
@@ -406,6 +409,8 @@ golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
406409
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
407410
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
408411
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
412+
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=
413+
golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=
409414
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
410415
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
411416
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=

peers.json

Lines changed: 0 additions & 5 deletions
This file was deleted.

pkg/config/config_test.go

Lines changed: 58 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,9 @@ func TestAppConfig_MarshalJSONMask(t *testing.T) {
2626
masked := config.MarshalJSONMask()
2727

2828
// Verify that sensitive data is masked
29-
assert.Contains(t, masked, "localhost:8500") // Address should not be masked
30-
assert.Contains(t, masked, "admin") // Username should not be masked
31-
assert.Contains(t, masked, "nats_user") // Username should not be masked
29+
assert.Contains(t, masked, "localhost:8500") // Address should not be masked
30+
assert.Contains(t, masked, "admin") // Username should not be masked
31+
assert.Contains(t, masked, "nats_user") // Username should not be masked
3232
assert.Contains(t, masked, "nats://localhost:4222") // URL should not be masked
3333

3434
// Verify that passwords are masked
@@ -120,4 +120,58 @@ func TestAppConfig_PartialConfig(t *testing.T) {
120120
assert.Contains(t, masked, "localhost:8500")
121121
assert.NotContains(t, masked, "test")
122122
assert.Contains(t, masked, "****") // masked badger password
123-
}
123+
}
124+
125+
func TestValidateEnvironment(t *testing.T) {
126+
tests := []struct {
127+
name string
128+
environment string
129+
wantErr bool
130+
}{
131+
{
132+
name: "valid production environment",
133+
environment: "production",
134+
wantErr: false,
135+
},
136+
{
137+
name: "valid development environment",
138+
environment: "development",
139+
wantErr: false,
140+
},
141+
{
142+
name: "invalid environment",
143+
environment: "staging",
144+
wantErr: true,
145+
},
146+
{
147+
name: "empty environment",
148+
environment: "",
149+
wantErr: true,
150+
},
151+
{
152+
name: "case sensitive - Production",
153+
environment: "Production",
154+
wantErr: true,
155+
},
156+
{
157+
name: "case sensitive - PRODUCTION",
158+
environment: "PRODUCTION",
159+
wantErr: true,
160+
},
161+
}
162+
163+
for _, tt := range tests {
164+
t.Run(tt.name, func(t *testing.T) {
165+
err := validateEnvironment(tt.environment)
166+
if tt.wantErr {
167+
assert.Error(t, err)
168+
if err != nil {
169+
assert.Contains(t, err.Error(), "invalid environment")
170+
assert.Contains(t, err.Error(), "production, development")
171+
}
172+
} else {
173+
assert.NoError(t, err)
174+
}
175+
})
176+
}
177+
}

0 commit comments

Comments
 (0)