Skip to content

Commit

Permalink
- Small refactoring
Browse files Browse the repository at this point in the history
- Better webserver implementation
  • Loading branch information
HS-Joe committed Nov 21, 2021
1 parent 35e47a7 commit d88186d
Show file tree
Hide file tree
Showing 6 changed files with 104 additions and 114 deletions.
Empty file removed assets/gmaps.js
Empty file.
Empty file removed assets/main.css
Empty file.
170 changes: 89 additions & 81 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package main

import (
"embed"
"fmt"
"github.com/mitchellh/go-homedir"
"github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/libs/log"
tmos "github.com/tendermint/tendermint/libs/os"
Expand All @@ -11,27 +11,20 @@ import (
"github.com/tendermint/tendermint/p2p/pex"
"github.com/tendermint/tendermint/version"
"html/template"
oslog "log"
"net/http"
"os"
"path/filepath"
"googlemaps.github.io/maps"
)

var (
//https://socketloop.com/tutorials/golang-find-location-by-ip-address-and-display-with-google-map
//go:embed assets web
res embed.FS
files = map[string]string{
"/": "web/index.html",
"/assets/gmaps.js": "assets/gmaps.js",
"/assets/main.css": "assets/main.css",
}
configDir = ".tinyseed"
logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout))
)

// Config defines the configuration format
type Config struct {
ListenAddress string `toml:"laddr" comment:"Address to listen for incoming connections"`
HttpPort string `toml:"http_port" comment:"Port for the http server"`
ChainID string `toml:"chain_id" comment:"network identifier (todo move to cli flag argument? keeps the config network agnostic)"`
NodeKeyFile string `toml:"node_key_file" comment:"path to node_key (relative to tendermint-seed home directory or an absolute path)"`
AddrBookFile string `toml:"addr_book_file" comment:"path to address book (relative to tendermint-seed home directory or an absolute path)"`
Expand All @@ -45,68 +38,95 @@ type Config struct {
func DefaultConfig() *Config {
return &Config{
ListenAddress: "tcp://0.0.0.0:6969",
HttpPort: "3000",
ChainID: "osmosis-1",
NodeKeyFile: "config/node_key.json",
AddrBookFile: "data/addrbook.json",
NodeKeyFile: "node_key.json",
AddrBookFile: "addrbook.json",
AddrBookStrict: true,
MaxNumInboundPeers: 1000,
MaxNumInboundPeers: 3000,
MaxNumOutboundPeers: 1000,
Seeds: "[email protected]:26656,[email protected]:26656,[email protected]:26656,[email protected]:26656",
}
}

func startWebServer() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
page, ok := files[r.URL.Path]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
tpl, err := template.ParseFS(res, page)
if err != nil {
oslog.Printf("page %s not found in pages cache...", r.RequestURI)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
data := map[string]interface{}{
"userAgent": r.UserAgent(),
}
if err := tpl.Execute(w, data); err != nil {
return
}
})
http.FileServer(http.FS(res))
oslog.Println("server started...")
err := http.ListenAndServe(":8888", nil)
if err != nil {
panic(err)
}
}

func main() {

startWebServer()

/* idOverride := os.Getenv("ID")
idOverride := os.Getenv("ID")
seedOverride := os.Getenv("SEEDS")
userHomeDir, err := homedir.Dir()
seedConfig := DefaultConfig()

if err != nil {
panic(err)
}
homeDir := filepath.Join(userHomeDir, ".terranseed")
configFile := "config/config.toml"
configFilePath := filepath.Join(homeDir, configFile)

// init config directory & files
homeDir := filepath.Join(userHomeDir, configDir, "config")
configFilePath := filepath.Join(homeDir, "config.toml")
nodeKeyFilePath := filepath.Join(homeDir, seedConfig.NodeKeyFile)
addrBookFilePath := filepath.Join(homeDir, seedConfig.AddrBookFile)

MkdirAllPanic(filepath.Dir(nodeKeyFilePath), os.ModePerm)
MkdirAllPanic(filepath.Dir(addrBookFilePath), os.ModePerm)
MkdirAllPanic(filepath.Dir(configFilePath), os.ModePerm)
SeedConfig := DefaultConfig()

if idOverride != "" {
SeedConfig.ChainID = idOverride
seedConfig.ChainID = idOverride
}
if seedOverride != "" {
SeedConfig.Seeds = seedOverride
seedConfig.Seeds = seedOverride
}
logger.Info("Starting Web Server...")
StartWebServer(*seedConfig)
logger.Info("Starting Seed Node...")
Start(*seedConfig)
}

func StartWebServer(seedConfig Config) {

// serve static assets
fs := http.FileServer(http.Dir("./web/assets"))
http.Handle("/assets/", http.StripPrefix("/assets/", fs))

// serve html files
http.HandleFunc("/", serveTemplate)

// start web server in non-blocking
go func() {
err := http.ListenAndServe(":"+seedConfig.HttpPort, nil)
logger.Info("HTTP Server started", "port", seedConfig.HttpPort)
if err != nil {
panic(err)
}
}()
}

func serveTemplate(w http.ResponseWriter, r *http.Request) {
index := filepath.Join("./web/templates", "index.html")
templates := filepath.Join("./web/templates", filepath.Clean(r.URL.Path))
logger.Info("index", "i", index, "t", templates)

// Return a 404 if the template doesn't exist
fileInfo, err := os.Stat(templates)

if err != nil || fileInfo.IsDir() {
http.Redirect(w, r,"/index.html", 302)
return
}

tmpl, err := template.ParseFiles(index, templates)
if err != nil {
// Log the detailed error
logger.Error(err.Error())
// Return a generic "Internal Server Error" message
http.Error(w, http.StatusText(500), 500)
return
}

err = tmpl.ExecuteTemplate(w, "index", nil)
if err != nil {
logger.Error(err.Error())
http.Error(w, http.StatusText(500), 500)
}
Start(*SeedConfig)*/
}

