upgrade to istio 1.19 (#1211)

Co-authored-by: CH3CHO <ch3cho@qq.com>
Co-authored-by: rinfx <893383980@qq.com>
This commit is contained in:
澄潭
2024-08-26 09:51:47 +08:00
committed by GitHub
parent a2c2d1d521
commit f7a419770d
401 changed files with 21171 additions and 7255 deletions

365
hgctl/pkg/helm/common.go Normal file
View File

@@ -0,0 +1,365 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helm
import (
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/alibaba/higress/hgctl/pkg/helm/tpath"
"github.com/alibaba/higress/hgctl/pkg/util"
"sigs.k8s.io/yaml"
)
// GetProfileFromFlags get profile name from flags.
func GetProfileFromFlags(setFlags []string) (string, error) {
profileName := DefaultProfileName
// The profile coming from --set flag has the highest precedence.
psf := GetValueForSetFlag(setFlags, "profile")
if psf != "" {
profileName = psf
}
return profileName, nil
}
func GetValuesOverylayFromFiles(inFilenames []string) (string, error) {
// Convert layeredYamls under values node in profile file to support helm values
overLayYamls := ""
// Get Overlays from files
if len(inFilenames) > 0 {
layeredYamls, err := ReadLayeredYAMLs(inFilenames)
if err != nil {
return "", err
}
vals := make(map[string]any)
if err := yaml.Unmarshal([]byte(layeredYamls), &vals); err != nil {
return "", fmt.Errorf("%s:\n\nYAML:\n%s", err, layeredYamls)
}
values := make(map[string]any)
values["values"] = vals
out, err := yaml.Marshal(values)
if err != nil {
return "", err
}
overLayYamls = string(out)
}
return overLayYamls, nil
}
func GetUninstallProfileName() string {
return DefaultUninstallProfileName
}
func ReadLayeredYAMLs(filenames []string) (string, error) {
return readLayeredYAMLs(filenames, os.Stdin)
}
func readLayeredYAMLs(filenames []string, stdinReader io.Reader) (string, error) {
var ly string
var stdin bool
for _, fn := range filenames {
var b []byte
var err error
if fn == "-" {
if stdin {
continue
}
stdin = true
b, err = io.ReadAll(stdinReader)
} else {
b, err = os.ReadFile(strings.TrimSpace(fn))
}
if err != nil {
return "", err
}
ly, err = util.OverlayYAML(ly, string(b))
if err != nil {
return "", err
}
}
return ly, nil
}
// GetValueForSetFlag parses the passed set flags which have format key=value and if any set the given path,
// returns the corresponding value, otherwise returns the empty string. setFlags must have valid format.
func GetValueForSetFlag(setFlags []string, path string) string {
ret := ""
for _, sf := range setFlags {
p, v := getPV(sf)
if p == path {
ret = v
}
// if set multiple times, return last set value
}
return ret
}
// getPV returns the path and value components for the given set flag string, which must be in path=value format.
func getPV(setFlag string) (path string, value string) {
pv := strings.Split(setFlag, "=")
if len(pv) != 2 {
return setFlag, ""
}
path, value = strings.TrimSpace(pv[0]), strings.TrimSpace(pv[1])
return
}
func GenerateConfig(inFilenames []string, setFlags []string) (string, *Profile, string, error) {
if err := validateSetFlags(setFlags); err != nil {
return "", nil, "", err
}
profileName, err := GetProfileFromFlags(setFlags)
if err != nil {
return "", nil, "", err
}
valuesOverlay, err := GetValuesOverylayFromFiles(inFilenames)
if err != nil {
return "", nil, "", err
}
profileString, profile, err := GenProfile(profileName, valuesOverlay, setFlags)
if err != nil {
return "", nil, "", err
}
return profileString, profile, profileName, nil
}
// validateSetFlags validates that setFlags all have path=value format.
func validateSetFlags(setFlags []string) error {
for _, sf := range setFlags {
pv := strings.Split(sf, "=")
if len(pv) != 2 {
return fmt.Errorf("set flag %s has incorrect format, must be path=value", sf)
}
}
return nil
}
func overlaySetFlagValues(iopYAML string, setFlags []string) (string, error) {
iop := make(map[string]any)
if err := yaml.Unmarshal([]byte(iopYAML), &iop); err != nil {
return "", err
}
// Unmarshal returns nil for empty manifests but we need something to insert into.
if iop == nil {
iop = make(map[string]any)
}
for _, sf := range setFlags {
p, v := getPV(sf)
inc, _, err := tpath.GetPathContext(iop, util.PathFromString(p), true)
if err != nil {
return "", err
}
// input value type is always string, transform it to correct type before setting.
if err := tpath.WritePathContext(inc, util.ParseValue(v), false); err != nil {
return "", err
}
}
out, err := yaml.Marshal(iop)
if err != nil {
return "", err
}
return string(out), nil
}
// getInstallPackagePath returns the installPackagePath in the given IstioOperator YAML string.
func getInstallPackagePath(profileYAML string) (string, error) {
profile, err := UnmarshalProfile(profileYAML)
if err != nil {
return "", err
}
if profile == nil {
return "", nil
}
return profile.InstallPackagePath, nil
}
// GetProfileYAML returns the YAML for the given profile name, using the given profileOrPath string, which may be either
// a profile label or a file path.
func GetProfileYAML(installPackagePath, profileOrPath string) (string, error) {
if profileOrPath == "" {
profileOrPath = DefaultProfileFilename
}
profiles, err := readProfiles(installPackagePath)
if err != nil {
return "", fmt.Errorf("failed to read profiles: %v", err)
}
// If charts are a file path and profile is a name like default, transform it to the file path.
if profiles[profileOrPath] && installPackagePath != "" {
profileOrPath = filepath.Join(installPackagePath, "profiles", profileOrPath+".yaml")
}
// This contains the IstioOperator CR.
baseCRYAML, err := ReadProfileYAML(profileOrPath, installPackagePath)
if err != nil {
return "", err
}
//if !IsDefaultProfile(profileOrPath) {
// // Profile definitions are relative to the default profileOrPath, so read that first.
// dfn := DefaultFilenameForProfile(profileOrPath)
// defaultYAML, err := ReadProfileYAML(dfn, installPackagePath)
// if err != nil {
// return "", err
// }
// baseCRYAML, err = util.OverlayYAML(defaultYAML, baseCRYAML)
// if err != nil {
// return "", err
// }
//}
return baseCRYAML, nil
}
// IsDefaultProfile reports whether the given profile is the default profile.
func IsDefaultProfile(profile string) bool {
return profile == "" || profile == DefaultProfileName || filepath.Base(profile) == DefaultProfileFilename
}
// DefaultFilenameForProfile returns the profile name of the default profile for the given profile.
func DefaultFilenameForProfile(profile string) string {
switch {
case util.IsFilePath(profile):
return filepath.Join(filepath.Dir(profile), DefaultProfileFilename)
default:
return DefaultProfileName
}
}
// ReadProfileYAML reads the YAML values associated with the given profile. It uses an appropriate reader for the
// profile format (compiled-in, file, HTTP, etc.).
func ReadProfileYAML(profile, manifestsPath string) (string, error) {
var err error
var globalValues string
// Get global values from profile.
switch {
case util.IsFilePath(profile):
if globalValues, err = readFile(profile); err != nil {
return "", err
}
default:
if globalValues, err = LoadValues(profile, manifestsPath); err != nil {
return "", fmt.Errorf("failed to read profile %v from %v: %v", profile, manifestsPath, err)
}
}
return globalValues, nil
}
func readFile(path string) (string, error) {
b, err := os.ReadFile(path)
return string(b), err
}
// UnmarshalProfile unmarshals a string containing Profile as YAML.
func UnmarshalProfile(profileYAML string) (*Profile, error) {
profile := &Profile{}
if err := yaml.Unmarshal([]byte(profileYAML), profile); err != nil {
return nil, fmt.Errorf("%s:\n\nYAML:\n%s", err, profileYAML)
}
return profile, nil
}
// GenProfile generates an Profile from the given profile name or path, and overlay YAMLs from user
// files and the --set flag. If successful, it returns an Profile string and struct.
func GenProfile(profileOrPath, fileOverlayYAML string, setFlags []string) (string, *Profile, error) {
installPackagePath, err := getInstallPackagePath(fileOverlayYAML)
if err != nil {
return "", nil, err
}
if sfp := GetValueForSetFlag(setFlags, "installPackagePath"); sfp != "" {
// set flag installPackagePath has the highest precedence, if set.
installPackagePath = sfp
}
// To generate the base profileOrPath for overlaying with user values, we need the installPackagePath where the profiles
// can be found, and the selected profileOrPath. Both of these can come from either the user overlay file or --set flag.
outYAML, err := GetProfileYAML(installPackagePath, profileOrPath)
if err != nil {
return "", nil, err
}
// Combine file and --set overlays and translate any K8s settings in values to Profile format
overlayYAML, err := overlaySetFlagValues(fileOverlayYAML, setFlags)
if err != nil {
return "", nil, err
}
// Merge user file and --set flags.
outYAML, err = util.OverlayYAML(outYAML, overlayYAML)
if err != nil {
return "", nil, fmt.Errorf("could not overlay user config over base: %s", err)
}
finalProfile, err := UnmarshalProfile(outYAML)
if err != nil {
return "", nil, err
}
if len(installPackagePath) > 0 {
finalProfile.InstallPackagePath = installPackagePath
}
if finalProfile.Profile == "" {
finalProfile.Profile = DefaultProfileName
}
return util.ToYAML(finalProfile), finalProfile, nil
}
func GenProfileFromProfileContent(profileContent, fileOverlayYAML string, setFlags []string) (string, *Profile, error) {
installPackagePath, err := getInstallPackagePath(fileOverlayYAML)
if err != nil {
return "", nil, err
}
if sfp := GetValueForSetFlag(setFlags, "installPackagePath"); sfp != "" {
// set flag installPackagePath has the highest precedence, if set.
installPackagePath = sfp
}
// Combine file and --set overlays and translate any K8s settings in values to Profile format
overlayYAML, err := overlaySetFlagValues(fileOverlayYAML, setFlags)
if err != nil {
return "", nil, err
}
// Merge user file and --set flags.
outYAML, err := util.OverlayYAML(profileContent, overlayYAML)
if err != nil {
return "", nil, fmt.Errorf("could not overlay user config over base: %s", err)
}
finalProfile, err := UnmarshalProfile(outYAML)
if err != nil {
return "", nil, err
}
if len(installPackagePath) > 0 {
finalProfile.InstallPackagePath = installPackagePath
}
if finalProfile.Profile == "" {
finalProfile.Profile = DefaultProfileName
}
return util.ToYAML(finalProfile), finalProfile, nil
}

View File

@@ -0,0 +1,63 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package name
// Kubernetes Kind strings.
const (
CRDStr = "CustomResourceDefinition"
ClusterRoleStr = "ClusterRole"
ClusterRoleBindingStr = "ClusterRoleBinding"
CMStr = "ConfigMap"
DaemonSetStr = "DaemonSet"
DeploymentStr = "Deployment"
EndpointStr = "Endpoints"
HPAStr = "HorizontalPodAutoscaler"
IngressStr = "Ingress"
IstioOperator = "IstioOperator"
MutatingWebhookConfigurationStr = "MutatingWebhookConfiguration"
NamespaceStr = "Namespace"
PVCStr = "PersistentVolumeClaim"
PodStr = "Pod"
PDBStr = "PodDisruptionBudget"
ReplicationControllerStr = "ReplicationController"
ReplicaSetStr = "ReplicaSet"
RoleStr = "Role"
RoleBindingStr = "RoleBinding"
SAStr = "ServiceAccount"
ServiceStr = "Service"
SecretStr = "Secret"
StatefulSetStr = "StatefulSet"
ValidatingWebhookConfigurationStr = "ValidatingWebhookConfiguration"
)
// Istio Kind strings
const (
EnvoyFilterStr = "EnvoyFilter"
GatewayStr = "Gateway"
DestinationRuleStr = "DestinationRule"
MeshPolicyStr = "MeshPolicy"
PeerAuthenticationStr = "PeerAuthentication"
VirtualServiceStr = "VirtualService"
IstioOperatorStr = "IstioOperator"
)
// Istio API Group Names
const (
AuthenticationAPIGroupName = "authentication.istio.io"
ConfigAPIGroupName = "config.istio.io"
NetworkingAPIGroupName = "networking.istio.io"
OperatorAPIGroupName = "operator.istio.io"
SecurityAPIGroupName = "security.istio.io"
)

View File

@@ -0,0 +1,573 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"bufio"
"bytes"
"fmt"
"sort"
"strings"
names "github.com/alibaba/higress/hgctl/pkg/helm/name"
"github.com/alibaba/higress/hgctl/pkg/helm/tpath"
"github.com/alibaba/higress/hgctl/pkg/util"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/intstr"
k8syaml "k8s.io/apimachinery/pkg/util/yaml"
"sigs.k8s.io/yaml"
)
const (
// YAMLSeparator is a separator for multi-document YAML files.
YAMLSeparator = "\n---\n"
)
// K8sObject is an in-memory representation of a k8s object, used for moving between different representations
// (Unstructured, JSON, YAML) with cached rendering.
type K8sObject struct {
object *unstructured.Unstructured
Group string
Kind string
Name string
Namespace string
json []byte
yaml []byte
}
// NewK8sObject creates a new K8sObject and returns a ptr to it.
func NewK8sObject(u *unstructured.Unstructured, json, yaml []byte) *K8sObject {
o := &K8sObject{
object: u,
json: json,
yaml: yaml,
}
gvk := u.GetObjectKind().GroupVersionKind()
o.Group = gvk.Group
o.Kind = gvk.Kind
o.Name = u.GetName()
o.Namespace = u.GetNamespace()
return o
}
// Hash returns a unique, insecure hash based on kind, namespace and name.
func Hash(kind, namespace, name string) string {
switch kind {
case names.ClusterRoleStr, names.ClusterRoleBindingStr, names.MeshPolicyStr:
namespace = ""
}
return strings.Join([]string{kind, namespace, name}, ":")
}
// FromHash parses kind, namespace and name from a hash.
func FromHash(hash string) (kind, namespace, name string) {
hv := strings.Split(hash, ":")
if len(hv) != 3 {
return "Bad hash string: " + hash, "", ""
}
kind, namespace, name = hv[0], hv[1], hv[2]
return
}
// HashNameKind returns a unique, insecure hash based on kind and name.
func HashNameKind(kind, name string) string {
return strings.Join([]string{kind, name}, ":")
}
// ParseJSONToK8sObject parses JSON to an K8sObject.
func ParseJSONToK8sObject(json []byte) (*K8sObject, error) {
o, _, err := unstructured.UnstructuredJSONScheme.Decode(json, nil, nil)
if err != nil {
return nil, fmt.Errorf("error parsing json into unstructured object: %v", err)
}
u, ok := o.(*unstructured.Unstructured)
if !ok {
return nil, fmt.Errorf("parsed unexpected type %T", o)
}
return NewK8sObject(u, json, nil), nil
}
// ParseYAMLToK8sObject parses YAML to an Object.
func ParseYAMLToK8sObject(yaml []byte) (*K8sObject, error) {
r := bytes.NewReader(yaml)
decoder := k8syaml.NewYAMLOrJSONDecoder(r, 1024)
out := &unstructured.Unstructured{}
err := decoder.Decode(out)
if err != nil {
return nil, fmt.Errorf("error decoding object %v: %v", string(yaml), err)
}
return NewK8sObject(out, nil, yaml), nil
}
// UnstructuredObject exposes the raw object, primarily for testing
func (o *K8sObject) UnstructuredObject() *unstructured.Unstructured {
return o.object
}
// ResolveK8sConflict - This method resolves k8s object possible
// conflicting settings. Which K8sObjects may need such method
// depends on the type of the K8sObject.
func (o *K8sObject) ResolveK8sConflict() *K8sObject {
if o.Kind == names.PDBStr {
return resolvePDBConflict(o)
}
return o
}
// Unstructured exposes the raw object content, primarily for testing
func (o *K8sObject) Unstructured() map[string]any {
return o.UnstructuredObject().UnstructuredContent()
}
// Container returns a container subtree for Deployment objects if one is found, or nil otherwise.
func (o *K8sObject) Container(name string) map[string]any {
u := o.Unstructured()
path := fmt.Sprintf("spec.template.spec.containers.[name:%s]", name)
node, f, err := tpath.GetPathContext(u, util.PathFromString(path), false)
if err == nil && f {
// Must be the type from the schema.
return node.Node.(map[string]any)
}
return nil
}
// GroupVersionKind returns the GroupVersionKind for the K8sObject
func (o *K8sObject) GroupVersionKind() schema.GroupVersionKind {
return o.object.GroupVersionKind()
}
// Version returns the APIVersion of the K8sObject
func (o *K8sObject) Version() string {
return o.object.GetAPIVersion()
}
// Hash returns a unique hash for the K8sObject
func (o *K8sObject) Hash() string {
return Hash(o.Kind, o.Namespace, o.Name)
}
// HashNameKind returns a hash for the K8sObject based on the name and kind only.
func (o *K8sObject) HashNameKind() string {
return HashNameKind(o.Kind, o.Name)
}
// JSON returns a JSON representation of the K8sObject, using an internal cache.
func (o *K8sObject) JSON() ([]byte, error) {
if o.json != nil {
return o.json, nil
}
b, err := o.object.MarshalJSON()
if err != nil {
return nil, err
}
return b, nil
}
// YAML returns a YAML representation of the K8sObject, using an internal cache.
func (o *K8sObject) YAML() ([]byte, error) {
if o == nil {
return nil, nil
}
if o.yaml != nil {
return o.yaml, nil
}
oj, err := o.JSON()
if err != nil {
return nil, err
}
o.json = oj
y, err := yaml.JSONToYAML(oj)
if err != nil {
return nil, err
}
o.yaml = y
return y, nil
}
// YAMLDebugString returns a YAML representation of the K8sObject, or an error string if the K8sObject cannot be rendered to YAML.
func (o *K8sObject) YAMLDebugString() string {
y, err := o.YAML()
if err != nil {
return err.Error()
}
return string(y)
}
// K8sObjects holds a collection of k8s objects, so that we can filter / sequence them
type K8sObjects []*K8sObject
// String implements the Stringer interface.
func (os K8sObjects) String() string {
var out []string
for _, oo := range os {
out = append(out, oo.YAMLDebugString())
}
return strings.Join(out, YAMLSeparator)
}
// Keys returns a slice with the keys of os.
func (os K8sObjects) Keys() []string {
var out []string
for _, oo := range os {
out = append(out, oo.Hash())
}
return out
}
// UnstructuredItems returns the list of items of unstructured.Unstructured.
func (os K8sObjects) UnstructuredItems() []unstructured.Unstructured {
var usList []unstructured.Unstructured
for _, obj := range os {
usList = append(usList, *obj.UnstructuredObject())
}
return usList
}
// ParseK8sObjectsFromYAMLManifest returns a K8sObjects representation of manifest.
func ParseK8sObjectsFromYAMLManifest(manifest string) (K8sObjects, error) {
return ParseK8sObjectsFromYAMLManifestFailOption(manifest, true)
}
// ParseK8sObjectsFromYAMLManifestFailOption returns a K8sObjects representation of manifest. Continues parsing when a bad object
// is found if failOnError is set to false.
func ParseK8sObjectsFromYAMLManifestFailOption(manifest string, failOnError bool) (K8sObjects, error) {
var b bytes.Buffer
var yamls []string
scanner := bufio.NewScanner(strings.NewReader(manifest))
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "---") {
// yaml separator
yamls = append(yamls, b.String())
b.Reset()
} else {
if _, err := b.WriteString(line); err != nil {
return nil, err
}
if _, err := b.WriteString("\n"); err != nil {
return nil, err
}
}
}
yamls = append(yamls, b.String())
var objects K8sObjects
for _, yaml := range yamls {
yaml = removeNonYAMLLines(yaml)
if yaml == "" {
continue
}
o, err := ParseYAMLToK8sObject([]byte(yaml))
if err != nil {
e := fmt.Errorf("failed to parse YAML to a k8s object: %s", err)
if failOnError {
return nil, e
}
continue
}
if o.Valid() {
objects = append(objects, o)
}
}
return objects, nil
}
func removeNonYAMLLines(yms string) string {
var b strings.Builder
for _, s := range strings.Split(yms, "\n") {
if strings.HasPrefix(s, "#") {
continue
}
b.WriteString(s)
b.WriteString("\n")
}
// helm charts sometimes emits blank objects with just a "disabled" comment.
return strings.TrimSpace(b.String())
}
// YAMLManifest returns a YAML representation of K8sObjects os.
func (os K8sObjects) YAMLManifest() (string, error) {
var b bytes.Buffer
for i, item := range os {
if i != 0 {
if _, err := b.WriteString("\n\n"); err != nil {
return "", err
}
}
ym, err := item.YAML()
if err != nil {
return "", fmt.Errorf("error building yaml: %v", err)
}
if _, err := b.Write(ym); err != nil {
return "", err
}
if _, err := b.Write([]byte(YAMLSeparator)); err != nil {
return "", err
}
}
return b.String(), nil
}
// Sort will order the items in K8sObjects in order of score, group, kind, name. The intent is to
// have a deterministic ordering in which K8sObjects are applied.
func (os K8sObjects) Sort(score func(o *K8sObject) int) {
sort.Slice(os, func(i, j int) bool {
iScore := score(os[i])
jScore := score(os[j])
return iScore < jScore ||
(iScore == jScore &&
os[i].Group < os[j].Group) ||
(iScore == jScore &&
os[i].Group == os[j].Group &&
os[i].Kind < os[j].Kind) ||
(iScore == jScore &&
os[i].Group == os[j].Group &&
os[i].Kind == os[j].Kind &&
os[i].Name < os[j].Name)
})
}
// ToMap returns a map of K8sObject hash to K8sObject.
func (os K8sObjects) ToMap() map[string]*K8sObject {
ret := make(map[string]*K8sObject)
for _, oo := range os {
if oo.Valid() {
ret[oo.Hash()] = oo
}
}
return ret
}
// ToNameKindMap returns a map of K8sObject name/kind hash to K8sObject.
func (os K8sObjects) ToNameKindMap() map[string]*K8sObject {
ret := make(map[string]*K8sObject)
for _, oo := range os {
if oo.Valid() {
ret[oo.HashNameKind()] = oo
}
}
return ret
}
// Valid checks returns true if Kind of K8sObject is not empty.
func (o *K8sObject) Valid() bool {
return o.Kind != ""
}
// FullName returns namespace/name of K8s object
func (o *K8sObject) FullName() string {
return fmt.Sprintf("%s/%s", o.Namespace, o.Name)
}
// Equal returns true if o and other are both valid and equal to each other.
func (o *K8sObject) Equal(other *K8sObject) bool {
if o == nil {
return other == nil
}
if other == nil {
return o == nil
}
ay, err := o.YAML()
if err != nil {
return false
}
by, err := other.YAML()
if err != nil {
return false
}
return util.IsYAMLEqual(string(ay), string(by))
}
func istioCustomResources(group string) bool {
switch group {
case names.ConfigAPIGroupName,
names.SecurityAPIGroupName,
names.AuthenticationAPIGroupName,
names.NetworkingAPIGroupName:
return true
}
return false
}
// DefaultObjectOrder is default sorting function used to sort k8s objects.
func DefaultObjectOrder() func(o *K8sObject) int {
return func(o *K8sObject) int {
gk := o.Group + "/" + o.Kind
switch {
// Create CRDs asap - both because they are slow and because we will likely create instances of them soon
case gk == "apiextensions.k8s.io/CustomResourceDefinition":
return -1000
// We need to create ServiceAccounts, Roles before we bind them with a RoleBinding
case gk == "/ServiceAccount" || gk == "rbac.authorization.k8s.io/ClusterRole":
return 1
case gk == "rbac.authorization.k8s.io/ClusterRoleBinding":
return 2
// validatingwebhookconfiguration is configured to FAIL-OPEN in the default install. For the
// re-install case we want to apply the validatingwebhookconfiguration first to reset any
// orphaned validatingwebhookconfiguration that is FAIL-CLOSE.
case gk == "admissionregistration.k8s.io/ValidatingWebhookConfiguration":
return 3
case istioCustomResources(o.Group):
return 4
// Pods might need configmap or secrets - avoid backoff by creating them first
case gk == "/ConfigMap" || gk == "/Secrets":
return 100
// Create the pods after we've created other things they might be waiting for
case gk == "extensions/Deployment" || gk == "app/Deployment":
return 1000
// Autoscalers typically act on a deployment
case gk == "autoscaling/HorizontalPodAutoscaler":
return 1001
// Create services late - after pods have been started
case gk == "/Service":
return 10000
default:
return 1000
}
}
}
func ObjectsNotInLists(objects K8sObjects, lists ...K8sObjects) K8sObjects {
var ret K8sObjects
filterMap := make(map[*K8sObject]bool)
for _, list := range lists {
for _, object := range list {
filterMap[object] = true
}
}
for _, o := range objects {
if !filterMap[o] {
ret = append(ret, o)
}
}
return ret
}
// KindObjects returns the subset of objs with the given kind.
func KindObjects(objs K8sObjects, kind string) K8sObjects {
var ret K8sObjects
for _, o := range objs {
if o.Kind == kind {
ret = append(ret, o)
}
}
return ret
}
//// ParseK8SYAMLToIstioOperator parses a IstioOperator CustomResource YAML string and unmarshals in into
//// an IstioOperatorSpec object. It returns the object and an API group/version with it.
//func ParseK8SYAMLToIstioOperator(yml string) (*v1alpha1.HigressOperator, *schema.GroupVersionKind, error) {
// o, err := ParseYAMLToK8sObject([]byte(yml))
// if err != nil {
// return nil, nil, err
// }
// iop := &v1alpha1.HigressOperator{}
// if err := yaml.UnmarshalStrict([]byte(yml), iop); err != nil {
// return nil, nil, err
// }
// gvk := o.GroupVersionKind()
// //v1alpha1.SetNamespace(iop.Spec, o.Namespace)
// return iop, &gvk, nil
//}
// AllObjectHashes returns a map with object hashes of all the objects contained in cmm as the keys.
func AllObjectHashes(m string) map[string]bool {
ret := make(map[string]bool)
objs, err := ParseK8sObjectsFromYAMLManifest(m)
if err != nil {
}
for _, o := range objs {
ret[o.Hash()] = true
}
return ret
}
// resolvePDBConflict When user uses both minAvailable and
// maxUnavailable to configure istio instances, these two
// parameters are mutually exclusive, care must be taken
// to resolve the issue
func resolvePDBConflict(o *K8sObject) *K8sObject {
if o.json == nil {
return o
}
if o.object.Object["spec"] == nil {
return o
}
spec := o.object.Object["spec"].(map[string]any)
isDefault := func(item any) bool {
var ii intstr.IntOrString
switch item := item.(type) {
case int:
ii = intstr.FromInt(item)
case int64:
ii = intstr.FromInt(int(item))
case string:
ii = intstr.FromString(item)
default:
ii = intstr.FromInt(0)
}
intVal, err := intstr.GetScaledValueFromIntOrPercent(&ii, 100, false)
if err != nil || intVal == 0 {
return true
}
return false
}
if spec["maxUnavailable"] != nil && spec["minAvailable"] != nil {
// When both maxUnavailable and minAvailable present and
// neither has value 0, this is considered a conflict,
// then maxUnavailale will take precedence.
if !isDefault(spec["maxUnavailable"]) && !isDefault(spec["minAvailable"]) {
delete(spec, "minAvailable")
// Make sure that the json and yaml representation of the object
// is consistent with the changed object
o.json = nil
o.json, _ = o.JSON()
if o.yaml != nil {
o.yaml = nil
o.yaml, _ = o.YAML()
}
}
}
return o
}

