github.com/midokura/kubeedge@v1.2.0-mido.0/tests/e2e/utils/node.go (about)

     1  /*
     2  Copyright 2019 The KubeEdge Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8     http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package utils
    18  
    19  import (
    20  	"bytes"
    21  	"crypto/tls"
    22  	"encoding/json"
    23  	"fmt"
    24  	"io/ioutil"
    25  	"net/http"
    26  	"path"
    27  	"path/filepath"
    28  	"runtime"
    29  	"time"
    30  
    31  	"github.com/ghodss/yaml"
    32  	. "github.com/onsi/gomega"
    33  	"k8s.io/api/core/v1"
    34  )
    35  
    36  func getpwd() string {
    37  	_, file, _, _ := runtime.Caller(0)
    38  	dir, err := filepath.Abs(filepath.Dir(file))
    39  	if err != nil {
    40  		Errorf("get current dir fail %+v", err)
    41  		return " "
    42  	}
    43  	return dir
    44  }
    45  
    46  //DeRegisterNodeFromMaster function to deregister the node from master
    47  func DeRegisterNodeFromMaster(nodehandler, nodename string) error {
    48  	err, resp := SendHttpRequest(http.MethodDelete, nodehandler+"/"+nodename)
    49  	if err != nil {
    50  		Fatalf("Sending SenHttpRequest failed: %v", err)
    51  		return err
    52  	}
    53  	defer resp.Body.Close()
    54  	Expect(resp.StatusCode).Should(Equal(http.StatusOK))
    55  
    56  	return nil
    57  }
    58  
    59  //GenerateNodeReqBody function to generate the node request body
    60  func GenerateNodeReqBody(nodeid, nodeselector string) (error, map[string]interface{}) {
    61  	var temp map[string]interface{}
    62  
    63  	body := fmt.Sprintf(`{"kind": "Node","apiVersion": "v1","metadata": {"name": "%s","labels": {"name": "edgenode", "disktype":"%s", "node-role.kubernetes.io/edge": ""}}}`, nodeid, nodeselector)
    64  	err := json.Unmarshal([]byte(body), &temp)
    65  	if err != nil {
    66  		Fatalf("Unmarshal body failed: %v", err)
    67  		return err, temp
    68  	}
    69  
    70  	return nil, temp
    71  }
    72  
    73  //RegisterNodeToMaster function to register node to master
    74  func RegisterNodeToMaster(UID, nodehandler, nodeselector string) error {
    75  	err, body := GenerateNodeReqBody(UID, nodeselector)
    76  	if err != nil {
    77  		Fatalf("Unmarshal body failed: %v", err)
    78  		return err
    79  	}
    80  
    81  	tr := &http.Transport{
    82  		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    83  	}
    84  	client := &http.Client{
    85  		Transport: tr,
    86  	}
    87  
    88  	t := time.Now()
    89  	nodebody, err := json.Marshal(body)
    90  	if err != nil {
    91  		Fatalf("Marshal body failed: %v", err)
    92  		return err
    93  	}
    94  	BodyBuf := bytes.NewReader(nodebody)
    95  	req, err := http.NewRequest(http.MethodPost, nodehandler, BodyBuf)
    96  	req.Header.Set("Content-Type", "application/json")
    97  	if err != nil {
    98  		Fatalf("Frame HTTP request failed: %v", err)
    99  		return err
   100  	}
   101  	resp, err := client.Do(req)
   102  	if err != nil {
   103  		Fatalf("Sending HTTP request failed: %v", err)
   104  		return err
   105  	}
   106  	Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t))
   107  	defer resp.Body.Close()
   108  
   109  	Expect(resp.StatusCode).Should(Equal(http.StatusCreated))
   110  	return nil
   111  }
   112  
   113  //CheckNodeReadyStatus function to get node status
   114  func CheckNodeReadyStatus(nodehandler, nodename string) string {
   115  	var node v1.Node
   116  	var nodeStatus = "unknown"
   117  	err, resp := SendHttpRequest(http.MethodGet, nodehandler+"/"+nodename)
   118  	if err != nil {
   119  		Fatalf("Sending SenHttpRequest failed: %v", err)
   120  		return nodeStatus
   121  	}
   122  	defer resp.Body.Close()
   123  
   124  	contents, err := ioutil.ReadAll(resp.Body)
   125  	if err != nil {
   126  		Fatalf("HTTP Response reading has failed: %v", err)
   127  		return nodeStatus
   128  	}
   129  	err = json.Unmarshal(contents, &node)
   130  	if err != nil {
   131  		Fatalf("Unmarshal HTTP Response has failed: %v", err)
   132  		return nodeStatus
   133  	}
   134  
   135  	return string(node.Status.Phase)
   136  }
   137  
   138  //CheckNodeDeleteStatus function to check node delete status
   139  func CheckNodeDeleteStatus(nodehandler, nodename string) int {
   140  	err, resp := SendHttpRequest(http.MethodGet, nodehandler+"/"+nodename)
   141  	if err != nil {
   142  		Fatalf("Sending SenHttpRequest failed: %v", err)
   143  		return -1
   144  	}
   145  	defer resp.Body.Close()
   146  	return resp.StatusCode
   147  }
   148  
   149  //HandleConfigmap function to create configmaps for respective edgenodes
   150  func HandleConfigmap(configName chan error, operation, confighandler string, IsEdgeCore bool) {
   151  	var req *http.Request
   152  	var file string
   153  	curpath := getpwd()
   154  	if IsEdgeCore == true {
   155  		file = path.Join(curpath, "../../performance/assets/02-edgeconfigmap.yaml")
   156  	} else {
   157  		file = path.Join(curpath, "../../performance/assets/01-configmap.yaml")
   158  	}
   159  	body, err := ioutil.ReadFile(file)
   160  	if err == nil {
   161  		client := &http.Client{}
   162  		t := time.Now()
   163  		if operation == http.MethodPost {
   164  			BodyBuf := bytes.NewReader(body)
   165  			req, err = http.NewRequest(operation, confighandler, BodyBuf)
   166  			Expect(err).Should(BeNil())
   167  			req.Header.Set("Content-Type", "application/yaml")
   168  		} else if operation == http.MethodPatch {
   169  			jsondata, err := yaml.YAMLToJSON(body)
   170  			if err != nil {
   171  				fmt.Printf("err: %v\n", err)
   172  				return
   173  			}
   174  			BodyBuf := bytes.NewReader(jsondata)
   175  			req, err = http.NewRequest(operation, confighandler, BodyBuf)
   176  			Expect(err).Should(BeNil())
   177  			req.Header.Set("Content-Type", "application/strategic-merge-patch+json")
   178  		} else {
   179  			req, err = http.NewRequest(operation, confighandler, bytes.NewReader([]byte("")))
   180  			Expect(err).Should(BeNil())
   181  			req.Header.Set("Content-Type", "application/json")
   182  		}
   183  
   184  		if err != nil {
   185  			Fatalf("Frame HTTP request failed: %v", err)
   186  		}
   187  		resp, err := client.Do(req)
   188  		if err != nil {
   189  			Fatalf("Sending HTTP request failed: %v", err)
   190  		}
   191  		Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t))
   192  		defer resp.Body.Close()
   193  		if operation == http.MethodPost {
   194  			Expect(resp.StatusCode).Should(Equal(http.StatusCreated))
   195  		} else {
   196  			Expect(resp.StatusCode).Should(Equal(http.StatusOK))
   197  		}
   198  		configName <- nil
   199  
   200  	} else {
   201  		configName <- err
   202  	}
   203  }
   204  
   205  //GetConfigmap function to get configmaps for respective edgenodes
   206  func GetConfigmap(apiConfigMap string) (int, []byte) {
   207  	err, resp := SendHttpRequest(http.MethodGet, apiConfigMap)
   208  	if err != nil {
   209  		Fatalf("Sending SenHttpRequest failed: %v", err)
   210  		return -1, nil
   211  	}
   212  	body, _ := ioutil.ReadAll(resp.Body)
   213  	defer resp.Body.Close()
   214  	return resp.StatusCode, body
   215  
   216  }
   217  
   218  //DeleteConfigmap function to delete configmaps
   219  func DeleteConfigmap(apiConfigMap string) int {
   220  	err, resp := SendHttpRequest(http.MethodDelete, apiConfigMap)
   221  	if err != nil {
   222  		Fatalf("Sending SenHttpRequest failed: %v", err)
   223  		return -1
   224  	}
   225  	defer resp.Body.Close()
   226  	return resp.StatusCode
   227  }
   228  
   229  func TaintEdgeDeployedNode(toTaint bool, taintHandler string) error {
   230  	var temp map[string]interface{}
   231  	var body string
   232  	if toTaint == true {
   233  		body = fmt.Sprintf(`{"spec":{"taints":[{"effect":"NoSchedule","key":"key","value":"value"}]}}`)
   234  	} else {
   235  		body = fmt.Sprintf(`{"spec":{"taints":null}}`)
   236  	}
   237  	err := json.Unmarshal([]byte(body), &temp)
   238  	if err != nil {
   239  		Fatalf("Unmarshal body failed: %v", err)
   240  		return nil
   241  	}
   242  	nodebody, err := json.Marshal(temp)
   243  	if err != nil {
   244  		Fatalf("Marshal body failed: %v", err)
   245  		return err
   246  	}
   247  	BodyBuf := bytes.NewReader(nodebody)
   248  	req, err := http.NewRequest(http.MethodPatch, taintHandler, BodyBuf)
   249  	Expect(err).Should(BeNil())
   250  	client := &http.Client{}
   251  	t := time.Now()
   252  	req.Header.Set("Content-Type", "application/strategic-merge-patch+json")
   253  	resp, err := client.Do(req)
   254  	if err != nil {
   255  		Fatalf("Sending HTTP request failed: %v", err)
   256  		return err
   257  	}
   258  	Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t))
   259  	defer resp.Body.Close()
   260  	Expect(resp.StatusCode).Should(Equal(http.StatusOK))
   261  	return nil
   262  }
   263  
   264  //GetNodes function to get configmaps for respective edgenodes
   265  func GetNodes(api string) v1.NodeList {
   266  	var nodes v1.NodeList
   267  	err, resp := SendHttpRequest(http.MethodGet, api)
   268  	if err != nil {
   269  		Fatalf("Sending SenHttpRequest failed: %v", err)
   270  	}
   271  	defer resp.Body.Close()
   272  
   273  	contents, err := ioutil.ReadAll(resp.Body)
   274  	if err != nil {
   275  		Fatalf("HTTP Response reading has failed: %v", err)
   276  	}
   277  	err = json.Unmarshal(contents, &nodes)
   278  	if err != nil {
   279  		Fatalf("Unmarshal HTTP Response has failed: %v", err)
   280  	}
   281  
   282  	return nodes
   283  }
   284  
   285  func ApplyLabelToNode(apiserver, key, val string) error {
   286  	var temp map[string]interface{}
   287  	var body string
   288  	body = fmt.Sprintf(`{"metadata":{"labels":{"%s":"%s"}}}`, key, val)
   289  	err := json.Unmarshal([]byte(body), &temp)
   290  	if err != nil {
   291  		Fatalf("Unmarshal body failed: %v", err)
   292  		return nil
   293  	}
   294  	nodebody, err := json.Marshal(temp)
   295  	if err != nil {
   296  		Fatalf("Marshal body failed: %v", err)
   297  		return err
   298  	}
   299  	BodyBuf := bytes.NewReader(nodebody)
   300  	req, err := http.NewRequest(http.MethodPatch, apiserver, BodyBuf)
   301  	Expect(err).Should(BeNil())
   302  	client := &http.Client{}
   303  	t := time.Now()
   304  	req.Header.Set("Content-Type", "application/strategic-merge-patch+json")
   305  	resp, err := client.Do(req)
   306  	if err != nil {
   307  		Fatalf("Sending HTTP request failed: %v", err)
   308  		return err
   309  	}
   310  	Infof("%s %s %v in %v", req.Method, req.URL, resp.Status, time.Now().Sub(t))
   311  	defer resp.Body.Close()
   312  	Expect(resp.StatusCode).Should(Equal(http.StatusOK))
   313  	return nil
   314  }