github.com/fafucoder/cilium@v1.6.11/cilium/cmd/preflight.go (about)

     1  // Copyright 2019-2020 Authors of Cilium
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package cmd
    16  
    17  import (
    18  	"encoding/json"
    19  	"io"
    20  	"net"
    21  	"os"
    22  	"time"
    23  
    24  	"github.com/cilium/cilium/pkg/fqdn"
    25  	"github.com/cilium/cilium/pkg/fqdn/matchpattern"
    26  	"github.com/cilium/cilium/pkg/option"
    27  	policyAPI "github.com/cilium/cilium/pkg/policy/api"
    28  
    29  	"github.com/spf13/cobra"
    30  )
    31  
    32  const (
    33  	toFQDNsPreCachePathOption = "tofqdns-pre-cache"
    34  	toFQDNsPreCacheTTLOption  = "tofqdns-pre-cache-ttl"
    35  )
    36  
    37  var (
    38  	toFQDNsPreCachePath string
    39  	toFQDNsPreCacheTTL  int
    40  
    41  	k8sAPIServer      string
    42  	k8sKubeConfigPath string
    43  )
    44  
    45  // preflightCmd is the command used to manage preflight tasks for upgrades
    46  var preflightCmd = &cobra.Command{
    47  	Use:   "preflight",
    48  	Short: "cilium upgrade helper",
    49  	Long:  `CLI to help upgrade cilium`,
    50  }
    51  
    52  // pollerC, is the command used to upgrade a fqdn poller
    53  var pollerCmd = &cobra.Command{
    54  	Use:   "fqdn-poller",
    55  	Short: "Prepare for DNS Polling upgrades to cilium 1.4",
    56  	Long: `Prepare for DNS Polling upgrades to cilium 1.4 by creating a
    57  placeholder --tofqdns-pre-cache file that can be used to pre-seed the DNS
    58  cached used in toFQDNs rules. This is useful when upgrading cilium with
    59  DNS Polling policies where an interruption in allowed IPs is undesirable. It
    60  may also be used when switching from DNS Polling based DNS discovery to DNS
    61  Proxy based discovery where an endpoint may not make a DNS request soon
    62  enough to be used by toFQDNs policy rules`,
    63  	Run: func(cmd *cobra.Command, args []string) {
    64  		preflightPoller()
    65  	},
    66  }
    67  
    68  func init() {
    69  	pollerCmd.Flags().StringVar(&toFQDNsPreCachePath, toFQDNsPreCachePathOption, "", "The path to write serialized ToFQDNs pre-cache information. stdout is the default")
    70  	pollerCmd.Flags().IntVar(&toFQDNsPreCacheTTL, toFQDNsPreCacheTTLOption, 604800, "TTL, in seconds, to set on generated ToFQDNs pre-cache information")
    71  	preflightCmd.AddCommand(pollerCmd)
    72  
    73  	// From preflight_migrate_crd_identity.go
    74  	migrateIdentityCmd.Flags().StringVar(&k8sAPIServer, "k8s-api-server", "", "Kubernetes api address server (for https use --k8s-kubeconfig-path instead)")
    75  	migrateIdentityCmd.Flags().StringVar(&k8sKubeConfigPath, "k8s-kubeconfig-path", "", "Absolute path of the kubernetes kubeconfig file")
    76  	migrateIdentityCmd.Flags().StringVar(&kvStore, "kvstore", "", "Key-value store type")
    77  	migrateIdentityCmd.Flags().Var(option.NewNamedMapOptions("kvstore-opts", &kvStoreOpts, nil), "kvstore-opt", "Key-value store options")
    78  	preflightCmd.AddCommand(migrateIdentityCmd)
    79  
    80  	validateCNP.Flags().StringVar(&k8sAPIServer, "k8s-api-server", "", "Kubernetes api address server (for https use --k8s-kubeconfig-path instead)")
    81  	validateCNP.Flags().StringVar(&k8sKubeConfigPath, "k8s-kubeconfig-path", "", "Absolute path of the kubernetes kubeconfig file")
    82  	preflightCmd.AddCommand(validateCNP)
    83  
    84  	rootCmd.AddCommand(preflightCmd)
    85  }
    86  
    87  // preflightPoller collects IP data in toCIDRSet rules that are siblings to
    88  // toFQDNs rules. These can only be created by toFQDNs updates and correspond
    89  // to the matchName entries in that egressRule (the API rejects rules with two
    90  // L3 components like this). This data is turned into json parsable by
    91  // fqdn.DNSCache UnmarshalJSON.
    92  func preflightPoller() {
    93  	lookupTime := time.Now()
    94  
    95  	// Get data from the local cilium-agent
    96  	DNSData, err := getDNSMappings()
    97  	if err != nil {
    98  		Fatalf("Cannot extract DNS data from local cilium-agent: %s", err)
    99  	}
   100  
   101  	// Build a cache from this data to be serialized
   102  	cache := fqdn.NewDNSCache(0)
   103  	for name, IPs := range DNSData {
   104  		cache.Update(lookupTime, name, IPs, toFQDNsPreCacheTTL)
   105  	}
   106  
   107  	// Marshal into a writeable format
   108  	serialized, err := json.Marshal(cache)
   109  	if err != nil {
   110  		Fatalf("Cannot create DNS pre-cache data from policy DNS data: %s", err)
   111  	}
   112  
   113  	var outWriter io.WriteCloser = os.Stdout
   114  	if toFQDNsPreCachePath != "" {
   115  		outWriter, err = os.OpenFile(toFQDNsPreCachePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0755)
   116  		if err != nil {
   117  			Fatalf("Cannot open target destination for DNS pre-cache data: %s", err)
   118  		}
   119  	}
   120  	defer outWriter.Close()
   121  	if _, err = outWriter.Write(serialized); err != nil {
   122  		Fatalf("Error writing data: %s", err)
   123  	}
   124  }
   125  
   126  // getDNSMappings reads the policy from a local agent via its API and collects
   127  // the IPs seen for each matchName.
   128  // Note: No attempt is made to ensure an IP belongs only to one/the correct
   129  // matchName. In cases where different sets of matchNames are used, each with a
   130  // different combination of names, the IPs set per name will reflects IPs that
   131  // actuall belong to other names also seen in the toFQDNs section of that rule.
   132  func getDNSMappings() (DNSData map[string][]net.IP, err error) {
   133  	policy, err := client.PolicyGet(nil)
   134  	if err != nil {
   135  		return nil, err
   136  	}
   137  
   138  	var rules policyAPI.Rules
   139  	if err := json.Unmarshal([]byte(policy.Policy), &rules); err != nil {
   140  		return nil, err
   141  	}
   142  
   143  	// for each egressrule, when ToFQDNs.matchName is filled in, use the IPs we
   144  	// inserted into that rule as IPs for that DNS name (this may be shared by many
   145  	// DNS names). We ensure that we only read /32 CIDRs, since we only ever insert
   146  	// those.
   147  	DNSData = make(map[string][]net.IP)
   148  	for _, rule := range rules {
   149  		for _, egressRule := range rule.Egress {
   150  			for _, ToFQDN := range egressRule.ToFQDNs {
   151  				// nothing to do when no matchName exists or there are no IPs in this
   152  				// rule
   153  				if ToFQDN.MatchName == "" || len(egressRule.ToCIDRSet) == 0 {
   154  					continue
   155  				}
   156  				for _, cidr := range egressRule.ToCIDRSet {
   157  					ip, _, err := net.ParseCIDR(string(cidr.Cidr))
   158  					if err != nil {
   159  						return nil, err
   160  					}
   161  					name := matchpattern.Sanitize(ToFQDN.MatchName)
   162  					DNSData[name] = append(DNSData[name], ip)
   163  				}
   164  			}
   165  		}
   166  	}
   167  
   168  	return DNSData, nil
   169  }