github.com/nmstate/kubernetes-nmstate@v0.82.0/pkg/bridge/bridge.go (about)

     1  /*
     2  Copyright The Kubernetes NMState Authors.
     3  
     4  
     5  Licensed under the Apache License, Version 2.0 (the "License");
     6  you may not use this file except in compliance with the License.
     7  You may obtain a copy of the License at
     8  
     9      http://www.apache.org/licenses/LICENSE-2.0
    10  
    11  Unless required by applicable law or agreed to in writing, software
    12  distributed under the License is distributed on an "AS IS" BASIS,
    13  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  See the License for the specific language governing permissions and
    15  limitations under the License.
    16  */
    17  
    18  package bridge
    19  
    20  import (
    21  	"fmt"
    22  
    23  	"github.com/tidwall/gjson"
    24  	"github.com/tidwall/sjson"
    25  
    26  	yaml "sigs.k8s.io/yaml"
    27  
    28  	nmstate "github.com/nmstate/kubernetes-nmstate/api/shared"
    29  )
    30  
    31  const minVlanID = 2
    32  const maxVlanID = 4094
    33  
    34  var defaultVlanFiltering = map[string]interface{}{
    35  	"mode": "trunk",
    36  	"trunk-tags": []map[string]interface{}{
    37  		{
    38  			"id-range": map[string]interface{}{
    39  				"min": minVlanID,
    40  				"max": maxVlanID,
    41  			},
    42  		},
    43  	},
    44  }
    45  
    46  func ApplyDefaultVlanFiltering(desiredState nmstate.State) (nmstate.State, error) {
    47  	result, err := yaml.YAMLToJSON(desiredState.Raw)
    48  	if err != nil {
    49  		return desiredState, fmt.Errorf("error converting desiredState to JSON: %v", err)
    50  	}
    51  
    52  	ifaces := gjson.ParseBytes(result).Get("interfaces").Array()
    53  	for ifaceIndex, iface := range ifaces {
    54  		if !isLinuxBridgeUp(iface) {
    55  			continue
    56  		}
    57  		for portIndex, port := range iface.Get("bridge.port").Array() {
    58  			if hasVlanConfiguration(port) {
    59  				continue
    60  			}
    61  			result, err = sjson.SetBytes(
    62  				result,
    63  				fmt.Sprintf("interfaces.%d.bridge.port.%d.vlan", ifaceIndex, portIndex),
    64  				defaultVlanFiltering,
    65  			)
    66  			if err != nil {
    67  				return desiredState, err
    68  			}
    69  		}
    70  	}
    71  
    72  	resultYaml, err := yaml.JSONToYAML(result)
    73  	if err != nil {
    74  		return desiredState, err
    75  	}
    76  	return nmstate.State{Raw: resultYaml}, nil
    77  }
    78  
    79  func isLinuxBridgeUp(iface gjson.Result) bool {
    80  	return iface.Get("type").String() == "linux-bridge" && iface.Get("state").String() == "up"
    81  }
    82  
    83  func hasVlanConfiguration(port gjson.Result) bool {
    84  	return port.Get("vlan").Exists()
    85  }