nodeGrpcController.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. package controller
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/gravitl/netmaker/functions"
  6. nodepb "github.com/gravitl/netmaker/grpc"
  7. "github.com/gravitl/netmaker/models"
  8. "github.com/gravitl/netmaker/servercfg"
  9. "go.mongodb.org/mongo-driver/mongo"
  10. "google.golang.org/grpc/codes"
  11. "google.golang.org/grpc/status"
  12. )
  13. type NodeServiceServer struct {
  14. NodeDB *mongo.Collection
  15. nodepb.UnimplementedNodeServiceServer
  16. }
  17. func (s *NodeServiceServer) ReadNode(ctx context.Context, req *nodepb.ReadNodeReq) (*nodepb.ReadNodeRes, error) {
  18. // convert string id (from proto) to mongoDB ObjectId
  19. macaddress := req.GetMacaddress()
  20. networkName := req.GetNetwork()
  21. network, _ := functions.GetParentNetwork(networkName)
  22. node, err := GetNode(macaddress, networkName)
  23. if err != nil {
  24. return nil, status.Errorf(codes.InvalidArgument, fmt.Sprintf("Something went wrong: %v", err))
  25. }
  26. /*
  27. if node == nil {
  28. return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not find node with Mac Address %s: %v", req.GetMacaddress(), err))
  29. }
  30. */
  31. // Cast to ReadNodeRes type
  32. dualvar := false
  33. if network.IsDualStack != nil {
  34. dualvar = *network.IsDualStack
  35. }
  36. localvar := false
  37. if network.IsLocal != nil {
  38. localvar = *network.IsLocal
  39. }
  40. response := &nodepb.ReadNodeRes{
  41. Node: &nodepb.Node{
  42. Macaddress: node.MacAddress,
  43. Name: node.Name,
  44. Address: node.Address,
  45. Address6: node.Address6,
  46. Endpoint: node.Endpoint,
  47. Password: node.Password,
  48. Nodenetwork: node.Network,
  49. Interface: node.Interface,
  50. Localaddress: node.LocalAddress,
  51. Postdown: node.PostDown,
  52. Postup: node.PostUp,
  53. Checkininterval: node.CheckInInterval,
  54. Dnsoff: !servercfg.IsDNSMode(),
  55. Ispending: node.IsPending,
  56. Isingressgateway: node.IsIngressGateway,
  57. Ingressgatewayrange: node.IngressGatewayRange,
  58. Publickey: node.PublicKey,
  59. Listenport: node.ListenPort,
  60. Keepalive: node.PersistentKeepalive,
  61. Islocal: localvar,
  62. Isdualstack: dualvar,
  63. Localrange: network.LocalRange,
  64. },
  65. }
  66. return response, nil
  67. }
  68. func (s *NodeServiceServer) GetConn(ctx context.Context, data *nodepb.Client) (*nodepb.Client, error) {
  69. // Get the protobuf node type from the protobuf request type
  70. // Essentially doing req.Node to access the struct with a nil check
  71. // Now we have to convert this into a NodeItem type to convert into BSON
  72. clientreq := models.IntClient{
  73. // ID: primitive.NilObjectID,
  74. Address: data.GetAddress(),
  75. Address6: data.GetAddress6(),
  76. AccessKey: data.GetAccesskey(),
  77. PublicKey: data.GetPublickey(),
  78. PrivateKey: data.GetPrivatekey(),
  79. ServerPort: data.GetServerport(),
  80. ServerKey: data.GetServerkey(),
  81. ServerEndpoint: data.GetServerendpoint(),
  82. }
  83. //Check to see if key is valid
  84. //TODO: Triple inefficient!!! This is the third call to the DB we make for networks
  85. if servercfg.IsRegisterKeyRequired() {
  86. validKey := functions.IsKeyValidGlobal(clientreq.AccessKey)
  87. if !validKey {
  88. return nil, status.Errorf(
  89. codes.Internal,
  90. fmt.Sprintf("Invalid key, and server does not allow no-key signups"),
  91. )
  92. }
  93. }
  94. client, err := RegisterIntClient(clientreq)
  95. if err != nil {
  96. // return internal gRPC error to be handled later
  97. return nil, status.Errorf(
  98. codes.Internal,
  99. fmt.Sprintf("Internal error: %v", err),
  100. )
  101. }
  102. // return the node in a CreateNodeRes type
  103. response := &nodepb.Client{
  104. Privatekey: client.PrivateKey,
  105. Publickey: client.PublicKey,
  106. Accesskey: client.AccessKey,
  107. Address: client.Address,
  108. Address6: client.Address6,
  109. Serverendpoint: client.ServerEndpoint,
  110. Serverport: client.ServerPort,
  111. Serverkey: client.ServerKey,
  112. }
  113. return response, nil
  114. }
  115. func (s *NodeServiceServer) CreateNode(ctx context.Context, req *nodepb.CreateNodeReq) (*nodepb.CreateNodeRes, error) {
  116. // Get the protobuf node type from the protobuf request type
  117. // Essentially doing req.Node to access the struct with a nil check
  118. data := req.GetNode()
  119. // Now we have to convert this into a NodeItem type to convert into BSON
  120. node := models.Node{
  121. // ID: primitive.NilObjectID,
  122. MacAddress: data.GetMacaddress(),
  123. LocalAddress: data.GetLocaladdress(),
  124. Name: data.GetName(),
  125. Address: data.GetAddress(),
  126. Address6: data.GetAddress6(),
  127. AccessKey: data.GetAccesskey(),
  128. Endpoint: data.GetEndpoint(),
  129. PersistentKeepalive: data.GetKeepalive(),
  130. Password: data.GetPassword(),
  131. Interface: data.GetInterface(),
  132. Network: data.GetNodenetwork(),
  133. IsPending: data.GetIspending(),
  134. PublicKey: data.GetPublickey(),
  135. ListenPort: data.GetListenport(),
  136. }
  137. err := ValidateNodeCreate(node.Network, node)
  138. if err != nil {
  139. // return internal gRPC error to be handled later
  140. return nil, err
  141. }
  142. //Check to see if key is valid
  143. //TODO: Triple inefficient!!! This is the third call to the DB we make for networks
  144. validKey := functions.IsKeyValid(node.Network, node.AccessKey)
  145. network, err := functions.GetParentNetwork(node.Network)
  146. if err != nil {
  147. return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not find network: %v", err))
  148. } else {
  149. fmt.Println("Creating node in network " + network.NetID)
  150. }
  151. if !validKey {
  152. //Check to see if network will allow manual sign up
  153. //may want to switch this up with the valid key check and avoid a DB call that way.
  154. if *network.AllowManualSignUp {
  155. node.IsPending = true
  156. } else {
  157. return nil, status.Errorf(
  158. codes.Internal,
  159. fmt.Sprintf("Invalid key, and network does not allow no-key signups"),
  160. )
  161. }
  162. }
  163. node, err = CreateNode(node, node.Network)
  164. if err != nil {
  165. // return internal gRPC error to be handled later
  166. return nil, status.Errorf(
  167. codes.Internal,
  168. fmt.Sprintf("Internal error: %v", err),
  169. )
  170. }
  171. dualvar := false
  172. if network.IsDualStack != nil {
  173. dualvar = *network.IsDualStack
  174. }
  175. localvar := false
  176. if network.IsLocal != nil {
  177. localvar = *network.IsLocal
  178. }
  179. // return the node in a CreateNodeRes type
  180. response := &nodepb.CreateNodeRes{
  181. Node: &nodepb.Node{
  182. Macaddress: node.MacAddress,
  183. Localaddress: node.LocalAddress,
  184. Name: node.Name,
  185. Address: node.Address,
  186. Address6: node.Address6,
  187. Endpoint: node.Endpoint,
  188. Password: node.Password,
  189. Interface: node.Interface,
  190. Nodenetwork: node.Network,
  191. Dnsoff: !servercfg.IsDNSMode(),
  192. Ispending: node.IsPending,
  193. Publickey: node.PublicKey,
  194. Listenport: node.ListenPort,
  195. Keepalive: node.PersistentKeepalive,
  196. Islocal: localvar,
  197. Isdualstack: dualvar,
  198. Localrange: network.LocalRange,
  199. },
  200. }
  201. err = SetNetworkNodesLastModified(node.Network)
  202. if err != nil {
  203. return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not update network last modified date: %v", err))
  204. }
  205. return response, nil
  206. }
  207. func (s *NodeServiceServer) CheckIn(ctx context.Context, req *nodepb.CheckInReq) (*nodepb.CheckInRes, error) {
  208. // Get the protobuf node type from the protobuf request type
  209. // Essentially doing req.Node to access the struct with a nil check
  210. data := req.GetNode()
  211. //postchanges := req.GetPostchanges()
  212. // Now we have to convert this into a NodeItem type to convert into BSON
  213. node := models.Node{
  214. // ID: primitive.NilObjectID,
  215. MacAddress: data.GetMacaddress(),
  216. Address: data.GetAddress(),
  217. Address6: data.GetAddress6(),
  218. Endpoint: data.GetEndpoint(),
  219. Network: data.GetNodenetwork(),
  220. Password: data.GetPassword(),
  221. LocalAddress: data.GetLocaladdress(),
  222. ListenPort: data.GetListenport(),
  223. PersistentKeepalive: data.GetKeepalive(),
  224. PublicKey: data.GetPublickey(),
  225. }
  226. checkinresponse, err := NodeCheckIn(node, node.Network)
  227. if err != nil {
  228. // return internal gRPC error to be handled later
  229. if checkinresponse == (models.CheckInResponse{}) || !checkinresponse.IsPending {
  230. return nil, status.Errorf(
  231. codes.Internal,
  232. fmt.Sprintf("Internal error: %v", err),
  233. )
  234. }
  235. }
  236. // return the node in a CreateNodeRes type
  237. response := &nodepb.CheckInRes{
  238. Checkinresponse: &nodepb.CheckInResponse{
  239. Success: checkinresponse.Success,
  240. Needpeerupdate: checkinresponse.NeedPeerUpdate,
  241. Needdelete: checkinresponse.NeedDelete,
  242. Needconfigupdate: checkinresponse.NeedConfigUpdate,
  243. Needkeyupdate: checkinresponse.NeedKeyUpdate,
  244. Nodemessage: checkinresponse.NodeMessage,
  245. Ispending: checkinresponse.IsPending,
  246. },
  247. }
  248. return response, nil
  249. }
  250. func (s *NodeServiceServer) UpdateNode(ctx context.Context, req *nodepb.UpdateNodeReq) (*nodepb.UpdateNodeRes, error) {
  251. // Get the node data from the request
  252. data := req.GetNode()
  253. // Now we have to convert this into a NodeItem type to convert into BSON
  254. nodechange := models.NodeUpdate{
  255. // ID: primitive.NilObjectID,
  256. MacAddress: data.GetMacaddress(),
  257. Name: data.GetName(),
  258. Address: data.GetAddress(),
  259. Address6: data.GetAddress6(),
  260. LocalAddress: data.GetLocaladdress(),
  261. Endpoint: data.GetEndpoint(),
  262. Password: data.GetPassword(),
  263. PersistentKeepalive: data.GetKeepalive(),
  264. Network: data.GetNodenetwork(),
  265. Interface: data.GetInterface(),
  266. PostDown: data.GetPostdown(),
  267. PostUp: data.GetPostup(),
  268. IsPending: data.GetIspending(),
  269. PublicKey: data.GetPublickey(),
  270. ListenPort: data.GetListenport(),
  271. }
  272. // Convert the Id string to a MongoDB ObjectId
  273. macaddress := nodechange.MacAddress
  274. networkName := nodechange.Network
  275. network, _ := functions.GetParentNetwork(networkName)
  276. err := ValidateNodeUpdate(networkName, nodechange)
  277. if err != nil {
  278. return nil, err
  279. }
  280. node, err := functions.GetNodeByMacAddress(networkName, macaddress)
  281. if err != nil {
  282. return nil, status.Errorf(
  283. codes.NotFound,
  284. fmt.Sprintf("Could not find node with supplied Mac Address: %v", err),
  285. )
  286. }
  287. newnode, err := UpdateNode(nodechange, node)
  288. if err != nil {
  289. return nil, status.Errorf(
  290. codes.NotFound,
  291. fmt.Sprintf("Could not find node with supplied Mac Address: %v", err),
  292. )
  293. }
  294. dualvar := false
  295. if network.IsDualStack != nil {
  296. dualvar = *network.IsDualStack
  297. }
  298. localvar := false
  299. if network.IsLocal != nil {
  300. localvar = *network.IsLocal
  301. }
  302. return &nodepb.UpdateNodeRes{
  303. Node: &nodepb.Node{
  304. Macaddress: newnode.MacAddress,
  305. Localaddress: newnode.LocalAddress,
  306. Name: newnode.Name,
  307. Address: newnode.Address,
  308. Address6: newnode.Address6,
  309. Endpoint: newnode.Endpoint,
  310. Password: newnode.Password,
  311. Interface: newnode.Interface,
  312. Postdown: newnode.PostDown,
  313. Postup: newnode.PostUp,
  314. Nodenetwork: newnode.Network,
  315. Ispending: newnode.IsPending,
  316. Publickey: newnode.PublicKey,
  317. Dnsoff: !servercfg.IsDNSMode(),
  318. Listenport: newnode.ListenPort,
  319. Keepalive: newnode.PersistentKeepalive,
  320. Islocal: localvar,
  321. Isdualstack: dualvar,
  322. Localrange: network.LocalRange,
  323. },
  324. }, nil
  325. }
  326. func (s *NodeServiceServer) DeleteNode(ctx context.Context, req *nodepb.DeleteNodeReq) (*nodepb.DeleteNodeRes, error) {
  327. fmt.Println("beginning node delete")
  328. macaddress := req.GetMacaddress()
  329. network := req.GetNetworkName()
  330. success, err := DeleteNode(macaddress, network)
  331. if err != nil || !success {
  332. fmt.Println("Error deleting node.")
  333. fmt.Println(err)
  334. return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not find/delete node with mac address %s", macaddress))
  335. }
  336. fmt.Println("updating network last modified of " + req.GetNetworkName())
  337. err = SetNetworkNodesLastModified(req.GetNetworkName())
  338. if err != nil {
  339. fmt.Println("Error updating Network")
  340. fmt.Println(err)
  341. return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not update network last modified date: %v", err))
  342. }
  343. return &nodepb.DeleteNodeRes{
  344. Success: true,
  345. }, nil
  346. }
  347. func (s *NodeServiceServer) GetPeers(req *nodepb.GetPeersReq, stream nodepb.NodeService_GetPeersServer) error {
  348. // Initiate a NodeItem type to write decoded data to
  349. //data := &models.PeersResponse{}
  350. // collection.Find returns a cursor for our (empty) query
  351. //cursor, err := s.NodeDB.Find(context.Background(), bson.M{})
  352. peers, err := GetPeersList(req.GetNetwork())
  353. if err != nil {
  354. return status.Errorf(codes.Internal, fmt.Sprintf("Unknown internal error: %v", err))
  355. }
  356. // cursor.Next() returns a boolean, if false there are no more items and loop will break
  357. for i := 0; i < len(peers); i++ {
  358. // If no error is found send node over stream
  359. stream.Send(&nodepb.GetPeersRes{
  360. Peers: &nodepb.PeersResponse{
  361. Address: peers[i].Address,
  362. Address6: peers[i].Address6,
  363. Endpoint: peers[i].Endpoint,
  364. Egressgatewayrange: peers[i].EgressGatewayRange,
  365. Isegressgateway: peers[i].IsEgressGateway,
  366. Publickey: peers[i].PublicKey,
  367. Keepalive: peers[i].KeepAlive,
  368. Listenport: peers[i].ListenPort,
  369. Localaddress: peers[i].LocalAddress,
  370. },
  371. })
  372. }
  373. node, err := functions.GetNodeByMacAddress(req.GetNetwork(), req.GetMacaddress())
  374. if err != nil {
  375. return status.Errorf(codes.Internal, fmt.Sprintf("Could not get node: %v", err))
  376. }
  377. err = TimestampNode(node, false, true, false)
  378. if err != nil {
  379. return status.Errorf(codes.Internal, fmt.Sprintf("Internal error occurred: %v", err))
  380. }
  381. return nil
  382. }
  383. func (s *NodeServiceServer) GetExtPeers(req *nodepb.GetExtPeersReq, stream nodepb.NodeService_GetExtPeersServer) error {
  384. // Initiate a NodeItem type to write decoded data to
  385. //data := &models.PeersResponse{}
  386. // collection.Find returns a cursor for our (empty) query
  387. //cursor, err := s.NodeDB.Find(context.Background(), bson.M{})
  388. peers, err := GetExtPeersList(req.GetNetwork(), req.GetMacaddress())
  389. if err != nil {
  390. return status.Errorf(codes.Internal, fmt.Sprintf("Unknown internal error: %v", err))
  391. }
  392. // cursor.Next() returns a boolean, if false there are no more items and loop will break
  393. for i := 0; i < len(peers); i++ {
  394. // If no error is found send node over stream
  395. stream.Send(&nodepb.GetExtPeersRes{
  396. Extpeers: &nodepb.ExtPeersResponse{
  397. Address: peers[i].Address,
  398. Address6: peers[i].Address6,
  399. Endpoint: peers[i].Endpoint,
  400. Publickey: peers[i].PublicKey,
  401. Keepalive: peers[i].KeepAlive,
  402. Listenport: peers[i].ListenPort,
  403. Localaddress: peers[i].LocalAddress,
  404. },
  405. })
  406. }
  407. node, err := functions.GetNodeByMacAddress(req.GetNetwork(), req.GetMacaddress())
  408. if err != nil {
  409. return status.Errorf(codes.Internal, fmt.Sprintf("Could not get node: %v", err))
  410. }
  411. err = TimestampNode(node, false, true, false)
  412. if err != nil {
  413. return status.Errorf(codes.Internal, fmt.Sprintf("Internal error occurred: %v", err))
  414. }
  415. return nil
  416. }