Debian Codegraph @

pkg/hns/endpoint_windows.go

raw symbols SCIP
1 // Copyright 2017 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 hns
16
17 import (
18 "fmt"
19 "net"
20 "strings"
21
22 "github.com/Microsoft/hcsshim"
23 "github.com/Microsoft/hcsshim/hcn"
24
25 "github.com/containernetworking/cni/pkg/types"
26 current "github.com/containernetworking/cni/pkg/types/100"
27
28 "github.com/containernetworking/plugins/pkg/errors"
29 )
30
31 const (
32 pauseContainerNetNS = "none"
33 )
34
35 type EndpointInfo struct {
36 EndpointName string
37 DNS types.DNS
38 NetworkName string
39 NetworkId string
40 Gateway net.IP
41 IpAddress net.IP
42 MacAddress string
43 }
44
45 // GetSandboxContainerID returns the sandbox ID of this pod.
46 func GetSandboxContainerID(containerID string, netNs string) string {
47 if len(netNs) != 0 && netNs != pauseContainerNetNS {
48 splits := strings.SplitN(netNs, ":", 2)
49 if len(splits) == 2 {
50 containerID = splits[1]
51 }
52 }
53
54 return containerID
55 }
56
57 // GetIpString returns the given IP as a string.
58 func GetIpString(ip *net.IP) string {
59 if len(*ip) == 0 {
60 return ""
61 } else {
62 return ip.String()
63 }
64 }
65
66 // GetDefaultDestinationPrefix returns the default destination prefix according to the given IP type.
67 func GetDefaultDestinationPrefix(ip *net.IP) string {
68 destinationPrefix := "0.0.0.0/0"
69 if ip.To4() == nil {
70 destinationPrefix = "::/0"
71 }
72 return destinationPrefix
73 }
74
75 // ConstructEndpointName constructs endpoint id which is used to identify an endpoint from HNS/HCN.
76 func ConstructEndpointName(containerID string, netNs string, networkName string) string {
77 return GetSandboxContainerID(containerID, netNs) + "_" + networkName
78 }
79
80 // GenerateHnsEndpoint generates an HNSEndpoint with given info and config.
81 func GenerateHnsEndpoint(epInfo *EndpointInfo, n *NetConf) (*hcsshim.HNSEndpoint, error) {
82 // run the IPAM plugin and get back the config to apply
83 hnsEndpoint, err := hcsshim.GetHNSEndpointByName(epInfo.EndpointName)
84 if err != nil && !hcsshim.IsNotExist(err) {
85 return nil, errors.Annotatef(err, "failed to get HNSEndpoint %s", epInfo.EndpointName)
86 }
87
88 if hnsEndpoint != nil {
89 if strings.EqualFold(hnsEndpoint.VirtualNetwork, epInfo.NetworkId) {
90 return nil, fmt.Errorf("HNSEndpoint %s is already existed", epInfo.EndpointName)
91 }
92 // remove endpoint if corrupted
93 if _, err = hnsEndpoint.Delete(); err != nil {
94 return nil, errors.Annotatef(err, "failed to delete corrupted HNSEndpoint %s", epInfo.EndpointName)
95 }
96 }
97
98 if n.LoopbackDSR {
99 n.ApplyLoopbackDSRPolicy(&epInfo.IpAddress)
100 }
101 hnsEndpoint = &hcsshim.HNSEndpoint{
102 Name: epInfo.EndpointName,
103 VirtualNetwork: epInfo.NetworkId,
104 DNSServerList: strings.Join(epInfo.DNS.Nameservers, ","),
105 DNSSuffix: strings.Join(epInfo.DNS.Search, ","),
106 GatewayAddress: GetIpString(&epInfo.Gateway),
107 IPAddress: epInfo.IpAddress,
108 Policies: n.GetHNSEndpointPolicies(),
109 }
110 return hnsEndpoint, nil
111 }
112
113 // RemoveHnsEndpoint detaches the given name endpoint from container specified by containerID,
114 // or removes the given name endpoint completely.
115 func RemoveHnsEndpoint(epName string, netns string, containerID string) error {
116 if len(netns) == 0 {
117 return nil
118 }
119
120 hnsEndpoint, err := hcsshim.GetHNSEndpointByName(epName)
121 if err != nil {
122 if hcsshim.IsNotExist(err) {
123 return nil
124 }
125 return errors.Annotatef(err, "failed to find HNSEndpoint %s", epName)
126 }
127
128 // for shared endpoint, detach it from the container
129 if netns != pauseContainerNetNS {
130 _ = hnsEndpoint.ContainerDetach(containerID)
131 return nil
132 }
133
134 // for removing the endpoint completely, hot detach is used at first
135 _ = hcsshim.HotDetachEndpoint(containerID, hnsEndpoint.Id)
136 _, _ = hnsEndpoint.Delete()
137 return nil
138 }
139
140 type HnsEndpointMakerFunc func() (*hcsshim.HNSEndpoint, error)
141
142 // AddHnsEndpoint attaches an HNSEndpoint to a container specified by containerID.
143 func AddHnsEndpoint(epName string, expectedNetworkId string, containerID string, netns string, makeEndpoint HnsEndpointMakerFunc) (*hcsshim.HNSEndpoint, error) {
144 hnsEndpoint, err := hcsshim.GetHNSEndpointByName(epName)
145 if err != nil {
146 if !hcsshim.IsNotExist(err) {
147 return nil, errors.Annotatef(err, "failed to find HNSEndpoint %s", epName)
148 }
149 }
150
151 // for shared endpoint, we expect that the endpoint already exists
152 if netns != pauseContainerNetNS {
153 if hnsEndpoint == nil {
154 return nil, errors.Annotatef(err, "failed to find HNSEndpoint %s", epName)
155 }
156 }
157
158 // verify the existing endpoint is corrupted or not
159 if hnsEndpoint != nil {
160 if !strings.EqualFold(hnsEndpoint.VirtualNetwork, expectedNetworkId) {
161 if _, err := hnsEndpoint.Delete(); err != nil {
162 return nil, errors.Annotatef(err, "failed to delete corrupted HNSEndpoint %s", epName)
163 }
164 hnsEndpoint = nil
165 }
166 }
167
168 // create endpoint if not found
169 var isNewEndpoint bool
170 if hnsEndpoint == nil {
171 if hnsEndpoint, err = makeEndpoint(); err != nil {
172 return nil, errors.Annotate(err, "failed to make a new HNSEndpoint")
173 }
174 if hnsEndpoint, err = hnsEndpoint.Create(); err != nil {
175 return nil, errors.Annotate(err, "failed to create the new HNSEndpoint")
176 }
177 isNewEndpoint = true
178 }
179
180 // attach to container
181 if err := hcsshim.HotAttachEndpoint(containerID, hnsEndpoint.Id); err != nil {
182 if isNewEndpoint {
183 if err := RemoveHnsEndpoint(epName, netns, containerID); err != nil {
184 return nil, errors.Annotatef(err, "failed to remove the new HNSEndpoint %s after attaching container %s failure", hnsEndpoint.Id, containerID)
185 }
186 } else if hcsshim.ErrComputeSystemDoesNotExist == err {
187 return hnsEndpoint, nil
188 }
189 return nil, errors.Annotatef(err, "failed to attach container %s to HNSEndpoint %s", containerID, hnsEndpoint.Id)
190 }
191 return hnsEndpoint, nil
192 }
193
194 // ConstructHnsResult constructs the CNI result for the HNSEndpoint.
195 func ConstructHnsResult(hnsNetwork *hcsshim.HNSNetwork, hnsEndpoint *hcsshim.HNSEndpoint) (*current.Result, error) {
196 resultInterface := &current.Interface{
197 Name: hnsEndpoint.Name,
198 Mac: hnsEndpoint.MacAddress,
199 }
200 _, ipSubnet, err := net.ParseCIDR(hnsNetwork.Subnets[0].AddressPrefix)
201 if err != nil {
202 return nil, errors.Annotatef(err, "failed to parse CIDR from %s", hnsNetwork.Subnets[0].AddressPrefix)
203 }
204
205 resultIPConfig := &current.IPConfig{
206 Address: net.IPNet{
207 IP: hnsEndpoint.IPAddress,
208 Mask: ipSubnet.Mask},
209 Gateway: net.ParseIP(hnsEndpoint.GatewayAddress),
210 }
211 result := &current.Result{
212 CNIVersion: current.ImplementedSpecVersion,
213 Interfaces: []*current.Interface{resultInterface},
214 IPs: []*current.IPConfig{resultIPConfig},
215 DNS: types.DNS{
216 Search: strings.Split(hnsEndpoint.DNSSuffix, ","),
217 Nameservers: strings.Split(hnsEndpoint.DNSServerList, ","),
218 },
219 }
220
221 return result, nil
222 }
223
224 // GenerateHcnEndpoint generates a HostComputeEndpoint with given info and config.
225 func GenerateHcnEndpoint(epInfo *EndpointInfo, n *NetConf) (*hcn.HostComputeEndpoint, error) {
226 // run the IPAM plugin and get back the config to apply
227 hcnEndpoint, err := hcn.GetEndpointByName(epInfo.EndpointName)
228 if err != nil && !hcn.IsNotFoundError(err) {
229 return nil, errors.Annotatef(err, "failed to get HostComputeEndpoint %s", epInfo.EndpointName)
230 }
231
232 // verify the existing endpoint is corrupted or not
233 if hcnEndpoint != nil {
234 if strings.EqualFold(hcnEndpoint.HostComputeNetwork, epInfo.NetworkId) {
235 return nil, fmt.Errorf("HostComputeNetwork %s is already existed", epInfo.EndpointName)
236 }
237 // remove endpoint if corrupted
238 if err := hcnEndpoint.Delete(); err != nil {
239 return nil, errors.Annotatef(err, "failed to delete corrupted HostComputeEndpoint %s", epInfo.EndpointName)
240 }
241 }
242
243 if n.LoopbackDSR {
244 n.ApplyLoopbackDSRPolicy(&epInfo.IpAddress)
245 }
246 hcnEndpoint = &hcn.HostComputeEndpoint{
247 SchemaVersion: hcn.SchemaVersion{
248 Major: 2,
249 Minor: 0,
250 },
251 Name: epInfo.EndpointName,
252 MacAddress: epInfo.MacAddress,
253 HostComputeNetwork: epInfo.NetworkId,
254 Dns: hcn.Dns{
255 Domain: epInfo.DNS.Domain,
256 Search: epInfo.DNS.Search,
257 ServerList: epInfo.DNS.Nameservers,
258 Options: epInfo.DNS.Options,
259 },
260 Routes: []hcn.Route{
261 {
262 NextHop: GetIpString(&epInfo.Gateway),
263 DestinationPrefix: GetDefaultDestinationPrefix(&epInfo.Gateway),
264 },
265 },
266 IpConfigurations: []hcn.IpConfig{
267 {
268 IpAddress: GetIpString(&epInfo.IpAddress),
269 },
270 },
271 Policies: n.GetHostComputeEndpointPolicies(),
272 }
273 return hcnEndpoint, nil
274 }
275
276 // RemoveHcnEndpoint removes the given name endpoint from namespace.
277 func RemoveHcnEndpoint(epName string) error {
278 hcnEndpoint, err := hcn.GetEndpointByName(epName)
279 if err != nil {
280 if hcn.IsNotFoundError(err) {
281 return nil
282 }
283 return errors.Annotatef(err, "failed to find HostComputeEndpoint %s", epName)
284 }
285 epNamespace, err := hcn.GetNamespaceByID(hcnEndpoint.HostComputeNamespace)
286 if err != nil && !hcn.IsNotFoundError(err) {
287 return errors.Annotatef(err, "failed to get HostComputeNamespace %s", epName)
288 }
289 if epNamespace != nil {
290 err = hcn.RemoveNamespaceEndpoint(hcnEndpoint.HostComputeNamespace, hcnEndpoint.Id)
291 if err != nil && !hcn.IsNotFoundError(err) {
292 return errors.Annotatef(err,"error removing endpoint: %s from namespace", epName)
293 }
294 }
295
296 err = hcnEndpoint.Delete()
297 if err != nil {
298 return errors.Annotatef(err, "failed to remove HostComputeEndpoint %s", epName)
299 }
300 return nil
301 }
302
303 type HcnEndpointMakerFunc func() (*hcn.HostComputeEndpoint, error)
304
305 // AddHcnEndpoint attaches a HostComputeEndpoint to the given namespace.
306 func AddHcnEndpoint(epName string, expectedNetworkId string, namespace string, makeEndpoint HcnEndpointMakerFunc) (*hcn.HostComputeEndpoint, error) {
307 hcnEndpoint, err := hcn.GetEndpointByName(epName)
308 if err != nil {
309 if !hcn.IsNotFoundError(err) {
310 return nil, errors.Annotatef(err, "failed to find HostComputeEndpoint %s", epName)
311 }
312 }
313
314 // verify the existing endpoint is corrupted or not
315 if hcnEndpoint != nil {
316 if !strings.EqualFold(hcnEndpoint.HostComputeNetwork, expectedNetworkId) {
317 if err := hcnEndpoint.Delete(); err != nil {
318 return nil, errors.Annotatef(err, "failed to delete corrupted HostComputeEndpoint %s", epName)
319 }
320 hcnEndpoint = nil
321 }
322 }
323
324 // create endpoint if not found
325 var isNewEndpoint bool
326 if hcnEndpoint == nil {
327 if hcnEndpoint, err = makeEndpoint(); err != nil {
328 return nil, errors.Annotate(err, "failed to make a new HostComputeEndpoint")
329 }
330 if hcnEndpoint, err = hcnEndpoint.Create(); err != nil {
331 return nil, errors.Annotate(err, "failed to create the new HostComputeEndpoint")
332 }
333 isNewEndpoint = true
334 }
335
336 // add to namespace
337 err = hcn.AddNamespaceEndpoint(namespace, hcnEndpoint.Id)
338 if err != nil {
339 if isNewEndpoint {
340 if err := RemoveHcnEndpoint(epName); err != nil {
341 return nil, errors.Annotatef(err, "failed to remove the new HostComputeEndpoint %s after adding HostComputeNamespace %s failure", epName, namespace)
342 }
343 }
344 return nil, errors.Annotatef(err, "failed to add HostComputeEndpoint %s to HostComputeNamespace %s", epName, namespace)
345 }
346 return hcnEndpoint, nil
347 }
348
349 // ConstructHcnResult constructs the CNI result for the HostComputeEndpoint.
350 func ConstructHcnResult(hcnNetwork *hcn.HostComputeNetwork, hcnEndpoint *hcn.HostComputeEndpoint) (*current.Result, error) {
351 resultInterface := &current.Interface{
352 Name: hcnEndpoint.Name,
353 Mac: hcnEndpoint.MacAddress,
354 }
355 _, ipSubnet, err := net.ParseCIDR(hcnNetwork.Ipams[0].Subnets[0].IpAddressPrefix)
356 if err != nil {
357 return nil, err
358 }
359
360 ipAddress := net.ParseIP(hcnEndpoint.IpConfigurations[0].IpAddress)
361 resultIPConfig := &current.IPConfig{
362 Address: net.IPNet{
363 IP: ipAddress,
364 Mask: ipSubnet.Mask},
365 Gateway: net.ParseIP(hcnEndpoint.Routes[0].NextHop),
366 }
367 result := &current.Result{
368 CNIVersion: current.ImplementedSpecVersion,
369 Interfaces: []*current.Interface{resultInterface},
370 IPs: []*current.IPConfig{resultIPConfig},
371 DNS: types.DNS{
372 Search: hcnEndpoint.Dns.Search,
373 Nameservers: hcnEndpoint.Dns.ServerList,
374 Options: hcnEndpoint.Dns.Options,
375 Domain: hcnEndpoint.Dns.Domain,
376 },
377 }
378
379 return result, nil
380 }