github.com/alibaba/sealer@v0.8.6-0.20220430115802-37a2bdaa8173/pkg/plugin/labels.go (about)

     1  // Copyright © 2021 Alibaba Group Holding Ltd.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package plugin
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  
    21  	"github.com/alibaba/sealer/utils"
    22  
    23  	v1 "k8s.io/api/core/v1"
    24  
    25  	"github.com/alibaba/sealer/logger"
    26  	"github.com/alibaba/sealer/pkg/client/k8s"
    27  )
    28  
    29  type LabelsNodes struct {
    30  	data   map[string][]label
    31  	client *k8s.Client
    32  }
    33  
    34  type label struct {
    35  	key   string
    36  	value string
    37  }
    38  
    39  func NewLabelsPlugin() Interface {
    40  	return &LabelsNodes{data: map[string][]label{}}
    41  }
    42  
    43  func init() {
    44  	Register(LabelPlugin, NewLabelsPlugin())
    45  }
    46  
    47  func (l LabelsNodes) Run(context Context, phase Phase) error {
    48  	if phase != PhasePreGuest || context.Plugin.Spec.Type != LabelPlugin {
    49  		logger.Warn("current phase is %s, label need set action to `PreGuest` !")
    50  		return nil
    51  	}
    52  	c, err := k8s.Newk8sClient()
    53  	if err != nil {
    54  		return err
    55  	}
    56  	l.client = c
    57  	l.data = l.formatData(context.Plugin.Spec.Data, context.Host)
    58  
    59  	nodeList, err := l.client.ListNodes()
    60  	if err != nil {
    61  		return fmt.Errorf("current cluster nodes not found, %v", err)
    62  	}
    63  	for _, v := range nodeList.Items {
    64  		internalIP := l.getAddress(v.Status.Addresses)
    65  		labels, ok := l.data[internalIP]
    66  		if ok {
    67  			m := v.GetLabels()
    68  			for _, val := range labels {
    69  				m[val.key] = val.value
    70  			}
    71  			v.SetLabels(m)
    72  			v.SetResourceVersion("")
    73  
    74  			if _, err := l.client.UpdateNode(v); err != nil {
    75  				return fmt.Errorf("current cluster nodes label failed, %v", err)
    76  			}
    77  			logger.Info("successfully added node %s labels %v.", internalIP, labels)
    78  		}
    79  	}
    80  	return nil
    81  }
    82  
    83  func (l LabelsNodes) formatData(data string, hosts []string) map[string][]label {
    84  	m := make(map[string][]label)
    85  	items := strings.Split(data, "\n")
    86  	if len(items) == 0 {
    87  		logger.Debug("label data is empty!")
    88  		return m
    89  	}
    90  	for _, v := range items {
    91  		tmps := strings.Split(v, " ")
    92  		if len(tmps) != 2 {
    93  			//logger.Warn("label data is no-compliance with the rules! label data: %v", v)
    94  			continue
    95  		}
    96  		ip := tmps[0]
    97  		if utils.NotIn(ip, hosts) {
    98  			continue
    99  		}
   100  		labelStr := strings.Split(tmps[1], ",")
   101  		var labels []label
   102  		for _, l := range labelStr {
   103  			tmp := strings.Split(l, "=")
   104  			if len(tmp) != 2 {
   105  				logger.Warn("label data is no-compliance with the rules! label data: %v", l)
   106  				continue
   107  			}
   108  			labels = append(labels, label{
   109  				key:   tmp[0],
   110  				value: tmp[1],
   111  			})
   112  		}
   113  		m[ip] = labels
   114  	}
   115  	return m
   116  }
   117  
   118  func (l LabelsNodes) getAddress(addresses []v1.NodeAddress) string {
   119  	for _, v := range addresses {
   120  		if strings.EqualFold(string(v.Type), "InternalIP") {
   121  			return v.Address
   122  		}
   123  	}
   124  	return ""
   125  }