Debian Codegraph @

pkg/hns/netconf_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 "bytes"
19 "encoding/json"
20 "errors"
21 "fmt"
22 "net"
23 "strconv"
24 "strings"
25
26 "github.com/Microsoft/hcsshim/hcn"
27 "github.com/buger/jsonparser"
28 "github.com/containernetworking/cni/pkg/types"
29 )
30
31 // NetConf is the CNI spec
32 type NetConf struct {
33 types.NetConf
34 // ApiVersion specifies the policies type of HNS or HCN, select one of [1, 2].
35 // HNS is the v1 API, which is the default version and applies to dockershim.
36 // HCN is the v2 API, which can leverage HostComputeNamespace and use in containerd.
37 ApiVersion int `json:"apiVersion,omitempty"`
38 // Policies specifies the policy list for HNSEndpoint or HostComputeEndpoint.
39 Policies []Policy `json:"policies,omitempty"`
40 // RuntimeConfig represents the options to be passed in by the runtime.
41 RuntimeConfig RuntimeConfig `json:"runtimeConfig"`
42 // LoopbackDSR specifies whether to support loopback direct server return.
43 LoopbackDSR bool `json:"loopbackDSR,omitempty"`
44 }
45
46 type RuntimeDNS struct {
47 Nameservers []string `json:"servers,omitempty"`
48 Search []string `json:"searches,omitempty"`
49 }
50
51 type PortMapEntry struct {
52 HostPort int `json:"hostPort"`
53 ContainerPort int `json:"containerPort"`
54 Protocol string `json:"protocol"`
55 HostIP string `json:"hostIP,omitempty"`
56 }
57
58 // constants of the supported Windows Socket protocol,
59 // ref to https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.protocoltype.
60 var protocolEnums = map[string]uint32{
61 "icmpv4": 1,
62 "igmp": 2,
63 "tcp": 6,
64 "udp": 17,
65 "icmpv6": 58,
66 }
67
68 func (p *PortMapEntry) GetProtocolEnum() (uint32, error) {
69 var u, err = strconv.ParseUint(p.Protocol, 0, 10)
70 if err != nil {
71 var pe, exist = protocolEnums[strings.ToLower(p.Protocol)]
72 if !exist {
73 return 0, errors.New("invalid protocol supplied to port mapping policy")
74 }
75 return pe, nil
76 }
77 return uint32(u), nil
78 }
79
80 type RuntimeConfig struct {
81 DNS RuntimeDNS `json:"dns"`
82 PortMaps []PortMapEntry `json:"portMappings,omitempty"`
83 }
84
85 type Policy struct {
86 Name string `json:"name"`
87 Value json.RawMessage `json:"value"`
88 }
89
90 // GetHNSEndpointPolicies converts the configuration policies to HNSEndpoint policies.
91 func (n *NetConf) GetHNSEndpointPolicies() []json.RawMessage {
92 result := make([]json.RawMessage, 0, len(n.Policies))
93 for _, p := range n.Policies {
94 if !strings.EqualFold(p.Name, "EndpointPolicy") {
95 continue
96 }
97 result = append(result, p.Value)
98 }
99 return result
100 }
101
102 // GetHostComputeEndpointPolicies converts the configuration policies to HostComputeEndpoint policies.
103 func (n *NetConf) GetHostComputeEndpointPolicies() []hcn.EndpointPolicy {
104 result := make([]hcn.EndpointPolicy, 0, len(n.Policies))
105 for _, p := range n.Policies {
106 if !strings.EqualFold(p.Name, "EndpointPolicy") {
107 continue
108 }
109 var policy hcn.EndpointPolicy
110 if err := json.Unmarshal(p.Value, &policy); err != nil {
111 continue
112 }
113 result = append(result, policy)
114 }
115 return result
116 }
117
118 // GetDNS returns the DNS values if they are there use that else use netconf supplied DNS.
119 func (n *NetConf) GetDNS() types.DNS {
120 dnsResult := n.DNS
121 if len(n.RuntimeConfig.DNS.Nameservers) > 0 {
122 dnsResult.Nameservers = n.RuntimeConfig.DNS.Nameservers
123 }
124 if len(n.RuntimeConfig.DNS.Search) > 0 {
125 dnsResult.Search = n.RuntimeConfig.DNS.Search
126 }
127 return dnsResult
128 }
129
130 // ApplyLoopbackDSRPolicy configures the given IP to support loopback DSR.
131 func (n *NetConf) ApplyLoopbackDSRPolicy(ip *net.IP) {
132 if err := hcn.DSRSupported(); err != nil || ip == nil {
133 return
134 }
135
136 toPolicyValue := func(addr string) json.RawMessage {
137 if n.ApiVersion == 2 {
138 return bprintf(`{"Type": "OutBoundNAT", "Settings": {"Destinations": ["%s"]}}`, addr)
139 }
140 return bprintf(`{"Type": "OutBoundNAT", "Destinations": ["%s"]}`, addr)
141 }
142 ipBytes := []byte(ip.String())
143
144 // find OutBoundNAT policy
145 for i := range n.Policies {
146 p := &n.Policies[i]
147 if !strings.EqualFold(p.Name, "EndpointPolicy") {
148 continue
149 }
150
151 // filter OutBoundNAT policy
152 typeValue, _ := jsonparser.GetUnsafeString(p.Value, "Type")
153 if typeValue != "OutBoundNAT" {
154 continue
155 }
156
157 // parse destination address list
158 var (
159 destinationsValue []byte
160 dt jsonparser.ValueType
161 )
162 if n.ApiVersion == 2 {
163 destinationsValue, dt, _, _ = jsonparser.Get(p.Value, "Settings", "Destinations")
164 } else {
165 destinationsValue, dt, _, _ = jsonparser.Get(p.Value, "Destinations")
166 }
167
168 // skip if Destinations/DestinationList field is not found
169 if dt == jsonparser.NotExist {
170 continue
171 }
172
173 // return if found the given address
174 if dt == jsonparser.Array {
175 var found bool
176 _, _ = jsonparser.ArrayEach(destinationsValue, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
177 if dataType == jsonparser.String && len(value) != 0 {
178 if bytes.Compare(value, ipBytes) == 0 {
179 found = true
180 }
181 }
182 })
183 if found {
184 return
185 }
186 }
187 }
188
189 // or add a new OutBoundNAT if not found
190 n.Policies = append(n.Policies, Policy{
191 Name: "EndpointPolicy",
192 Value: toPolicyValue(ip.String()),
193 })
194 }
195
196 // ApplyOutboundNatPolicy applies the sNAT policy in HNS/HCN and configures the given CIDR as an exception.
197 func (n *NetConf) ApplyOutboundNatPolicy(exceptionCIDR string) {
198 if exceptionCIDR == "" {
199 return
200 }
201
202 toPolicyValue := func(cidr ...string) json.RawMessage {
203 if n.ApiVersion == 2 {
204 return bprintf(`{"Type": "OutBoundNAT", "Settings": {"Exceptions": ["%s"]}}`, strings.Join(cidr, `","`))
205 }
206 return bprintf(`{"Type": "OutBoundNAT", "ExceptionList": ["%s"]}`, strings.Join(cidr, `","`))
207 }
208 exceptionCIDRBytes := []byte(exceptionCIDR)
209
210 // find OutBoundNAT policy
211 for i := range n.Policies {
212 p := &n.Policies[i]
213 if !strings.EqualFold(p.Name, "EndpointPolicy") {
214 continue
215 }
216
217 // filter OutBoundNAT policy
218 typeValue, _ := jsonparser.GetUnsafeString(p.Value, "Type")
219 if typeValue != "OutBoundNAT" {
220 continue
221 }
222
223 // parse exception CIDR list
224 var (
225 exceptionsValue []byte
226 dt jsonparser.ValueType
227 )
228 if n.ApiVersion == 2 {
229 exceptionsValue, dt, _, _ = jsonparser.Get(p.Value, "Settings", "Exceptions")
230 } else {
231 exceptionsValue, dt, _, _ = jsonparser.Get(p.Value, "ExceptionList")
232 }
233
234 // skip if Exceptions/ExceptionList field is not found
235 if dt == jsonparser.NotExist {
236 continue
237 }
238
239 // return if found the given CIDR
240 if dt == jsonparser.Array {
241 var found bool
242 _, _ = jsonparser.ArrayEach(exceptionsValue, func(value []byte, dataType jsonparser.ValueType, offset int, err error) {
243 if dataType == jsonparser.String && len(value) != 0 {
244 if bytes.Compare(value, exceptionCIDRBytes) == 0 {
245 found = true
246 }
247 }
248 })
249 if found {
250 return
251 }
252 }
253 }
254
255 // or add a new OutBoundNAT if not found
256 n.Policies = append(n.Policies, Policy{
257 Name: "EndpointPolicy",
258 Value: toPolicyValue(exceptionCIDR),
259 })
260 }
261
262 // ApplyDefaultPAPolicy applies an endpoint PA policy in HNS/HCN.
263 func (n *NetConf) ApplyDefaultPAPolicy(address string) {
264 if address == "" {
265 return
266 }
267
268 toPolicyValue := func(addr string) json.RawMessage {
269 if n.ApiVersion == 2 {
270 return bprintf(`{"Type": "ProviderAddress", "Settings": {"ProviderAddress": "%s"}}`, addr)
271 }
272 return bprintf(`{"Type": "PA", "PA": "%s"}`, addr)
273 }
274 addressBytes := []byte(address)
275
276 // find ProviderAddress policy
277 for i := range n.Policies {
278 p := &n.Policies[i]
279 if !strings.EqualFold(p.Name, "EndpointPolicy") {
280 continue
281 }
282
283 // filter ProviderAddress policy
284 typeValue, _ := jsonparser.GetUnsafeString(p.Value, "Type")
285 if typeValue != "PA" && typeValue != "ProviderAddress" {
286 continue
287 }
288
289 // parse provider address
290 var (
291 paValue []byte
292 dt jsonparser.ValueType
293 )
294 if n.ApiVersion == 2 {
295 paValue, dt, _, _ = jsonparser.Get(p.Value, "Settings", "ProviderAddress")
296 } else {
297 paValue, dt, _, _ = jsonparser.Get(p.Value, "PA")
298 }
299
300 // skip if ProviderAddress/PA field is not found
301 if dt == jsonparser.NotExist {
302 continue
303 }
304
305 // return if found the given address
306 if dt == jsonparser.String && bytes.Compare(paValue, addressBytes) == 0 {
307 return
308 }
309 }
310
311 // or add a new ProviderAddress if not found
312 n.Policies = append(n.Policies, Policy{
313 Name: "EndpointPolicy",
314 Value: toPolicyValue(address),
315 })
316 }
317
318 // ApplyPortMappingPolicy applies the host/container port mapping policies in HNS/HCN.
319 func (n *NetConf) ApplyPortMappingPolicy(portMappings []PortMapEntry) {
320 if len(portMappings) == 0 {
321 return
322 }
323
324 toPolicyValue := func(p *PortMapEntry) json.RawMessage {
325 if n.ApiVersion == 2 {
326 var protocolEnum, _ = p.GetProtocolEnum()
327 return bprintf(`{"Type": "PortMapping", "Settings": {"InternalPort": %d, "ExternalPort": %d, "Protocol": %d, "VIP": "%s"}}`, p.ContainerPort, p.HostPort, protocolEnum, p.HostIP)
328 }
329 return bprintf(`{"Type": "NAT", "InternalPort": %d, "ExternalPort": %d, "Protocol": "%s"}`, p.ContainerPort, p.HostPort, p.Protocol)
330 }
331
332 for i := range portMappings {
333 p := &portMappings[i]
334 // skip the invalid protocol mapping
335 if _, err := p.GetProtocolEnum(); err != nil {
336 continue
337 }
338 n.Policies = append(n.Policies, Policy{
339 Name: "EndpointPolicy",
340 Value: toPolicyValue(p),
341 })
342 }
343 }
344
345 // bprintf is similar to fmt.Sprintf and returns a byte array as result.
346 func bprintf(format string, a ...interface{}) []byte {
347 return []byte(fmt.Sprintf(format, a...))
348 }