nodeGrpcController.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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. /*
  69. func (s *NodeServiceServer) GetConn(ctx context.Context, data *nodepb.Client) (*nodepb.Client, error) {
  70. // Get the protobuf node type from the protobuf request type
  71. // Essentially doing req.Node to access the struct with a nil check
  72. // Now we have to convert this into a NodeItem type to convert into BSON
  73. clientreq := models.IntClient{
  74. // ID: primitive.NilObjectID,
  75. Address: data.GetAddress(),
  76. Address6: data.GetAddress6(),
  77. AccessKey: data.GetAccesskey(),
  78. PublicKey: data.GetPublickey(),
  79. PrivateKey: data.GetPrivatekey(),
  80. ServerPort: data.GetServerport(),
  81. ServerKey: data.GetServerkey(),
  82. ServerWGEndpoint: data.GetServerwgendpoint(),
  83. }
  84. //Check to see if key is valid
  85. //TODO: Triple inefficient!!! This is the third call to the DB we make for networks
  86. if servercfg.IsRegisterKeyRequired() {
  87. validKey := functions.IsKeyValidGlobal(clientreq.AccessKey)
  88. if !validKey {
  89. return nil, status.Errorf(
  90. codes.Internal,
  91. fmt.Sprintf("Invalid key, and server does not allow no-key signups"),
  92. )
  93. }
  94. }
  95. client, err := RegisterIntClient(clientreq)
  96. if err != nil {
  97. // return internal gRPC error to be handled later
  98. return nil, status.Errorf(
  99. codes.Internal,
  100. fmt.Sprintf("Internal error: %v", err),
  101. )
  102. }
  103. // return the node in a CreateNodeRes type
  104. response := &nodepb.Client{
  105. Privatekey: client.PrivateKey,
  106. Publickey: client.PublicKey,
  107. Accesskey: client.AccessKey,
  108. Address: client.Address,
  109. Address6: client.Address6,
  110. Serverwgendpoint: client.ServerWGEndpoint,
  111. Serverport: client.ServerPort,
  112. Serverkey: client.ServerKey,
  113. }
  114. return response, nil
  115. }
  116. */
  117. func (s *NodeServiceServer) CreateNode(ctx context.Context, req *nodepb.CreateNodeReq) (*nodepb.CreateNodeRes, error) {
  118. // Get the protobuf node type from the protobuf request type
  119. // Essentially doing req.Node to access the struct with a nil check
  120. data := req.GetNode()
  121. // Now we have to convert this into a NodeItem type to convert into BSON
  122. node := models.Node{
  123. // ID: primitive.NilObjectID,
  124. MacAddress: data.GetMacaddress(),
  125. LocalAddress: data.GetLocaladdress(),
  126. Name: data.GetName(),
  127. Address: data.GetAddress(),
  128. Address6: data.GetAddress6(),
  129. AccessKey: data.GetAccesskey(),
  130. Endpoint: data.GetEndpoint(),
  131. PersistentKeepalive: data.GetKeepalive(),
  132. Password: data.GetPassword(),
  133. Interface: data.GetInterface(),
  134. Network: data.GetNodenetwork(),
  135. IsPending: data.GetIspending(),
  136. PublicKey: data.GetPublickey(),
  137. ListenPort: data.GetListenport(),
  138. }
  139. err := ValidateNodeCreate(node.Network, node)
  140. if err != nil {
  141. // return internal gRPC error to be handled later
  142. return nil, err
  143. }
  144. //Check to see if key is valid
  145. //TODO: Triple inefficient!!! This is the third call to the DB we make for networks
  146. validKey := functions.IsKeyValid(node.Network, node.AccessKey)
  147. network, err := functions.GetParentNetwork(node.Network)
  148. if err != nil {
  149. return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not find network: %v", err))
  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. macaddress := req.GetMacaddress()
  328. network := req.GetNetworkName()
  329. success, err := DeleteNode(macaddress, network)
  330. if err != nil || !success {
  331. fmt.Println("Error deleting node.")
  332. fmt.Println(err)
  333. return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not find/delete node with mac address %s", macaddress))
  334. }
  335. fmt.Println("updating network last modified of " + req.GetNetworkName())
  336. err = SetNetworkNodesLastModified(req.GetNetworkName())
  337. if err != nil {
  338. fmt.Println("Error updating Network")
  339. fmt.Println(err)
  340. return nil, status.Errorf(codes.NotFound, fmt.Sprintf("Could not update network last modified date: %v", err))
  341. }
  342. return &nodepb.DeleteNodeRes{
  343. Success: true,
  344. }, nil
  345. }
  346. func (s *NodeServiceServer) GetPeers(req *nodepb.GetPeersReq, stream nodepb.NodeService_GetPeersServer) error {
  347. // Initiate a NodeItem type to write decoded data to
  348. //data := &models.PeersResponse{}
  349. // collection.Find returns a cursor for our (empty) query
  350. //cursor, err := s.NodeDB.Find(context.Background(), bson.M{})
  351. peers, err := GetPeersList(req.GetNetwork())
  352. if err != nil {
  353. return status.Errorf(codes.Internal, fmt.Sprintf("Unknown internal error: %v", err))
  354. }
  355. // cursor.Next() returns a boolean, if false there are no more items and loop will break
  356. for i := 0; i < len(peers); i++ {
  357. // If no error is found send node over stream
  358. stream.Send(&nodepb.GetPeersRes{
  359. Peers: &nodepb.PeersResponse{
  360. Address: peers[i].Address,
  361. Address6: peers[i].Address6,
  362. Endpoint: peers[i].Endpoint,
  363. Egressgatewayrange: peers[i].EgressGatewayRange,
  364. Isegressgateway: peers[i].IsEgressGateway,
  365. Publickey: peers[i].PublicKey,
  366. Keepalive: peers[i].KeepAlive,
  367. Listenport: peers[i].ListenPort,
  368. Localaddress: peers[i].LocalAddress,
  369. },
  370. })
  371. }
  372. node, err := functions.GetNodeByMacAddress(req.GetNetwork(), req.GetMacaddress())
  373. if err != nil {
  374. return status.Errorf(codes.Internal, fmt.Sprintf("Could not get node: %v", err))
  375. }
  376. err = TimestampNode(node, false, true, false)
  377. if err != nil {
  378. return status.Errorf(codes.Internal, fmt.Sprintf("Internal error occurred: %v", err))
  379. }
  380. return nil
  381. }
  382. func (s *NodeServiceServer) GetExtPeers(req *nodepb.GetExtPeersReq, stream nodepb.NodeService_GetExtPeersServer) error {
  383. // Initiate a NodeItem type to write decoded data to
  384. //data := &models.PeersResponse{}
  385. // collection.Find returns a cursor for our (empty) query
  386. //cursor, err := s.NodeDB.Find(context.Background(), bson.M{})
  387. peers, err := GetExtPeersList(req.GetNetwork(), req.GetMacaddress())
  388. if err != nil {
  389. return status.Errorf(codes.Internal, fmt.Sprintf("Unknown internal error: %v", err))
  390. }
  391. // cursor.Next() returns a boolean, if false there are no more items and loop will break
  392. for i := 0; i < len(peers); i++ {
  393. // If no error is found send node over stream
  394. stream.Send(&nodepb.GetExtPeersRes{
  395. Extpeers: &nodepb.ExtPeersResponse{
  396. Address: peers[i].Address,
  397. Address6: peers[i].Address6,
  398. Endpoint: peers[i].Endpoint,
  399. Publickey: peers[i].PublicKey,
  400. Keepalive: peers[i].KeepAlive,
  401. Listenport: peers[i].ListenPort,
  402. Localaddress: peers[i].LocalAddress,
  403. },
  404. })
  405. }
  406. node, err := functions.GetNodeByMacAddress(req.GetNetwork(), req.GetMacaddress())
  407. if err != nil {
  408. return status.Errorf(codes.Internal, fmt.Sprintf("Could not get node: %v", err))
  409. }
  410. err = TimestampNode(node, false, true, false)
  411. if err != nil {
  412. return status.Errorf(codes.Internal, fmt.Sprintf("Internal error occurred: %v", err))
  413. }
  414. return nil
  415. }