config abstraction changes added

This commit is contained in:
2023-03-22 09:43:40 +00:00
parent 88dddd0230
commit 69c0aa5cb1
14 changed files with 2015 additions and 1924 deletions

View File

@@ -1,256 +1,257 @@
package p2p
import (
"encoding/json"
"fmt"
"github.com/Akilan1999/p2p-rendering-computation/config"
"io/ioutil"
"net"
"net/http"
"os"
"time"
"encoding/json"
"fmt"
"github.com/Akilan1999/p2p-rendering-computation/config"
"io/ioutil"
"net"
"net/http"
"os"
"time"
)
// Get IP table Data
type IpAddresses struct {
IpAddress []IpAddress `json:"ip_address"`
IpAddress []IpAddress `json:"ip_address"`
}
type IpAddress struct {
Name string `json:"Name"`
Ipv4 string `json:"IPV4"`
Ipv6 string `json:"IPV6"`
Latency time.Duration `json:"Latency"`
Download float64 `json:"Download"`
Upload float64 `json:"Upload"`
ServerPort string `json:"ServerPort"`
NAT string `json:"NAT"`
EscapeImplementation string `json:"EscapeImplementation"`
Name string `json:"Name"`
Ipv4 string `json:"IPV4"`
Ipv6 string `json:"IPV6"`
Latency time.Duration `json:"Latency"`
Download float64 `json:"Download"`
Upload float64 `json:"Upload"`
ServerPort string `json:"ServerPort"`
NAT string `json:"NAT"`
EscapeImplementation string `json:"EscapeImplementation"`
CustomInformation []byte
}
type IP struct {
Query string
Query string
}
// ReadIpTable Read data from Ip tables from json file
func ReadIpTable() (*IpAddresses, error) {
// Get Path from config
config, err := config.ConfigInit(nil)
if err != nil {
return nil, err
}
jsonFile, err := os.Open(config.IPTable)
// if we os.Open returns an error then handle it
if err != nil {
return nil, err
}
// Get Path from config
config, err := config.ConfigInit(nil, nil)
if err != nil {
return nil, err
}
jsonFile, err := os.Open(config.IPTable)
// if we os.Open returns an error then handle it
if err != nil {
return nil, err
}
// defer the closing of our jsonFile so that we can parse it later on
defer jsonFile.Close()
// defer the closing of our jsonFile so that we can parse it later on
defer jsonFile.Close()
// read our opened xmlFile as a byte array.
byteValue, _ := ioutil.ReadAll(jsonFile)
// read our opened xmlFile as a byte array.
byteValue, _ := ioutil.ReadAll(jsonFile)
// we initialize our Users array
var ipAddresses IpAddresses
// we initialize our Users array
var ipAddresses IpAddresses
// we unmarshal our byteArray which contains our
// jsonFile's content into 'users' which we defined above
json.Unmarshal(byteValue, &ipAddresses)
// we unmarshal our byteArray which contains our
// jsonFile's content into 'users' which we defined above
json.Unmarshal(byteValue, &ipAddresses)
var PublicIP IpAddress
var PublicIP IpAddress
ipv6, err := GetCurrentIPV6()
if err != nil {
return nil, err
}
ipv6, err := GetCurrentIPV6()
if err != nil {
return nil, err
}
ip, err := CurrentPublicIP()
if err != nil {
return nil, err
}
PublicIP.Ipv4 = ip
PublicIP.Ipv6 = ipv6
PublicIP.ServerPort = config.ServerPort
PublicIP.Name = config.MachineName
PublicIP.NAT = config.BehindNAT
PublicIP.EscapeImplementation = "None"
ip, err := CurrentPublicIP()
if err != nil {
return nil, err
}
PublicIP.Ipv4 = ip
PublicIP.Ipv6 = ipv6
PublicIP.ServerPort = config.ServerPort
PublicIP.Name = config.MachineName
PublicIP.NAT = config.BehindNAT
PublicIP.EscapeImplementation = "None"
// Updates current machine IP address to the IP table
ipAddresses.IpAddress = append(ipAddresses.IpAddress, PublicIP)
// Updates current machine IP address to the IP table
ipAddresses.IpAddress = append(ipAddresses.IpAddress, PublicIP)
//before writing to iptable ensures the duplicates are removed
if err = ipAddresses.RemoveDuplicates(); err != nil {
return nil, err
}
//before writing to iptable ensures the duplicates are removed
if err = ipAddresses.RemoveDuplicates(); err != nil {
return nil, err
}
return &ipAddresses, nil
return &ipAddresses, nil
}
// WriteIpTable Write to IP table json file
func (i *IpAddresses) WriteIpTable() error {
//before writing to iptable ensures the duplicates are removed
if err := i.RemoveDuplicates(); err != nil {
return err
}
//before writing to iptable ensures the duplicates are removed
if err := i.RemoveDuplicates(); err != nil {
return err
}
file, err := json.MarshalIndent(i, "", " ")
if err != nil {
return err
}
file, err := json.MarshalIndent(i, "", " ")
if err != nil {
return err
}
// Get Path from config
config, err := config.ConfigInit(nil)
if err != nil {
return err
}
// Get Path from config
config, err := config.ConfigInit(nil, nil)
if err != nil {
return err
}
err = ioutil.WriteFile(config.IPTable, file, 0644)
if err != nil {
return err
}
err = ioutil.WriteFile(config.IPTable, file, 0644)
if err != nil {
return err
}
return nil
return nil
}
// PrintIpTable Print Ip table data for Cli
func PrintIpTable() error {
table, err := ReadIpTable()
table, err := ReadIpTable()
if err != nil {
return err
}
if err != nil {
return err
}
for i := 0; i < len(table.IpAddress); i++ {
fmt.Printf("\nMachine Name: %s\nIP Address: %s\nIPV6: %s\nLatency: %s\nServerPort: %s\nbehindNAT: %s\nEscapeImplementation: %s\n-----------"+
"-----------------\n", table.IpAddress[i].Name, table.IpAddress[i].Ipv4, table.IpAddress[i].Ipv6,
table.IpAddress[i].Latency, table.IpAddress[i].ServerPort, table.IpAddress[i].NAT, table.IpAddress[i].EscapeImplementation)
}
//PrettyPrint(table)
for i := 0; i < len(table.IpAddress); i++ {
fmt.Printf("\nMachine Name: %s\nIP Address: %s\nIPV6: %s\nLatency: %s\nServerPort: %s\nbehindNAT: %s\nEscapeImplementation: %s\n-----------"+
"-----------------\n", table.IpAddress[i].Name, table.IpAddress[i].Ipv4, table.IpAddress[i].Ipv6,
table.IpAddress[i].Latency, table.IpAddress[i].ServerPort, table.IpAddress[i].NAT, table.IpAddress[i].EscapeImplementation)
}
//PrettyPrint(table)
return nil
return nil
}
// RemoveDuplicates This is a temporary fix current functions failing to remove
// Duplicate IP addresses from local IP table
func (table *IpAddresses) RemoveDuplicates() error {
var NoDuplicates IpAddresses
for i, _ := range table.IpAddress {
Exists := false
for k := range NoDuplicates.IpAddress {
// Statements checked for
// - duplicate IPV4 addresses [<IPV4>:<Port No>]
// - duplicate IPV6 addresses [<IPV6>]
// - Node is behind NAT and no escape implementation provided
if (NoDuplicates.IpAddress[k].Ipv4 != "" && NoDuplicates.IpAddress[k].Ipv4 == table.IpAddress[i].Ipv4 &&
NoDuplicates.IpAddress[k].ServerPort == table.IpAddress[i].ServerPort) ||
(NoDuplicates.IpAddress[k].Ipv6 != "" && NoDuplicates.IpAddress[k].Ipv6 == table.IpAddress[i].Ipv6) {
Exists = true
break
}
}
var NoDuplicates IpAddresses
for i, _ := range table.IpAddress {
Exists := false
for k := range NoDuplicates.IpAddress {
// Statements checked for
// - duplicate IPV4 addresses [<IPV4>:<Port No>]
// - duplicate IPV6 addresses [<IPV6>]
// - Node is behind NAT and no escape implementation provided
if (NoDuplicates.IpAddress[k].Ipv4 != "" && NoDuplicates.IpAddress[k].Ipv4 == table.IpAddress[i].Ipv4 &&
NoDuplicates.IpAddress[k].ServerPort == table.IpAddress[i].ServerPort) ||
(NoDuplicates.IpAddress[k].Ipv6 != "" && NoDuplicates.IpAddress[k].Ipv6 == table.IpAddress[i].Ipv6) {
Exists = true
break
}
}
if table.IpAddress[i].NAT == "True" && table.IpAddress[i].EscapeImplementation == "None" {
Exists = true
}
if table.IpAddress[i].NAT == "True" && table.IpAddress[i].EscapeImplementation == "None" {
Exists = true
}
if Exists {
continue
}
NoDuplicates.IpAddress = append(NoDuplicates.IpAddress, table.IpAddress[i])
}
if Exists {
continue
}
NoDuplicates.IpAddress = append(NoDuplicates.IpAddress, table.IpAddress[i])
}
table.IpAddress = NoDuplicates.IpAddress
table.IpAddress = NoDuplicates.IpAddress
return nil
return nil
}
// CurrentPublicIP Get Current Public IP address
func CurrentPublicIP() (string, error) {
req, err := http.Get("http://ip-api.com/json/")
if err != nil {
return "", err
}
defer req.Body.Close()
req, err := http.Get("http://ip-api.com/json/")
if err != nil {
return "", err
}
defer req.Body.Close()
body, err := ioutil.ReadAll(req.Body)
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(req.Body)
if err != nil {
return "", err
}
var ip IP
json.Unmarshal(body, &ip)
var ip IP
json.Unmarshal(body, &ip)
return ip.Query, nil
return ip.Query, nil
}
// GetCurrentIPV6 gets the current IPV6 address based on the interface
// specified in the config file
func GetCurrentIPV6() (string, error) {
Config, err := config.ConfigInit(nil)
if err != nil {
return "", err
}
Config, err := config.ConfigInit(nil, nil)
if err != nil {
return "", err
}
// Fix in future release
//byNameInterface, err := net.InterfaceByName(Config.NetworkInterface)
//if err != nil {
// return "",err
//}
//addresses, err := byNameInterface.Addrs()
//if err != nil {
// return "",err
//}
//if addresses[1].String() == "" {
// return "",errors.New("IPV6 address not detected")
//}
//IP,_,err := net.ParseCIDR(addresses[Config.NetworkInterfaceIPV6Index].String())
//if err != nil {
// return "",err
//}
// Fix in future release
//byNameInterface, err := net.InterfaceByName(Config.NetworkInterface)
//if err != nil {
// return "",err
//}
//addresses, err := byNameInterface.Addrs()
//if err != nil {
// return "",err
//}
//if addresses[1].String() == "" {
// return "",errors.New("IPV6 address not detected")
//}
//IP,_,err := net.ParseCIDR(addresses[Config.NetworkInterfaceIPV6Index].String())
//if err != nil {
// return "",err
//}
return Config.IPV6Address, nil
return Config.IPV6Address, nil
}
// ViewNetworkInterface This function is created to view the network interfaces available
func ViewNetworkInterface() error {
ifaces, err := net.Interfaces()
if err != nil {
return err
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
return err
}
for index, a := range addrs {
switch v := a.(type) {
case *net.IPAddr:
fmt.Printf("(%v) %v : %s (%s)\n", index, i.Name, v, v.IP.DefaultMask())
ifaces, err := net.Interfaces()
if err != nil {
return err
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
return err
}
for index, a := range addrs {
switch v := a.(type) {
case *net.IPAddr:
fmt.Printf("(%v) %v : %s (%s)\n", index, i.Name, v, v.IP.DefaultMask())
case *net.IPNet:
fmt.Printf("(%v) %v : %s \n", index, i.Name, v)
}
case *net.IPNet:
fmt.Printf("(%v) %v : %s \n", index, i.Name, v)
}
}
}
return nil
}
}
return nil
}
// Ip4or6 Helper function to check if the IP address is IPV4 or
// IPV6 (https://socketloop.com/tutorials/golang-check-if-ip-address-is-version-4-or-6)
func Ip4or6(s string) string {
for i := 0; i < len(s); i++ {
switch s[i] {
case '.':
return "version 4"
case ':':
return "version 6"
}
}
return "version 6"
for i := 0; i < len(s); i++ {
switch s[i] {
case '.':
return "version 4"
case ':':
return "version 6"
}
}
return "version 6"
}

