github.com/containerd/nerdctl@v1.7.7/pkg/rootlessutil/rootlessutil_linux.go (about)

     1  /*
     2     Copyright The containerd Authors.
     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 rootlessutil
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  	"path/filepath"
    23  	"strconv"
    24  
    25  	"github.com/rootless-containers/rootlesskit/pkg/api/client"
    26  )
    27  
    28  func IsRootless() bool {
    29  	return IsRootlessParent() || IsRootlessChild()
    30  }
    31  
    32  func ParentEUID() int {
    33  	if !IsRootlessChild() {
    34  		return os.Geteuid()
    35  	}
    36  	env := os.Getenv("ROOTLESSKIT_PARENT_EUID")
    37  	if env == "" {
    38  		panic("environment variable ROOTLESSKIT_PARENT_EUID is not set")
    39  	}
    40  	i, err := strconv.Atoi(env)
    41  	if err != nil {
    42  		panic(fmt.Errorf("failed to parse ROOTLESSKIT_PARENT_EUID=%q: %w", env, err))
    43  	}
    44  	return i
    45  }
    46  
    47  func ParentEGID() int {
    48  	if !IsRootlessChild() {
    49  		return os.Getegid()
    50  	}
    51  	env := os.Getenv("ROOTLESSKIT_PARENT_EGID")
    52  	if env == "" {
    53  		panic("environment variable ROOTLESSKIT_PARENT_EGID is not set")
    54  	}
    55  	i, err := strconv.Atoi(env)
    56  	if err != nil {
    57  		panic(fmt.Errorf("failed to parse ROOTLESSKIT_PARENT_EGID=%q: %w", env, err))
    58  	}
    59  	return i
    60  }
    61  
    62  func NewRootlessKitClient() (client.Client, error) {
    63  	stateDir, err := RootlessKitStateDir()
    64  	if err != nil {
    65  		return nil, err
    66  	}
    67  	apiSock := filepath.Join(stateDir, "api.sock")
    68  	return client.New(apiSock)
    69  }
    70  
    71  // RootlessContainredSockAddress returns sock address of rootless containerd based on https://github.com/containerd/nerdctl/blob/main/docs/faq.md#containerd-socket-address
    72  func RootlessContainredSockAddress() (string, error) {
    73  	stateDir, err := RootlessKitStateDir()
    74  	if err != nil {
    75  		return "", err
    76  	}
    77  	childPid, err := RootlessKitChildPid(stateDir)
    78  	if err != nil {
    79  		return "", err
    80  	}
    81  	return filepath.Join(fmt.Sprintf("/proc/%d/root/run/containerd/containerd.sock", childPid)), nil
    82  }