package models

import (
	"errors"
	"k8s-console/utils"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"log"
)

/**
  获取集群node节点，除master节点
*/
func GetNodes() ([]string, error) {
	nodes := []string{}
	k8sClient := utils.GetK8sClient()
	if k8sClient == nil {
		log.Printf("获取k8s集群失败")
		return nodes, errors.New("连接k8s集群失败")
	}
	nodeList, err := k8sClient.CoreV1().Nodes().List(metav1.ListOptions{})
	if err != nil {
		return nodes, err
	}
	items := nodeList.Items
	for _, v := range items {
		nodeRole := v.Labels["kubernetes.io/role"] // 节点角色
		if nodeRole == "node" {
			if !v.Spec.Unschedulable {
				nodes = append(nodes, v.Name)
			}
		} else if nodeRole == "master" {
			if !v.Spec.Unschedulable {
				nodes = append(nodes, v.Name)
			}
		}
	}
	return nodes, nil
}

/**
  是否包含节点
*/
func IsContainNode(nodeIp string) bool {
	flag := false
	nodes, _ := GetNodes()
	if len(nodes) > 0 {
		for _, v := range nodes {
			if v == nodeIp {
				flag = true
				break
			}
		}
	}
	return flag
}
