github.com/nilium/gitlab-runner@v12.5.0+incompatible/commands/helpers/artifacts_downloader.go (about)

     1  package helpers
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"time"
     7  
     8  	"github.com/sirupsen/logrus"
     9  	"github.com/urfave/cli"
    10  
    11  	"gitlab.com/gitlab-org/gitlab-runner/common"
    12  	"gitlab.com/gitlab-org/gitlab-runner/helpers/archives"
    13  	"gitlab.com/gitlab-org/gitlab-runner/log"
    14  	"gitlab.com/gitlab-org/gitlab-runner/network"
    15  )
    16  
    17  type ArtifactsDownloaderCommand struct {
    18  	common.JobCredentials
    19  	retryHelper
    20  	network common.Network
    21  }
    22  
    23  func (c *ArtifactsDownloaderCommand) download(file string) error {
    24  	switch c.network.DownloadArtifacts(c.JobCredentials, file) {
    25  	case common.DownloadSucceeded:
    26  		return nil
    27  	case common.DownloadNotFound:
    28  		return os.ErrNotExist
    29  	case common.DownloadForbidden:
    30  		return os.ErrPermission
    31  	case common.DownloadFailed:
    32  		return retryableErr{err: os.ErrInvalid}
    33  	default:
    34  		return os.ErrInvalid
    35  	}
    36  }
    37  
    38  func (c *ArtifactsDownloaderCommand) Execute(context *cli.Context) {
    39  	log.SetRunnerFormatter()
    40  
    41  	if len(c.URL) == 0 || len(c.Token) == 0 {
    42  		logrus.Fatalln("Missing runner credentials")
    43  	}
    44  	if c.ID <= 0 {
    45  		logrus.Fatalln("Missing build ID")
    46  	}
    47  
    48  	// Create temporary file
    49  	file, err := ioutil.TempFile("", "artifacts")
    50  	if err != nil {
    51  		logrus.Fatalln(err)
    52  	}
    53  	file.Close()
    54  	defer os.Remove(file.Name())
    55  
    56  	// Download artifacts file
    57  	err = c.doRetry(func() error {
    58  		return c.download(file.Name())
    59  	})
    60  	if err != nil {
    61  		logrus.Fatalln(err)
    62  	}
    63  
    64  	// Extract artifacts file
    65  	err = archives.ExtractZipFile(file.Name())
    66  	if err != nil {
    67  		logrus.Fatalln(err)
    68  	}
    69  }
    70  
    71  func init() {
    72  	common.RegisterCommand2("artifacts-downloader", "download and extract build artifacts (internal)", &ArtifactsDownloaderCommand{
    73  		network: network.NewGitLabClient(),
    74  		retryHelper: retryHelper{
    75  			Retry:     2,
    76  			RetryTime: time.Second,
    77  		},
    78  	})
    79  }