gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/tools/gvisor_k8s_tool/util/util.go (about)

     1  // Copyright 2023 The gVisor 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 util contains utility functions for gvisor_k8s_tools.
    16  package util
    17  
    18  import (
    19  	"fmt"
    20  	"os"
    21  	"path"
    22  )
    23  
    24  // TempDir creates and returns the path to a private temporary directory.
    25  // The caller must call the given cleanup function to clean up the directory.
    26  func TempDir() (string, func(), error) {
    27  	tempDir, err := os.MkdirTemp("", "gvisor_k8s_tool.*.tmp")
    28  	if err != nil {
    29  		return "", nil, err
    30  	}
    31  	// Create a private subdirectory (0700) within the temporary directory.
    32  	privateSubdir := path.Join(tempDir, "tmp")
    33  	if err := os.Mkdir(privateSubdir, 0700); err != nil {
    34  		os.RemoveAll(tempDir)
    35  		return "", nil, fmt.Errorf("cannot create subdir %q: %w", privateSubdir, err)
    36  	}
    37  	return privateSubdir, func() { os.RemoveAll(tempDir) }, nil
    38  }