From 8813665c9048a31b0627dffa5b4994b3727ee8c1 Mon Sep 17 00:00:00 2001 From: Dimitrij Denissenko Date: Thu, 2 Mar 2017 15:57:18 +0000 Subject: [PATCH] First release --- .dockerignore | 2 + .gitignore | 29 +++++++ DOCS.md | 52 ++++++++++++ Dockerfile | 10 +++ LICENSE | 202 ++++++++++++++++++++++++++++++++++++++++++++ Makefile | 25 ++++++ README.md | 51 +++++++++++ cache/archive.go | 67 +++++++++++++++ cache/cache.go | 82 ++++++++++++++++++ cache/cache_test.go | 1 + cache/s3.go | 55 ++++++++++++ glide.lock | 46 ++++++++++ glide.yaml | 11 +++ main.go | 126 +++++++++++++++++++++++++++ plugin.go | 131 ++++++++++++++++++++++++++++ 15 files changed, 890 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 DOCS.md create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 cache/archive.go create mode 100644 cache/cache.go create mode 100644 cache/cache_test.go create mode 100644 cache/s3.go create mode 100644 glide.lock create mode 100644 glide.yaml create mode 100644 main.go create mode 100644 plugin.go diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 00000000..77800c81 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,2 @@ +* +!drone-s3-cache diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..dda8c954 --- /dev/null +++ b/.gitignore @@ -0,0 +1,29 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof +.env + +coverage.out +drone-s3-cache +vendor/ diff --git a/DOCS.md b/DOCS.md new file mode 100644 index 00000000..41cb5594 --- /dev/null +++ b/DOCS.md @@ -0,0 +1,52 @@ +Use this plugin for caching build artifacts to speed up your build times. This +plugin can create and restore caches of any folders. + +## Config + +The following parameters are used to configure the plugin: + +* **endpoint** - custom endpoint URL (optional, to use a S3 compatible non-Amazon service) +* **access_key** - amazon key (optional) +* **secret_key** - amazon secret key (optional) +* **bucket** - bucket name +* **region** - bucket region (`us-east-1`, `eu-west-1`, etc) +* **encryption** - if provided, use server-side encryption (`AES256`, `aws:kms`, etc) +* **acl** - access to files that are uploaded (`private`, `public-read`, etc) +* **path_style** - whether path style URLs should be used (true for minio, false for aws) +* **mount** - one or an array of folders to cache +* **rebuild** - boolean flag to trigger a rebuild +* **restore** - boolean flag to trigger a restore + +The following secret values can be set to configure the plugin. + +* **AWS_ACCESS_KEY_ID** - corresponds to **access_key** +* **AWS_SECRET_ACCESS_KEY** - corresponds to **secret_key** +* **S3_BUCKET** - corresponds to **bucket** +* **S3_REGION** - corresponds to **region** +* **PLUGIN_ENDPOINT** - corresponds to **endpoint** + +## Example + +The following is a sample configuration in your .drone.yml file: + +```yaml +pipeline: + s3_cache: + bucket: my-drone-bucket + image: plugins/s3-cache + restore: true + mount: + - node_modules + + build: + image: node:latest + commands: + - npm install + + s3_cache: + bucket: my-drone-bucket + image: plugins/s3-cache + rebuild: true + mount: + - node_modules +``` diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..73dec434 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,10 @@ +FROM alpine:3.4 + +RUN set -ex \ + && apk add --no-cache \ + ca-certificates \ + tar \ + && rm -rf /var/cache/apk/* + +ADD drone-s3-cache /bin/ +ENTRYPOINT ["/bin/drone-s3-cache"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..ee37526f --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2017 Black Square Media Ltd + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..34c41aa6 --- /dev/null +++ b/Makefile @@ -0,0 +1,25 @@ +PKG=$(shell glide nv) + +default: vet test + +vet: + go vet $(PKG) + +test: + go test $(PKG) + +all: drone-s3-cache + +.PHONY: default vet test all + +docker.build: drone-s3-cache Dockerfile + docker build -t blacksquaremedia/drone-s3-cache:latest . + +docker.push: docker.build + docker push blacksquaremedia/drone:latest + +.PHONY: docker.build docker.push + +drone-s3-cache: main.go $(wildcard *.go) $(wildcard */*.go) + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -ldflags '-w' -o $@ . + diff --git a/README.md b/README.md new file mode 100644 index 00000000..bfe5ccfc --- /dev/null +++ b/README.md @@ -0,0 +1,51 @@ +# drone-s3-cache + +[![Go Doc](https://godoc.org/bitbucket.org/bsm/drone-s3-cache?status.svg)](http://godoc.org/bitbucket.org/bsm/drone-s3-cache) + +Drone plugin for caching artifacts to a S3 bucket. For the +usage information and a listing of the available options please take a look at +[the docs](DOCS.md). + +## Build + +Build the binary with the following commands: + +``` +go build +go test +``` + +## Docker + +Build the docker image with the following commands: + +``` +CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -tags netgo +docker build --rm=true -t plugins/s3-cache . +``` + +Please note incorrectly building the image for the correct x64 linux and with +GCO disabled will result in an error when running the Docker image: + +``` +docker: Error response from daemon: Container command +'/bin/drone-s3-cache' not found or does not exist.. +``` + +## Usage + +Execute from the working directory: + +``` +docker run --rm \ + -e DRONE_REPO=octocat/hello-world \ + -e DRONE_REPO_BRANCH=master \ + -e DRONE_COMMIT_BRANCH=master \ + -e PLUGIN_MOUNT=node_modules \ + -e PLUGIN_RESTORE=false \ + -e PLUGIN_REBUILD=true \ + -e PLUGIN_BUCKET= \ + -e AWS_ACCESS_KEY_ID= \ + -e AWS_SECRET_ACCESS_KEY= \ + plugins/s3-cache +``` diff --git a/cache/archive.go b/cache/archive.go new file mode 100644 index 00000000..d05e56c7 --- /dev/null +++ b/cache/archive.go @@ -0,0 +1,67 @@ +package cache + +// special thanks to this medium article: +// https://medium.com/@skdomino/taring-untaring-files-in-go-6b07cf56bc07 + +import ( + "archive/tar" + "io" + "os" + "path/filepath" +) + +// helper function to untar io.Reader r to the destincation directory. +func extract(dst string, r io.Reader) error { + tr := tar.NewReader(r) + + for { + header, err := tr.Next() + + switch { + + // if no more files are found return + case err == io.EOF: + return nil + + // return any other error + case err != nil: + return err + + // if the header is nil, just skip it (not sure how this happens) + case header == nil: + continue + } + + // the target location where the dir/file should be created + target := filepath.Join(dst, header.Name) + + // the following switch could also be done using fi.Mode(), not sure if there + // a benefit of using one vs. the other. + // fi := header.FileInfo() + + // check the file type + switch header.Typeflag { + + // if its a dir and it doesn't exist create it + case tar.TypeDir: + if _, err := os.Stat(target); err != nil { + if err := os.MkdirAll(target, 0755); err != nil { + return err + } + } + + // if it's a file create it + case tar.TypeReg: + f, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(header.Mode)) + if err != nil { + return err + } + defer f.Close() + + // copy over contents + if _, err := io.Copy(f, tr); err != nil { + return err + } + } + } +} diff --git a/cache/cache.go b/cache/cache.go new file mode 100644 index 00000000..0a80d850 --- /dev/null +++ b/cache/cache.go @@ -0,0 +1,82 @@ +package cache + +import ( + "io" + "io/ioutil" + "os" + "os/exec" + "path/filepath" +) + +// Cache implements operations for caching files. +type Cache interface { + Get(string) (io.ReadCloser, error) + Put(string, io.ReadSeeker) error +} + +// RebuildCmd is a helper function that pushes the archived file to the cache. +func RebuildCmd(c Cache, src, dst string) (err error) { + + src = filepath.Clean(src) + src, err = filepath.Abs(src) + if err != nil { + return err + } + + // create a temporary file for the archive + dir, err := ioutil.TempDir("", "") + if err != nil { + return err + } + tar := filepath.Join(dir, "archive.tar") + + // run archive command + cmd := exec.Command("tar", "-cf", tar, src) + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + if err := cmd.Run(); err != nil { + return err + } + + // upload file to server + f, err := os.Open(tar) + if err != nil { + return err + } + defer f.Close() + return c.Put(dst, f) +} + +// RestoreCmd is a helper function that fetches the archived file from the cache +// and restores to the host machine's file system. +func RestoreCmd(c Cache, src, dst string) error { + rc, err := c.Get(src) + if err != nil { + return err + } + defer rc.Close() + + // create temp file for archive + temp, err := ioutil.TempFile("", "") + if err != nil { + return err + } + defer func() { + temp.Close() + os.Remove(temp.Name()) + }() + + // download archive to temp file + if _, err := io.Copy(temp, rc); err != nil { + return err + } + + // cleanup after ourself + temp.Close() + + // run extraction command + cmd := exec.Command("tar", "-xf", temp.Name(), "-C", "/") + cmd.Stdout = os.Stdout + cmd.Stderr = os.Stderr + return cmd.Run() +} diff --git a/cache/cache_test.go b/cache/cache_test.go new file mode 100644 index 00000000..08bf029d --- /dev/null +++ b/cache/cache_test.go @@ -0,0 +1 @@ +package cache diff --git a/cache/s3.go b/cache/s3.go new file mode 100644 index 00000000..2c778229 --- /dev/null +++ b/cache/s3.go @@ -0,0 +1,55 @@ +package cache + +import ( + "io" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/s3" +) + +// cacher is an SFTP implementation of the Cache. +type cacher struct { + bucket string + acl string + encryption string + client *s3.S3 +} + +// New returns a new SFTP remote Cache implementated. +func New(bucket, acl, encryption string, conf *aws.Config) Cache { + client := s3.New(session.New(), conf) + return &cacher{ + bucket: bucket, + acl: acl, + encryption: encryption, + client: client, + } +} + +// Get returns an io.Reader for reading the contents of the file. +func (c *cacher) Get(p string) (io.ReadCloser, error) { + out, err := c.client.GetObject(&s3.GetObjectInput{ + Bucket: aws.String(c.bucket), + Key: aws.String(p), + }) + if err != nil { + return nil, err + } + return out.Body, nil +} + +// Put uploads the contents of the io.ReadSeeker +func (c *cacher) Put(p string, src io.ReadSeeker) error { + in := &s3.PutObjectInput{ + Bucket: aws.String(c.bucket), + Key: aws.String(p), + ACL: aws.String(c.acl), + Body: src, + } + if c.encryption != "" { + in.ServerSideEncryption = aws.String(c.encryption) + } + _, err := c.client.PutObject(in) + return err +} diff --git a/glide.lock b/glide.lock new file mode 100644 index 00000000..d6cbbebb --- /dev/null +++ b/glide.lock @@ -0,0 +1,46 @@ +hash: e9fb4829edc6284d14de987a6b01f5fe30565cea2887087bec9357919df0ad08 +updated: 2017-03-02T15:08:21.323225907Z +imports: +- name: github.com/aws/aws-sdk-go + version: f25c58028ccaa4be2726c172d970ba1cc0f26c99 + subpackages: + - aws + - aws/awserr + - aws/awsutil + - aws/client + - aws/client/metadata + - aws/corehandlers + - aws/credentials + - aws/credentials/ec2rolecreds + - aws/credentials/endpointcreds + - aws/credentials/stscreds + - aws/defaults + - aws/ec2metadata + - aws/endpoints + - aws/request + - aws/session + - aws/signer/v4 + - private/protocol + - private/protocol/query + - private/protocol/query/queryutil + - private/protocol/rest + - private/protocol/restxml + - private/protocol/xml/xmlutil + - private/waiter + - service/s3 + - service/sts +- name: github.com/go-ini/ini + version: c437d20015c2ab6454b7a66a13109ff0fb99e17a +- name: github.com/jmespath/go-jmespath + version: bd40a432e4c76585ef6b72d3fd96fb9b6dc7b68d +- name: github.com/joho/godotenv + version: d10b3fbe007de7a25e086524ad17597afa3d238b +- name: github.com/Sirupsen/logrus + version: 0208149b40d863d2c1a2f8fe5753096a9cf2cc8b +- name: github.com/urfave/cli + version: 2526b57c56f30b50466c96c4133b1a4ad0f0191f +- name: golang.org/x/sys + version: 075e574b89e4c2d22f2286a7e2b919519c6f3547 + subpackages: + - unix +testImports: [] diff --git a/glide.yaml b/glide.yaml new file mode 100644 index 00000000..ec22c667 --- /dev/null +++ b/glide.yaml @@ -0,0 +1,11 @@ +package: bitbucket.org/bsm/drone-s3-cache +import: +- package: github.com/Sirupsen/logrus +- package: github.com/aws/aws-sdk-go + subpackages: + - aws + - aws/credentials + - aws/session + - service/s3 +- package: github.com/joho/godotenv +- package: github.com/urfave/cli diff --git a/main.go b/main.go new file mode 100644 index 00000000..27432b26 --- /dev/null +++ b/main.go @@ -0,0 +1,126 @@ +package main + +import ( + "os" + + "github.com/Sirupsen/logrus" + "github.com/joho/godotenv" + "github.com/urfave/cli" +) + +func main() { + app := cli.NewApp() + app.Name = "S3 cache plugin" + app.Usage = "S3 cache plugin" + app.Action = run + app.Version = "0.8.0" + app.Flags = []cli.Flag{ + cli.StringFlag{ + Name: "repo.name", + Usage: "repository full name", + EnvVar: "DRONE_REPO", + }, + cli.StringFlag{ + Name: "repo.branch", + Usage: "repository default branch", + EnvVar: "DRONE_REPO_BRANCH", + }, + cli.StringFlag{ + Name: "commit.branch", + Value: "master", + Usage: "repository branch", + EnvVar: "DRONE_COMMIT_BRANCH", + }, + cli.StringSliceFlag{ + Name: "mount", + Usage: "cache directories", + EnvVar: "PLUGIN_MOUNT", + }, + cli.BoolFlag{ + Name: "rebuild", + Usage: "rebuild the cache directories", + EnvVar: "PLUGIN_REBUILD", + }, + cli.BoolFlag{ + Name: "restore", + Usage: "restore the cache directories", + EnvVar: "PLUGIN_RESTORE", + }, + cli.StringFlag{ + Name: "endpoint", + Usage: "endpoint for the s3 connection", + EnvVar: "PLUGIN_ENDPOINT,S3_ENDPOINT", + }, + cli.StringFlag{ + Name: "access-key", + Usage: "aws access key", + EnvVar: "PLUGIN_ACCESS_KEY,AWS_ACCESS_KEY_ID", + }, + cli.StringFlag{ + Name: "secret-key", + Usage: "aws secret key", + EnvVar: "PLUGIN_SECRET_KEY,AWS_SECRET_ACCESS_KEY", + }, + cli.StringFlag{ + Name: "bucket", + Usage: "aws bucket", + Value: "us-east-1", + EnvVar: "PLUGIN_BUCKET,S3_BUCKET", + }, + cli.StringFlag{ + Name: "region", + Usage: "aws region", + Value: "us-east-1", + EnvVar: "PLUGIN_REGION,S3_REGION", + }, + cli.BoolFlag{ + Name: "path-style", + Usage: "use path style for bucket paths", + EnvVar: "PLUGIN_PATH_STYLE", + }, + cli.StringFlag{ + Name: "acl", + Usage: "upload files with acl", + Value: "private", + EnvVar: "PLUGIN_ACL", + }, + cli.StringFlag{ + Name: "encryption", + Usage: "server-side encryption algorithm, defaults to none", + EnvVar: "PLUGIN_ENCRYPTION", + }, + cli.StringFlag{ + Name: "env-file", + Usage: "source env file", + }, + } + + if err := app.Run(os.Args); err != nil { + logrus.Fatal(err) + } +} + +func run(c *cli.Context) error { + if c.String("env-file") != "" { + _ = godotenv.Load(c.String("env-file")) + } + + plugin := Plugin{ + Rebuild: c.Bool("rebuild"), + Restore: c.Bool("restore"), + Mount: c.StringSlice("mount"), + Endpoint: c.String("endpoint"), + Key: c.String("access-key"), + Secret: c.String("secret-key"), + Bucket: c.String("bucket"), + Region: c.String("region"), + ACL: c.String("acl"), + Encryption: c.String("encryption"), + PathStyle: c.Bool("path-style"), + Repo: c.String("repo.name"), + Default: c.String("repo.branch"), + Branch: c.String("commit.branch"), + } + + return plugin.Exec() +} diff --git a/plugin.go b/plugin.go new file mode 100644 index 00000000..9e23e1e3 --- /dev/null +++ b/plugin.go @@ -0,0 +1,131 @@ +package main + +import ( + "crypto/md5" + "fmt" + "io" + "log" + "path/filepath" + "strings" + "time" + + "bitbucket.org/bsm/drone-s3-cache/cache" + "github.com/Sirupsen/logrus" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/credentials" +) + +// Plugin for caching directories to an SFTP server. +type Plugin struct { + Rebuild bool + Restore bool + Mount []string + + Endpoint string + Key string + Secret string + Bucket string + Region string + + // if not "", enable server-side encryption + // valid values are: + // AES256 + // aws:kms + Encryption string + + // Indicates the files ACL, which should be one + // of the following: + // private + // public-read + // public-read-write + // authenticated-read + // bucket-owner-read + // bucket-owner-full-control + ACL string + + // Use path style instead of domain style. + // + // Should be true for minio and false for AWS. + PathStyle bool + + Repo string + Branch string + Default string // default master branch +} + +func (p *Plugin) Exec() error { + conf := &aws.Config{ + Region: aws.String(p.Region), + Endpoint: &p.Endpoint, + DisableSSL: aws.Bool(strings.HasPrefix(p.Endpoint, "http://")), + S3ForcePathStyle: aws.Bool(p.PathStyle), + } + + //Allowing to use the instance role or provide a key and secret + if p.Key != "" && p.Secret != "" { + conf.Credentials = credentials.NewStaticCredentials(p.Key, p.Secret, "") + } + + cc := cache.New(p.Bucket, p.ACL, p.Encryption, conf) + if p.Rebuild { + now := time.Now() + if err := p.ProcessRebuild(cc); err != nil { + logrus.Println(err) + } else { + logrus.Printf("cache built in %v", time.Since(now)) + } + } + + if p.Restore { + now := time.Now() + if err := p.ProcessRestore(cc); err != nil { + logrus.Println(err) + } else { + logrus.Printf("cache restored in %v", time.Since(now)) + } + } + + return nil +} + +// Rebuild the remote cache from the local environment. +func (p Plugin) ProcessRebuild(c cache.Cache) error { + for _, mount := range p.Mount { + hash := hasher(mount, p.Branch) + path := filepath.Join(p.Repo, hash) + + log.Printf("archiving directory <%s> to remote cache <%s>", mount, path) + err := cache.RebuildCmd(c, mount, path) + if err != nil { + return err + } + } + return nil +} + +// Restore the local environment from the remote cache. +func (p Plugin) ProcessRestore(c cache.Cache) error { + for _, mount := range p.Mount { + hash := hasher(mount, p.Branch) + path := filepath.Join(p.Repo, hash) + + log.Printf("restoring directory <%s> from remote cache <%s>", mount, path) + err := cache.RestoreCmd(c, path, mount) + if err != nil { + return err + } + } + return nil +} + +// helper function to hash a file name based on path and branch. +func hasher(mount, branch string) string { + parts := []string{mount, branch} + + // calculate the hash using the branch + h := md5.New() + for _, part := range parts { + io.WriteString(h, part) + } + return fmt.Sprintf("%x", h.Sum(nil)) +}