Skip to content

Commit

Permalink
Merge branch 'main' into feat/disable-ui-for-sync
Browse files Browse the repository at this point in the history
# Conflicts:
#	ui/status.go
  • Loading branch information
PhearZero committed Nov 5, 2024
2 parents 3d240f9 + 0017855 commit ff0348b
Show file tree
Hide file tree
Showing 15 changed files with 161 additions and 20 deletions.
78 changes: 63 additions & 15 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cmd
import (
"context"
"encoding/json"
"fmt"
"github.com/algorandfoundation/hack-tui/api"
"github.com/algorandfoundation/hack-tui/internal"
"github.com/algorandfoundation/hack-tui/ui"
Expand Down Expand Up @@ -39,11 +40,24 @@ var (
},
RunE: func(cmd *cobra.Command, args []string) error {
log.SetOutput(cmd.OutOrStdout())
initConfig()

if viper.GetString("server") == "" {
return fmt.Errorf(style.Red.Render("server is required"))
}
if viper.GetString("token") == "" {
return fmt.Errorf(style.Red.Render("token is required"))
}

client, err := getClient()
cobra.CheckErr(err)

partkeys, err := internal.GetPartKeys(context.Background(), client)
cobra.CheckErr(err)
if err != nil {
return fmt.Errorf(
style.Red.Render("failed to get participation keys: %s"),
err)
}

state := internal.StateModel{
Status: internal.StatusModel{
Expand Down Expand Up @@ -106,7 +120,7 @@ func check(err interface{}) {
// Handle global flags and set usage templates
func init() {
log.SetReportTimestamp(false)
initConfig()

// Configure Version
if Version == "" {
Version = "unknown (built from source)"
Expand Down Expand Up @@ -142,6 +156,15 @@ type AlgodConfig struct {
EndpointAddress string `json:"EndpointAddress"`
}

func replaceEndpointUrl(s string) string {
s = strings.Replace(s, "\n", "", 1)
s = strings.Replace(s, "0.0.0.0", "127.0.0.1", 1)
s = strings.Replace(s, "[::]", "127.0.0.1", 1)
return s
}
func hasWildcardEndpointUrl(s string) bool {
return strings.Contains(s, "0.0.0.0") || strings.Contains(s, "::")
}
func initConfig() {
// Find home directory.
home, err := os.UserHomeDir()
Expand All @@ -159,12 +182,17 @@ func initConfig() {

// Load Configurations
viper.AutomaticEnv()
err = viper.ReadInConfig()
_ = viper.ReadInConfig()

// Check for server
loadedServer := viper.GetString("server")
loadedToken := viper.GetString("token")

// Load ALGORAND_DATA/config.json
algorandData, exists := os.LookupEnv("ALGORAND_DATA")

// Load the Algorand Data Configuration
if exists && algorandData != "" {
if exists && algorandData != "" && loadedServer == "" {
// Placeholder for Struct
var algodConfig AlgodConfig

Expand All @@ -183,23 +211,43 @@ func initConfig() {
err = configFile.Close()
check(err)

// Replace catchall address with localhost
if strings.Contains(algodConfig.EndpointAddress, "0.0.0.0") {
algodConfig.EndpointAddress = strings.Replace(algodConfig.EndpointAddress, "0.0.0.0", "127.0.0.1", 1)
// Check for endpoint address
if hasWildcardEndpointUrl(algodConfig.EndpointAddress) {
algodConfig.EndpointAddress = replaceEndpointUrl(algodConfig.EndpointAddress)
} else if algodConfig.EndpointAddress == "" {
// Assume it is not set, try to discover the port from the network file
networkPath := algorandData + "/algod.net"
networkFile, err := os.Open(networkPath)
check(err)

byteValue, err = io.ReadAll(networkFile)
check(err)

if hasWildcardEndpointUrl(string(byteValue)) {
algodConfig.EndpointAddress = replaceEndpointUrl(string(byteValue))
} else {
algodConfig.EndpointAddress = string(byteValue)
}

}
if strings.Contains(algodConfig.EndpointAddress, ":0") {
algodConfig.EndpointAddress = strings.Replace(algodConfig.EndpointAddress, ":0", ":8080", 1)
}
if loadedToken == "" {
// Handle Token Path
tokenPath := algorandData + "/algod.admin.token"

// Handle Token Path
tokenPath := algorandData + "/algod.admin.token"
tokenFile, err := os.Open(tokenPath)
check(err)

tokenFile, err := os.Open(tokenPath)
check(err)
byteValue, err = io.ReadAll(tokenFile)
check(err)

byteValue, err = io.ReadAll(tokenFile)
check(err)
viper.Set("token", strings.Replace(string(byteValue), "\n", "", 1))
}

// Set the server configuration
viper.Set("server", "http://"+algodConfig.EndpointAddress)
viper.Set("token", string(byteValue))
viper.Set("server", "http://"+strings.Replace(algodConfig.EndpointAddress, "\n", "", 1))
viper.Set("data", dataConfigPath)
}

Expand Down
54 changes: 53 additions & 1 deletion cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,64 @@ func Test_ExecuteRootCommand(t *testing.T) {

func Test_InitConfig(t *testing.T) {
cwd, _ := os.Getwd()
t.Setenv("ALGORAND_DATA", cwd+"/testdata")
viper.Set("token", "")
viper.Set("server", "")
t.Setenv("ALGORAND_DATA", cwd+"/testdata/Test_InitConfig")

initConfig()
server := viper.Get("server")
if server == "" {
t.Fatal("Invalid Server")
}
if server != "http://127.0.0.1:8080" {
t.Fatal("Invalid Server")
}
}

func Test_InitConfigWithoutEndpoint(t *testing.T) {
cwd, _ := os.Getwd()
viper.Set("token", "")
viper.Set("server", "")
t.Setenv("ALGORAND_DATA", cwd+"/testdata/Test_InitConfigWithoutEndpoint")

initConfig()
server := viper.Get("server")
if server == "" {
t.Fatal("Invalid Server")
}
if server != "http://127.0.0.1:8080" {
t.Fatal("Invalid Server")
}
}

func Test_InitConfigWithAddress(t *testing.T) {
cwd, _ := os.Getwd()
viper.Set("token", "")
viper.Set("server", "")
t.Setenv("ALGORAND_DATA", cwd+"/testdata/Test_InitConfigWithAddress")

initConfig()
server := viper.Get("server")
if server == "" {
t.Fatal("Invalid Server")
}
if server != "http://255.255.255.255:8080" {
t.Fatal("Invalid Server")
}
}

func Test_InitConfigWithAddressAndDefaultPort(t *testing.T) {
cwd, _ := os.Getwd()
viper.Set("token", "")
viper.Set("server", "")
t.Setenv("ALGORAND_DATA", cwd+"/testdata/Test_InitConfigWithAddressAndDefaultPort")

initConfig()
server := viper.Get("server")
if server == "" {
t.Fatal("Invalid Server")
}
if server != "http://255.255.255.255:8080" {
t.Fatal("Invalid Server")
}
}
1 change: 1 addition & 0 deletions cmd/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ var statusCmd = &cobra.Command{
Short: "Get the node status",
Long: style.Purple(BANNER) + "\n" + style.LightBlue("View the node status"),
RunE: func(cmd *cobra.Command, args []string) error {
initConfig()
if viper.GetString("server") == "" {
return errors.New(style.Magenta("server is required"))
}
Expand Down
File renamed without changes.
File renamed without changes.
1 change: 1 addition & 0 deletions cmd/testdata/Test_InitConfigWithAddress/algod.admin.token
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
4 changes: 4 additions & 0 deletions cmd/testdata/Test_InitConfigWithAddress/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"EndpointAddress": "255.255.255.255:8080",
"OtherKey": ""
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"EndpointAddress": "255.255.255.255:0",
"OtherKey": ""
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
1 change: 1 addition & 0 deletions cmd/testdata/Test_InitConfigWithoutEndpoint/algod.net
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
[::]:8080
2 changes: 2 additions & 0 deletions cmd/testdata/Test_InitConfigWithoutEndpoint/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{
}
3 changes: 3 additions & 0 deletions internal/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ type MetricsModel struct {
TPS float64
RX int
TX int
LastTS time.Time
LastRX int
LastTX int
}

type MetricsResponse map[string]int
Expand Down
11 changes: 9 additions & 2 deletions internal/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,8 +96,15 @@ func (s *StateModel) UpdateMetricsFromRPC(ctx context.Context, client *api.Clien
}
if err == nil {
s.Metrics.Enabled = true
s.Metrics.TX = res["algod_network_sent_bytes_total"]
s.Metrics.RX = res["algod_network_received_bytes_total"]
now := time.Now()
diff := now.Sub(s.Metrics.LastTS)

s.Metrics.TX = max(0, int(float64(res["algod_network_sent_bytes_total"]-s.Metrics.LastTX)/diff.Seconds()))
s.Metrics.RX = max(0, int(float64(res["algod_network_received_bytes_total"]-s.Metrics.LastRX)/diff.Seconds()))

s.Metrics.LastTS = now
s.Metrics.LastTX = res["algod_network_sent_bytes_total"]
s.Metrics.LastRX = res["algod_network_received_bytes_total"]
}
}
func (s *StateModel) UpdateAccounts(client *api.ClientWithResponses) {
Expand Down
20 changes: 18 additions & 2 deletions ui/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"github.com/algorandfoundation/hack-tui/ui/style"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"math"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -44,6 +45,21 @@ func (m StatusViewModel) HandleMessage(msg tea.Msg) (StatusViewModel, tea.Cmd) {
return m, nil
}

func getBitRate(bytes int) string {
txString := fmt.Sprintf("%d B/s ", bytes)
if bytes >= 1024 {
txString = fmt.Sprintf("%d KB/s ", bytes/(1<<10))
}
if bytes >= int(math.Pow(1024, 2)) {
txString = fmt.Sprintf("%d MB/s ", bytes/(1<<20))
}
if bytes >= int(math.Pow(1024, 3)) {
txString = fmt.Sprintf("%d GB/s ", bytes/(1<<30))
}

return txString
}

// View handles the render cycle
func (m StatusViewModel) View() string {
if !m.IsVisible {
Expand Down Expand Up @@ -74,7 +90,7 @@ func (m StatusViewModel) View() string {
roundTime = "--"
}
beginning = style.Blue.Render(" Round time: ") + roundTime
end = fmt.Sprintf("%d KB/s ", m.Data.Metrics.TX/1024) + style.Green.Render("TX ")
end = getBitRate(m.Data.Metrics.TX) + style.Green.Render("TX ")
middle = strings.Repeat(" ", max(0, size-(lipgloss.Width(beginning)+lipgloss.Width(end)+2)))

row2 := lipgloss.JoinHorizontal(lipgloss.Left, beginning, middle, end)
Expand All @@ -84,7 +100,7 @@ func (m StatusViewModel) View() string {
tps = "--"
}
beginning = style.Blue.Render(" TPS: ") + tps
end = fmt.Sprintf("%d KB/s ", m.Data.Metrics.RX/1024) + style.Green.Render("RX ")
end = getBitRate(m.Data.Metrics.RX) + style.Green.Render("RX ")
middle = strings.Repeat(" ", max(0, size-(lipgloss.Width(beginning)+lipgloss.Width(end)+2)))

row3 := lipgloss.JoinHorizontal(lipgloss.Left, beginning, middle, end)
Expand Down

0 comments on commit ff0348b

Please sign in to comment.