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

     1  /*
     2  Copyright 2016 Mirantis
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package cni
    18  
    19  import (
    20  	"os/exec"
    21  	"path"
    22  
    23  	"github.com/golang/glog"
    24  )
    25  
    26  // we are using "ip netns" command instead of cni/pkg/ns because usage
    27  // of later will lead to file descriptor leakages
    28  // also we could be affected by https://github.com/containernetworking/cni/issues/262
    29  
    30  const (
    31  	netnsBasePath = "/var/run/netns"
    32  )
    33  
    34  // CreateNetNS creates new network namespace using provided name.
    35  func CreateNetNS(name string) error {
    36  	return callIPNetns("add", name)
    37  }
    38  
    39  // DestroyNetNS deletes the network namespace pointed by provided name.
    40  func DestroyNetNS(name string) error {
    41  	return callIPNetns("del", name)
    42  }
    43  
    44  func callIPNetns(command, name string) error {
    45  	cmd := exec.Command("ip", "netns", command, name)
    46  	output, err := cmd.CombinedOutput()
    47  	if err != nil {
    48  		glog.Errorf("\"ip netns %s %s\" failed with output: %s", command, name, string(output))
    49  	}
    50  	return err
    51  }
    52  
    53  // PodNetNSPath converts netns name to its path in host filesystem.
    54  func PodNetNSPath(name string) string {
    55  	return path.Join(netnsBasePath, name)
    56  }