-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
202 lines (183 loc) · 7.04 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package main
import (
"byte" // needed for WakeOnLan and misc. stuff
"bufio" // for console input from user
"encoding/json"
"flag" //Package flag implements command-line flag parsing
"fmt" //formatting and printing
"golang.org/x/crypto/ssh" // for SSH tunneling into other clients/servers
"log" // for logging purposes
"math/rand" // for cryptographically secured random number
"net" //net provides a portable interface for network I/O
"os" // provides a platform-independent interface to operating system functionality
"strconv" //implements conversions to and from string representations of basic data types
"strings"
"syscall" // contains an interface to the low-level operating system
// primitives
"time"
)
/* Information about node */
type NodeInfo struct {
NodeId int `json:"nodeId"`
NodeIpAddr string `json:"nodeIpAddr"`
Port string `json:"port"`
}
// A standard format for adding node to cluster
type AddToClusterMessage struct {
Source NodeInfo `json:"source"`
Dest NodeInfo `json:"dest"`
Message string `json:"message"`
}
/* Just for pretty printing the node info */
/* using go's method implementation to attach String method to the
NodeInfo struct */
func (node NodeInfo) String() string {
return "NodeInfo:{ nodeId: " + strconv.Itoa(node.NodeId) + ", nodeIpAddr: " + node.NodeIpAddr + ", port:" + node.Port + " }"
}
/* Just for pretty printing Request/Response info */
// here we are overloading the String() function
func (req AddToClusterMessage) String() string {
return "AddToClusterMessage:{\n source: " + req.Source.String() + ",\n dest: " + req.Dest.String() + ",\n message: " + req.Message + " }"
}
// function for displaying available network interfaces
func availableInterfaces() {
// get network interfaces currently available
interfaces, err := net.Interfaces()
// error handling
if err != nil {
fmt.Println("Error in detecting network interfaces: " + err.Error())
os.Exit(0)
}
if len(interfaces) > 0 {
fmt.Println("\nList of available network interfaces:")
for index, i := range interfaces {
fmt.Printf("%d.%v\n", index, i.Name)
}
fmt.Printf("\nSelect the interface that you want to use: (0-%d): ", len(interfaces))
reader := bufio.NewReader(os.Stdin)
char, _, err := reader.ReadRune()
if err != nil {
fmt.Println(err)
}
fmt.Println(char)
}
}
func main() {
/* get command-line arguments */
makeMasterOnError := flag.Bool("makeMasterOnError", false, "make this node master if unable to connect to the cluster ip provided.")
clusterip := flag.String("clusterip", "127.0.0.1:8001", "ip address of any node to connect")
myport := flag.String("myport", "8001", "ip address to run this node on. default is 8001.")
flag.Parse()
var myIp string
/* Generate id */
/* here we are using the rand.Seed() method to generate random seed
for the RNG */
// rand.Seed() expects a 64 bit integer value and here we are doing so
// by passing the value of current time and converting the time into
// 64 bit integer using UnixNano() function
rand.Seed(time.Now().UTC().UnixNano())
myid := rand.Intn(99999999)
// InterfaceAddrs returns a list of the system's network interface addresses.
addr, err := net.InterfaceAddrs()
// if there's an error, show error message and exit program
if err != nil {
os.Stderr.WriteString("Could not retrieve interface addresses.\nError: " + err.Error() + "\n")
os.Exit(1)
}
// go through all the network interfaces found
// range cycles through the whole array/slice of InterfaceAddrs()
for _, a := range addr {
// short one-liner to retrieve the value for IP address
// the ok keyword is a boolean in Go and it is true if the function
// returns true
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
// IP.To4 converts the IPv4 address to a 4-byte representation
if ipnet.IP.To4() != nil {
myIp = ipnet.IP.String()
}
}
}
/* create a NodeInfo object using the values provided
*myport is deferencing the pointer myport to retrieve the actual value */
me := NodeInfo{NodeId: myid, NodeIpAddr: myIp, Port: *myport}
/* Still figuring out why the NodeId is -1.
getting the IP address and Port number by using the split func on clusterip */
dest := NodeInfo{NodeId: -1, NodeIpAddr: strings.Split(*clusterip, ":")[0], Port: strings.Split(*clusterip, ":")[1]}
fmt.Println("My details:", me.String())
/* Try to connect to the cluster, and send request to cluster if able to connect */
ableToConnect := connectToCluster(me, dest)
/* Check if you are able to connect to a cluster and also check
if makeMasterOnError is checked or not. If no cluster is found and
makeMasterOnError is checked, then configure this node as the master */
if ableToConnect || (!ableToConnect && *makeMasterOnError) {
if *makeMasterOnError {
fmt.Println("Will start this node as master.")
}
listenOnPort(me)
} else {
fmt.Println("Quitting system. Set makeMasterOnError flag to make the node master.", myid)
}
}
/*
* This is a useful utility to format the json packet to send requests
* This tiny block is sort of important else you will end up sending blank messages.
*/
func getAddToClusterMessage(source NodeInfo, dest NodeInfo, message string) AddToClusterMessage {
return AddToClusterMessage{
Source: NodeInfo{
NodeId: source.NodeId,
NodeIpAddr: source.NodeIpAddr,
Port: source.Port,
},
Dest: NodeInfo{
NodeId: dest.NodeId,
NodeIpAddr: dest.NodeIpAddr,
Port: dest.Port,
},
Message: message,
}
}
func connectToCluster(me NodeInfo, dest NodeInfo) bool {
/* connect to this socket details provided */
connOut, err := net.DialTimeout("tcp", dest.NodeIpAddr+":"+dest.Port, time.Duration(10)*time.Second)
// if an error occurred
if err != nil {
if _, ok := err.(net.Error); ok {
fmt.Println("Couldn't connect to cluster.", me.NodeId)
return false
}
} else {
fmt.Println("Connected to cluster. Sending message to node.")
text := "Hi nody.. please add me to the cluster.."
requestMessage := getAddToClusterMessage(me, dest, text)
json.NewEncoder(connOut).Encode(&requestMessage)
decoder := json.NewDecoder(connOut)
var responseMessage AddToClusterMessage
decoder.Decode(&responseMessage)
fmt.Println("Got response:\n" + responseMessage.String())
return true
}
return false
}
func listenOnPort(me NodeInfo) {
/* Listen for incoming messages */
ln, _ := net.Listen("tcp", fmt.Sprint(":"+me.Port))
/* accept connection on port */
/* not sure if looping infinetely on ln.Accept() is good idea */
for {
connIn, err := ln.Accept()
if err != nil {
if _, ok := err.(net.Error); ok {
fmt.Println("Error received while listening.", me.NodeId)
}
} else {
var requestMessage AddToClusterMessage
json.NewDecoder(connIn).Decode(&requestMessage)
fmt.Println("Got request:\n" + requestMessage.String())
text := "OK."
responseMessage := getAddToClusterMessage(me, requestMessage.Source, text)
json.NewEncoder(connIn).Encode(&responseMessage)
connIn.Close()
}
}
}