github.com/coreos/mantle@v0.13.0/system/ns/enter.go (about)

     1  // Copyright 2015 CoreOS, Inc.
     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  
    23  // NsEnter locks the current goroutine the OS thread and switches to a
    24  // new network namespace. The returned function must be called in order
    25  // to restore the previous state and unlock the thread.
    26  func Enter(ns netns.NsHandle) (func() error, error) {
    27  	runtime.LockOSThread()
    28  
    29  	origns, err := netns.Get()
    30  	if err != nil {
    31  		runtime.UnlockOSThread()
    32  		return nil, err
    33  	}
    34  
    35  	err = netns.Set(ns)
    36  	if err != nil {
    37  		origns.Close()
    38  		runtime.UnlockOSThread()
    39  		return nil, err
    40  	}
    41  
    42  	return func() error {
    43  		defer runtime.UnlockOSThread()
    44  		defer origns.Close()
    45  		if err := netns.Set(origns); err != nil {
    46  			return err
    47  		}
    48  		return nil
    49  	}, nil
    50  }
    51  
    52  // NsCreate returns a handle to a new network namespace.
    53  // NsEnter must be used to safely enter and exit the new namespace.
    54  func Create() (netns.NsHandle, error) {
    55  	runtime.LockOSThread()
    56  	defer runtime.UnlockOSThread()
    57  
    58  	origns, err := netns.Get()
    59  	if err != nil {
    60  		return netns.None(), err
    61  	}
    62  	defer origns.Close()
    63  	defer netns.Set(origns)
    64  
    65  	return netns.New()
    66  }