github.phpd.cn/cilium/cilium@v1.6.12/test/helpers/manifest_generator.go (about)

     1  // Copyright 2017 Authors of Cilium
     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 helpers
    16  
    17  import (
    18  	"bytes"
    19  	"io/ioutil"
    20  	"os"
    21  	"path"
    22  	"text/template"
    23  )
    24  
    25  // ManifestValues wraps manifest index
    26  type ManifestValues struct {
    27  	Index int
    28  }
    29  
    30  // GenerateManifestForEndpoints generates k8s manifests that will create
    31  // endpointCount Cilium endpoints when applied.
    32  // 1/3 of endpoints are servers, the rest are clients.
    33  // returns lastServer index
    34  // Saves generated manifest to manifestPath, also returns it via string
    35  func GenerateManifestForEndpoints(endpointCount int, manifestPath string) (string, int, error) {
    36  	configMapStr, err := ioutil.ReadFile(path.Join(K8sManifestBase, GeneratedHTMLManifest))
    37  	if err != nil {
    38  		return "", 0, err
    39  	}
    40  
    41  	serverTemplateStr, err := ioutil.ReadFile(path.Join(K8sManifestBase, GeneratedServerManifest))
    42  	if err != nil {
    43  		return "", 0, err
    44  	}
    45  	serverTemplate, err := template.New("server").Parse(string(serverTemplateStr))
    46  	if err != nil {
    47  		return "", 0, err
    48  	}
    49  
    50  	clientTemplateStr, err := ioutil.ReadFile(path.Join(K8sManifestBase, GeneratedClientManifest))
    51  	if err != nil {
    52  		return "", 0, err
    53  	}
    54  	clientTemplate, err := template.New("client").Parse(string(clientTemplateStr))
    55  	if err != nil {
    56  		return "", 0, err
    57  	}
    58  
    59  	separator := "\n---\n"
    60  	buf := new(bytes.Buffer)
    61  	buf.Write(configMapStr)
    62  	i := 0
    63  	for ; i < endpointCount/3; i++ {
    64  		buf.WriteString(separator)
    65  
    66  		vals := ManifestValues{i}
    67  		serverTemplate.Execute(buf, vals)
    68  	}
    69  	lastServer := i
    70  
    71  	for ; i < endpointCount; i++ {
    72  		buf.WriteString(separator)
    73  
    74  		vals := ManifestValues{i}
    75  		clientTemplate.Execute(buf, vals)
    76  	}
    77  
    78  	result := buf.String()
    79  	ioutil.WriteFile(manifestPath, []byte(result), os.ModePerm)
    80  
    81  	return result, lastServer, nil
    82  }