github.com/GoogleCloudPlatform/compute-image-tools/cli_tools@v0.0.0-20240516224744-de2dabc4ed1b/common/gcsfuse/client.go (about)

     1  //  Copyright 2020 Google Inc. All Rights Reserved.
     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 gcsfuse
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"io/ioutil"
    21  	"os/exec"
    22  )
    23  
    24  // Client provides methods for mounting and unmounting FUSE filesystems
    25  // that are backed by GCS.
    26  type Client interface {
    27  	// MountToTemp mounts a bucket within within the operating system's temporary directory,
    28  	// and returns an absolute path to the newly-created directory. IO operations will retry
    29  	// until the context is cancelled.
    30  	MountToTemp(ctx context.Context, bucket string) (string, error)
    31  	Unmount(directory string) error
    32  }
    33  
    34  // NewClient creates a new gcsfuse.Client.
    35  func NewClient() Client {
    36  	return defaultClient{}
    37  }
    38  
    39  type defaultClient struct{}
    40  
    41  func (client defaultClient) MountToTemp(ctx context.Context, bucket string) (string, error) {
    42  	dir, err := ioutil.TempDir("", bucket)
    43  	if err != nil {
    44  		return "", fmt.Errorf("failed to create a destination directory: %w", err)
    45  	}
    46  	cmd := exec.CommandContext(ctx, "gcsfuse", "--implicit-dirs", bucket, dir)
    47  	_, err = cmd.Output()
    48  	if err != nil {
    49  		return "", err
    50  	}
    51  	return dir, nil
    52  }
    53  
    54  func (client defaultClient) Unmount(directory string) error {
    55  	cmd := exec.Command("umount", directory)
    56  	_, err := cmd.Output()
    57  	return err
    58  }