github.com/sacloud/libsacloud/v2@v2.32.3/helper/service/archive/upload_service.go (about)

     1  // Copyright 2016-2022 The Libsacloud 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 archive
    16  
    17  import (
    18  	"context"
    19  	"fmt"
    20  	"io"
    21  	"os"
    22  
    23  	"github.com/sacloud/ftps"
    24  	"github.com/sacloud/libsacloud/v2/sacloud"
    25  	"github.com/sacloud/libsacloud/v2/sacloud/types"
    26  )
    27  
    28  func (s *Service) Upload(req *UploadRequest) error {
    29  	return s.UploadWithContext(context.Background(), req)
    30  }
    31  
    32  func (s *Service) UploadWithContext(ctx context.Context, req *UploadRequest) error {
    33  	if err := req.Validate(); err != nil {
    34  		return err
    35  	}
    36  
    37  	client := sacloud.NewArchiveOp(s.caller)
    38  	resource, err := client.Read(ctx, req.Zone, req.ID)
    39  	if err != nil {
    40  		return fmt.Errorf("reading Archive[%s] failed: %s", req.ID, err)
    41  	}
    42  
    43  	if resource.Scope != types.Scopes.User {
    44  		return fmt.Errorf("Archive[%s] is not allowed to download", req.ID)
    45  	}
    46  
    47  	ftpServer, err := client.OpenFTP(ctx, req.Zone, req.ID, &sacloud.OpenFTPRequest{ChangePassword: true})
    48  	if err != nil {
    49  		return fmt.Errorf("requesting FTP server information failed: %s", err)
    50  	}
    51  
    52  	ftpsClient := ftps.NewClient(ftpServer.User, ftpServer.Password, ftpServer.HostName)
    53  	var reader io.Reader
    54  	switch req.Path {
    55  	case "":
    56  		reader = os.Stdin
    57  		if req.Reader != nil {
    58  			reader = req.Reader
    59  		}
    60  	default:
    61  		f, err := os.Open(req.Path)
    62  		if err != nil {
    63  			return fmt.Errorf("opening upload file failed: %s", err)
    64  		}
    65  		defer f.Close()
    66  		reader = f
    67  	}
    68  
    69  	if err := ftpsClient.UploadReader("upload.raw", reader); err != nil {
    70  		return fmt.Errorf("uploading file failed: %s", err)
    71  	}
    72  
    73  	// close FTP
    74  	if err := client.CloseFTP(ctx, req.Zone, resource.ID); err != nil {
    75  		return fmt.Errorf("closing FTP server failed: %s", err)
    76  	}
    77  	return nil
    78  }