netmaker/logic/nodes.go

620 lines
16 KiB
Go
Raw Normal View History

package logic
import (
2022-11-15 22:52:17 +08:00
"context"
"encoding/json"
2021-10-27 00:27:29 +08:00
"errors"
"fmt"
"net"
"time"
2022-09-26 20:17:20 +08:00
validator "github.com/go-playground/validator/v10"
2022-01-21 05:39:54 +08:00
"github.com/google/uuid"
"github.com/gravitl/netmaker/database"
2021-12-07 04:31:08 +08:00
"github.com/gravitl/netmaker/logger"
2022-02-26 05:28:58 +08:00
"github.com/gravitl/netmaker/logic/acls"
"github.com/gravitl/netmaker/logic/acls/nodeacls"
2022-09-14 03:25:56 +08:00
"github.com/gravitl/netmaker/logic/pro"
"github.com/gravitl/netmaker/logic/pro/proacls"
"github.com/gravitl/netmaker/models"
"github.com/gravitl/netmaker/netclient/ncutils"
"github.com/gravitl/netmaker/servercfg"
2022-12-21 19:40:43 +08:00
"github.com/gravitl/netmaker/validation"
2022-01-21 05:39:54 +08:00
"golang.org/x/crypto/bcrypt"
)
2022-11-15 22:52:17 +08:00
const (
// RELAY_NODE_ERR - error to return if relay node is unfound
RELAY_NODE_ERR = "could not find relay for node"
// NodePurgeTime time to wait for node to response to a NODE_DELETE actions
NodePurgeTime = time.Second * 10
// NodePurgeCheckTime is how often to check nodes for Pending Delete
NodePurgeCheckTime = time.Second * 30
)
2021-10-09 03:07:12 +08:00
// GetNetworkNodes - gets the nodes of a network
func GetNetworkNodes(network string) ([]models.Node, error) {
var nodes []models.Node
allnodes, err := GetAllNodes()
if err != nil {
return []models.Node{}, err
}
for _, node := range allnodes {
if node.Network == network {
nodes = append(nodes, node)
}
}
return nodes, nil
}
2021-10-27 00:27:29 +08:00
// UpdateNode - takes a node and updates another node with it's values
func UpdateNode(currentNode *models.Node, newNode *models.Node) error {
if newNode.Address.String() != currentNode.Address.String() {
2022-01-21 05:39:54 +08:00
if network, err := GetParentNetwork(newNode.Network); err == nil {
if !IsAddressInCIDR(newNode.Address.String(), network.AddressRange) {
2022-01-21 05:39:54 +08:00
return fmt.Errorf("invalid address provided; out of network range for node %s", newNode.ID)
}
}
}
2022-09-14 03:25:56 +08:00
nodeACLDelta := currentNode.DefaultACL != newNode.DefaultACL
2021-10-27 00:27:29 +08:00
newNode.Fill(currentNode)
2022-02-01 09:29:00 +08:00
// check for un-settable server values
2021-10-27 00:27:29 +08:00
if err := ValidateNode(newNode, true); err != nil {
return err
}
2022-09-14 03:25:56 +08:00
2021-10-27 00:27:29 +08:00
if newNode.ID == currentNode.ID {
2022-09-14 03:25:56 +08:00
if nodeACLDelta {
if err := updateProNodeACLS(newNode); err != nil {
logger.Log(1, "failed to apply node level ACLs during creation of node", newNode.ID.String(), "-", err.Error())
2022-09-14 03:25:56 +08:00
return err
}
}
2021-10-27 00:27:29 +08:00
newNode.SetLastModified()
if data, err := json.Marshal(newNode); err != nil {
return err
} else {
return database.Insert(newNode.ID.String(), string(data), database.NODES_TABLE_NAME)
2021-10-27 00:27:29 +08:00
}
}
2022-09-14 03:25:56 +08:00
return fmt.Errorf("failed to update node " + currentNode.ID.String() + ", cannot change ID.")
2021-10-27 00:27:29 +08:00
}
2022-11-15 22:52:17 +08:00
// DeleteNode - marks node for deletion if called by UI or deletes node if called by node
func DeleteNode(node *models.Node, purge bool) error {
2022-11-15 22:52:17 +08:00
if !purge {
newnode := node
newnode.PendingDelete = true
newnode.Action = models.NODE_DELETE
if err := UpdateNode(node, newnode); err != nil {
return err
}
return nil
}
if err := DeleteNodeByID(node); err != nil {
return err
}
if servercfg.Is_EE {
host, _ := GetHost(node.HostID.String())
if err := EnterpriseResetAllPeersFailovers(node.ID.String(), node.Network); err != nil {
logger.Log(0, "failed to reset failover lists during node delete for node", host.Name, node.Network)
2022-11-15 22:52:17 +08:00
}
}
return nil
}
// DeleteNodeByID - deletes a node from database
func DeleteNodeByID(node *models.Node) error {
2022-02-26 05:28:58 +08:00
var err error
var key = node.ID.String()
2022-06-08 04:31:25 +08:00
//delete any ext clients as required
if node.IsIngressGateway {
if err := DeleteGatewayExtClients(node.ID.String(), node.Network); err != nil {
2022-06-08 04:31:25 +08:00
logger.Log(0, "failed to deleted ext clients", err.Error())
}
}
2022-02-26 05:28:58 +08:00
if err = database.DeleteRecord(database.NODES_TABLE_NAME, key); err != nil {
2022-10-06 03:28:13 +08:00
if !database.IsEmptyRecord(err) {
return err
}
2022-02-26 05:28:58 +08:00
}
if servercfg.IsDNSMode() {
SetDNS()
}
2022-09-14 03:25:56 +08:00
if node.OwnerID != "" {
err = pro.DissociateNetworkUserNode(node.OwnerID, node.Network, node.ID.String())
2022-09-14 03:25:56 +08:00
if err != nil {
logger.Log(0, "failed to dissasociate", node.OwnerID, "from node", node.ID.String(), ":", err.Error())
2022-09-14 03:25:56 +08:00
}
}
_, err = nodeacls.RemoveNodeACL(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID.String()))
2022-02-26 05:28:58 +08:00
if err != nil {
// ignoring for now, could hit a nil pointer if delete called twice
logger.Log(2, "attempted to remove node ACL for node", node.ID.String())
2022-02-26 05:28:58 +08:00
}
2022-08-24 23:04:52 +08:00
// removeZombie <- node.ID
if err = DeleteMetrics(node.ID.String()); err != nil {
logger.Log(1, "unable to remove metrics from DB for node", node.ID.String(), err.Error())
}
return nil
2022-02-26 05:28:58 +08:00
}
2021-12-11 04:01:10 +08:00
// IsNodeIDUnique - checks if node id is unique
func IsNodeIDUnique(node *models.Node) (bool, error) {
_, err := database.FetchRecord(database.NODES_TABLE_NAME, node.ID.String())
2021-10-27 00:27:29 +08:00
return database.IsEmptyRecord(err), err
}
2021-12-11 04:01:10 +08:00
// ValidateNode - validates node values
func ValidateNode(node *models.Node, isUpdate bool) error {
2021-10-27 00:27:29 +08:00
v := validator.New()
2022-06-01 00:07:56 +08:00
_ = v.RegisterValidation("id_unique", func(fl validator.FieldLevel) bool {
2021-10-27 00:27:29 +08:00
if isUpdate {
return true
}
isFieldUnique, _ := IsNodeIDUnique(node)
2022-06-01 00:07:56 +08:00
return isFieldUnique
2021-10-27 00:27:29 +08:00
})
_ = v.RegisterValidation("network_exists", func(fl validator.FieldLevel) bool {
_, err := GetNetworkByNode(node)
return err == nil
})
2022-12-21 19:40:43 +08:00
_ = v.RegisterValidation("checkyesornoorunset", func(f1 validator.FieldLevel) bool {
return validation.CheckYesOrNoOrUnset(f1)
})
2021-10-27 00:27:29 +08:00
err := v.Struct(node)
return err
}
2022-09-29 03:49:02 +08:00
// IsFailoverPresent - checks if a node is marked as a failover in given network
func IsFailoverPresent(network string) bool {
netNodes, err := GetNetworkNodes(network)
if err != nil {
return false
}
for i := range netNodes {
if netNodes[i].Failover {
2022-09-29 03:49:02 +08:00
return true
}
}
return false
}
2022-01-21 05:39:54 +08:00
// CreateNode - creates a node in database
func CreateNode(node *models.Node) error {
host, err := GetHost(node.HostID.String())
if err != nil {
return err
}
2022-01-21 05:39:54 +08:00
//encrypt that password so we never see it
hash, err := bcrypt.GenerateFromPassword([]byte(host.HostPass), 5)
2022-01-21 05:39:54 +08:00
if err != nil {
return err
}
//set password to encrypted password
host.HostPass = string(hash)
if !node.DNSOn {
2022-01-21 05:39:54 +08:00
if servercfg.IsDNSMode() {
node.DNSOn = true
2022-01-21 05:39:54 +08:00
} else {
node.DNSOn = false
2022-01-21 05:39:54 +08:00
}
}
2022-02-02 04:27:00 +08:00
2022-01-21 05:39:54 +08:00
SetNodeDefaults(node)
2022-02-02 04:27:00 +08:00
defaultACLVal := acls.Allowed
parentNetwork, err := GetNetwork(node.Network)
if err == nil {
if parentNetwork.DefaultACL != "yes" {
defaultACLVal = acls.NotAllowed
2022-02-02 04:27:00 +08:00
}
}
2022-09-14 03:25:56 +08:00
if node.DefaultACL == "" {
node.DefaultACL = "unset"
}
if node.Address.IP == nil {
if parentNetwork.IsIPv4 == "yes" {
if node.Address.IP, err = UniqueAddress(node.Network, false); err != nil {
return err
}
2022-02-02 04:27:00 +08:00
}
} else if !IsIPUnique(node.Network, node.Address.String(), database.NODES_TABLE_NAME, false) {
return fmt.Errorf("invalid address: ipv4 " + node.Address.String() + " is not unique")
2022-01-21 05:39:54 +08:00
}
2022-02-02 04:27:00 +08:00
if node.Address6.IP == nil {
if parentNetwork.IsIPv6 == "yes" {
if node.Address6.IP, err = UniqueAddress6(node.Network, false); err != nil {
return err
}
2022-02-02 04:27:00 +08:00
}
} else if !IsIPUnique(node.Network, node.Address6.String(), database.NODES_TABLE_NAME, true) {
return fmt.Errorf("invalid address: ipv6 " + node.Address6.String() + " is not unique")
}
2022-01-21 05:39:54 +08:00
node.ID = uuid.New()
2022-01-21 05:39:54 +08:00
//Create a JWT for the node
tokenString, _ := CreateJWT(node.ID.String(), host.MacAddress.String(), node.Network)
2022-01-21 05:39:54 +08:00
if tokenString == "" {
2022-09-15 01:26:31 +08:00
//logic.ReturnErrorResponse(w, r, errorResponse)
2022-01-21 05:39:54 +08:00
return err
}
err = ValidateNode(node, false)
if err != nil {
return err
}
CheckZombies(node, host.MacAddress)
2022-01-21 05:39:54 +08:00
nodebytes, err := json.Marshal(&node)
if err != nil {
return err
}
err = database.Insert(node.ID.String(), string(nodebytes), database.NODES_TABLE_NAME)
2022-01-21 05:39:54 +08:00
if err != nil {
return err
}
_, err = nodeacls.CreateNodeACL(nodeacls.NetworkID(node.Network), nodeacls.NodeID(node.ID.String()), defaultACLVal)
2022-02-26 05:28:58 +08:00
if err != nil {
logger.Log(1, "failed to create node ACL for node,", node.ID.String(), "err:", err.Error())
2022-02-26 05:28:58 +08:00
return err
}
2022-09-14 03:25:56 +08:00
if err = updateProNodeACLS(node); err != nil {
logger.Log(1, "failed to apply node level ACLs during creation of node", node.ID.String(), "-", err.Error())
2022-09-14 03:25:56 +08:00
return err
}
if err = UpdateMetrics(node.ID.String(), &models.Metrics{Connectivity: make(map[string]models.Metric)}); err != nil {
logger.Log(1, "failed to initialize metrics for node", node.ID.String(), err.Error())
2022-09-14 03:25:56 +08:00
}
2022-01-21 05:39:54 +08:00
SetNetworkNodesLastModified(node.Network)
if servercfg.IsDNSMode() {
err = SetDNS()
}
return err
}
2021-10-27 00:27:29 +08:00
// GetAllNodes - returns all nodes in the DB
func GetAllNodes() ([]models.Node, error) {
var nodes []models.Node
2021-10-27 00:27:29 +08:00
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
if err != nil {
if database.IsEmptyRecord(err) {
return []models.Node{}, nil
2021-10-27 00:27:29 +08:00
}
return []models.Node{}, err
2021-10-27 00:27:29 +08:00
}
for _, value := range collection {
var node models.Node
2021-10-27 00:27:29 +08:00
if err := json.Unmarshal([]byte(value), &node); err != nil {
return []models.Node{}, err
2021-10-27 00:27:29 +08:00
}
// add node to our array
nodes = append(nodes, node)
}
return nodes, nil
}
// GetNetworkByNode - gets the network model from a node
func GetNetworkByNode(node *models.Node) (models.Network, error) {
2021-12-11 04:01:10 +08:00
var network = models.Network{}
2021-10-27 00:27:29 +08:00
networkData, err := database.FetchRecord(database.NETWORKS_TABLE_NAME, node.Network)
if err != nil {
return network, err
}
if err = json.Unmarshal([]byte(networkData), &network); err != nil {
return models.Network{}, err
}
return network, nil
}
// SetNodeDefaults - sets the defaults of a node to avoid empty fields
func SetNodeDefaults(node *models.Node) {
2021-10-27 00:27:29 +08:00
parentNetwork, _ := GetNetworkByNode(node)
_, cidr, err := net.ParseCIDR(parentNetwork.AddressRange)
if err == nil {
node.NetworkRange = *cidr
}
_, cidr, err = net.ParseCIDR(parentNetwork.AddressRange6)
if err == nil {
node.NetworkRange6 = *cidr
}
node.ExpirationDateTime = time.Now().Add(models.TEN_YEARS_IN_SECONDS)
2021-10-27 00:27:29 +08:00
if node.DefaultACL == "" {
2022-09-20 04:20:58 +08:00
node.DefaultACL = parentNetwork.DefaultACL
}
2021-10-27 00:27:29 +08:00
if node.PersistentKeepalive == 0 {
node.PersistentKeepalive = int(parentNetwork.DefaultKeepalive)
2021-10-27 00:27:29 +08:00
}
if node.PostUp == "" {
postup := parentNetwork.DefaultPostUp
node.PostUp = postup
}
2022-01-06 03:14:32 +08:00
if node.PostDown == "" {
postdown := parentNetwork.DefaultPostDown
node.PostDown = postdown
}
2021-10-27 00:27:29 +08:00
// == Parent Network settings ==
2022-04-20 02:42:04 +08:00
2021-10-27 00:27:29 +08:00
// == node defaults if not set by parent ==
///TODO ___ REVISIT ------
///TODO ___ REVISIT ------
///TODO ___ REVISIT ------
///TODO ___ REVISIT ------
///TODO ___ REVISIT ------
//node.SetIPForwardingDefault()
//node.SetDNSOnDefault()
//node.SetIsLocalDefault()
//node.SetLastModified()
//node.SetDefaultName()
//node.SetLastCheckIn()
//node.SetLastPeerUpdate()
//node.SetDefaultAction()
//node.SetIsServerDefault()
//node.SetIsStaticDefault()
//node.SetDefaultEgressGateway()
//node.SetDefaultIngressGateway()
//node.SetDefaulIsPending()
//node.SetDefaultMTU()
//node.SetDefaultNFTablesPresent()
//node.SetDefaultIsRelayed()
//node.SetDefaultIsRelay()
//node.SetDefaultIsDocker()
//node.SetDefaultIsK8S()
//node.SetDefaultIsHub()
//node.SetDefaultConnected()
//node.SetDefaultACL()
//node.SetDefaultFailover()
///TODO ___ REVISIT ------
///TODO ___ REVISIT ------
///TODO ___ REVISIT ------
///TODO ___ REVISIT ------
2021-10-27 00:27:29 +08:00
}
// GetRecordKey - get record key
2022-01-11 06:52:21 +08:00
// depricated
2021-10-27 00:27:29 +08:00
func GetRecordKey(id string, network string) (string, error) {
if id == "" || network == "" {
return "", errors.New("unable to get record key")
}
return id + "###" + network, nil
}
// GetNodeByMacAddress - gets a node by mac address
func GetNodeByMacAddress(network string, macaddress string) (models.Node, error) {
2021-10-27 00:27:29 +08:00
var node models.Node
2021-10-27 00:27:29 +08:00
key, err := GetRecordKey(macaddress, network)
if err != nil {
return node, err
}
record, err := database.FetchRecord(database.NODES_TABLE_NAME, key)
if err != nil {
return models.Node{}, err
2021-10-27 00:27:29 +08:00
}
if err = json.Unmarshal([]byte(record), &node); err != nil {
return models.Node{}, err
2021-10-27 00:27:29 +08:00
}
SetNodeDefaults(&node)
return node, nil
}
// GetNodesByAddress - gets a node by mac address
func GetNodesByAddress(network string, addresses []string) ([]models.Node, error) {
var nodes []models.Node
allnodes, err := GetAllNodes()
if err != nil {
return []models.Node{}, err
}
for _, node := range allnodes {
if node.Network == network && ncutils.StringSliceContains(addresses, node.Address.String()) {
nodes = append(nodes, node)
}
}
return nodes, nil
}
2021-10-27 00:27:29 +08:00
// GetDeletedNodeByMacAddress - get a deleted node
func GetDeletedNodeByMacAddress(network string, macaddress string) (models.Node, error) {
2021-10-27 00:27:29 +08:00
var node models.Node
2021-10-27 00:27:29 +08:00
key, err := GetRecordKey(macaddress, network)
if err != nil {
return node, err
}
record, err := database.FetchRecord(database.DELETED_NODES_TABLE_NAME, key)
if err != nil {
return models.Node{}, err
2021-10-27 00:27:29 +08:00
}
if err = json.Unmarshal([]byte(record), &node); err != nil {
return models.Node{}, err
2021-10-27 00:27:29 +08:00
}
SetNodeDefaults(&node)
return node, nil
}
// GetNodeRelay - gets the relay node of a given network
func GetNodeRelay(network string, relayedNodeAddr string) (models.Node, error) {
2021-10-27 00:27:29 +08:00
collection, err := database.FetchRecords(database.NODES_TABLE_NAME)
var relay models.Node
2021-10-27 00:27:29 +08:00
if err != nil {
if database.IsEmptyRecord(err) {
return relay, nil
}
2021-12-07 04:31:08 +08:00
logger.Log(2, err.Error())
2021-10-27 00:27:29 +08:00
return relay, err
}
for _, value := range collection {
err := json.Unmarshal([]byte(value), &relay)
if err != nil {
2021-12-07 04:31:08 +08:00
logger.Log(2, err.Error())
2021-10-27 00:27:29 +08:00
continue
}
if relay.IsRelay {
2021-10-27 00:27:29 +08:00
for _, addr := range relay.RelayAddrs {
if addr == relayedNodeAddr {
return relay, nil
}
}
}
}
2022-02-07 00:43:07 +08:00
return relay, errors.New(RELAY_NODE_ERR + " " + relayedNodeAddr)
2021-10-27 00:27:29 +08:00
}
2022-01-10 23:55:05 +08:00
func GetNodeByID(uuid string) (models.Node, error) {
2022-01-10 23:55:05 +08:00
var record, err = database.FetchRecord(database.NODES_TABLE_NAME, uuid)
if err != nil {
return models.Node{}, err
2022-01-10 23:55:05 +08:00
}
var node models.Node
2022-01-10 23:55:05 +08:00
if err = json.Unmarshal([]byte(record), &node); err != nil {
return models.Node{}, err
2022-01-10 23:55:05 +08:00
}
return node, nil
}
2022-01-11 06:52:21 +08:00
// GetDeletedNodeByID - get a deleted node
func GetDeletedNodeByID(uuid string) (models.Node, error) {
2022-01-11 06:52:21 +08:00
var node models.Node
2022-01-11 06:52:21 +08:00
record, err := database.FetchRecord(database.DELETED_NODES_TABLE_NAME, uuid)
if err != nil {
return models.Node{}, err
2022-01-11 06:52:21 +08:00
}
if err = json.Unmarshal([]byte(record), &node); err != nil {
return models.Node{}, err
2022-01-11 06:52:21 +08:00
}
SetNodeDefaults(&node)
return node, nil
}
2022-06-14 04:06:00 +08:00
// FindRelay - returns the node that is the relay for a relayed node
func FindRelay(node *models.Node) *models.Node {
if !node.IsRelayed {
return nil
}
peers, err := GetNetworkNodes(node.Network)
if err != nil {
return nil
}
for _, peer := range peers {
if !peer.IsRelay {
continue
}
for _, ip := range peer.RelayAddrs {
if ip == node.Address.IP.String() || ip == node.Address6.IP.String() {
return &peer
}
}
}
return nil
}
2022-06-14 22:36:30 +08:00
func findNode(ip string) (*models.Node, error) {
2022-06-14 22:36:30 +08:00
nodes, err := GetAllNodes()
if err != nil {
return nil, err
}
for _, node := range nodes {
if node.Address.IP.String() == ip {
2022-06-14 22:36:30 +08:00
return &node, nil
}
if node.Address6.IP.String() == ip {
2022-06-14 22:36:30 +08:00
return &node, nil
}
}
return nil, errors.New("node not found")
}
2022-09-14 03:25:56 +08:00
// GetNetworkIngresses - gets the gateways of a network
func GetNetworkIngresses(network string) ([]models.Node, error) {
var ingresses []models.Node
netNodes, err := GetNetworkNodes(network)
if err != nil {
return []models.Node{}, err
}
for i := range netNodes {
if netNodes[i].IsIngressGateway {
ingresses = append(ingresses, netNodes[i])
}
}
return ingresses, nil
}
2022-09-14 03:25:56 +08:00
// == PRO ==
func updateProNodeACLS(node *models.Node) error {
2022-09-14 03:25:56 +08:00
// == PRO node ACLs ==
networkNodes, err := GetNetworkNodes(node.Network)
if err != nil {
return err
}
if err = proacls.AdjustNodeAcls(node, networkNodes[:]); err != nil {
return err
}
return nil
}
2022-11-15 22:52:17 +08:00
func PurgePendingNodes(ctx context.Context) {
ticker := time.NewTicker(NodePurgeCheckTime)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
nodes, err := GetAllNodes()
if err != nil {
logger.Log(0, "PurgePendingNodes failed to retrieve nodes", err.Error())
continue
}
for _, node := range nodes {
if node.PendingDelete {
modified := node.LastModified
2022-11-15 22:52:17 +08:00
if time.Since(modified) > NodePurgeTime {
if err := DeleteNode(&node, true); err != nil {
logger.Log(0, "failed to purge node", node.ID.String(), err.Error())
2022-11-15 22:52:17 +08:00
} else {
logger.Log(0, "purged node ", node.ID.String())
2022-11-15 22:52:17 +08:00
}
}
}
}
}
}
}
2022-09-14 03:25:56 +08:00
// == END PRO ==