View File

@@ -1,16 +1,16 @@
package p2p
import (
"bytes"
"errors"
"github.com/Akilan1999/p2p-rendering-computation/config"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"os"
"time"
"bytes"
"errors"
"github.com/Akilan1999/p2p-rendering-computation/config"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"os"
"time"
)
// var dlSizes = [...]int{350, 500, 750, 1000, 1500, 2000, 2500, 3000, 3500, 4000}
@@ -80,100 +80,100 @@ var httpclient = http.Client{}
// Download Speed
func (s *IpAddress) DownloadSpeed() error {
start := time.Now()
resp, err := httpclient.Get("http://" + s.Ipv4 + ":8088/50")
if err != nil {
return err
}
defer resp.Body.Close()
ioutil.ReadAll(resp.Body)
t := time.Since(start)
//fmt.Println(s.Seconds())
// size * time (seconds)
s.Download = (50 / t.Seconds()) * 8
return nil
start := time.Now()
resp, err := httpclient.Get("http://" + s.Ipv4 + ":8088/50")
if err != nil {
return err
}
defer resp.Body.Close()
ioutil.ReadAll(resp.Body)
t := time.Since(start)
//fmt.Println(s.Seconds())
// size * time (seconds)
s.Download = (50 / t.Seconds()) * 8
return nil
}
func (s *IpAddress) UploadSpeed() error {
start := time.Now()
start := time.Now()
// Get upload file path from config file
// Get Path from config
config, err := config.ConfigInit(nil)
if err != nil {
return err
}
// Get upload file path from config file
// Get Path from config
config, err := config.ConfigInit(nil, nil)
if err != nil {
return err
}
b, w := createMultipartFormData("file", config.SpeedTestFile)
b, w := createMultipartFormData("file", config.SpeedTestFile)
req, err := http.NewRequest("GET", "http://"+s.Ipv4+":"+s.ServerPort+"/upload", &b)
if err != nil {
return err
}
// Don't forget to set the content type, this will contain the boundary.
req.Header.Set("Content-Type", w.FormDataContentType())
defer req.Body.Close()
ioutil.ReadAll(req.Body)
t := time.Since(start)
//fmt.Println(s.Seconds())
// size * time (seconds)
s.Upload = (50 / t.Seconds()) * 8
return nil
req, err := http.NewRequest("GET", "http://"+s.Ipv4+":"+s.ServerPort+"/upload", &b)
if err != nil {
return err
}
// Don't forget to set the content type, this will contain the boundary.
req.Header.Set("Content-Type", w.FormDataContentType())
defer req.Body.Close()
ioutil.ReadAll(req.Body)
t := time.Since(start)
//fmt.Println(s.Seconds())
// size * time (seconds)
s.Upload = (50 / t.Seconds()) * 8
return nil
}
// Upload helper function for uploading
// (https://stackoverflow.com/questions/20205796/post-data-using-the-content-type-multipart-form-data
func createMultipartFormData(fieldName, fileName string) (bytes.Buffer, *multipart.Writer) {
var b bytes.Buffer
var err error
w := multipart.NewWriter(&b)
var fw io.Writer
file := mustOpen(fileName)
if fw, err = w.CreateFormFile(fieldName, file.Name()); err != nil {
log.Fatalf("Error creating writer: %v", err)
}
if _, err = io.Copy(fw, file); err != nil {
log.Fatalf("Error with io.Copy: %v", err)
//t.Errorf("Error with io.Copy: %v", err)
}
w.Close()
return b, w
var b bytes.Buffer
var err error
w := multipart.NewWriter(&b)
var fw io.Writer
file := mustOpen(fileName)
if fw, err = w.CreateFormFile(fieldName, file.Name()); err != nil {
log.Fatalf("Error creating writer: %v", err)
}
if _, err = io.Copy(fw, file); err != nil {
log.Fatalf("Error with io.Copy: %v", err)
//t.Errorf("Error with io.Copy: %v", err)
}
w.Close()
return b, w
}
func mustOpen(f string) *os.File {
r, err := os.Open(f)
if err != nil {
log.Fatalf("Error with mustOpen: %v", err)
}
return r
r, err := os.Open(f)
if err != nil {
log.Fatalf("Error with mustOpen: %v", err)
}
return r
}
// PingTest executes test to measure latency
func (s *IpAddress) PingTest() error {
//pingURL := strings.Split(s.URL, "/upload")[0] + "/latency.txt"
var pingURL string
if s.Ipv6 != "" {
pingURL = "http://[" + s.Ipv6 + "]:" + s.ServerPort + "/server_info"
s.Ipv4 = ""
} else {
pingURL = "http://" + s.Ipv4 + ":" + s.ServerPort + "/server_info"
}
//pingURL := strings.Split(s.URL, "/upload")[0] + "/latency.txt"
var pingURL string
if s.Ipv6 != "" {
pingURL = "http://[" + s.Ipv6 + "]:" + s.ServerPort + "/server_info"
s.Ipv4 = ""
} else {
pingURL = "http://" + s.Ipv4 + ":" + s.ServerPort + "/server_info"
}
l := time.Duration(100000000000) // 10sec
for i := 0; i < 3; i++ {
sTime := time.Now()
resp, err := http.Get(pingURL)
fTime := time.Now()
if err != nil || resp.StatusCode != 200 {
return errors.New("Node not found")
}
if fTime.Sub(sTime) < l {
l = fTime.Sub(sTime)
}
resp.Body.Close()
}
l := time.Duration(100000000000) // 10sec
for i := 0; i < 3; i++ {
sTime := time.Now()
resp, err := http.Get(pingURL)
fTime := time.Now()
if err != nil || resp.StatusCode != 200 {
return errors.New("Node not found")
}
if fTime.Sub(sTime) < l {
l = fTime.Sub(sTime)
}
resp.Body.Close()
}
s.Latency = time.Duration(int64(l.Nanoseconds() / 2))
s.Latency = time.Duration(int64(l.Nanoseconds() / 2))
return nil
return nil
}