Debian Codegraph @

pkg/ns/ns_linux.go

raw
1 // Copyright 2022 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 ns
16
17 import (
18 "runtime"
19
20 "github.com/vishvananda/netns"
21
22 "github.com/containernetworking/cni/pkg/types"
23 )
24
25 // Returns an object representing the current OS thread's network namespace
26 func getCurrentNS() (netns.NsHandle, error) {
27 // Lock the thread in case other goroutine executes in it and changes its
28 // network namespace after getCurrentThreadNetNSPath(), otherwise it might
29 // return an unexpected network namespace.
30 runtime.LockOSThread()
31 defer runtime.UnlockOSThread()
32 return netns.Get()
33 }
34
35 func CheckNetNS(nsPath string) (bool, *types.Error) {
36 ns, err := netns.GetFromPath(nsPath)
37 // Let plugins check whether nsPath from args is valid. Also support CNI DEL for empty nsPath as already-deleted nsPath.
38 if err != nil {
39 return false, nil
40 }
41 defer ns.Close()
42
43 pluginNS, err := getCurrentNS()
44 if err != nil {
45 return false, types.NewError(types.ErrInvalidNetNS, "get plugin's netns failed", "")
46 }
47 defer pluginNS.Close()
48
49 return pluginNS.Equal(ns), nil
50 }