// MkdirAllPanic invokes os.MkdirAll but panics if there is an error
Expand All @@ -118,42 +138,29 @@ func MkdirAllPanic(path string, perm os.FileMode) {
}

// Start starts a Tenderseed
func Start(SeedConfig Config) {
logger := log.NewTMLogger(
log.NewSyncWriter(os.Stdout),
)
func Start(seedConfig Config) {

chainID := SeedConfig.ChainID
nodeKeyFilePath := SeedConfig.NodeKeyFile
addrBookFilePath := SeedConfig.AddrBookFile

MkdirAllPanic(filepath.Dir(nodeKeyFilePath), os.ModePerm)
MkdirAllPanic(filepath.Dir(addrBookFilePath), os.ModePerm)
chainID := seedConfig.ChainID

cfg := config.DefaultP2PConfig()
cfg.AllowDuplicateIP = true

// allow a lot of inbound peers since we disconnect from them quickly in seed mode
cfg.MaxNumInboundPeers = 3000

// keep trying to make outbound connections to exchange peering info
cfg.MaxNumOutboundPeers = 400

userHomeDir, err := homedir.Dir()
nodeKeyFilePath := filepath.Join(userHomeDir, configDir, "config", seedConfig.NodeKeyFile)
nodeKey, err := p2p.LoadOrGenNodeKey(nodeKeyFilePath)
if err != nil {
panic(err)
}

logger.Info("terranseed",
logger.Info("Configuration",
"key", nodeKey.ID(),
"listen", SeedConfig.ListenAddress,
"listen", seedConfig.ListenAddress,
"chain", chainID,
"strict-routing", SeedConfig.AddrBookStrict,
"max-inbound", SeedConfig.MaxNumInboundPeers,
"max-outbound", SeedConfig.MaxNumOutboundPeers,
"strict-routing", seedConfig.AddrBookStrict,
"max-inbound", seedConfig.MaxNumInboundPeers,
"max-outbound", seedConfig.MaxNumOutboundPeers,
)

// TODO(roman) expose per-module log levels in the config
filteredLogger := log.NewFilter(logger, log.AllowInfo())

protocolVersion :=
Expand All @@ -163,11 +170,11 @@ func Start(SeedConfig Config) {
0,
)

// NodeInfo gets info on yhour node
// NodeInfo gets info on your node
nodeInfo := p2p.DefaultNodeInfo{
ProtocolVersion: protocolVersion,
DefaultNodeID: nodeKey.ID(),
ListenAddr: SeedConfig.ListenAddress,
ListenAddr: seedConfig.ListenAddress,
Network: chainID,
Version: "0.6.9",
Channels: []byte{pex.PexChannel},
Expand All @@ -184,12 +191,13 @@ func Start(SeedConfig Config) {
panic(err)
}

book := pex.NewAddrBook(addrBookFilePath, SeedConfig.AddrBookStrict)
addrBookFilePath := filepath.Join(userHomeDir, configDir, "config", seedConfig.AddrBookFile)
book := pex.NewAddrBook(addrBookFilePath, seedConfig.AddrBookStrict)
book.SetLogger(filteredLogger.With("module", "book"))

pexReactor := pex.NewReactor(book, &pex.ReactorConfig{
SeedMode: true,
Seeds: tmstrings.SplitAndTrim(SeedConfig.Seeds, ",", " "),
Seeds: tmstrings.SplitAndTrim(seedConfig.Seeds, ",", " "),
})
pexReactor.SetLogger(filteredLogger.With("module", "pex"))

Expand Down
3 changes: 3 additions & 0 deletions web/assets/css/main.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
h2 {
color: grey;
}
33 changes: 0 additions & 33 deletions web/index.html

This file was deleted.

12 changes: 12 additions & 0 deletions web/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{{define "index"}}

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/assets/css/main.css" />
</head>
<body>
<h2>It works!</h2>
</body>
</html>
{{end}}

0 comments on commit d88186d

Please sign in to comment.