| 1 | // Copyright 2015 CNI authors |
| 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 main |
| 16 | |
| 17 | import ( |
| 18 | "context" |
| 19 | "encoding/json" |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | "net" |
| 23 | "net/http" |
| 24 | "net/rpc" |
| 25 | "os" |
| 26 | "os/signal" |
| 27 | "path/filepath" |
| 28 | "runtime" |
| 29 | "sync" |
| 30 | "syscall" |
| 31 | "time" |
| 32 | |
| 33 | "github.com/coreos/go-systemd/v22/activation" |
| 34 | |
| 35 | "github.com/containernetworking/cni/pkg/skel" |
| 36 | current "github.com/containernetworking/cni/pkg/types/100" |
| 37 | ) |
| 38 | |
| 39 | var errNoMoreTries = errors.New("no more tries") |
| 40 | |
| 41 | type DHCP struct { |
| 42 | mux sync.Mutex |
| 43 | leases map[string]*DHCPLease |
| 44 | hostNetnsPrefix string |
| 45 | clientTimeout time.Duration |
| 46 | clientResendMax time.Duration |
| 47 | clientResendTimeout time.Duration |
| 48 | broadcast bool |
| 49 | } |
| 50 | |
| 51 | func newDHCP(clientTimeout, clientResendMax time.Duration, resendTimeout time.Duration) *DHCP { |
| 52 | return &DHCP{ |
| 53 | leases: make(map[string]*DHCPLease), |
| 54 | clientTimeout: clientTimeout, |
| 55 | clientResendMax: clientResendMax, |
| 56 | clientResendTimeout: resendTimeout, |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | // TODO: current client ID is too long. At least the container ID should not be used directly. |
| 61 | // A separate issue is necessary to ensure no breaking change is affecting other users. |
| 62 | func generateClientID(containerID string, netName string, ifName string) string { |
| 63 | clientID := containerID + "/" + netName + "/" + ifName |
| 64 | // defined in RFC 2132, length size can not be larger than 1 octet. So we truncate 254 to make everyone happy. |
| 65 | if len(clientID) > 254 { |
| 66 | clientID = clientID[0:254] |
| 67 | } |
| 68 | return clientID |
| 69 | } |
| 70 | |
| 71 | // Allocate acquires an IP from a DHCP server for a specified container. |
| 72 | // The acquired lease will be maintained until Release() is called. |
| 73 | func (d *DHCP) Allocate(args *skel.CmdArgs, result *current.Result) error { |
| 74 | conf := NetConf{} |
| 75 | if err := json.Unmarshal(args.StdinData, &conf); err != nil { |
| 76 | return fmt.Errorf("error parsing netconf: %v", err) |
| 77 | } |
| 78 | |
| 79 | opts, err := prepareOptions(args.Args, conf.IPAM.ProvideOptions, conf.IPAM.RequestOptions) |
| 80 | if err != nil { |
| 81 | return err |
| 82 | } |
| 83 | |
| 84 | clientID := generateClientID(args.ContainerID, conf.Name, args.IfName) |
| 85 | |
| 86 | // If we already have an active lease for this clientID, do not create |
| 87 | // another one |
| 88 | l := d.getLease(clientID) |
| 89 | if l != nil { |
| 90 | l.Check() |
| 91 | } else { |
| 92 | hostNetns := d.hostNetnsPrefix + args.Netns |
| 93 | l, err = AcquireLease(clientID, hostNetns, args.IfName, |
| 94 | opts, |
| 95 | d.clientTimeout, d.clientResendMax, d.clientResendTimeout, d.broadcast) |
| 96 | if err != nil { |
| 97 | return err |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | ipn, err := l.IPNet() |
| 102 | if err != nil { |
| 103 | l.Stop() |
| 104 | return err |
| 105 | } |
| 106 | |
| 107 | d.setLease(clientID, l) |
| 108 | |
| 109 | result.IPs = []*current.IPConfig{{ |
| 110 | Address: *ipn, |
| 111 | Gateway: l.Gateway(), |
| 112 | }} |
| 113 | result.Routes = l.Routes() |
| 114 | if conf.IPAM.Priority != 0 { |
| 115 | for _, r := range result.Routes { |
| 116 | r.Priority = conf.IPAM.Priority |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | return nil |
| 121 | } |
| 122 | |
| 123 | // Release stops maintenance of the lease acquired in Allocate() |
| 124 | // and sends a release msg to the DHCP server. |
| 125 | func (d *DHCP) Release(args *skel.CmdArgs, _ *struct{}) error { |
| 126 | conf := NetConf{} |
| 127 | if err := json.Unmarshal(args.StdinData, &conf); err != nil { |
| 128 | return fmt.Errorf("error parsing netconf: %v", err) |
| 129 | } |
| 130 | |
| 131 | clientID := generateClientID(args.ContainerID, conf.Name, args.IfName) |
| 132 | if l := d.getLease(clientID); l != nil { |
| 133 | l.Stop() |
| 134 | d.clearLease(clientID) |
| 135 | } |
| 136 | |
| 137 | return nil |
| 138 | } |
| 139 | |
| 140 | func (d *DHCP) getLease(clientID string) *DHCPLease { |
| 141 | d.mux.Lock() |
| 142 | defer d.mux.Unlock() |
| 143 | |
| 144 | // TODO(eyakubovich): hash it to avoid collisions |
| 145 | l, ok := d.leases[clientID] |
| 146 | if !ok { |
| 147 | return nil |
| 148 | } |
| 149 | return l |
| 150 | } |
| 151 | |
| 152 | func (d *DHCP) setLease(clientID string, l *DHCPLease) { |
| 153 | d.mux.Lock() |
| 154 | defer d.mux.Unlock() |
| 155 | |
| 156 | // TODO(eyakubovich): hash it to avoid collisions |
| 157 | d.leases[clientID] = l |
| 158 | } |
| 159 | |
| 160 | // func (d *DHCP) clearLease(contID, netName, ifName string) { |
| 161 | func (d *DHCP) clearLease(clientID string) { |
| 162 | d.mux.Lock() |
| 163 | defer d.mux.Unlock() |
| 164 | |
| 165 | // TODO(eyakubovich): hash it to avoid collisions |
| 166 | delete(d.leases, clientID) |
| 167 | } |
| 168 | |
| 169 | func getListener(socketPath string) (net.Listener, error) { |
| 170 | l, err := activation.Listeners() |
| 171 | if err != nil { |
| 172 | return nil, err |
| 173 | } |
| 174 | |
| 175 | switch { |
| 176 | case len(l) == 0: |
| 177 | if err := os.MkdirAll(filepath.Dir(socketPath), 0o700); err != nil { |
| 178 | return nil, err |
| 179 | } |
| 180 | return net.Listen("unix", socketPath) |
| 181 | |
| 182 | case len(l) == 1: |
| 183 | if l[0] == nil { |
| 184 | return nil, fmt.Errorf("LISTEN_FDS=1 but no FD found") |
| 185 | } |
| 186 | return l[0], nil |
| 187 | |
| 188 | default: |
| 189 | return nil, fmt.Errorf("Too many (%v) FDs passed through socket activation", len(l)) |
| 190 | } |
| 191 | } |
| 192 | |
| 193 | func runDaemon( |
| 194 | pidfilePath, hostPrefix, socketPath string, |
| 195 | dhcpClientTimeout time.Duration, resendMax time.Duration, resendTimeout time.Duration, |
| 196 | broadcast bool, |
| 197 | ) error { |
| 198 | // since other goroutines (on separate threads) will change namespaces, |
| 199 | // ensure the RPC server does not get scheduled onto those |
| 200 | runtime.LockOSThread() |
| 201 | |
| 202 | // Write the pidfile |
| 203 | if pidfilePath != "" { |
| 204 | if !filepath.IsAbs(pidfilePath) { |
| 205 | return fmt.Errorf("Error writing pidfile %q: path not absolute", pidfilePath) |
| 206 | } |
| 207 | if err := os.WriteFile(pidfilePath, []byte(fmt.Sprintf("%d", os.Getpid())), 0o644); err != nil { |
| 208 | return fmt.Errorf("Error writing pidfile %q: %v", pidfilePath, err) |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | l, err := getListener(hostPrefix + socketPath) |
| 213 | if err != nil { |
| 214 | return fmt.Errorf("Error getting listener: %v", err) |
| 215 | } |
| 216 | |
| 217 | srv := http.Server{} |
| 218 | exit := make(chan os.Signal, 1) |
| 219 | done := make(chan bool, 1) |
| 220 | signal.Notify(exit, os.Interrupt, syscall.SIGTERM) |
| 221 | |
| 222 | go func() { |
| 223 | <-exit |
| 224 | srv.Shutdown(context.TODO()) |
| 225 | os.Remove(hostPrefix + socketPath) |
| 226 | os.Remove(pidfilePath) |
| 227 | |
| 228 | done <- true |
| 229 | }() |
| 230 | |
| 231 | dhcp := newDHCP(dhcpClientTimeout, resendMax, resendTimeout) |
| 232 | dhcp.hostNetnsPrefix = hostPrefix |
| 233 | dhcp.broadcast = broadcast |
| 234 | rpc.Register(dhcp) |
| 235 | rpc.HandleHTTP() |
| 236 | srv.Serve(l) |
| 237 | |
| 238 | <-done |
| 239 | return nil |
| 240 | } |