github.com/mirantis/virtlet@v1.5.2-0.20191204181327-1659b8a48e9b/pkg/utils/netns_linux.go (about)

     1  // +build linux
     2  
     3  /*
     4  Copyright 2018 Mirantis
     5  
     6  Licensed under the Apache License, Version 2.0 (the "License");
     7  you may not use this file except in compliance with the License.
     8  You may obtain a copy of the License at
     9  
    10      http://www.apache.org/licenses/LICENSE-2.0
    11  
    12  Unless required by applicable law or agreed to in writing, software
    13  distributed under the License is distributed on an "AS IS" BASIS,
    14  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    15  See the License for the specific language governing permissions and
    16  limitations under the License.
    17  */
    18  
    19  package utils
    20  
    21  import (
    22  	"syscall"
    23  
    24  	"github.com/containernetworking/cni/pkg/ns"
    25  	"github.com/golang/glog"
    26  )
    27  
    28  // mountSysfs adds new mount of sysfs on /sys to have a correct view
    29  // in current netns on /sys/class/net
    30  func mountSysfs() error {
    31  	return syscall.Mount("none", "/sys", "sysfs", 0, "")
    32  }
    33  
    34  // unmountSysfs unmounts current fs bound to /sys
    35  func unmountSysfs() error {
    36  	return syscall.Unmount("/sys", syscall.MNT_DETACH)
    37  }
    38  
    39  // CallInNetNSWithSysfsRemounted enters particular netns, adds new sysfs
    40  // mount on top of /sys, calls "toCall" callback in this netns removing
    41  // temporary mount on /sys at the end.
    42  func CallInNetNSWithSysfsRemounted(innerNS ns.NetNS, toCall func(ns.NetNS) error) error {
    43  	return innerNS.Do(func(outerNS ns.NetNS) error {
    44  		// switch /sys to corresponding one in netns
    45  		// to have the correct items under /sys/class/net
    46  		if err := mountSysfs(); err != nil {
    47  			return err
    48  		}
    49  		defer func() {
    50  			if err := unmountSysfs(); err != nil {
    51  				glog.V(3).Infof("Warning, error during umount of /sys: %v", err)
    52  			}
    53  		}()
    54  
    55  		return toCall(outerNS)
    56  	})
    57  }