| 1 | /* |
| 2 | * This file is part of the go-nft project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | * |
| 16 | * Copyright 2021 Red Hat, Inc. |
| 17 | * |
| 18 | */ |
| 19 | |
| 20 | package example |
| 21 | |
| 22 | import ( |
| 23 | "fmt" |
| 24 | |
| 25 | "github.com/networkplumbing/go-nft/tests/testlib" |
| 26 | |
| 27 | "github.com/networkplumbing/go-nft/nft" |
| 28 | ) |
| 29 | |
| 30 | type buildConfigT func() *nft.Config |
| 31 | |
| 32 | func setupExample(buildConfig buildConfigT) (string, string, error) { |
| 33 | desiredConfig := buildConfig() |
| 34 | if err := nft.ApplyConfig(desiredConfig); err != nil { |
| 35 | return "", "", fmt.Errorf("failed to setup example: %v", err) |
| 36 | } |
| 37 | |
| 38 | actualConfig, err := nft.ReadConfig() |
| 39 | if err != nil { |
| 40 | return "", "", fmt.Errorf("failed to setup example: %v", err) |
| 41 | } |
| 42 | |
| 43 | desiredNftablesEntries := len(desiredConfig.Nftables) + 1 // +1 for the metainfo entry. |
| 44 | actualNftablesEntries := len(actualConfig.Nftables) |
| 45 | if actualNftablesEntries != desiredNftablesEntries { |
| 46 | desiredJson, _ := desiredConfig.ToJSON() |
| 47 | actualJson, _ := actualConfig.ToJSON() |
| 48 | return "", "", fmt.Errorf( |
| 49 | "failed to setup example, unexpected entries in post-setup resuts, desired(%d): %s, actual(%d): %s", |
| 50 | desiredNftablesEntries, desiredJson, actualNftablesEntries, actualJson, |
| 51 | ) |
| 52 | } |
| 53 | |
| 54 | desiredConfig = testlib.NormalizeConfigForComparison(desiredConfig) |
| 55 | actualConfig = testlib.NormalizeConfigForComparison(actualConfig) |
| 56 | |
| 57 | desiredJson, err := desiredConfig.ToJSON() |
| 58 | if err != nil { |
| 59 | return "", "", fmt.Errorf("failed to setup example, error json encoding: %v", err) |
| 60 | } |
| 61 | actualJson, err := actualConfig.ToJSON() |
| 62 | if err != nil { |
| 63 | return "", "", fmt.Errorf("failed to setup example, error json encoding: %v", err) |
| 64 | } |
| 65 | |
| 66 | return string(desiredJson), string(actualJson), nil |
| 67 | } |