save peers RIVM-31

This commit is contained in:
Mihail Slobodyanuk 2022-12-16 22:58:12 +02:00
parent d68d3db702
commit 0b54277ece
7 changed files with 164 additions and 165 deletions

View file

@ -19,6 +19,7 @@ import (
"github.com/RiV-chain/RiV-mesh/src/config"
"github.com/RiV-chain/RiV-mesh/src/core"
"github.com/RiV-chain/RiV-mesh/src/defaults"
)
// TODO: Add authentication
@ -246,7 +247,7 @@ func (a *AdminSocket) SetupAdminHandlers() {
}
// Start runs http server
func (a *AdminSocket) StartHttpServer(nc *config.NodeConfig) {
func (a *AdminSocket) StartHttpServer(configFn string, nc *config.NodeConfig) {
if nc.HttpAddress != "none" && nc.HttpAddress != "" && nc.WwwRoot != "none" && nc.WwwRoot != "" {
u, err := url.Parse(nc.HttpAddress)
if err != nil {
@ -275,6 +276,46 @@ func (a *AdminSocket) StartHttpServer(nc *config.NodeConfig) {
}
})
http.HandleFunc("/api/peers", func(w http.ResponseWriter, r *http.Request) {
var handleDelete = func() error {
err := a.core.RemovePeers()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return err
}
var handlePost = func() error {
var peers []string
err := json.NewDecoder(r.Body).Decode(&peers)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return err
}
for _, peer := range peers {
if err := a.core.AddPeer(peer, ""); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return err
}
}
if len(configFn) > 0 {
saveHeaders := r.Header["Riv-Save-Config"]
if len(saveHeaders) > 0 && saveHeaders[0] == "true" {
cfg, err := defaults.ReadConfig(configFn)
if err == nil {
cfg.Peers = peers
err := defaults.WriteConfig(configFn, cfg)
if err != nil {
a.log.Errorln("Config file read error:", err)
}
} else {
a.log.Errorln("Config file read error:", err)
}
}
}
return nil
}
switch r.Method {
case "GET":
w.Header().Add("Content-Type", "application/json")
@ -290,61 +331,17 @@ func (a *AdminSocket) StartHttpServer(nc *config.NodeConfig) {
}
fmt.Fprint(w, string(b[:]))
case "POST":
req := &AddPeersRequest{}
res := &AddPeersResponse{}
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := a.addPeersHandler(req, res); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
b, err := json.Marshal(res)
if err != nil {
http.Error(w, err.Error(), 503)
}
w.Header().Add("Content-Type", "application/json")
fmt.Fprint(w, string(b[:]))
handlePost()
case "PUT":
err := a.core.RemovePeers()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
if handleDelete() == nil {
if handlePost() == nil {
http.Error(w, "No content", http.StatusNoContent)
}
}
req := &AddPeersRequest{}
res := &AddPeersResponse{}
err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := a.addPeersHandler(req, res); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
b, err := json.Marshal(res)
if err != nil {
http.Error(w, err.Error(), 503)
}
w.Header().Add("Content-Type", "application/json")
fmt.Fprint(w, string(b[:]))
//TODO save peers
// saveHeaders := r.Header["Riv-Save-Config"]
// if len(saveHeaders) > 0 && saveHeaders[0] == "true" {
// nc.Peers =
// }
case "DELETE":
err := a.core.RemovePeers()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
if handleDelete() == nil {
http.Error(w, "No content", http.StatusNoContent)
}
http.Error(w, "No content", http.StatusNoContent)
default:
http.Error(w, "Method Not Allowed", 405)
}

View file

@ -1,6 +1,16 @@
package defaults
import "github.com/RiV-chain/RiV-mesh/src/config"
import (
"bytes"
"encoding/json"
"io"
"os"
"github.com/RiV-chain/RiV-mesh/src/config"
"github.com/hjson/hjson-go"
"github.com/mitchellh/mapstructure"
"golang.org/x/text/encoding/unicode"
)
type MulticastInterfaceConfig = config.MulticastInterfaceConfig
type NetworkDomainConfig = config.NetworkDomainConfig
@ -77,3 +87,89 @@ func GenerateConfig() *config.NodeConfig {
return cfg
}
func Genconf(isjson bool) string {
cfg := GenerateConfig()
var bs []byte
if isjson {
bs, _ = json.MarshalIndent(cfg, "", " ")
} else {
bs, _ = hjson.Marshal(cfg)
}
return string(bs)
}
func ReadConfig(useconffile string) (*config.NodeConfig, error) {
// Use a configuration file. If -useconf, the configuration will be read
// from stdin. If -useconffile, the configuration will be read from the
// filesystem.
var conf []byte
var err error
if useconffile != "" {
// Read the file from the filesystem
conf, err = os.ReadFile(useconffile)
} else {
// Read the file from stdin.
conf, err = io.ReadAll(os.Stdin)
}
if err != nil {
return nil, err
}
// If there's a byte order mark - which Windows 10 is now incredibly fond of
// throwing everywhere when it's converting things into UTF-16 for the hell
// of it - remove it and decode back down into UTF-8. This is necessary
// because hjson doesn't know what to do with UTF-16 and will panic
if bytes.Equal(conf[0:2], []byte{0xFF, 0xFE}) ||
bytes.Equal(conf[0:2], []byte{0xFE, 0xFF}) {
utf := unicode.UTF16(unicode.BigEndian, unicode.UseBOM)
decoder := utf.NewDecoder()
conf, err = decoder.Bytes(conf)
if err != nil {
return nil, err
}
}
// Generate a new configuration - this gives us a set of sane defaults -
// then parse the configuration we loaded above on top of it. The effect
// of this is that any configuration item that is missing from the provided
// configuration will use a sane default.
cfg := GenerateConfig()
var dat map[string]interface{}
if err := hjson.Unmarshal(conf, &dat); err != nil {
return nil, err
}
// Sanitise the config
confJson, err := json.Marshal(dat)
if err != nil {
return nil, err
}
if err := json.Unmarshal(confJson, &cfg); err != nil {
return nil, err
}
// Overlay our newly mapped configuration onto the autoconf node config that
// we generated above.
if err = mapstructure.Decode(dat, &cfg); err != nil {
return nil, err
}
return cfg, nil
}
func WriteConfig(confFn string, cfg *config.NodeConfig) error {
bs, err := hjson.Marshal(cfg)
if err != nil {
return err
}
err = os.WriteFile(confFn, bs, 0644)
if err != nil {
return err
}
return nil
}
func GetHttpEndpoint(defaultEndpoint string) string {
if config, err := ReadConfig(GetDefaults().DefaultConfigFile); err == nil {
if ep := config.HttpAddress; ep != "none" && ep != "" {
return ep
}
}
return defaultEndpoint
}