View File

@@ -0,0 +1,713 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package object
import (
"strings"
"testing"
"github.com/alibaba/higress/hgctl/pkg/util"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
func TestHash(t *testing.T) {
hashTests := []struct {
desc string
kind string
namespace string
name string
want string
}{
{"CalculateHashForObjectWithNormalCharacter", "Service", "default", "ingressgateway", "Service:default:ingressgateway"},
{"CalculateHashForObjectWithDash", "Deployment", "istio-system", "istio-pilot", "Deployment:istio-system:istio-pilot"},
{"CalculateHashForObjectWithDot", "ConfigMap", "istio-system", "my.config", "ConfigMap:istio-system:my.config"},
}
for _, tt := range hashTests {
t.Run(tt.desc, func(t *testing.T) {
got := Hash(tt.kind, tt.namespace, tt.name)
if got != tt.want {
t.Errorf("Hash(%s): got %s for kind %s, namespace %s, name %s, want %s", tt.desc, got, tt.kind, tt.namespace, tt.name, tt.want)
}
})
}
}
func TestFromHash(t *testing.T) {
hashTests := []struct {
desc string
hash string
kind string
namespace string
name string
}{
{"ParseHashWithNormalCharacter", "Service:default:ingressgateway", "Service", "default", "ingressgateway"},
{"ParseHashForObjectWithDash", "Deployment:istio-system:istio-pilot", "Deployment", "istio-system", "istio-pilot"},
{"ParseHashForObjectWithDot", "ConfigMap:istio-system:my.config", "ConfigMap", "istio-system", "my.config"},
{"InvalidHash", "test", "Bad hash string: test", "", ""},
}
for _, tt := range hashTests {
t.Run(tt.desc, func(t *testing.T) {
k, ns, name := FromHash(tt.hash)
if k != tt.kind || ns != tt.namespace || name != tt.name {
t.Errorf("FromHash(%s): got kind %s, namespace %s, name %s, want kind %s, namespace %s, name %s", tt.desc, k, ns, name, tt.kind, tt.namespace, tt.name)
}
})
}
}
func TestHashNameKind(t *testing.T) {
hashNameKindTests := []struct {
desc string
kind string
name string
want string
}{
{"CalculateHashNameKindForObjectWithNormalCharacter", "Service", "ingressgateway", "Service:ingressgateway"},
{"CalculateHashNameKindForObjectWithDash", "Deployment", "istio-pilot", "Deployment:istio-pilot"},
{"CalculateHashNameKindForObjectWithDot", "ConfigMap", "my.config", "ConfigMap:my.config"},
}
for _, tt := range hashNameKindTests {
t.Run(tt.desc, func(t *testing.T) {
got := HashNameKind(tt.kind, tt.name)
if got != tt.want {
t.Errorf("HashNameKind(%s): got %s for kind %s, name %s, want %s", tt.desc, got, tt.kind, tt.name, tt.want)
}
})
}
}
func TestParseJSONToK8sObject(t *testing.T) {
testDeploymentJSON := `{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"name": "istio-citadel",
"namespace": "istio-system",
"labels": {
"istio": "citadel"
}
},
"spec": {
"replicas": 1,
"selector": {
"matchLabels": {
"istio": "citadel"
}
},
"template": {
"metadata": {
"labels": {
"istio": "citadel"
}
},
"spec": {
"containers": [
{
"name": "citadel",
"image": "docker.io/istio/citadel:1.1.8",
"args": [
"--append-dns-names=true",
"--grpc-port=8060",
"--grpc-hostname=citadel",
"--citadel-storage-namespace=istio-system",
"--custom-dns-names=istio-pilot-service-account.istio-system:istio-pilot.istio-system",
"--monitoring-port=15014",
"--self-signed-ca=true"
]
}
]
}
}
}
}`
testPodJSON := `{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": "istio-galley-75bcd59768-hpt5t",
"namespace": "istio-system",
"labels": {
"istio": "galley"
}
},
"spec": {
"containers": [
{
"name": "galley",
"image": "docker.io/istio/galley:1.1.8",
"command": [
"/usr/local/bin/galley",
"server",
"--meshConfigFile=/etc/mesh-config/mesh",
"--livenessProbeInterval=1s",
"--livenessProbePath=/healthliveness",
"--readinessProbePath=/healthready",
"--readinessProbeInterval=1s",
"--deployment-namespace=istio-system",
"--insecure=true",
"--validation-webhook-config-file",
"/etc/config/validatingwebhookconfiguration.yaml",
"--monitoringPort=15014",
"--log_output_level=default:info"
],
"ports": [
{
"containerPort": 443,
"protocol": "TCP"
},
{
"containerPort": 15014,
"protocol": "TCP"
},
{
"containerPort": 9901,
"protocol": "TCP"
}
]
}
]
}
}`
testServiceJSON := `{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"labels": {
"app": "pilot"
},
"name": "istio-pilot",
"namespace": "istio-system"
},
"spec": {
"clusterIP": "10.102.230.31",
"ports": [
{
"name": "grpc-xds",
"port": 15010,
"protocol": "TCP",
"targetPort": 15010
},
{
"name": "https-xds",
"port": 15011,
"protocol": "TCP",
"targetPort": 15011
},
{
"name": "http-legacy-discovery",
"port": 8080,
"protocol": "TCP",
"targetPort": 8080
},
{
"name": "http-monitoring",
"port": 15014,
"protocol": "TCP",
"targetPort": 15014
}
],
"selector": {
"istio": "pilot"
},
"sessionAffinity": "None",
"type": "ClusterIP"
}
}`
testInvalidJSON := `invalid json`
parseJSONToK8sObjectTests := []struct {
desc string
objString string
wantGroup string
wantKind string
wantName string
wantNamespace string
wantErr bool
}{
{"ParseJsonToK8sDeployment", testDeploymentJSON, "apps", "Deployment", "istio-citadel", "istio-system", false},
{"ParseJsonToK8sPod", testPodJSON, "", "Pod", "istio-galley-75bcd59768-hpt5t", "istio-system", false},
{"ParseJsonToK8sService", testServiceJSON, "", "Service", "istio-pilot", "istio-system", false},
{"ParseJsonError", testInvalidJSON, "", "", "", "", true},
}
for _, tt := range parseJSONToK8sObjectTests {
t.Run(tt.desc, func(t *testing.T) {
k8sObj, err := ParseJSONToK8sObject([]byte(tt.objString))
if err == nil {
if tt.wantErr {
t.Errorf("ParseJsonToK8sObject(%s): should be error", tt.desc)
}
k8sObjStr := k8sObj.YAMLDebugString()
if k8sObj.Group != tt.wantGroup {
t.Errorf("ParseJsonToK8sObject(%s): got group %s for k8s object %s, want %s", tt.desc, k8sObj.Group, k8sObjStr, tt.wantGroup)
}
if k8sObj.Kind != tt.wantKind {
t.Errorf("ParseJsonToK8sObject(%s): got kind %s for k8s object %s, want %s", tt.desc, k8sObj.Kind, k8sObjStr, tt.wantKind)
}
if k8sObj.Name != tt.wantName {
t.Errorf("ParseJsonToK8sObject(%s): got name %s for k8s object %s, want %s", tt.desc, k8sObj.Name, k8sObjStr, tt.wantName)
}
if k8sObj.Namespace != tt.wantNamespace {
t.Errorf("ParseJsonToK8sObject(%s): got group %s for k8s object %s, want %s", tt.desc, k8sObj.Namespace, k8sObjStr, tt.wantNamespace)
}
} else if !tt.wantErr {
t.Errorf("ParseJsonToK8sObject(%s): got unexpected error: %v", tt.desc, err)
}
})
}
}
func TestParseYAMLToK8sObject(t *testing.T) {
testDeploymentYaml := `apiVersion: apps/v1
kind: Deployment
metadata:
name: istio-citadel
namespace: istio-system
labels:
istio: citadel
spec:
replicas: 1
selector:
matchLabels:
istio: citadel
template:
metadata:
labels:
istio: citadel
spec:
containers:
- name: citadel
image: docker.io/istio/citadel:1.1.8
args:
- "--append-dns-names=true"
- "--grpc-port=8060"
- "--grpc-hostname=citadel"
- "--citadel-storage-namespace=istio-system"
- "--custom-dns-names=istio-pilot-service-account.istio-system:istio-pilot.istio-system"
- "--monitoring-port=15014"
- "--self-signed-ca=true"`
testPodYaml := `apiVersion: v1
kind: Pod
metadata:
name: istio-galley-75bcd59768-hpt5t
namespace: istio-system
labels:
istio: galley
spec:
containers:
- name: galley
image: docker.io/istio/galley:1.1.8
command:
- "/usr/local/bin/galley"
- server
- "--meshConfigFile=/etc/mesh-config/mesh"
- "--livenessProbeInterval=1s"
- "--livenessProbePath=/healthliveness"
- "--readinessProbePath=/healthready"
- "--readinessProbeInterval=1s"
- "--deployment-namespace=istio-system"
- "--insecure=true"
- "--validation-webhook-config-file"
- "/etc/config/validatingwebhookconfiguration.yaml"
- "--monitoringPort=15014"
- "--log_output_level=default:info"
ports:
- containerPort: 443
protocol: TCP
- containerPort: 15014
protocol: TCP
- containerPort: 9901
protocol: TCP`
testServiceYaml := `apiVersion: v1
kind: Service
metadata:
labels:
app: pilot
name: istio-pilot
namespace: istio-system
spec:
clusterIP: 10.102.230.31
ports:
- name: grpc-xds
port: 15010
protocol: TCP
targetPort: 15010
- name: https-xds
port: 15011
protocol: TCP
targetPort: 15011
- name: http-legacy-discovery
port: 8080
protocol: TCP
targetPort: 8080
- name: http-monitoring
port: 15014
protocol: TCP
targetPort: 15014
selector:
istio: pilot
sessionAffinity: None
type: ClusterIP`
parseYAMLToK8sObjectTests := []struct {
desc string
objString string
wantGroup string
wantKind string
wantName string
wantNamespace string
}{
{"ParseYamlToK8sDeployment", testDeploymentYaml, "apps", "Deployment", "istio-citadel", "istio-system"},
{"ParseYamlToK8sPod", testPodYaml, "", "Pod", "istio-galley-75bcd59768-hpt5t", "istio-system"},
{"ParseYamlToK8sService", testServiceYaml, "", "Service", "istio-pilot", "istio-system"},
}
for _, tt := range parseYAMLToK8sObjectTests {
t.Run(tt.desc, func(t *testing.T) {
k8sObj, err := ParseYAMLToK8sObject([]byte(tt.objString))
if err != nil {
k8sObjStr := k8sObj.YAMLDebugString()
if k8sObj.Group != tt.wantGroup {
t.Errorf("ParseYAMLToK8sObject(%s): got group %s for k8s object %s, want %s", tt.desc, k8sObj.Group, k8sObjStr, tt.wantGroup)
}
if k8sObj.Group != tt.wantGroup {
t.Errorf("ParseYAMLToK8sObject(%s): got kind %s for k8s object %s, want %s", tt.desc, k8sObj.Kind, k8sObjStr, tt.wantKind)
}
if k8sObj.Name != tt.wantName {
t.Errorf("ParseYAMLToK8sObject(%s): got name %s for k8s object %s, want %s", tt.desc, k8sObj.Name, k8sObjStr, tt.wantName)
}
if k8sObj.Namespace != tt.wantNamespace {
t.Errorf("ParseYAMLToK8sObject(%s): got group %s for k8s object %s, want %s", tt.desc, k8sObj.Namespace, k8sObjStr, tt.wantNamespace)
}
}
})
}
}
func TestParseK8sObjectsFromYAMLManifest(t *testing.T) {
testDeploymentYaml := `apiVersion: apps/v1
kind: Deployment
metadata:
name: istio-citadel
namespace: istio-system
labels:
istio: citadel
spec:
replicas: 1
selector:
matchLabels:
istio: citadel
template:
metadata:
labels:
istio: citadel
spec:
containers:
- name: citadel
image: docker.io/istio/citadel:1.1.8
args:
- "--append-dns-names=true"
- "--grpc-port=8060"
- "--grpc-hostname=citadel"
- "--citadel-storage-namespace=istio-system"
- "--custom-dns-names=istio-pilot-service-account.istio-system:istio-pilot.istio-system"
- "--monitoring-port=15014"
- "--self-signed-ca=true"`
testPodYaml := `apiVersion: v1
kind: Pod
metadata:
name: istio-galley-75bcd59768-hpt5t
namespace: istio-system
labels:
istio: galley
spec:
containers:
- name: galley
image: docker.io/istio/galley:1.1.8
command:
- "/usr/local/bin/galley"
- server
- "--meshConfigFile=/etc/mesh-config/mesh"
- "--livenessProbeInterval=1s"
- "--livenessProbePath=/healthliveness"
- "--readinessProbePath=/healthready"
- "--readinessProbeInterval=1s"
- "--deployment-namespace=istio-system"
- "--insecure=true"
- "--validation-webhook-config-file"
- "/etc/config/validatingwebhookconfiguration.yaml"
- "--monitoringPort=15014"
- "--log_output_level=default:info"
ports:
- containerPort: 443
protocol: TCP
- containerPort: 15014
protocol: TCP
- containerPort: 9901
protocol: TCP`
testServiceYaml := `apiVersion: v1
kind: Service
metadata:
labels:
app: pilot
name: istio-pilot
namespace: istio-system
spec:
clusterIP: 10.102.230.31
ports:
- name: grpc-xds
port: 15010
protocol: TCP
targetPort: 15010
- name: https-xds
port: 15011
protocol: TCP
targetPort: 15011
- name: http-legacy-discovery
port: 8080
protocol: TCP
targetPort: 8080
- name: http-monitoring
port: 15014
protocol: TCP
targetPort: 15014
selector:
istio: pilot
sessionAffinity: None
type: ClusterIP`
parseK8sObjectsFromYAMLManifestTests := []struct {
desc string
objsMap map[string]string
}{
{
"FromHybridYAMLManifest",
map[string]string{
"Deployment:istio-system:istio-citadel": testDeploymentYaml,
"Pod:istio-system:istio-galley-75bcd59768-hpt5t": testPodYaml,
"Service:istio-system:istio-pilot": testServiceYaml,
},
},
}
for _, tt := range parseK8sObjectsFromYAMLManifestTests {
t.Run(tt.desc, func(t *testing.T) {
testManifestYaml := strings.Join([]string{testDeploymentYaml, testPodYaml, testServiceYaml}, YAMLSeparator)
gotK8sObjs, err := ParseK8sObjectsFromYAMLManifest(testManifestYaml)
if err != nil {
gotK8sObjsMap := gotK8sObjs.ToMap()
for objHash, want := range tt.objsMap {
if gotObj, ok := gotK8sObjsMap[objHash]; ok {
gotObjYaml := gotObj.YAMLDebugString()
if !util.IsYAMLEqual(gotObjYaml, want) {
t.Errorf("ParseK8sObjectsFromYAMLManifest(%s): got:\n%s\n\nwant:\n%s\nDiff:\n%s\n", tt.desc, gotObjYaml, want, util.YAMLDiff(gotObjYaml, want))
}
}
}
}
})
}
}
func TestK8sObject_Equal(t *testing.T) {
obj1 := K8sObject{
object: &unstructured.Unstructured{Object: map[string]any{
"key": "value1",
}},
}
obj2 := K8sObject{
object: &unstructured.Unstructured{Object: map[string]any{
"key": "value2",
}},
}
cases := []struct {
desc string
o1 *K8sObject
o2 *K8sObject
want bool
}{
{
desc: "Equals",
o1: &obj1,
o2: &obj1,
want: true,
},
{
desc: "NotEquals",
o1: &obj1,
o2: &obj2,
want: false,
},
{
desc: "NilSource",
o1: nil,
o2: &obj2,
want: false,
},
{
desc: "NilDest",
o1: &obj1,
o2: nil,
want: false,
},
{
desc: "TwoNils",
o1: nil,
o2: nil,
want: true,
},
}
for _, tt := range cases {
t.Run(tt.desc, func(t *testing.T) {
res := tt.o1.Equal(tt.o2)
if res != tt.want {
t.Errorf("got %v, want: %v", res, tt.want)
}
})
}
}
func TestK8sObject_ResolveK8sConflict(t *testing.T) {
getK8sObject := func(ystr string) *K8sObject {
o, err := ParseYAMLToK8sObject([]byte(ystr))
if err != nil {
panic(err)
}
// Ensure that json data is in sync.
// Since the object was created using yaml, json is empty.
// make sure the object json is set correctly.
o.json, _ = o.JSON()
return o
}
cases := []struct {
desc string
o1 *K8sObject
o2 *K8sObject
}{
{
desc: "not applicable kind",
o1: getK8sObject(`
apiVersion: v1
kind: Service
metadata:
labels:
app: pilot
name: istio-pilot
namespace: istio-system
spec:
clusterIP: 10.102.230.31`),
o2: getK8sObject(`
apiVersion: v1
kind: Service
metadata:
labels:
app: pilot
name: istio-pilot
namespace: istio-system
spec:
clusterIP: 10.102.230.31`),
},
{
desc: "only minAvailable is set",
o1: getK8sObject(`
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: zk-pdb
spec:
minAvailable: 2`),
o2: getK8sObject(`
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: zk-pdb
spec:
minAvailable: 2`),
},
{
desc: "only maxUnavailable is set",
o1: getK8sObject(`
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: istio
spec:
maxUnavailable: 3`),
o2: getK8sObject(`
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: istio
spec:
maxUnavailable: 3`),
},
{
desc: "minAvailable and maxUnavailable are set to none zero values",
o1: getK8sObject(`
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: istio
spec:
maxUnavailable: 50%
minAvailable: 3`),
o2: getK8sObject(`
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: istio
spec:
maxUnavailable: 50%`),
},
{
desc: "both minAvailable and maxUnavailable are set default",
o1: getK8sObject(`
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: istio
spec:
minAvailable: 0
maxUnavailable: 0`),
o2: getK8sObject(`
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
name: istio
spec:
maxUnavailable: 0
minAvailable: 0`),
},
}
for _, tt := range cases {
t.Run(tt.desc, func(t *testing.T) {
newObj := tt.o1.ResolveK8sConflict()
if !newObj.Equal(tt.o2) {
newObjjson, _ := newObj.JSON()
wantedObjjson, _ := tt.o2.JSON()
t.Errorf("Got: %s, want: %s", string(newObjjson), string(wantedObjjson))
}
})
}
}

498
hgctl/pkg/helm/profile.go Normal file
View File

@@ -0,0 +1,498 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helm
import (
"errors"
"fmt"
"regexp"
"strings"
"istio.io/istio/operator/pkg/util"
"sigs.k8s.io/yaml"
)
type InstallMode string
const (
InstallK8s InstallMode = "k8s"
InstallLocalK8s InstallMode = "local-k8s"
InstallLocalDocker InstallMode = "local-docker"
InstallLocal InstallMode = "local"
)
type Profile struct {
Profile string `json:"profile,omitempty"`
InstallPackagePath string `json:"installPackagePath,omitempty"`
HigressVersion string `json:"higressVersion,omitempty"`
Global ProfileGlobal `json:"global,omitempty"`
Console ProfileConsole `json:"console,omitempty"`
Gateway ProfileGateway `json:"gateway,omitempty"`
Controller ProfileController `json:"controller,omitempty"`
Storage ProfileStorage `json:"storage,omitempty"`
Values map[string]any `json:"values,omitempty"`
Charts ProfileCharts `json:"charts,omitempty"`
}
type ProfileGlobal struct {
Install InstallMode `json:"install,omitempty"`
IngressClass string `json:"ingressClass,omitempty"`
EnableIstioAPI bool `json:"enableIstioAPI,omitempty"`
EnableGatewayAPI bool `json:"enableGatewayAPI,omitempty"`
Namespace string `json:"namespace,omitempty"`
}
func (p ProfileGlobal) SetFlags(install InstallMode) ([]string, error) {
sets := make([]string, 0)
if install == InstallK8s || install == InstallLocalK8s {
sets = append(sets, fmt.Sprintf("global.ingressClass=%s", p.IngressClass))
sets = append(sets, fmt.Sprintf("global.enableIstioAPI=%t", p.EnableIstioAPI))
sets = append(sets, fmt.Sprintf("global.enableGatewayAPI=%t", p.EnableGatewayAPI))
if install == InstallLocalK8s {
sets = append(sets, fmt.Sprintf("global.local=%t", true))
}
}
return sets, nil
}
func (p ProfileGlobal) Validate(install InstallMode) []error {
errs := make([]error, 0)
// now only support k8s, local-k8s, local-docker installation mode
if install != InstallK8s && install != InstallLocalK8s && install != InstallLocalDocker {
errs = append(errs, errors.New("global.install only can be set to k8s, local-k8s or local-docker"))
}
if install == InstallK8s || install == InstallLocalK8s {
if len(p.IngressClass) == 0 {
errs = append(errs, errors.New("global.ingressClass can't be empty"))
}
if len(p.Namespace) == 0 {
errs = append(errs, errors.New("global.namespace can't be empty"))
}
}
return errs
}
type ProfileConsole struct {
Port uint32 `json:"port,omitempty"`
Replicas uint32 `json:"replicas,omitempty"`
O11yEnabled bool `json:"o11YEnabled,omitempty"`
Resources Resource `json:"resources,omitempty"`
}
func (p ProfileConsole) SetFlags(install InstallMode) ([]string, error) {
sets := make([]string, 0)
if install == InstallK8s || install == InstallLocalK8s {
sets = append(sets, fmt.Sprintf("higress-console.replicaCount=%d", p.Replicas))
sets = append(sets, fmt.Sprintf("higress-console.o11y.enabled=%t", p.O11yEnabled))
}
return sets, nil
}
func (p ProfileConsole) Validate(install InstallMode) []error {
errs := make([]error, 0)
if install == InstallK8s || install == InstallLocalK8s {
if p.Replicas <= 0 {
errs = append(errs, errors.New("console.replica need be large than zero"))
}
}
if install == InstallLocalDocker {
if p.Port <= 0 {
errs = append(errs, errors.New("console.port need be large than zero"))
}
}
// set default value
if p.Resources.Requests.CPU == "" {
p.Resources.Requests.CPU = "250m"
}
if p.Resources.Requests.Memory == "" {
p.Resources.Requests.Memory = "512Mi"
}
if p.Resources.Limits.CPU == "" {
p.Resources.Limits.CPU = "2000m"
}
if p.Resources.Limits.Memory == "" {
p.Resources.Limits.Memory = "2048Mi"
}
errs = append(errs, p.Resources.Validate()...)
return errs
}
type ProfileGateway struct {
Replicas uint32 `json:"replicas,omitempty"`
HttpPort uint32 `json:"httpPort,omitempty"`
HttpsPort uint32 `json:"httpsPort,omitempty"`
MetricsPort uint32 `json:"metricsPort,omitempty"`
Resources Resource `json:"resources,omitempty"`
}
func (p ProfileGateway) SetFlags(install InstallMode) ([]string, error) {
sets := make([]string, 0)
if install == InstallK8s || install == InstallLocalK8s {
sets = append(sets, fmt.Sprintf("higress-core.gateway.replicas=%d", p.Replicas))
}
return sets, nil
}
func (p ProfileGateway) Validate(install InstallMode) []error {
errs := make([]error, 0)
if install == InstallK8s || install == InstallLocalK8s {
if p.Replicas <= 0 {
errs = append(errs, errors.New("gateway.replica need be large than zero"))
}
}
if install == InstallLocalDocker {
if p.HttpPort <= 0 {
errs = append(errs, errors.New("gateway.httpPort need be large than zero"))
}
if p.HttpsPort <= 0 {
errs = append(errs, errors.New("gateway.httpsPort need be large than zero"))
}
if p.MetricsPort <= 0 {
errs = append(errs, errors.New("gateway.MetricsPort need be large than zero"))
}
}
// set default value
if p.Resources.Requests.CPU == "" {
p.Resources.Requests.CPU = "2000m"
}
if p.Resources.Requests.Memory == "" {
p.Resources.Requests.Memory = "2048Mi"
}
if p.Resources.Limits.CPU == "" {
p.Resources.Limits.CPU = "2000m"
}
if p.Resources.Limits.Memory == "" {
p.Resources.Limits.Memory = "2048Mi"
}
errs = append(errs, p.Resources.Validate()...)
return errs
}
type ProfileController struct {
Replicas uint32 `json:"replicas,omitempty"`
Resources Resource `json:"resources,omitempty"`
}
func (p ProfileController) SetFlags(install InstallMode) ([]string, error) {
sets := make([]string, 0)
if install == InstallK8s || install == InstallLocalK8s {
sets = append(sets, fmt.Sprintf("higress-core.controller.replicas=%d", p.Replicas))
}
return sets, nil
}
func (p ProfileController) Validate(install InstallMode) []error {
errs := make([]error, 0)
if install == InstallK8s || install == InstallLocalK8s {
if p.Replicas <= 0 {
errs = append(errs, errors.New("controller.replica need be large than zero"))
}
}
// set default value
if p.Resources.Requests.CPU == "" {
p.Resources.Requests.CPU = "500m"
}
if p.Resources.Requests.Memory == "" {
p.Resources.Requests.Memory = "2048Mi"
}
if p.Resources.Limits.CPU == "" {
p.Resources.Limits.CPU = "1000m"
}
if p.Resources.Limits.Memory == "" {
p.Resources.Limits.Memory = "2048Mi"
}
errs = append(errs, p.Resources.Validate()...)
return errs
}
type ProfileStorage struct {
Url string `json:"url,omitempty"`
Ns string `json:"ns,omitempty"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
DataEncKey string `json:"DataEncKey,omitempty"`
}
func (p ProfileStorage) Validate(install InstallMode) []error {
errs := make([]error, 0)
if install == InstallLocalDocker {
if len(p.Url) == 0 {
errs = append(errs, errors.New("storage.url can't be empty"))
}
if len(p.Ns) == 0 {
errs = append(errs, errors.New("storage.ns can't be empty"))
}
if !strings.HasPrefix(p.Url, "nacos://") && !strings.HasPrefix(p.Url, "file://") {
errs = append(errs, fmt.Errorf("invalid storage url: %s", p.Url))
} else {
// check localhost or 127.0.0.0
if strings.Contains(p.Url, "localhost") || strings.Contains(p.Url, "/127.") {
errs = append(errs, errors.New("localhost or loopback addresses in nacos url won't work"))
}
}
if len(p.DataEncKey) > 0 && len(p.DataEncKey) != 32 {
errs = append(errs, fmt.Errorf("expecting 32 characters for dataEncKey, but got %d length", len(p.DataEncKey)))
}
if len(p.Username) > 0 && len(p.Password) == 0 || len(p.Username) == 0 && len(p.Password) > 0 {
errs = append(errs, errors.New("both nacos username and password should be provided"))
}
}
return errs
}
type Chart struct {
Url string `json:"url,omitempty"`
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
}
type ProfileCharts struct {
Higress Chart `json:"higress,omitempty"`
Standalone Chart `json:"standalone,omitempty"`
}
func (p ProfileCharts) Validate(install InstallMode) []error {
errs := make([]error, 0)
return errs
}
func (p *Profile) ValuesYaml() (string, error) {
setFlags := make([]string, 0)
// Get global setting
globalFlags, _ := p.Global.SetFlags(p.Global.Install)
setFlags = append(setFlags, globalFlags...)
// Get console setting
consoleFlags, _ := p.Console.SetFlags(p.Global.Install)
setFlags = append(setFlags, consoleFlags...)
// Get gateway setting
gatewayFlags, _ := p.Gateway.SetFlags(p.Global.Install)
setFlags = append(setFlags, gatewayFlags...)
// Get controller setting
controllerFlags, _ := p.Controller.SetFlags(p.Global.Install)
setFlags = append(setFlags, controllerFlags...)
valueOverlayYAML := ""
if p.Values == nil {
p.Values = make(map[string]any)
}
resourceMap := make(map[string]any)
resourceMap["higress-core"] = map[string]interface{}{
"controller": map[string]interface{}{
"resources": map[string]interface{}{
"requests": map[string]interface{}{
"cpu": p.Controller.Resources.Requests.CPU,
"memory": p.Controller.Resources.Requests.Memory,
},
"limits": map[string]interface{}{
"cpu": p.Controller.Resources.Limits.CPU,
"memory": p.Controller.Resources.Limits.Memory,
},
},
},
"gateway": map[string]interface{}{
"resources": map[string]interface{}{
"requests": map[string]interface{}{
"cpu": p.Gateway.Resources.Requests.CPU,
"memory": p.Gateway.Resources.Requests.Memory,
},
"limits": map[string]interface{}{
"cpu": p.Gateway.Resources.Limits.CPU,
"memory": p.Gateway.Resources.Limits.Memory,
},
},
},
}
resourceMap["higress-console"] = map[string]interface{}{
"resources": map[string]interface{}{
"requests": map[string]interface{}{
"cpu": p.Console.Resources.Requests.CPU,
"memory": p.Console.Resources.Requests.Memory,
},
"limits": map[string]interface{}{
"cpu": p.Console.Resources.Limits.CPU,
"memory": p.Console.Resources.Limits.Memory,
},
},
}
resourceYAML, err := yaml.Marshal(resourceMap)
if err != nil {
return "", err
}
out, err := yaml.Marshal(p.Values)
if err != nil {
return "", err
}
valueOverlayYAML, err = util.OverlayYAML(string(resourceYAML), string(out))
flagsYAML, err := overlaySetFlagValues("", setFlags)
if err != nil {
return "", err
}
// merge values and setFlags
overlayYAML, err := util.OverlayYAML(flagsYAML, valueOverlayYAML)
if err != nil {
return "", err
}
return overlayYAML, nil
}
func (p *Profile) IstioEnabled() bool {
if (p.Global.Install == InstallK8s || p.Global.Install == InstallLocalK8s) && p.Global.EnableIstioAPI {
return true
}
return false
}
func (p *Profile) GatewayAPIEnabled() bool {
if (p.Global.Install == InstallK8s || p.Global.Install == InstallLocalK8s) && p.Global.EnableGatewayAPI {
return true
}
return false
}
func (p *Profile) GetIstioNamespace() string {
if valuesGlobal, ok1 := p.Values["global"]; ok1 {
if global, ok2 := valuesGlobal.(map[string]any); ok2 {
if istioNamespace, ok3 := global["istioNamespace"]; ok3 {
if namespace, ok4 := istioNamespace.(string); ok4 {
return namespace
}
}
}
}
return ""
}
func (p *Profile) Validate() error {
errs := make([]error, 0)
errsGlobal := p.Global.Validate(p.Global.Install)
if len(errsGlobal) > 0 {
errs = append(errs, errsGlobal...)
}
errsConsole := p.Console.Validate(p.Global.Install)
if len(errsConsole) > 0 {
errs = append(errs, errsConsole...)
}
errsGateway := p.Gateway.Validate(p.Global.Install)
if len(errsGateway) > 0 {
errs = append(errs, errsGateway...)
}
errsController := p.Controller.Validate(p.Global.Install)
if len(errsController) > 0 {
errs = append(errs, errsController...)
}
errsStorage := p.Storage.Validate(p.Global.Install)
if len(errsStorage) > 0 {
errs = append(errs, errsStorage...)
}
errsCharts := p.Charts.Validate(p.Global.Install)
if len(errsCharts) > 0 {
errs = append(errs, errsCharts...)
}
if len(errs) == 0 {
return nil
}
return errors.New(ToString(errs, "\n"))
}
// ToString returns a string representation of errors, with elements separated by separator string. Any nil errors in the
// slice are skipped.
func ToString(errors []error, separator string) string {
var out string
for i, e := range errors {
if e == nil {
continue
}
if i != 0 {
out += separator
}
out += e.Error()
}
return out
}
type Resource struct {
Requests Requests `json:"requests,omitempty"`
Limits Limits `json:"limits,omitempty"`
}
type Requests struct {
CPU string `json:"cpu,omitempty"`
Memory string `json:"memory,omitempty"`
}
type Limits struct {
CPU string `json:"cpu,omitempty"`
Memory string `json:"memory,omitempty"`
}
func (r Resource) Validate() []error {
errs := make([]error, 0)
r.Requests.CPU = strings.ReplaceAll(r.Requests.CPU, " ", "")
r.Requests.Memory = strings.ReplaceAll(r.Requests.Memory, " ", "")
r.Limits.CPU = strings.ReplaceAll(r.Limits.CPU, " ", "")
r.Limits.Memory = strings.ReplaceAll(r.Limits.Memory, " ", "")
if !isValidK8SResourceFormat(r.Requests.CPU) {
errs = append(errs, fmt.Errorf("requests CPU has invalid format"))
}
if !isValidK8SResourceFormat(r.Requests.Memory) {
errs = append(errs, fmt.Errorf("requests memory has invalid format"))
}
if !isValidK8SResourceFormat(r.Limits.CPU) {
errs = append(errs, fmt.Errorf("limits CPU has invalid format"))
}
if !isValidK8SResourceFormat(r.Limits.Memory) {
errs = append(errs, fmt.Errorf("limits memory has invalid format"))
}
return errs
}
func isValidK8SResourceFormat(resource string) bool {
pattern := `^\d+((n|u|m|k|Ki|M|Mi|G|Gi|T|Ti|P|Pi|E|Ei)?)$`
match, _ := regexp.MatchString(pattern, resource)
if !match {
return false
}
if len(resource) == 0 || resource[0] == '-' || resource[0] == '0' {
return false
}
return true
}

694
hgctl/pkg/helm/render.go Normal file
View File

@@ -0,0 +1,694 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package helm
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net/url"
"os"
"path"
"path/filepath"
"sort"
"strings"
"github.com/alibaba/higress/hgctl/pkg/manifests"
"github.com/alibaba/higress/hgctl/pkg/util"
"helm.sh/helm/v3/pkg/action"
"helm.sh/helm/v3/pkg/chart"
"helm.sh/helm/v3/pkg/chart/loader"
"helm.sh/helm/v3/pkg/chartutil"
"helm.sh/helm/v3/pkg/cli"
"helm.sh/helm/v3/pkg/downloader"
"helm.sh/helm/v3/pkg/engine"
"helm.sh/helm/v3/pkg/getter"
"helm.sh/helm/v3/pkg/repo"
"k8s.io/client-go/rest"
"sigs.k8s.io/yaml"
)
const (
// DefaultProfileName is the name of the default profile for installation.
DefaultProfileName = "local-k8s"
// DefaultProfileFilename is the name of the default profile yaml file for installation.
DefaultProfileFilename = "local-k8s.yaml"
// DefaultUninstallProfileName is the name of the default profile yaml file for uninstallation.
DefaultUninstallProfileName = "local-k8s"
// ChartsSubdirName = "charts"
profilesRoot = "profiles"
RepoLatestVersion = "latest"
RepoChartIndexYamlHigressIndex = "higress"
YAMLSeparator = "\n---\n"
NotesFileNameSuffix = ".txt"
)
func LoadValues(profileName string, chartsDir string) (string, error) {
path := strings.Join([]string{profilesRoot, builtinProfileToFilename(profileName)}, "/")
by, err := fs.ReadFile(manifests.BuiltinOrDir(chartsDir), path)
if err != nil {
return "", err
}
return string(by), nil
}
func readProfiles(chartsDir string) (map[string]bool, error) {
profiles := map[string]bool{}
f := manifests.BuiltinOrDir(chartsDir)
dir, err := fs.ReadDir(f, profilesRoot)
if err != nil {
return nil, err
}
for _, f := range dir {
if f.Name() == "_all.yaml" {
continue
}
trimmedString := strings.TrimSuffix(f.Name(), ".yaml")
if f.Name() != trimmedString {
profiles[trimmedString] = true
}
}
return profiles, nil
}
func builtinProfileToFilename(name string) string {
if name == "" {
return DefaultProfileFilename
}
return name + ".yaml"
}
// stripPrefix removes the given prefix from prefix.
func stripPrefix(path, prefix string) string {
pl := len(strings.Split(prefix, "/"))
pv := strings.Split(path, "/")
return strings.Join(pv[pl:], "/")
}
// ListProfiles list all the profiles.
func ListProfiles(charts string) ([]string, error) {
profiles, err := readProfiles(charts)
if err != nil {
return nil, err
}
return util.StringBoolMapToSlice(profiles), nil
}
var DefaultFilters = []util.FilterFunc{
util.LicenseFilter,
util.FormatterFilter,
util.SpaceFilter,
}
// Renderer is responsible for rendering helm chart with new values.
type Renderer interface {
Init() error
RenderManifest(valsYaml string) (string, error)
SetVersion(version string)
}
type RendererOptions struct {
Name string
Namespace string
// fields for LocalChartRenderer and LocalFileRenderer
FS fs.FS
Dir string
// fields for RemoteRenderer
Version string
RepoURL string
// Capabilities
Capabilities *chartutil.Capabilities
// rest config
restConfig *rest.Config
}
type RendererOption func(*RendererOptions)
func WithName(name string) RendererOption {
return func(opts *RendererOptions) {
opts.Name = name
}
}
func WithNamespace(ns string) RendererOption {
return func(opts *RendererOptions) {
opts.Namespace = ns
}
}
func WithFS(f fs.FS) RendererOption {
return func(opts *RendererOptions) {
opts.FS = f
}
}
func WithDir(dir string) RendererOption {
return func(opts *RendererOptions) {
opts.Dir = dir
}
}
func WithVersion(version string) RendererOption {
return func(opts *RendererOptions) {
opts.Version = version
}
}
func WithRepoURL(repo string) RendererOption {
return func(opts *RendererOptions) {
opts.RepoURL = repo
}
}
func WithCapabilities(capabilities *chartutil.Capabilities) RendererOption {
return func(opts *RendererOptions) {
opts.Capabilities = capabilities
}
}
func WithRestConfig(config *rest.Config) RendererOption {
return func(opts *RendererOptions) {
opts.restConfig = config
}
}
// LocalFileRenderer load yaml files from local file system
type LocalFileRenderer struct {
Opts *RendererOptions
filesMap map[string]string
Started bool
}
func NewLocalFileRenderer(opts ...RendererOption) (Renderer, error) {
newOpts := &RendererOptions{}
for _, opt := range opts {
opt(newOpts)
}
return &LocalFileRenderer{
Opts: newOpts,
filesMap: make(map[string]string),
}, nil
}
func (l *LocalFileRenderer) Init() error {
fileNames, err := getFileNames(l.Opts.FS, l.Opts.Dir)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("chart of component %s doesn't exist", l.Opts.Name)
}
return fmt.Errorf("getFileNames err: %s", err)
}
for _, fileName := range fileNames {
data, err := fs.ReadFile(l.Opts.FS, fileName)
if err != nil {
return fmt.Errorf("ReadFile %s err: %s", fileName, err)
}
l.filesMap[fileName] = string(data)
}
l.Started = true
return nil
}
func (l *LocalFileRenderer) RenderManifest(valsYaml string) (string, error) {
if !l.Started {
return "", errors.New("LocalFileRenderer has not been init")
}
keys := make([]string, 0, len(l.filesMap))
for key := range l.filesMap {
keys = append(keys, key)
}
// to ensure that every manifest rendered by same values are the same
sort.Strings(keys)
var builder strings.Builder
for i := 0; i < len(keys); i++ {
file := l.filesMap[keys[i]]
file = util.ApplyFilters(file, DefaultFilters...)
// ignore empty manifest
if file == "" {
continue
}
if !strings.HasSuffix(file, YAMLSeparator) {
file += YAMLSeparator
}
builder.WriteString(file)
}
return builder.String(), nil
}
func (l *LocalFileRenderer) SetVersion(version string) {
l.Opts.Version = version
}
// LocalChartRenderer load chart from local file system
type LocalChartRenderer struct {
Opts *RendererOptions
Chart *chart.Chart
Started bool
}
func (lr *LocalChartRenderer) Init() error {
fileNames, err := getFileNames(lr.Opts.FS, lr.Opts.Dir)
if err != nil {
if os.IsNotExist(err) {
return fmt.Errorf("chart of component %s doesn't exist", lr.Opts.Name)
}
return fmt.Errorf("getFileNames err: %s", err)
}
var files []*loader.BufferedFile
for _, fileName := range fileNames {
data, err := fs.ReadFile(lr.Opts.FS, fileName)
if err != nil {
return fmt.Errorf("ReadFile %s err: %s", fileName, err)
}
// todo:// explain why we need to do this
name := util.StripPrefix(fileName, lr.Opts.Dir)
file := &loader.BufferedFile{
Name: name,
Data: data,
}
files = append(files, file)
}
newChart, err := loader.LoadFiles(files)
if err != nil {
return fmt.Errorf("load chart of component %s err: %s", lr.Opts.Name, err)
}
lr.Chart = newChart
lr.Started = true
return nil
}
func (lr *LocalChartRenderer) RenderManifest(valsYaml string) (string, error) {
if !lr.Started {
return "", errors.New("LocalChartRenderer has not been init")
}
return renderManifest(valsYaml, lr.Chart, true, lr.Opts, DefaultFilters...)
}
func (lr *LocalChartRenderer) SetVersion(version string) {
lr.Opts.Version = version
}
func NewLocalChartRenderer(opts ...RendererOption) (Renderer, error) {
newOpts := &RendererOptions{}
for _, opt := range opts {
opt(newOpts)
}
if err := verifyRendererOptions(newOpts); err != nil {
return nil, fmt.Errorf("verify err: %s", err)
}
return &LocalChartRenderer{
Opts: newOpts,
}, nil
}
type RemoteRenderer struct {
Opts *RendererOptions
Chart *chart.Chart
Started bool
}
func (rr *RemoteRenderer) initChartPathOptions() *action.ChartPathOptions {
return &action.ChartPathOptions{
RepoURL: rr.Opts.RepoURL,
Version: rr.Opts.Version,
}
}
func (rr *RemoteRenderer) Init() error {
cpOpts := rr.initChartPathOptions()
settings := cli.New()
// using release name as chart name by default
cp, err := locateChart(cpOpts, rr.Opts.Name, settings)
if err != nil {
return err
}
// Check chart dependencies to make sure all are present in /charts
chartRequested, err := loader.Load(cp)
if err != nil {
return err
}
if err := verifyInstallable(chartRequested); err != nil {
return err
}
rr.Chart = chartRequested
rr.Started = true
return nil
}
func (rr *RemoteRenderer) SetVersion(version string) {
rr.Opts.Version = version
}
func (rr *RemoteRenderer) RenderManifest(valsYaml string) (string, error) {
if !rr.Started {
return "", errors.New("RemoteRenderer has not been init")
}
return renderManifest(valsYaml, rr.Chart, false, rr.Opts, DefaultFilters...)
}
func NewRemoteRenderer(opts ...RendererOption) (Renderer, error) {
newOpts := &RendererOptions{}
for _, opt := range opts {
opt(newOpts)
}
return &RemoteRenderer{
Opts: newOpts,
}, nil
}
func verifyRendererOptions(opts *RendererOptions) error {
if opts.Name == "" {
return errors.New("missing component name for Renderer")
}
if opts.Namespace == "" {
return errors.New("missing component namespace for Renderer")
}
if opts.FS == nil {
return errors.New("missing chart FS for Renderer")
}
if opts.Dir == "" {
return errors.New("missing chart dir for Renderer")
}
return nil
}
// read all files recursively under root path from a certain local file system
func getFileNames(f fs.FS, root string) ([]string, error) {
var fileNames []string
if err := fs.WalkDir(f, root, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
fileNames = append(fileNames, path)
return nil
}); err != nil {
return nil, err
}
return fileNames, nil
}
func verifyInstallable(cht *chart.Chart) error {
typ := cht.Metadata.Type
if typ == "" || typ == "application" {
return nil
}
return fmt.Errorf("%s chart %s is not installable", typ, cht.Name())
}
func renderManifest(valsYaml string, cht *chart.Chart, builtIn bool, opts *RendererOptions, filters ...util.FilterFunc) (string, error) {
valsMap := make(map[string]any)
if err := yaml.Unmarshal([]byte(valsYaml), &valsMap); err != nil {
return "", fmt.Errorf("unmarshal failed err: %s", err)
}
RelOpts := chartutil.ReleaseOptions{
Name: opts.Name,
Namespace: opts.Namespace,
}
var caps *chartutil.Capabilities
caps = opts.Capabilities
if caps == nil {
caps = chartutil.DefaultCapabilities
}
// maybe we need a configuration to change this caps
resVals, err := chartutil.ToRenderValues(cht, valsMap, RelOpts, caps)
if err != nil {
return "", fmt.Errorf("ToRenderValues failed err: %s", err)
}
if builtIn {
resVals["Values"].(chartutil.Values)["enabled"] = true
}
filesMap, err := engine.RenderWithClient(cht, resVals, opts.restConfig)
if err != nil {
return "", fmt.Errorf("Render chart failed err: %s", err)
}
keys := make([]string, 0, len(filesMap))
for key := range filesMap {
// remove notation files such as Notes.txt
if strings.HasSuffix(key, NotesFileNameSuffix) {
continue
}
keys = append(keys, key)
}
// to ensure that every manifest rendered by same values are the same
sort.Strings(keys)
var builder strings.Builder
for i := 0; i < len(keys); i++ {
file := filesMap[keys[i]]
file = util.ApplyFilters(file, filters...)
// ignore empty manifest
if file == "" {
continue
}
if !strings.HasSuffix(file, YAMLSeparator) {
file += YAMLSeparator
}
builder.WriteString(file)
}
// render CRD
crdFiles := cht.CRDObjects()
// Sort crd files by name to ensure stable manifest output
sort.Slice(crdFiles, func(i, j int) bool { return crdFiles[i].Name < crdFiles[j].Name })
for _, crdFile := range crdFiles {
f := string(crdFile.File.Data)
// add yaml separator if the rendered file doesn't have one at the end
f = strings.TrimSpace(f) + "\n"
if !strings.HasSuffix(f, YAMLSeparator) {
f += YAMLSeparator
}
builder.WriteString(f)
}
return builder.String(), nil
}
// locateChart locate the target chart path by sequential orders:
// 1. find local helm repository using "name-version.tgz" format
// 2. using downloader to pull remote chart
func locateChart(cpOpts *action.ChartPathOptions, name string, settings *cli.EnvSettings) (string, error) {
name = strings.TrimSpace(name)
version := strings.TrimSpace(cpOpts.Version)
// check if it's in Helm's chart cache
// cacheName is hardcoded as format of helm. eg: grafana-6.31.1.tgz
cacheName := name + "-" + cpOpts.Version + ".tgz"
cachePath := path.Join(settings.RepositoryCache, cacheName)
if _, err := os.Stat(cachePath); err == nil {
abs, err := filepath.Abs(cachePath)
if err != nil {
return abs, err
}
if cpOpts.Verify {
if _, err := downloader.VerifyChart(abs, cpOpts.Keyring); err != nil {
return "", err
}
}
return abs, nil
}
dl := downloader.ChartDownloader{
Out: os.Stdout,
Keyring: cpOpts.Keyring,
Getters: getter.All(settings),
Options: []getter.Option{
getter.WithPassCredentialsAll(cpOpts.PassCredentialsAll),
getter.WithTLSClientConfig(cpOpts.CertFile, cpOpts.KeyFile, cpOpts.CaFile),
getter.WithInsecureSkipVerifyTLS(cpOpts.InsecureSkipTLSverify),
},
RepositoryConfig: settings.RepositoryConfig,
RepositoryCache: settings.RepositoryCache,
}
if cpOpts.Verify {
dl.Verify = downloader.VerifyAlways
}
if cpOpts.RepoURL != "" {
chartURL, err := repo.FindChartInAuthAndTLSAndPassRepoURL(cpOpts.RepoURL, cpOpts.Username, cpOpts.Password, name, version,
cpOpts.CertFile, cpOpts.KeyFile, cpOpts.CaFile, cpOpts.InsecureSkipTLSverify, cpOpts.PassCredentialsAll, getter.All(settings))
if err != nil {
return "", err
}
name = chartURL
// Only pass the user/pass on when the user has said to or when the
// location of the chart repo and the chart are the same domain.
u1, err := url.Parse(cpOpts.RepoURL)
if err != nil {
return "", err
}
u2, err := url.Parse(chartURL)
if err != nil {
return "", err
}
// Host on URL (returned from url.Parse) contains the port if present.
// This check ensures credentials are not passed between different
// services on different ports.
if cpOpts.PassCredentialsAll || (u1.Scheme == u2.Scheme && u1.Host == u2.Host) {
dl.Options = append(dl.Options, getter.WithBasicAuth(cpOpts.Username, cpOpts.Password))
} else {
dl.Options = append(dl.Options, getter.WithBasicAuth("", ""))
}
} else {
dl.Options = append(dl.Options, getter.WithBasicAuth(cpOpts.Username, cpOpts.Password))
}
// if RepositoryCache doesn't exist, create it
if err := os.MkdirAll(settings.RepositoryCache, 0o755); err != nil {
return "", err
}
filename, _, err := dl.DownloadTo(name, version, settings.RepositoryCache)
if err != nil {
return "", err
}
fileAbsPath, err := filepath.Abs(filename)
if err != nil {
return filename, err
}
return fileAbsPath, nil
}
func ParseLatestVersion(repoUrl string, version string, devel bool) (string, error) {
cpOpts := &action.ChartPathOptions{
RepoURL: repoUrl,
Version: version,
}
settings := cli.New()
indexURL, err := repo.ResolveReferenceURL(repoUrl, "index.yaml")
if err != nil {
return "", err
}
u, err := url.Parse(repoUrl)
if err != nil {
return "", fmt.Errorf("invalid chart URL format: %s", repoUrl)
}
client, err := getter.All(settings).ByScheme(u.Scheme)
if err != nil {
return "", fmt.Errorf("could not find protocol handler for: %s", u.Scheme)
}
resp, err := client.Get(indexURL,
getter.WithURL(cpOpts.RepoURL),
getter.WithInsecureSkipVerifyTLS(cpOpts.InsecureSkipTLSverify),
getter.WithTLSClientConfig(cpOpts.CertFile, cpOpts.KeyFile, cpOpts.CaFile),
getter.WithBasicAuth(cpOpts.Username, cpOpts.Password),
getter.WithPassCredentialsAll(cpOpts.PassCredentialsAll),
)
if err != nil {
return "", err
}
index, err := io.ReadAll(resp)
if err != nil {
return "", err
}
indexFile, err := loadIndex(index)
if err != nil {
return "", err
}
// get higress helm chart latest version
if entries, ok := indexFile.Entries[RepoChartIndexYamlHigressIndex]; ok {
if devel {
return entries[0].AppVersion, nil
}
if chatVersion, err := indexFile.Get(RepoChartIndexYamlHigressIndex, ""); err != nil {
return "", errors.New("can't find higress latest version")
} else {
return chatVersion.Version, nil
}
}
return "", errors.New("can't find higress latest version")
}
// loadIndex loads an index file and does minimal validity checking.
//
// The source parameter is only used for logging.
// This will fail if API Version is not set (ErrNoAPIVersion) or if the unmarshal fails.
func loadIndex(data []byte) (*repo.IndexFile, error) {
i := &repo.IndexFile{}
if len(data) == 0 {
return i, errors.New("empty index.yaml file")
}
if err := jsonOrYamlUnmarshal(data, i); err != nil {
return i, err
}
for _, cvs := range i.Entries {
for idx := len(cvs) - 1; idx >= 0; idx-- {
if cvs[idx] == nil {
continue
}
if cvs[idx].APIVersion == "" {
cvs[idx].APIVersion = chart.APIVersionV1
}
if err := cvs[idx].Validate(); err != nil {
cvs = append(cvs[:idx], cvs[idx+1:]...)
}
}
}
i.SortEntries()
if i.APIVersion == "" {
return i, errors.New("no API version specified")
}
return i, nil
}
// jsonOrYamlUnmarshal unmarshals the given byte slice containing JSON or YAML
// into the provided interface.
//
// It automatically detects whether the data is in JSON or YAML format by
// checking its validity as JSON. If the data is valid JSON, it will use the
// `encoding/json` package to unmarshal it. Otherwise, it will use the
// `sigs.k8s.io/yaml` package to unmarshal the YAML data.
func jsonOrYamlUnmarshal(b []byte, i interface{}) error {
if json.Valid(b) {
return json.Unmarshal(b, i)
}
return yaml.UnmarshalStrict(b, i)
}

View File

@@ -0,0 +1,548 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tpath
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"github.com/alibaba/higress/hgctl/pkg/util"
"gopkg.in/yaml.v2"
yaml2 "sigs.k8s.io/yaml"
)
// PathContext provides a means for traversing a tree towards the root.
type PathContext struct {
// Parent in the Parent of this PathContext.
Parent *PathContext
// KeyToChild is the key required to reach the child.
KeyToChild any
// Node is the actual Node in the data tree.
Node any
}
// String implements the Stringer interface.
func (nc *PathContext) String() string {
ret := "\n--------------- NodeContext ------------------\n"
if nc.Parent != nil {
ret += fmt.Sprintf("Parent.Node=\n%s\n", nc.Parent.Node)
ret += fmt.Sprintf("KeyToChild=%v\n", nc.Parent.KeyToChild)
}
ret += fmt.Sprintf("Node=\n%s\n", nc.Node)
ret += "----------------------------------------------\n"
return ret
}
// GetPathContext returns the PathContext for the Node which has the given path from root.
// It returns false and no error if the given path is not found, or an error code in other error situations, like
// a malformed path.
// It also creates a tree of PathContexts during the traversal so that Parent nodes can be updated if required. This is
// required when (say) appending to a list, where the parent list itself must be updated.
func GetPathContext(root any, path util.Path, createMissing bool) (*PathContext, bool, error) {
return getPathContext(&PathContext{Node: root}, path, path, createMissing)
}
// WritePathContext writes the given value to the Node in the given PathContext.
func WritePathContext(nc *PathContext, value any, merge bool) error {
if !util.IsValueNil(value) {
return setPathContext(nc, value, merge)
}
if nc.Parent == nil {
return errors.New("cannot delete root element")
}
switch {
case isSliceOrPtrInterface(nc.Parent.Node):
if err := util.DeleteFromSlicePtr(nc.Parent.Node, nc.Parent.KeyToChild.(int)); err != nil {
return err
}
if isMapOrInterface(nc.Parent.Parent.Node) {
return util.InsertIntoMap(nc.Parent.Parent.Node, nc.Parent.Parent.KeyToChild, nc.Parent.Node)
}
// TODO: The case of deleting a list.list.node element is not currently supported.
return fmt.Errorf("cannot delete path: unsupported parent.parent type %T for delete", nc.Parent.Parent.Node)
case util.IsMap(nc.Parent.Node):
return util.DeleteFromMap(nc.Parent.Node, nc.Parent.KeyToChild)
default:
}
return fmt.Errorf("cannot delete path: unsupported parent type %T for delete", nc.Parent.Node)
}
// WriteNode writes value to the tree in root at the given path, creating any required missing internal nodes in path.
func WriteNode(root any, path util.Path, value any) error {
pc, _, err := getPathContext(&PathContext{Node: root}, path, path, true)
if err != nil {
return err
}
return WritePathContext(pc, value, false)
}
// MergeNode merges value to the tree in root at the given path, creating any required missing internal nodes in path.
func MergeNode(root any, path util.Path, value any) error {
pc, _, err := getPathContext(&PathContext{Node: root}, path, path, true)
if err != nil {
return err
}
return WritePathContext(pc, value, true)
}
// Find returns the value at path from the given tree, or false if the path does not exist.
// It behaves differently from GetPathContext in that it never creates map entries at the leaf and does not provide
// a way to mutate the parent of the found node.
func Find(inputTree map[string]any, path util.Path) (any, bool, error) {
if len(path) == 0 {
return nil, false, fmt.Errorf("path is empty")
}
node, found := find(inputTree, path)
return node, found, nil
}
// Delete sets value at path of input untyped tree to nil
func Delete(root map[string]any, path util.Path) (bool, error) {
pc, _, err := getPathContext(&PathContext{Node: root}, path, path, false)
if err != nil {
return false, err
}
return true, WritePathContext(pc, nil, false)
}
// getPathContext is the internal implementation of GetPathContext.
// If createMissing is true, it creates any missing map (but NOT list) path entries in root.
func getPathContext(nc *PathContext, fullPath, remainPath util.Path, createMissing bool) (*PathContext, bool, error) {
if len(remainPath) == 0 {
return nc, true, nil
}
pe := remainPath[0]
if nc.Node == nil {
if !createMissing {
return nil, false, fmt.Errorf("node %s is zero", pe)
}
if util.IsNPathElement(pe) || util.IsKVPathElement(pe) {
nc.Node = []any{}
} else {
nc.Node = make(map[string]any)
}
}
v := reflect.ValueOf(nc.Node)
if v.Kind() == reflect.Ptr || v.Kind() == reflect.Interface {
v = v.Elem()
}
ncNode := v.Interface()
// For list types, we need a key to identify the selected list item. This can be either a value key of the
// form :matching_value in the case of a leaf list, or a matching key:value in the case of a non-leaf list.
if lst, ok := ncNode.([]any); ok {
// If the path element has the form [N], a list element is being selected by index. Return the element at index
// N if it exists.
if util.IsNPathElement(pe) {
idx, err := util.PathN(pe)
if err != nil {
return nil, false, fmt.Errorf("path %s, index %s: %s", fullPath, pe, err)
}
var foundNode any
if idx >= len(lst) || idx < 0 {
if !createMissing {
return nil, false, fmt.Errorf("index %d exceeds list length %d at path %s", idx, len(lst), remainPath)
}
idx = len(lst)
foundNode = make(map[string]any)
} else {
foundNode = lst[idx]
}
nn := &PathContext{
Parent: nc,
Node: foundNode,
}
nc.KeyToChild = idx
return getPathContext(nn, fullPath, remainPath[1:], createMissing)
}
// Otherwise the path element must have form [key:value]. In this case, go through all list elements, which
// must have map type, and try to find one which has a matching key:value.
for idx, le := range lst {
// non-leaf list, expect to match item by key:value.
if lm, ok := le.(map[any]any); ok {
k, v, err := util.PathKV(pe)
if err != nil {
return nil, false, fmt.Errorf("path %s: %s", fullPath, err)
}
if stringsEqual(lm[k], v) {
nn := &PathContext{
Parent: nc,
Node: lm,
}
nc.KeyToChild = idx
nn.KeyToChild = k
if len(remainPath) == 1 {
return nn, true, nil
}
return getPathContext(nn, fullPath, remainPath[1:], createMissing)
}
continue
}
// repeat of the block above for the case where tree unmarshals to map[string]interface{}. There doesn't
// seem to be a way to merge this case into the above block.
if lm, ok := le.(map[string]any); ok {
k, v, err := util.PathKV(pe)
if err != nil {
return nil, false, fmt.Errorf("path %s: %s", fullPath, err)
}
if stringsEqual(lm[k], v) {
nn := &PathContext{
Parent: nc,
Node: lm,
}
nc.KeyToChild = idx
nn.KeyToChild = k
if len(remainPath) == 1 {
return nn, true, nil
}
return getPathContext(nn, fullPath, remainPath[1:], createMissing)
}
continue
}
// leaf list, expect path element [V], match based on value V.
v, err := util.PathV(pe)
if err != nil {
return nil, false, fmt.Errorf("path %s: %s", fullPath, err)
}
if matchesRegex(v, le) {
nn := &PathContext{
Parent: nc,
Node: le,
}
nc.KeyToChild = idx
return getPathContext(nn, fullPath, remainPath[1:], createMissing)
}
}
return nil, false, fmt.Errorf("path %s: element %s not found", fullPath, pe)
}
if util.IsMap(ncNode) {
var nn any
if m, ok := ncNode.(map[any]any); ok {
nn, ok = m[pe]
if !ok {
// remainPath == 1 means the patch is creation of a new leaf.
if createMissing || len(remainPath) == 1 {
m[pe] = make(map[any]any)
nn = m[pe]
} else {
return nil, false, fmt.Errorf("path not found at element %s in path %s", pe, fullPath)
}
}
}
if reflect.ValueOf(ncNode).IsNil() {
ncNode = make(map[string]any)
nc.Node = ncNode
}
if m, ok := ncNode.(map[string]any); ok {
nn, ok = m[pe]
if !ok {
// remainPath == 1 means the patch is creation of a new leaf.
if createMissing || len(remainPath) == 1 {
nextElementNPath := len(remainPath) > 1 && util.IsNPathElement(remainPath[1])
if nextElementNPath {
m[pe] = make([]any, 0)
} else {
m[pe] = make(map[string]any)
}
nn = m[pe]
} else {
return nil, false, fmt.Errorf("path not found at element %s in path %s", pe, fullPath)
}
}
}
npc := &PathContext{
Parent: nc,
Node: nn,
}
// for slices, use the address so that the slice can be mutated.
if util.IsSlice(nn) {
npc.Node = &nn
}
nc.KeyToChild = pe
return getPathContext(npc, fullPath, remainPath[1:], createMissing)
}
return nil, false, fmt.Errorf("leaf type %T in non-leaf Node %s", nc.Node, remainPath)
}
// setPathContext writes the given value to the Node in the given PathContext,
// enlarging all PathContext lists to ensure all indexes are valid.
func setPathContext(nc *PathContext, value any, merge bool) error {
processParent, err := setValueContext(nc, value, merge)
if err != nil || !processParent {
return err
}
// If the path included insertions, process them now
if nc.Parent.Parent == nil {
return nil
}
return setPathContext(nc.Parent, nc.Parent.Node, false) // note: tail recursive
}
// setValueContext writes the given value to the Node in the given PathContext.
// If setting the value requires growing the final slice, grows it.
func setValueContext(nc *PathContext, value any, merge bool) (bool, error) {
if nc.Parent == nil {
return false, nil
}
vv, mapFromString := tryToUnmarshalStringToYAML(value)
switch parentNode := nc.Parent.Node.(type) {
case *any:
switch vParentNode := (*parentNode).(type) {
case []any:
idx := nc.Parent.KeyToChild.(int)
if idx == -1 {
// Treat -1 as insert-at-end of list
idx = len(vParentNode)
}
if idx >= len(vParentNode) {
newElements := make([]any, idx-len(vParentNode)+1)
vParentNode = append(vParentNode, newElements...)
*parentNode = vParentNode
}
merged, err := mergeConditional(vv, nc.Node, merge)
if err != nil {
return false, err
}
vParentNode[idx] = merged
nc.Node = merged
default:
return false, fmt.Errorf("don't know about vtype %T", vParentNode)
}
case map[string]any:
key := nc.Parent.KeyToChild.(string)
// Update is treated differently depending on whether the value is a scalar or map type. If scalar,
// insert a new element into the terminal node, otherwise replace the terminal node with the new subtree.
if ncNode, ok := nc.Node.(*any); ok && !mapFromString {
switch vNcNode := (*ncNode).(type) {
case []any:
switch vv.(type) {
case map[string]any:
// the vv is a map, and the node is a slice
mergedValue := append(vNcNode, vv)
parentNode[key] = mergedValue
case *any:
merged, err := mergeConditional(vv, vNcNode, merge)
if err != nil {
return false, err
}
parentNode[key] = merged
nc.Node = merged
default:
// the vv is an basic JSON type (int, float, string, bool)
vv = append(vNcNode, vv)
parentNode[key] = vv
nc.Node = vv
}
default:
return false, fmt.Errorf("don't know about vnc type %T", vNcNode)
}
} else {
// For map passed as string type, the root is the new key.
if mapFromString {
if err := util.DeleteFromMap(nc.Parent.Node, nc.Parent.KeyToChild); err != nil {
return false, err
}
vm := vv.(map[string]any)
newKey := getTreeRoot(vm)
return false, util.InsertIntoMap(nc.Parent.Node, newKey, vm[newKey])
}
parentNode[key] = vv
nc.Node = vv
}
// TODO `map[interface{}]interface{}` is used by tests in operator/cmd/mesh, we should add our own tests
case map[any]any:
key := nc.Parent.KeyToChild.(string)
parentNode[key] = vv
nc.Node = vv
default:
return false, fmt.Errorf("don't know about type %T", parentNode)
}
return true, nil
}
// mergeConditional returns a merge of newVal and originalVal if merge is true, otherwise it returns newVal.
func mergeConditional(newVal, originalVal any, merge bool) (any, error) {
if !merge || util.IsValueNilOrDefault(originalVal) {
return newVal, nil
}
newS, err := yaml.Marshal(newVal)
if err != nil {
return nil, err
}
if util.IsYAMLEmpty(string(newS)) {
return originalVal, nil
}
originalS, err := yaml.Marshal(originalVal)
if err != nil {
return nil, err
}
if util.IsYAMLEmpty(string(originalS)) {
return newVal, nil
}
mergedS, err := util.OverlayYAML(string(originalS), string(newS))
if err != nil {
return nil, err
}
if util.IsMap(originalVal) {
// For JSON compatibility
out := make(map[string]any)
if err := yaml.Unmarshal([]byte(mergedS), &out); err != nil {
return nil, err
}
return out, nil
}
// For scalars and slices, copy the type
out := originalVal
if err := yaml.Unmarshal([]byte(mergedS), &out); err != nil {
return nil, err
}
return out, nil
}
// find returns the value at path from the given tree, or false if the path does not exist.
func find(treeNode any, path util.Path) (any, bool) {
if len(path) == 0 || treeNode == nil {
return nil, false
}
switch nt := treeNode.(type) {
case map[any]any:
val := nt[path[0]]
if val == nil {
return nil, false
}
if len(path) == 1 {
return val, true
}
return find(val, path[1:])
case map[string]any:
val := nt[path[0]]
if val == nil {
return nil, false
}
if len(path) == 1 {
return val, true
}
return find(val, path[1:])
case []any:
idx, err := strconv.Atoi(path[0])
if err != nil {
return nil, false
}
if idx >= len(nt) {
return nil, false
}
val := nt[idx]
return find(val, path[1:])
default:
return nil, false
}
}
// stringsEqual reports whether the string representations of a and b are equal. a and b may have different types.
func stringsEqual(a, b any) bool {
return fmt.Sprint(a) == fmt.Sprint(b)
}
// matchesRegex reports whether str regex matches pattern.
func matchesRegex(pattern, str any) bool {
match, err := regexp.MatchString(fmt.Sprint(pattern), fmt.Sprint(str))
if err != nil {
return false
}
return match
}
// isSliceOrPtrInterface reports whether v is a slice, a ptr to slice or interface to slice.
func isSliceOrPtrInterface(v any) bool {
vv := reflect.ValueOf(v)
if vv.Kind() == reflect.Ptr {
vv = vv.Elem()
}
if vv.Kind() == reflect.Interface {
vv = vv.Elem()
}
return vv.Kind() == reflect.Slice
}
// isMapOrInterface reports whether v is a map, or interface to a map.
func isMapOrInterface(v any) bool {
vv := reflect.ValueOf(v)
if vv.Kind() == reflect.Interface {
vv = vv.Elem()
}
return vv.Kind() == reflect.Map
}
// tryToUnmarshalStringToYAML tries to unmarshal something that may be a YAML list or map into a structure. If not
// possible, returns original scalar value.
func tryToUnmarshalStringToYAML(s any) (any, bool) {
// If value type is a string it could either be a literal string or a map type passed as a string. Try to unmarshal
// to discover it's the latter.
vv := s
if reflect.TypeOf(vv).Kind() == reflect.String {
sv := strings.Split(vv.(string), "\n")
// Need to be careful not to transform string literals into maps unless they really are maps, since scalar handling
// is different for inserts.
if len(sv) == 1 && strings.Contains(s.(string), ": ") ||
len(sv) > 1 && strings.Contains(s.(string), ":") {
nv := make(map[string]any)
if err := json.Unmarshal([]byte(vv.(string)), &nv); err == nil {
// treat JSON as string
return vv, false
}
if err := yaml2.Unmarshal([]byte(vv.(string)), &nv); err == nil {
return nv, true
}
}
}
// looks like a literal or failed unmarshal, return original type.
return vv, false
}
// getTreeRoot returns the first key found in m. It assumes a single root tree.
func getTreeRoot(m map[string]any) string {
for k := range m {
return k
}
return ""
}

View File

@@ -0,0 +1,843 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tpath
import (
"testing"
"github.com/alibaba/higress/hgctl/pkg/util"
"sigs.k8s.io/yaml"
)
func TestWritePathContext(t *testing.T) {
rootYAML := `
a:
b:
- name: n1
value: v1
- name: n2
list:
- v1
- v2
- v3_regex
`
tests := []struct {
desc string
path string
value any
want string
wantFound bool
wantErr string
}{
{
desc: "AddListEntry",
path: `a.b.[name:n2].list`,
value: `foo`,
wantFound: true,
want: `
a:
b:
- name: n1
value: v1
- name: n2
list:
- v1
- v2
- v3_regex
- foo
`,
},
{
desc: "ModifyListEntryValue",
path: `a.b.[name:n1].value`,
value: `v2`,
wantFound: true,
want: `
a:
b:
- name: n1
value: v2
- list:
- v1
- v2
- v3_regex
name: n2
`,
},
{
desc: "ModifyListEntryValueQuoted",
path: `a.b.[name:n1].value`,
value: `v2`,
wantFound: true,
want: `
a:
b:
- name: "n1"
value: v2
- list:
- v1
- v2
- v3_regex
name: n2
`,
},
{
desc: "ModifyListEntry",
path: `a.b.[name:n2].list.[:v2]`,
value: `v3`,
wantFound: true,
want: `
a:
b:
- name: n1
value: v1
- list:
- v1
- v3
- v3_regex
name: n2
`,
},
{
desc: "ModifyListEntryMapValue",
path: `a.b.[name:n2]`,
value: `name: n2
list:
- nk1: nv1
- nk2: nv2`,
wantFound: true,
want: `
a:
b:
- name: n1
value: v1
- name: n2
list:
- nk1: nv1
- nk2: nv2
`,
},
{
desc: "ModifyNthListEntry",
path: `a.b.[1].list.[:v2]`,
value: `v-the-second`,
wantFound: true,
want: `
a:
b:
- name: n1
value: v1
- list:
- v1
- v-the-second
- v3_regex
name: n2
`,
},
{
desc: "ModifyNthLeafListEntry",
path: `a.b.[1].list.[2]`,
value: `v-the-third`,
wantFound: true,
want: `
a:
b:
- name: n1
value: v1
- list:
- v1
- v2
- v-the-third
name: n2
`,
},
{
desc: "ModifyListEntryValueDotless",
path: `a.b[name:n1].value`,
value: `v2`,
wantFound: true,
want: `
a:
b:
- name: n1
value: v2
- list:
- v1
- v2
- v3_regex
name: n2
`,
},
{
desc: "DeleteListEntry",
path: `a.b.[name:n1]`,
wantFound: true,
want: `
a:
b:
- list:
- v1
- v2
- v3_regex
name: n2
`,
},
{
desc: "DeleteListEntryValue",
path: `a.b.[name:n2].list.[:v2]`,
wantFound: true,
want: `
a:
b:
- name: n1
value: v1
- list:
- v1
- v3_regex
name: n2
`,
},
{
desc: "DeleteListEntryIndex",
path: `a.b.[name:n2].list.[1]`,
wantFound: true,
want: `
a:
b:
- name: n1
value: v1
- list:
- v1
- v3_regex
name: n2
`,
},
{
desc: "DeleteListEntryValueRegex",
path: `a.b.[name:n2].list.[:v3]`,
wantFound: true,
want: `
a:
b:
- name: n1
value: v1
- list:
- v1
- v2
name: n2
`,
},
{
desc: "DeleteListLeafEntryBogusIndex",
path: `a.b.[name:n2].list.[-200]`,
wantFound: false,
wantErr: `path a.b.[name:n2].list.[-200]: element [-200] not found`,
},
{
desc: "DeleteListEntryBogusIndex",
path: `a.b.[1000000].list.[:v2]`,
wantFound: false,
wantErr: `index 1000000 exceeds list length 2 at path [1000000].list.[:v2]`,
},
{
desc: "AddMapEntry",
path: `a.new_key`,
value: `new_val`,
wantFound: true,
want: `
a:
b:
- name: n1
value: v1
- name: n2
list:
- v1
- v2
- v3_regex
new_key: new_val
`,
},
{
desc: "AddMapEntryMapValue",
path: `a.new_key`,
value: `new_key:
nk1:
nk2: nv2`,
wantFound: true,
want: `
a:
b:
- name: n1
value: v1
- name: n2
list:
- v1
- v2
- v3_regex
new_key:
nk1:
nk2: nv2
`,
},
{
desc: "ModifyMapEntryMapValue",
path: `a.b`,
value: `nk1:
nk2: nv2`,
wantFound: true,
want: `
a:
nk1:
nk2: nv2
`,
},
{
desc: "DeleteMapEntry",
path: `a.b`,
wantFound: true,
want: `
a: {}
`,
},
{
desc: "path not found",
path: `a.c.[name:n2].list.[:v3]`,
wantFound: false,
wantErr: `path not found at element c in path a.c.[name:n2].list.[:v3]`,
},
{
desc: "error key",
path: `a.b.[].list`,
wantFound: false,
wantErr: `path a.b.[].list: [] is not a valid key:value path element`,
},
{
desc: "invalid index",
path: `a.c.[n2].list.[:v3]`,
wantFound: false,
wantErr: `path not found at element c in path a.c.[n2].list.[:v3]`,
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
root := make(map[string]any)
if err := yaml.Unmarshal([]byte(rootYAML), &root); err != nil {
t.Fatal(err)
}
pc, gotFound, gotErr := GetPathContext(root, util.PathFromString(tt.path), false)
if gotErr, wantErr := errToString(gotErr), tt.wantErr; gotErr != wantErr {
t.Fatalf("GetPathContext(%s): gotErr:%s, wantErr:%s", tt.desc, gotErr, wantErr)
}
if gotFound != tt.wantFound {
t.Fatalf("GetPathContext(%s): gotFound:%v, wantFound:%v", tt.desc, gotFound, tt.wantFound)
}
if tt.wantErr != "" || !tt.wantFound {
if tt.want != "" {
t.Error("tt.want is set but never checked")
}
return
}
err := WritePathContext(pc, tt.value, false)
if err != nil {
t.Fatal(err)
}
gotYAML := util.ToYAML(root)
diff := util.YAMLDiff(gotYAML, tt.want)
if diff != "" {
t.Errorf("%s: (got:-, want:+):\n%s\n", tt.desc, diff)
}
})
}
}
func TestWriteNode(t *testing.T) {
testTreeYAML := `
a:
b:
c: val1
list1:
- i1: val1
- i2: val2
- i3a: key1
i3b:
list2:
- i1: val1
- i2: val2
- i3a: key1
i3b:
i1: va11
`
tests := []struct {
desc string
baseYAML string
path string
value string
want string
wantErr string
}{
{
desc: "insert empty",
path: "a.b.c",
value: "val1",
want: `
a:
b:
c: val1
`,
},
{
desc: "overwrite",
baseYAML: testTreeYAML,
path: "a.b.c",
value: "val2",
want: `
a:
b:
c: val2
list1:
- i1: val1
- i2: val2
- i3a: key1
i3b:
list2:
- i1: val1
- i2: val2
- i3a: key1
i3b:
i1: va11
`,
},
{
desc: "partial create",
baseYAML: testTreeYAML,
path: "a.b.d",
value: "val3",
want: `
a:
b:
c: val1
d: val3
list1:
- i1: val1
- i2: val2
- i3a: key1
i3b:
list2:
- i1: val1
- i2: val2
- i3a: key1
i3b:
i1: va11
`,
},
{
desc: "list keys",
baseYAML: testTreeYAML,
path: "a.b.list1.[i3a:key1].i3b.list2.[i3a:key1].i3b.i1",
value: "val2",
want: `
a:
b:
c: val1
list1:
- i1: val1
- i2: val2
- i3a: key1
i3b:
list2:
- i1: val1
- i2: val2
- i3a: key1
i3b:
i1: val2
`,
},
// For https://github.com/istio/istio/issues/20950
{
desc: "with initial list",
baseYAML: `
components:
ingressGateways:
- enabled: true
`,
path: "components.ingressGateways[0].enabled",
value: "false",
want: `
components:
ingressGateways:
- enabled: "false"
`,
},
{
desc: "no initial list",
baseYAML: "",
path: "components.ingressGateways[0].enabled",
value: "false",
want: `
components:
ingressGateways:
- enabled: "false"
`,
},
{
desc: "no initial list for entry",
baseYAML: `
a: {}
`,
path: "a.list.[0]",
value: "v1",
want: `
a:
list:
- v1
`,
},
{
desc: "ExtendNthLeafListEntry",
baseYAML: `
a:
list:
- v1
`,
path: `a.list.[1]`,
value: `v2`,
want: `
a:
list:
- v1
- v2
`,
},
{
desc: "ExtendLeafListEntryLargeIndex",
baseYAML: `
a:
list:
- v1
`,
path: `a.list.[999]`,
value: `v2`,
want: `
a:
list:
- v1
- v2
`,
},
{
desc: "ExtendLeafListEntryNegativeIndex",
baseYAML: `
a:
list:
- v1
`,
path: `a.list.[-1]`,
value: `v2`,
want: `
a:
list:
- v1
- v2
`,
},
{
desc: "ExtendNthListEntry",
baseYAML: `
a:
list:
- name: foo
`,
path: `a.list.[1].name`,
value: `bar`,
want: `
a:
list:
- name: foo
- name: bar
`,
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
root := make(map[string]any)
if tt.baseYAML != "" {
if err := yaml.Unmarshal([]byte(tt.baseYAML), &root); err != nil {
t.Fatal(err)
}
}
p := util.PathFromString(tt.path)
err := WriteNode(root, p, tt.value)
if gotErr, wantErr := errToString(err), tt.wantErr; gotErr != wantErr {
t.Errorf("%s: gotErr:%s, wantErr:%s", tt.desc, gotErr, wantErr)
return
}
if got, want := util.ToYAML(root), tt.want; err == nil && util.YAMLDiff(got, want) != "" {
t.Errorf("%s: got:\n%s\nwant:\n%s\ndiff:\n%s\n", tt.desc, got, want, util.YAMLDiff(got, want))
}
})
}
}
func TestMergeNode(t *testing.T) {
testTreeYAML := `
a:
b:
c: val1
list1:
- i1: val1
- i2: val2
`
tests := []struct {
desc string
baseYAML string
path string
value string
want string
wantErr string
}{
{
desc: "merge list entry",
baseYAML: testTreeYAML,
path: "a.b.list1.[i1:val1]",
value: `
i2b: val2`,
want: `
a:
b:
c: val1
list1:
- i1: val1
i2b: val2
- i2: val2
`,
},
{
desc: "merge list 2",
baseYAML: testTreeYAML,
path: "a.b.list1",
value: `
i3:
a: val3
`,
want: `
a:
b:
c: val1
list1:
- i1: val1
- i2: val2
- i3:
a: val3
`,
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
root := make(map[string]any)
if tt.baseYAML != "" {
if err := yaml.Unmarshal([]byte(tt.baseYAML), &root); err != nil {
t.Fatal(err)
}
}
p := util.PathFromString(tt.path)
iv := make(map[string]any)
err := yaml.Unmarshal([]byte(tt.value), &iv)
if err != nil {
t.Fatal(err)
}
err = MergeNode(root, p, iv)
if gotErr, wantErr := errToString(err), tt.wantErr; gotErr != wantErr {
t.Errorf("%s: gotErr:%s, wantErr:%s", tt.desc, gotErr, wantErr)
return
}
if got, want := util.ToYAML(root), tt.want; err == nil && util.YAMLDiff(got, want) != "" {
t.Errorf("%s: got:\n%s\nwant:\n%s\ndiff:\n%s\n", tt.desc, got, want, util.YAMLDiff(got, want))
}
})
}
}
// errToString returns the string representation of err and the empty string if
// err is nil.
func errToString(err error) string {
if err == nil {
return ""
}
return err.Error()
}
// TestSecretVolumes simulates https://github.com/istio/istio/issues/20381
func TestSecretVolumes(t *testing.T) {
rootYAML := `
values:
gateways:
istio-egressgateway:
secretVolumes: []
`
root := make(map[string]any)
if err := yaml.Unmarshal([]byte(rootYAML), &root); err != nil {
t.Fatal(err)
}
overrides := []struct {
path string
value any
}{
{
path: "values.gateways.istio-egressgateway.secretVolumes[0].name",
value: "egressgateway-certs",
},
{
path: "values.gateways.istio-egressgateway.secretVolumes[0].secretName",
value: "istio-egressgateway-certs",
},
{
path: "values.gateways.istio-egressgateway.secretVolumes[0].mountPath",
value: "/etc/istio/egressgateway-certs",
},
{
path: "values.gateways.istio-egressgateway.secretVolumes[1].name",
value: "egressgateway-ca-certs",
},
{
path: "values.gateways.istio-egressgateway.secretVolumes[1].secretName",
value: "istio-egressgateway-ca-certs",
},
{
path: "values.gateways.istio-egressgateway.secretVolumes[1].mountPath",
value: "/etc/istio/egressgateway-ca-certs",
},
{
path: "values.gateways.istio-egressgateway.secretVolumes[2].name",
value: "nginx-client-certs",
},
{
path: "values.gateways.istio-egressgateway.secretVolumes[2].secretName",
value: "nginx-client-certs",
},
{
path: "values.gateways.istio-egressgateway.secretVolumes[2].mountPath",
value: "/etc/istio/nginx-client-certs",
},
{
path: "values.gateways.istio-egressgateway.secretVolumes[3].name",
value: "nginx-ca-certs",
},
{
path: "values.gateways.istio-egressgateway.secretVolumes[3].secretName",
value: "nginx-ca-certs",
},
{
path: "values.gateways.istio-egressgateway.secretVolumes[3].mountPath",
value: "/etc/istio/nginx-ca-certs",
},
}
for _, override := range overrides {
pc, _, err := GetPathContext(root, util.PathFromString(override.path), true)
if err != nil {
t.Fatalf("GetPathContext(%q): %v", override.path, err)
}
err = WritePathContext(pc, override.value, false)
if err != nil {
t.Fatalf("WritePathContext(%q): %v", override.path, err)
}
}
want := `
values:
gateways:
istio-egressgateway:
secretVolumes:
- mountPath: /etc/istio/egressgateway-certs
name: egressgateway-certs
secretName: istio-egressgateway-certs
- mountPath: /etc/istio/egressgateway-ca-certs
name: egressgateway-ca-certs
secretName: istio-egressgateway-ca-certs
- mountPath: /etc/istio/nginx-client-certs
name: nginx-client-certs
secretName: nginx-client-certs
- mountPath: /etc/istio/nginx-ca-certs
name: nginx-ca-certs
secretName: nginx-ca-certs
`
gotYAML := util.ToYAML(root)
diff := util.YAMLDiff(gotYAML, want)
if diff != "" {
t.Errorf("TestSecretVolumes: diff:\n%s\n", diff)
}
}
// Simulates https://github.com/istio/istio/issues/19196
func TestWriteEscapedPathContext(t *testing.T) {
rootYAML := `
values:
sidecarInjectorWebhook:
injectedAnnotations: {}
`
tests := []struct {
desc string
path string
value any
want string
wantFound bool
wantErr string
}{
{
desc: "ModifyEscapedPathValue",
path: `values.sidecarInjectorWebhook.injectedAnnotations.container\.apparmor\.security\.beta\.kubernetes\.io/istio-proxy`,
value: `runtime/default`,
wantFound: true,
want: `
values:
sidecarInjectorWebhook:
injectedAnnotations:
container.apparmor.security.beta.kubernetes.io/istio-proxy: runtime/default
`,
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
root := make(map[string]any)
if err := yaml.Unmarshal([]byte(rootYAML), &root); err != nil {
t.Fatal(err)
}
pc, gotFound, gotErr := GetPathContext(root, util.PathFromString(tt.path), false)
if gotErr, wantErr := errToString(gotErr), tt.wantErr; gotErr != wantErr {
t.Fatalf("GetPathContext(%s): gotErr:%s, wantErr:%s", tt.desc, gotErr, wantErr)
}
if gotFound != tt.wantFound {
t.Fatalf("GetPathContext(%s): gotFound:%v, wantFound:%v", tt.desc, gotFound, tt.wantFound)
}
if tt.wantErr != "" || !tt.wantFound {
return
}
err := WritePathContext(pc, tt.value, false)
if err != nil {
t.Fatal(err)
}
gotYAML := util.ToYAML(root)
diff := util.YAMLDiff(gotYAML, tt.want)
if diff != "" {
t.Errorf("%s: diff:\n%s\n", tt.desc, diff)
}
})
}
}

View File

@@ -0,0 +1,58 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tpath
import (
"github.com/alibaba/higress/hgctl/pkg/util"
"gopkg.in/yaml.v2"
yaml2 "sigs.k8s.io/yaml"
)
// AddSpecRoot adds a root node called "spec" to the given tree and returns the resulting tree.
func AddSpecRoot(tree string) (string, error) {
t, nt := make(map[string]any), make(map[string]any)
if err := yaml.Unmarshal([]byte(tree), &t); err != nil {
return "", err
}
nt["spec"] = t
out, err := yaml.Marshal(nt)
if err != nil {
return "", err
}
return string(out), nil
}
// GetSpecSubtree returns the subtree under "spec".
func GetSpecSubtree(yml string) (string, error) {
return GetConfigSubtree(yml, "spec")
}
// GetConfigSubtree returns the subtree at the given path.
func GetConfigSubtree(manifest, path string) (string, error) {
root := make(map[string]any)
if err := yaml2.Unmarshal([]byte(manifest), &root); err != nil {
return "", err
}
nc, _, err := GetPathContext(root, util.PathFromString(path), false)
if err != nil {
return "", err
}
out, err := yaml2.Marshal(nc.Node)
if err != nil {
return "", err
}
return string(out), nil
}

View File

@@ -0,0 +1,122 @@
// Copyright (c) 2022 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package tpath
import (
"errors"
"testing"
)
func TestAddSpecRoot(t *testing.T) {
tests := []struct {
desc string
in string
expect string
err error
}{
{
desc: "empty",
in: ``,
expect: `spec: {}
`,
err: nil,
},
{
desc: "add-root",
in: `
a: va
b: foo`,
expect: `spec:
a: va
b: foo
`,
err: nil,
},
{
desc: "err",
in: `i can't be yaml, can I?`,
expect: ``,
err: errors.New(""),
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
if got, err := AddSpecRoot(tt.in); got != tt.expect ||
((err != nil && tt.err == nil) || (err == nil && tt.err != nil)) {
t.Errorf("%s AddSpecRoot(%s) => %s, want %s", tt.desc, tt.in, got, tt.expect)
}
})
}
}
func TestGetConfigSubtree(t *testing.T) {
tests := []struct {
desc string
manifest string
path string
expect string
err bool
}{
{
desc: "empty",
manifest: ``,
path: ``,
expect: `{}
`,
err: false,
},
{
desc: "subtree",
manifest: `
a:
b:
- name: n1
value: v2
- list:
- v1
- v2
- v3_regex
name: n2
`,
path: `a`,
expect: `b:
- name: n1
value: v2
- list:
- v1
- v2
- v3_regex
name: n2
`,
err: false,
},
{
desc: "err",
manifest: "not-yaml",
path: "not-subnode",
expect: ``,
err: true,
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
if got, err := GetConfigSubtree(tt.manifest, tt.path); got != tt.expect || (err == nil) == tt.err {
t.Errorf("%s GetConfigSubtree(%s, %s) => %s, want %s", tt.desc, tt.manifest, tt.path, got, tt.expect)
}
})
}
}