node.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. package models
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "math/rand"
  6. "net"
  7. "strings"
  8. "time"
  9. "log"
  10. "github.com/go-playground/validator/v10"
  11. "github.com/gravitl/netmaker/database"
  12. )
  13. const charset = "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  14. var seededRand *rand.Rand = rand.New(
  15. rand.NewSource(time.Now().UnixNano()))
  16. //node struct
  17. type Node struct {
  18. ID string `json:"id,omitempty" bson:"id,omitempty"`
  19. Address string `json:"address" bson:"address" validate:"omitempty,ipv4"`
  20. Address6 string `json:"address6" bson:"address6" validate:"omitempty,ipv6"`
  21. LocalAddress string `json:"localaddress" bson:"localaddress" validate:"omitempty,ip"`
  22. Name string `json:"name" bson:"name" validate:"omitempty,max=12,in_charset"`
  23. ListenPort int32 `json:"listenport" bson:"listenport" validate:"omitempty,numeric,min=1024,max=65535"`
  24. PublicKey string `json:"publickey" bson:"publickey" validate:"required,base64"`
  25. Endpoint string `json:"endpoint" bson:"endpoint" validate:"required,ip"`
  26. PostUp string `json:"postup" bson:"postup"`
  27. PostDown string `json:"postdown" bson:"postdown"`
  28. AllowedIPs []string `json:"allowedips" bson:"allowedips"`
  29. PersistentKeepalive int32 `json:"persistentkeepalive" bson:"persistentkeepalive" validate:"omitempty,numeric,max=1000"`
  30. SaveConfig string `json:"saveconfig" bson:"saveconfig" validate:"checkyesorno"`
  31. AccessKey string `json:"accesskey" bson:"accesskey"`
  32. Interface string `json:"interface" bson:"interface"`
  33. LastModified int64 `json:"lastmodified" bson:"lastmodified"`
  34. KeyUpdateTimeStamp int64 `json:"keyupdatetimestamp" bson:"keyupdatetimestamp"`
  35. ExpirationDateTime int64 `json:"expdatetime" bson:"expdatetime"`
  36. LastPeerUpdate int64 `json:"lastpeerupdate" bson:"lastpeerupdate"`
  37. LastCheckIn int64 `json:"lastcheckin" bson:"lastcheckin"`
  38. MacAddress string `json:"macaddress" bson:"macaddress" validate:"required,mac,macaddress_unique"`
  39. CheckInInterval int32 `json:"checkininterval" bson:"checkininterval"`
  40. Password string `json:"password" bson:"password" validate:"required,min=6"`
  41. Network string `json:"network" bson:"network" validate:"network_exists"`
  42. IsPending bool `json:"ispending" bson:"ispending"`
  43. IsEgressGateway bool `json:"isegressgateway" bson:"isegressgateway"`
  44. IsIngressGateway bool `json:"isingressgateway" bson:"isingressgateway"`
  45. EgressGatewayRanges []string `json:"egressgatewayranges" bson:"egressgatewayranges"`
  46. IngressGatewayRange string `json:"ingressgatewayrange" bson:"ingressgatewayrange"`
  47. PostChanges string `json:"postchanges" bson:"postchanges"`
  48. StaticIP string `json:"staticip" bson:"staticip"`
  49. StaticPubKey string `json:"staticpubkey" bson:"staticpubkey"`
  50. UDPHolePunch string `json:"udpholepunch" bson:"udpholepunch" validate:"checkyesorno"`
  51. }
  52. //TODO:
  53. //Not sure if below two methods are necessary. May want to revisit
  54. func (node *Node) SetLastModified() {
  55. node.LastModified = time.Now().Unix()
  56. }
  57. func (node *Node) SetLastCheckIn() {
  58. node.LastCheckIn = time.Now().Unix()
  59. }
  60. func (node *Node) SetLastPeerUpdate() {
  61. node.LastPeerUpdate = time.Now().Unix()
  62. }
  63. func (node *Node) SetID() {
  64. node.ID = node.MacAddress + "###" + node.Network
  65. }
  66. func (node *Node) SetExpirationDateTime() {
  67. node.ExpirationDateTime = time.Unix(33174902665, 0).Unix()
  68. }
  69. func (node *Node) SetDefaultName() {
  70. if node.Name == "" {
  71. nodeid := StringWithCharset(5, charset)
  72. nodename := "node-" + nodeid
  73. node.Name = nodename
  74. }
  75. }
  76. func (node *Node) GetNetwork() (Network, error) {
  77. var network Network
  78. networkData, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, node.Network)
  79. if err != nil {
  80. return network, err
  81. }
  82. if err = json.Unmarshal([]byte(networkData), &network); err != nil {
  83. return Network{}, err
  84. }
  85. return network, nil
  86. }
  87. //TODO: I dont know why this exists
  88. //This should exist on the node.go struct. I'm sure there was a reason?
  89. func (node *Node) SetDefaults() {
  90. //TODO: Maybe I should make Network a part of the node struct. Then we can just query the Network object for stuff.
  91. parentNetwork, _ := node.GetNetwork()
  92. node.ExpirationDateTime = time.Unix(33174902665, 0).Unix()
  93. if node.ListenPort == 0 {
  94. node.ListenPort = parentNetwork.DefaultListenPort
  95. }
  96. if node.SaveConfig == "" {
  97. if parentNetwork.DefaultSaveConfig != "" {
  98. node.SaveConfig = parentNetwork.DefaultSaveConfig
  99. } else {
  100. node.SaveConfig = "yes"
  101. }
  102. }
  103. if node.Interface == "" {
  104. node.Interface = parentNetwork.DefaultInterface
  105. }
  106. if node.PersistentKeepalive == 0 {
  107. node.PersistentKeepalive = parentNetwork.DefaultKeepalive
  108. }
  109. if node.PostUp == "" {
  110. postup := parentNetwork.DefaultPostUp
  111. node.PostUp = postup
  112. }
  113. if node.StaticIP == "" {
  114. node.StaticIP = "no"
  115. }
  116. if node.StaticPubKey == "" {
  117. node.StaticPubKey = "no"
  118. }
  119. if node.UDPHolePunch == "" {
  120. node.UDPHolePunch = parentNetwork.DefaultUDPHolePunch
  121. if node.UDPHolePunch == "" {
  122. node.UDPHolePunch = "yes"
  123. }
  124. }
  125. node.CheckInInterval = parentNetwork.DefaultCheckInInterval
  126. node.SetLastModified()
  127. node.SetDefaultName()
  128. node.SetLastCheckIn()
  129. node.SetLastPeerUpdate()
  130. node.SetID()
  131. node.KeyUpdateTimeStamp = time.Now().Unix()
  132. }
  133. func (currentNode *Node) Update(newNode *Node) error {
  134. log.Println("Node SaveConfig:",newNode.SaveConfig)
  135. if err := newNode.Validate(true); err != nil {
  136. return err
  137. }
  138. newNode.SetID()
  139. if newNode.ID == currentNode.ID {
  140. if data, err := json.Marshal(newNode); err != nil {
  141. return err
  142. } else {
  143. newNode.SetLastModified()
  144. err = database.Insert(newNode.ID, string(data), database.NODES_TABLE_NAME)
  145. return err
  146. }
  147. }
  148. // copy values
  149. return errors.New("failed to update node " + newNode.MacAddress + ", cannot change macaddress.")
  150. }
  151. func StringWithCharset(length int, charset string) string {
  152. b := make([]byte, length)
  153. for i := range b {
  154. b[i] = charset[seededRand.Intn(len(charset))]
  155. }
  156. return string(b)
  157. }
  158. //Check for valid IPv4 address
  159. //Note: We dont handle IPv6 AT ALL!!!!! This definitely is needed at some point
  160. //But for iteration 1, lets just stick to IPv4. Keep it simple stupid.
  161. func IsIpv4Net(host string) bool {
  162. return net.ParseIP(host) != nil
  163. }
  164. func (node *Node) Validate(isUpdate bool) error {
  165. log.Println("Node SaveConfig:",node.SaveConfig)
  166. v := validator.New()
  167. _ = v.RegisterValidation("macaddress_unique", func(fl validator.FieldLevel) bool {
  168. if isUpdate {
  169. return true
  170. }
  171. isFieldUnique, _ := node.IsIDUnique()
  172. return isFieldUnique
  173. })
  174. _ = v.RegisterValidation("network_exists", func(fl validator.FieldLevel) bool {
  175. _, err := node.GetNetwork()
  176. return err == nil
  177. })
  178. _ = v.RegisterValidation("in_charset", func(fl validator.FieldLevel) bool {
  179. isgood := node.NameInNodeCharSet()
  180. return isgood
  181. })
  182. _ = v.RegisterValidation("checkyesorno", func(fl validator.FieldLevel) bool {
  183. return CheckYesOrNo(fl)
  184. })
  185. err := v.Struct(node)
  186. return err
  187. }
  188. func (node *Node) IsIDUnique() (bool, error) {
  189. record, err := database.FetchRecord(database.NODES_TABLE_NAME, node.ID)
  190. if err != nil {
  191. return false, err
  192. }
  193. return record == "", err
  194. }
  195. func (node *Node) NameInNodeCharSet() bool {
  196. charset := "abcdefghijklmnopqrstuvwxyz1234567890-"
  197. for _, char := range node.Name {
  198. if !strings.Contains(charset, strings.ToLower(string(char))) {
  199. return false
  200. }
  201. }
  202. return true
  203. }
  204. func GetAllNodes() ([]Node, error) {
  205. var nodes []Node
  206. collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
  207. if err != nil {
  208. return []Node{}, err
  209. }
  210. for _, value := range collection {
  211. var node Node
  212. if err := json.Unmarshal([]byte(value), &node); err != nil {
  213. return []Node{}, err
  214. }
  215. // add node to our array
  216. nodes = append(nodes, node)
  217. }
  218. return nodes, nil
  219. }