diff --git a/cmd/registry/main.go b/cmd/registry/main.go index 09a09260d..a71d078e8 100644 --- a/cmd/registry/main.go +++ b/cmd/registry/main.go @@ -17,7 +17,6 @@ import ( _ "github.com/distribution/distribution/v3/registry/storage/driver/middleware/redirect" _ "github.com/distribution/distribution/v3/registry/storage/driver/oss" _ "github.com/distribution/distribution/v3/registry/storage/driver/s3-aws" - _ "github.com/distribution/distribution/v3/registry/storage/driver/swift" ) func main() { diff --git a/docs/configuration.md b/docs/configuration.md index 849689b25..23ce0ddab 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -139,18 +139,6 @@ storage: multipartcopythresholdsize: 33554432 rootdirectory: /s3/object/name/prefix usedualstack: false - swift: - username: username - password: password - authurl: https://storage.myprovider.com/auth/v1.0 or https://storage.myprovider.com/v2.0 or https://storage.myprovider.com/v3/auth - tenant: tenantname - tenantid: tenantid - domain: domain name for Openstack Identity v3 API - domainid: domain id for Openstack Identity v3 API - insecureskipverify: true - region: fr - container: containername - rootdirectory: /swift/object/name/prefix oss: accesskeyid: accesskeyid accesskeysecret: accesskeysecret @@ -447,18 +435,6 @@ storage: multipartcopymaxconcurrency: 100 multipartcopythresholdsize: 33554432 rootdirectory: /s3/object/name/prefix - swift: - username: username - password: password - authurl: https://storage.myprovider.com/auth/v1.0 or https://storage.myprovider.com/v2.0 or https://storage.myprovider.com/v3/auth - tenant: tenantname - tenantid: tenantid - domain: domain name for Openstack Identity v3 API - domainid: domain id for Openstack Identity v3 API - insecureskipverify: true - region: fr - container: containername - rootdirectory: /swift/object/name/prefix oss: accesskeyid: accesskeyid accesskeysecret: accesskeysecret @@ -499,7 +475,6 @@ returns an error. You can choose any of these backend storage drivers: | `azure` | Uses Microsoft Azure Blob Storage. See the [driver's reference documentation](https://github.com/docker/docker.github.io/tree/master/registry/storage-drivers/azure.md). | | `gcs` | Uses Google Cloud Storage. See the [driver's reference documentation](https://github.com/docker/docker.github.io/tree/master/registry/storage-drivers/gcs.md). | | `s3` | Uses Amazon Simple Storage Service (S3) and compatible Storage Services. See the [driver's reference documentation](https://github.com/docker/docker.github.io/tree/master/registry/storage-drivers/s3.md). | -| `swift` | Uses Openstack Swift object storage. See the [driver's reference documentation](https://github.com/docker/docker.github.io/tree/master/registry/storage-drivers/swift.md). | | `oss` | Uses Aliyun OSS for object storage. See the [driver's reference documentation](https://github.com/docker/docker.github.io/tree/master/registry/storage-drivers/oss.md). | For testing only, you can use the [`inmemory` storage diff --git a/docs/introduction.md b/docs/introduction.md index 471ad510d..8deb9e12d 100644 --- a/docs/introduction.md +++ b/docs/introduction.md @@ -15,7 +15,7 @@ Users interact with a registry by using docker push and pull commands. Storage itself is delegated to drivers. The default storage driver is the local posix filesystem, which is suitable for development or small deployments. -Additional cloud-based storage drivers like S3, Microsoft Azure, OpenStack Swift, +Additional cloud-based storage drivers like S3, Microsoft Azure, Google Cloud Storage and Aliyun OSS are also supported. People looking into using other storage backends may do so by writing their own driver implementing the [Storage API](storage-drivers/index.md). diff --git a/docs/storage-drivers/index.md b/docs/storage-drivers/index.md index f4884810e..c0184717c 100644 --- a/docs/storage-drivers/index.md +++ b/docs/storage-drivers/index.md @@ -16,9 +16,9 @@ This storage driver package comes bundled with several drivers: - [filesystem](filesystem.md): A local storage driver configured to use a directory tree in the local filesystem. - [s3](s3.md): A driver storing objects in an Amazon Simple Storage Service (S3) bucket. - [azure](azure.md): A driver storing objects in [Microsoft Azure Blob Storage](https://azure.microsoft.com/en-us/services/storage/). -- [swift](swift.md): A driver storing objects in [Openstack Swift](https://docs.openstack.org/swift/latest/). -- [oss](oss.md): A driver storing objects in [Aliyun OSS](https://www.aliyun.com/product/oss). - [gcs](gcs.md): A driver storing objects in a [Google Cloud Storage](https://cloud.google.com/storage/) bucket. +- [oss](oss.md): A driver storing objects in [Aliyun OSS](https://www.aliyun.com/product/oss). +- swift: *NO LONGER SUPPORTED* ## Storage driver API diff --git a/docs/storage-drivers/swift.md b/docs/storage-drivers/swift.md deleted file mode 100644 index 0aea77ea8..000000000 --- a/docs/storage-drivers/swift.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -description: Explains how to use the OpenStack swift storage driver -keywords: registry, service, driver, images, storage, swift -title: OpenStack Swift storage driver ---- - -An implementation of the `storagedriver.StorageDriver` interface that uses -[OpenStack Swift](http://docs.openstack.org/developer/swift/) for object -storage. - -## Parameters - -| Parameter | Required | Description | -|:--------------|:---------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `authurl` | yes | URL for obtaining an auth token. https://storage.myprovider.com/v2.0 or https://storage.myprovider.com/v3/auth | -| `username` | yes | Your Openstack user name. | -| `password` | yes | Your Openstack password. | -| `region` | no | The Openstack region in which your container exists. | -| `container` | yes | The name of your Swift container where you wish to store the registry's data. The driver creates the named container during its initialization. | -| `tenant` | no | Your Openstack tenant name. You can either use `tenant` or `tenantid`. | -| `tenantid` | no | Your Openstack tenant name. You can either use `tenant` or `tenantid`. | -| `domain` | no | Your Openstack domain name for Identity v3 API. You can either use `domain` or `domainid`. | -| `domainid` | no | Your Openstack domain name for Identity v3 API. You can either use `domain` or `domainid`. | -| `tenantdomain` | no | Your tenant's Openstack domain name for Identity v3 API. Only necessary if different from the domain. You can either use `tenantdomain` or `tenantdomainid`. | -| `tenantdomainid` | no | Your tenant's Openstack domain id for Identity v3 API. Only necessary if different from the domain. You can either use `tenantdomain` or `tenantdomainid`. | -| `trustid` | no | Your Openstack trust ID for Identity v3 API. | -| `insecureskipverify` | no | Skips TLS verification if the value is wet to `true`. The default is `false`. | -| `chunksize` | no | Size of the data segments for the Swift Dynamic Large Objects. This value should be a number (defaults to 5M). | -| `prefix` | no | This is a prefix that is applied to all Swift keys to allow you to segment data in your container if necessary. Defaults to the empty string which is the container's root. | -| `secretkey` | no | The secret key used to generate temporary URLs. | -| `accesskey` | no | The access key to generate temporary URLs. It is used by HP Cloud Object Storage in addition to the `secretkey` parameter. | -| `authversion` | no | Specify the OpenStack Auth's version, for example `3`. By default the driver autodetects the auth's version from the AuthURL. | -| `endpointtype` | no | The endpoint type used when connecting to swift. Possible values are `public`, `internal`, and `admin`. The default is `public`. | - -The features supported by the Swift server are queried by requesting the `/info` -URL on the server. In case the administrator disabled that feature, the -configuration file can specify the following optional parameters : - -| Optional parameter | Description | -|:--------------|:---------| -| `tempurlcontainerkey` | Specify whether to use container secret key to generate temporary URL when set to true, or the account secret key otherwise. | -| `tempurlmethods` | Array of HTTP methods that are supported by the TempURL middleware of the Swift server. For example: `["GET", "PUT", "HEAD", "POST", "DELETE"]` | diff --git a/go.mod b/go.mod index 8dd9dd16a..b8bca8ec8 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,6 @@ require ( github.com/hashicorp/golang-lru v0.5.4 github.com/klauspost/compress v1.16.5 github.com/mitchellh/mapstructure v1.1.2 - github.com/ncw/swift v1.0.47 github.com/opencontainers/go-digest v1.0.0 github.com/opencontainers/image-spec v1.0.2 github.com/prometheus/client_golang v1.12.1 // indirect; updated to latest diff --git a/go.sum b/go.sum index 7b580c24f..887b0020c 100644 --- a/go.sum +++ b/go.sum @@ -244,8 +244,6 @@ github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3Rllmb github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= -github.com/ncw/swift v1.0.47 h1:4DQRPj35Y41WogBxyhOXlrI37nzGlyEcsforeudyYPQ= -github.com/ncw/swift v1.0.47/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM= diff --git a/registry/storage/driver/swift/swift.go b/registry/storage/driver/swift/swift.go deleted file mode 100644 index 26cf05ce6..000000000 --- a/registry/storage/driver/swift/swift.go +++ /dev/null @@ -1,932 +0,0 @@ -// Package swift provides a storagedriver.StorageDriver implementation to -// store blobs in Openstack Swift object storage. -// -// This package leverages the ncw/swift client library for interfacing with -// Swift. -// -// It supports both TempAuth authentication and Keystone authentication -// (up to version 3). -// -// As Swift has a limit on the size of a single uploaded object (by default -// this is 5GB), the driver makes use of the Swift Large Object Support -// (http://docs.openstack.org/developer/swift/overview_large_objects.html). -// Only one container is used for both manifests and data objects. Manifests -// are stored in the 'files' pseudo directory, data objects are stored under -// 'segments'. -package swift - -import ( - "bufio" - "bytes" - "context" - "crypto/rand" - "crypto/sha1" - "crypto/tls" - "encoding/hex" - "fmt" - "io" - "net/http" - "net/url" - "strconv" - "strings" - "time" - - "github.com/mitchellh/mapstructure" - "github.com/ncw/swift" - - storagedriver "github.com/distribution/distribution/v3/registry/storage/driver" - "github.com/distribution/distribution/v3/registry/storage/driver/base" - "github.com/distribution/distribution/v3/registry/storage/driver/factory" - "github.com/distribution/distribution/v3/version" -) - -const driverName = "swift" - -// defaultChunkSize defines the default size of a segment -const defaultChunkSize = 20 * 1024 * 1024 - -// minChunkSize defines the minimum size of a segment -const minChunkSize = 1 << 20 - -// contentType defines the Content-Type header associated with stored segments -const contentType = "application/octet-stream" - -// readAfterWriteTimeout defines the time we wait before an object appears after having been uploaded -var readAfterWriteTimeout = 15 * time.Second - -// readAfterWriteWait defines the time to sleep between two retries -var readAfterWriteWait = 200 * time.Millisecond - -// Parameters A struct that encapsulates all of the driver parameters after all values have been set -type Parameters struct { - Username string - Password string - AuthURL string - Tenant string - TenantID string - Domain string - DomainID string - TenantDomain string - TenantDomainID string - TrustID string - Region string - AuthVersion int - Container string - Prefix string - EndpointType string - InsecureSkipVerify bool - ChunkSize int - SecretKey string - AccessKey string - TempURLContainerKey bool - TempURLMethods []string -} - -// swiftInfo maps the JSON structure returned by Swift /info endpoint -type swiftInfo struct { - Swift struct { - Version string `mapstructure:"version"` - } - Tempurl struct { - Methods []string `mapstructure:"methods"` - } - BulkDelete struct { - MaxDeletesPerRequest int `mapstructure:"max_deletes_per_request"` - } `mapstructure:"bulk_delete"` -} - -func init() { - factory.Register(driverName, &swiftDriverFactory{}) -} - -// swiftDriverFactory implements the factory.StorageDriverFactory interface -type swiftDriverFactory struct{} - -func (factory *swiftDriverFactory) Create(parameters map[string]interface{}) (storagedriver.StorageDriver, error) { - return FromParameters(parameters) -} - -type driver struct { - Conn *swift.Connection - Container string - Prefix string - BulkDeleteSupport bool - BulkDeleteMaxDeletes int - ChunkSize int - SecretKey string - AccessKey string - TempURLContainerKey bool - TempURLMethods []string -} - -type baseEmbed struct { - base.Base -} - -// Driver is a storagedriver.StorageDriver implementation backed by Openstack Swift -// Objects are stored at absolute keys in the provided container. -type Driver struct { - baseEmbed -} - -// FromParameters constructs a new Driver with a given parameters map -// Required parameters: -// - username -// - password -// - authurl -// - container -func FromParameters(parameters map[string]interface{}) (*Driver, error) { - params := Parameters{ - ChunkSize: defaultChunkSize, - InsecureSkipVerify: false, - } - - // Sanitize some entries before trying to decode parameters with mapstructure - // TenantID and Tenant when integers only and passed as ENV variables - // are considered as integer and not string. The parser fails in this - // case. - _, ok := parameters["tenant"] - if ok { - parameters["tenant"] = fmt.Sprint(parameters["tenant"]) - } - _, ok = parameters["tenantid"] - if ok { - parameters["tenantid"] = fmt.Sprint(parameters["tenantid"]) - } - - if err := mapstructure.Decode(parameters, ¶ms); err != nil { - return nil, err - } - - if params.Username == "" { - return nil, fmt.Errorf("no username parameter provided") - } - - if params.Password == "" { - return nil, fmt.Errorf("no password parameter provided") - } - - if params.AuthURL == "" { - return nil, fmt.Errorf("no authurl parameter provided") - } - - if params.Container == "" { - return nil, fmt.Errorf("no container parameter provided") - } - - if params.ChunkSize < minChunkSize { - return nil, fmt.Errorf("the chunksize %#v parameter should be a number that is larger than or equal to %d", params.ChunkSize, minChunkSize) - } - - return New(params) -} - -// New constructs a new Driver with the given Openstack Swift credentials and container name -func New(params Parameters) (*Driver, error) { - transport := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - MaxIdleConnsPerHost: 2048, - TLSClientConfig: &tls.Config{InsecureSkipVerify: params.InsecureSkipVerify}, - } - - ct := &swift.Connection{ - UserName: params.Username, - ApiKey: params.Password, - AuthUrl: params.AuthURL, - Region: params.Region, - AuthVersion: params.AuthVersion, - UserAgent: "distribution/" + version.Version, - Tenant: params.Tenant, - TenantId: params.TenantID, - Domain: params.Domain, - DomainId: params.DomainID, - TenantDomain: params.TenantDomain, - TenantDomainId: params.TenantDomainID, - TrustId: params.TrustID, - EndpointType: swift.EndpointType(params.EndpointType), - Transport: transport, - ConnectTimeout: 60 * time.Second, - Timeout: 15 * 60 * time.Second, - } - err := ct.Authenticate() - if err != nil { - return nil, fmt.Errorf("swift authentication failed: %s", err) - } - - if _, _, err := ct.Container(params.Container); err == swift.ContainerNotFound { - if err := ct.ContainerCreate(params.Container, nil); err != nil { - return nil, fmt.Errorf("failed to create container %s (%s)", params.Container, err) - } - } else if err != nil { - return nil, fmt.Errorf("failed to retrieve info about container %s (%s)", params.Container, err) - } - - d := &driver{ - Conn: ct, - Container: params.Container, - Prefix: params.Prefix, - ChunkSize: params.ChunkSize, - TempURLMethods: make([]string, 0), - AccessKey: params.AccessKey, - } - - info := swiftInfo{} - if config, err := d.Conn.QueryInfo(); err == nil { - _, d.BulkDeleteSupport = config["bulk_delete"] - - if err := mapstructure.Decode(config, &info); err == nil { - d.TempURLContainerKey = info.Swift.Version >= "2.3.0" - d.TempURLMethods = info.Tempurl.Methods - if d.BulkDeleteSupport { - d.BulkDeleteMaxDeletes = info.BulkDelete.MaxDeletesPerRequest - } - } - } else { - d.TempURLContainerKey = params.TempURLContainerKey - d.TempURLMethods = params.TempURLMethods - } - - if len(d.TempURLMethods) > 0 { - secretKey := params.SecretKey - if secretKey == "" { - secretKey, _ = generateSecret() - } - - // Since Swift 2.2.2, we can now set secret keys on containers - // in addition to the account secret keys. Use them in preference. - if d.TempURLContainerKey { - _, containerHeaders, err := d.Conn.Container(d.Container) - if err != nil { - return nil, fmt.Errorf("failed to fetch container info %s (%s)", d.Container, err) - } - - d.SecretKey = containerHeaders["X-Container-Meta-Temp-Url-Key"] - if d.SecretKey == "" || (params.SecretKey != "" && d.SecretKey != params.SecretKey) { - m := swift.Metadata{} - m["temp-url-key"] = secretKey - if d.Conn.ContainerUpdate(d.Container, m.ContainerHeaders()); err == nil { - d.SecretKey = secretKey - } - } - } else { - // Use the account secret key - _, accountHeaders, err := d.Conn.Account() - if err != nil { - return nil, fmt.Errorf("failed to fetch account info (%s)", err) - } - - d.SecretKey = accountHeaders["X-Account-Meta-Temp-Url-Key"] - if d.SecretKey == "" || (params.SecretKey != "" && d.SecretKey != params.SecretKey) { - m := swift.Metadata{} - m["temp-url-key"] = secretKey - if err := d.Conn.AccountUpdate(m.AccountHeaders()); err == nil { - d.SecretKey = secretKey - } - } - } - } - - return &Driver{ - baseEmbed: baseEmbed{ - Base: base.Base{ - StorageDriver: d, - }, - }, - }, nil -} - -// Implement the storagedriver.StorageDriver interface - -func (d *driver) Name() string { - return driverName -} - -// GetContent retrieves the content stored at "path" as a []byte. -func (d *driver) GetContent(ctx context.Context, path string) ([]byte, error) { - content, err := d.Conn.ObjectGetBytes(d.Container, d.swiftPath(path)) - if err == swift.ObjectNotFound { - return nil, storagedriver.PathNotFoundError{Path: path} - } - return content, err -} - -// PutContent stores the []byte content at a location designated by "path". -func (d *driver) PutContent(ctx context.Context, path string, contents []byte) error { - err := d.Conn.ObjectPutBytes(d.Container, d.swiftPath(path), contents, contentType) - if err == swift.ObjectNotFound { - return storagedriver.PathNotFoundError{Path: path} - } - return err -} - -// Reader retrieves an io.ReadCloser for the content stored at "path" with a -// given byte offset. -func (d *driver) Reader(ctx context.Context, path string, offset int64) (io.ReadCloser, error) { - headers := make(swift.Headers) - headers["Range"] = "bytes=" + strconv.FormatInt(offset, 10) + "-" - - waitingTime := readAfterWriteWait - endTime := time.Now().Add(readAfterWriteTimeout) - - for { - file, headers, err := d.Conn.ObjectOpen(d.Container, d.swiftPath(path), false, headers) - if err != nil { - if err == swift.ObjectNotFound { - return nil, storagedriver.PathNotFoundError{Path: path} - } - if swiftErr, ok := err.(*swift.Error); ok && swiftErr.StatusCode == http.StatusRequestedRangeNotSatisfiable { - return io.NopCloser(bytes.NewReader(nil)), nil - } - return file, err - } - - // if this is a DLO and it is clear that segments are still missing, - // wait until they show up - _, isDLO := headers["X-Object-Manifest"] - size, err := file.Length() - if err != nil { - return file, err - } - if isDLO && size == 0 { - if time.Now().Add(waitingTime).After(endTime) { - return nil, fmt.Errorf("timeout expired while waiting for segments of %s to show up", path) - } - time.Sleep(waitingTime) - waitingTime *= 2 - continue - } - - // if not, then this reader will be fine - return file, nil - } -} - -// Writer returns a FileWriter which will store the content written to it -// at the location designated by "path" after the call to Commit. -func (d *driver) Writer(ctx context.Context, path string, append bool) (storagedriver.FileWriter, error) { - var ( - segments []swift.Object - segmentsPath string - err error - ) - - if !append { - segmentsPath, err = d.swiftSegmentPath(path) - if err != nil { - return nil, err - } - } else { - info, headers, err := d.Conn.Object(d.Container, d.swiftPath(path)) - if err == swift.ObjectNotFound { - return nil, storagedriver.PathNotFoundError{Path: path} - } else if err != nil { - return nil, err - } - manifest, ok := headers["X-Object-Manifest"] - if !ok { - segmentsPath, err = d.swiftSegmentPath(path) - if err != nil { - return nil, err - } - if err := d.Conn.ObjectMove(d.Container, d.swiftPath(path), d.Container, getSegmentPath(segmentsPath, len(segments))); err != nil { - return nil, err - } - segments = []swift.Object{info} - } else { - _, segmentsPath = parseManifest(manifest) - if segments, err = d.getAllSegments(segmentsPath); err != nil { - return nil, err - } - } - } - - return d.newWriter(path, segmentsPath, segments), nil -} - -// Stat retrieves the FileInfo for the given path, including the current size -// in bytes and the creation time. -func (d *driver) Stat(ctx context.Context, path string) (storagedriver.FileInfo, error) { - swiftPath := d.swiftPath(path) - opts := &swift.ObjectsOpts{ - Prefix: swiftPath, - Delimiter: '/', - } - - objects, err := d.Conn.ObjectsAll(d.Container, opts) - if err != nil { - if err == swift.ContainerNotFound { - return nil, storagedriver.PathNotFoundError{Path: path} - } - return nil, err - } - - fi := storagedriver.FileInfoFields{ - Path: strings.TrimPrefix(strings.TrimSuffix(swiftPath, "/"), d.swiftPath("/")), - } - - for _, obj := range objects { - if obj.PseudoDirectory && obj.Name == swiftPath+"/" { - fi.IsDir = true - return storagedriver.FileInfoInternal{FileInfoFields: fi}, nil - } else if obj.Name == swiftPath { - // The file exists. But on Swift 1.12, the 'bytes' field is always 0 so - // we need to do a separate HEAD request. - break - } - } - - // Don't trust an empty `objects` slice. A container listing can be - // outdated. For files, we can make a HEAD request on the object which - // reports existence (at least) much more reliably. - waitingTime := readAfterWriteWait - endTime := time.Now().Add(readAfterWriteTimeout) - - for { - info, headers, err := d.Conn.Object(d.Container, swiftPath) - if err != nil { - if err == swift.ObjectNotFound { - return nil, storagedriver.PathNotFoundError{Path: path} - } - return nil, err - } - - // if this is a DLO and it is clear that segments are still missing, - // wait until they show up - _, isDLO := headers["X-Object-Manifest"] - if isDLO && info.Bytes == 0 { - if time.Now().Add(waitingTime).After(endTime) { - return nil, fmt.Errorf("timeout expired while waiting for segments of %s to show up", path) - } - time.Sleep(waitingTime) - waitingTime *= 2 - continue - } - - // otherwise, accept the result - fi.IsDir = false - fi.Size = info.Bytes - fi.ModTime = info.LastModified - return storagedriver.FileInfoInternal{FileInfoFields: fi}, nil - } -} - -// List returns a list of the objects that are direct descendants of the given path. -func (d *driver) List(ctx context.Context, path string) ([]string, error) { - var files []string - - prefix := d.swiftPath(path) - if prefix != "" { - prefix += "/" - } - - opts := &swift.ObjectsOpts{ - Prefix: prefix, - Delimiter: '/', - } - - objects, err := d.Conn.ObjectsAll(d.Container, opts) - for _, obj := range objects { - files = append(files, strings.TrimPrefix(strings.TrimSuffix(obj.Name, "/"), d.swiftPath("/"))) - } - - if err == swift.ContainerNotFound || (len(objects) == 0 && path != "/") { - return files, storagedriver.PathNotFoundError{Path: path} - } - return files, err -} - -// Move moves an object stored at sourcePath to destPath, removing the original -// object. -func (d *driver) Move(ctx context.Context, sourcePath string, destPath string) error { - _, headers, err := d.Conn.Object(d.Container, d.swiftPath(sourcePath)) - if err == nil { - if manifest, ok := headers["X-Object-Manifest"]; ok { - if err = d.createManifest(destPath, manifest); err != nil { - return err - } - err = d.Conn.ObjectDelete(d.Container, d.swiftPath(sourcePath)) - } else { - err = d.Conn.ObjectMove(d.Container, d.swiftPath(sourcePath), d.Container, d.swiftPath(destPath)) - } - } - if err == swift.ObjectNotFound { - return storagedriver.PathNotFoundError{Path: sourcePath} - } - return err -} - -// Delete recursively deletes all objects stored at "path" and its subpaths. -func (d *driver) Delete(ctx context.Context, path string) error { - opts := swift.ObjectsOpts{ - Prefix: d.swiftPath(path) + "/", - } - - objects, err := d.Conn.ObjectsAll(d.Container, &opts) - if err != nil { - if err == swift.ContainerNotFound { - return storagedriver.PathNotFoundError{Path: path} - } - return err - } - - for _, obj := range objects { - if obj.PseudoDirectory { - continue - } - if _, headers, err := d.Conn.Object(d.Container, obj.Name); err == nil { - manifest, ok := headers["X-Object-Manifest"] - if ok { - _, prefix := parseManifest(manifest) - segments, err := d.getAllSegments(prefix) - if err != nil { - return err - } - objects = append(objects, segments...) - } - } else { - if err == swift.ObjectNotFound { - return storagedriver.PathNotFoundError{Path: obj.Name} - } - return err - } - } - - if d.BulkDeleteSupport && len(objects) > 0 && d.BulkDeleteMaxDeletes > 0 { - filenames := make([]string, len(objects)) - for i, obj := range objects { - filenames[i] = obj.Name - } - - chunks, err := chunkFilenames(filenames, d.BulkDeleteMaxDeletes) - if err != nil { - return err - } - for _, chunk := range chunks { - _, err := d.Conn.BulkDelete(d.Container, chunk) - // Don't fail on ObjectNotFound because eventual consistency - // makes this situation normal. - if err != nil && err != swift.Forbidden && err != swift.ObjectNotFound { - if err == swift.ContainerNotFound { - return storagedriver.PathNotFoundError{Path: path} - } - return err - } - } - } else { - for _, obj := range objects { - if err := d.Conn.ObjectDelete(d.Container, obj.Name); err != nil { - if err == swift.ObjectNotFound { - return storagedriver.PathNotFoundError{Path: obj.Name} - } - return err - } - } - } - - _, _, err = d.Conn.Object(d.Container, d.swiftPath(path)) - if err == nil { - if err := d.Conn.ObjectDelete(d.Container, d.swiftPath(path)); err != nil { - if err == swift.ObjectNotFound { - return storagedriver.PathNotFoundError{Path: path} - } - return err - } - } else if err == swift.ObjectNotFound { - if len(objects) == 0 { - return storagedriver.PathNotFoundError{Path: path} - } - } else { - return err - } - return nil -} - -// URLFor returns a URL which may be used to retrieve the content stored at the given path. -func (d *driver) URLFor(ctx context.Context, path string, options map[string]interface{}) (string, error) { - if d.SecretKey == "" { - return "", storagedriver.ErrUnsupportedMethod{} - } - - methodString := http.MethodGet - method, ok := options["method"] - if ok { - if methodString, ok = method.(string); !ok { - return "", storagedriver.ErrUnsupportedMethod{} - } - } - - if methodString == http.MethodHead { - // A "HEAD" request on a temporary URL is allowed if the - // signature was generated with "GET", "POST" or "PUT" - methodString = http.MethodGet - } - - supported := false - for _, method := range d.TempURLMethods { - if method == methodString { - supported = true - break - } - } - - if !supported { - return "", storagedriver.ErrUnsupportedMethod{} - } - - expiresTime := time.Now().Add(20 * time.Minute) - expires, ok := options["expiry"] - if ok { - et, ok := expires.(time.Time) - if ok { - expiresTime = et - } - } - - tempURL := d.Conn.ObjectTempUrl(d.Container, d.swiftPath(path), d.SecretKey, methodString, expiresTime) - - if d.AccessKey != "" { - // On HP Cloud, the signature must be in the form of tenant_id:access_key:signature - url, _ := url.Parse(tempURL) - query := url.Query() - query.Set("temp_url_sig", fmt.Sprintf("%s:%s:%s", d.Conn.TenantId, d.AccessKey, query.Get("temp_url_sig"))) - url.RawQuery = query.Encode() - tempURL = url.String() - } - - return tempURL, nil -} - -// Walk traverses a filesystem defined within driver, starting -// from the given path, calling f on each file and directory -func (d *driver) Walk(ctx context.Context, path string, f storagedriver.WalkFn) error { - return storagedriver.WalkFallback(ctx, d, path, f) -} - -func (d *driver) swiftPath(path string) string { - return strings.TrimLeft(strings.TrimRight(d.Prefix+"/files"+path, "/"), "/") -} - -// swiftSegmentPath returns a randomly generated path in the segments directory. -func (d *driver) swiftSegmentPath(path string) (string, error) { - checksum := sha1.New() - checksum.Write([]byte(path)) - - if _, err := io.CopyN(checksum, rand.Reader, 32); err != nil { - return "", err - } - - path = hex.EncodeToString(checksum.Sum(nil)) - return strings.TrimLeft(strings.TrimRight(d.Prefix+"/segments/"+path[0:3]+"/"+path[3:], "/"), "/"), nil -} - -func (d *driver) getAllSegments(path string) ([]swift.Object, error) { - // a simple container listing works 99.9% of the time - segments, err := d.Conn.ObjectsAll(d.Container, &swift.ObjectsOpts{Prefix: path}) - if err != nil { - if err == swift.ContainerNotFound { - return nil, storagedriver.PathNotFoundError{Path: path} - } - return nil, err - } - - // build a lookup table by object name - hasObjectName := make(map[string]struct{}) - for _, segment := range segments { - hasObjectName[segment.Name] = struct{}{} - } - - // The container listing might be outdated (i.e. not contain all existing - // segment objects yet) because of temporary inconsistency (Swift is only - // eventually consistent!). Check its completeness. - segmentNumber := 0 - for { - segmentNumber++ - segmentPath := getSegmentPath(path, segmentNumber) - - if _, seen := hasObjectName[segmentPath]; seen { - continue - } - - // This segment is missing in the container listing. Use a more reliable - // request to check its existence. (HEAD requests on segments are - // guaranteed to return the correct metadata, except for the pathological - // case of an outage of large parts of the Swift cluster or its network, - // since every segment is only written once.) - segment, _, err := d.Conn.Object(d.Container, segmentPath) - switch err { - case nil: - // found new segment -> keep going, more might be missing - segments = append(segments, segment) - continue - case swift.ObjectNotFound: - // This segment is missing. Since we upload segments sequentially, - // there won't be any more segments after it. - return segments, nil - default: - return nil, err // unexpected error - } - } -} - -func (d *driver) createManifest(path string, segments string) error { - headers := make(swift.Headers) - headers["X-Object-Manifest"] = segments - manifest, err := d.Conn.ObjectCreate(d.Container, d.swiftPath(path), false, "", contentType, headers) - if err != nil { - if err == swift.ObjectNotFound { - return storagedriver.PathNotFoundError{Path: path} - } - return err - } - if err := manifest.Close(); err != nil { - if err == swift.ObjectNotFound { - return storagedriver.PathNotFoundError{Path: path} - } - return err - } - return nil -} - -func chunkFilenames(slice []string, maxSize int) (chunks [][]string, err error) { - if maxSize > 0 { - for offset := 0; offset < len(slice); offset += maxSize { - chunkSize := maxSize - if offset+chunkSize > len(slice) { - chunkSize = len(slice) - offset - } - chunks = append(chunks, slice[offset:offset+chunkSize]) - } - } else { - return nil, fmt.Errorf("max chunk size must be > 0") - } - return -} - -func parseManifest(manifest string) (container string, prefix string) { - container, prefix, _ = strings.Cut(manifest, "/") - return container, prefix -} - -func generateSecret() (string, error) { - var secretBytes [32]byte - if _, err := rand.Read(secretBytes[:]); err != nil { - return "", fmt.Errorf("could not generate random bytes for Swift secret key: %v", err) - } - return hex.EncodeToString(secretBytes[:]), nil -} - -func getSegmentPath(segmentsPath string, partNumber int) string { - return fmt.Sprintf("%s/%016d", segmentsPath, partNumber) -} - -type writer struct { - driver *driver - path string - segmentsPath string - size int64 - bw *bufio.Writer - closed bool - committed bool - cancelled bool -} - -func (d *driver) newWriter(path, segmentsPath string, segments []swift.Object) storagedriver.FileWriter { - var size int64 - for _, segment := range segments { - size += segment.Bytes - } - return &writer{ - driver: d, - path: path, - segmentsPath: segmentsPath, - size: size, - bw: bufio.NewWriterSize(&segmentWriter{ - conn: d.Conn, - container: d.Container, - segmentsPath: segmentsPath, - segmentNumber: len(segments) + 1, - maxChunkSize: d.ChunkSize, - }, d.ChunkSize), - } -} - -func (w *writer) Write(p []byte) (int, error) { - if w.closed { - return 0, fmt.Errorf("already closed") - } else if w.committed { - return 0, fmt.Errorf("already committed") - } else if w.cancelled { - return 0, fmt.Errorf("already cancelled") - } - - n, err := w.bw.Write(p) - w.size += int64(n) - return n, err -} - -func (w *writer) Size() int64 { - return w.size -} - -func (w *writer) Close() error { - if w.closed { - return fmt.Errorf("already closed") - } - - if err := w.bw.Flush(); err != nil { - return err - } - - if !w.committed && !w.cancelled { - if err := w.driver.createManifest(w.path, w.driver.Container+"/"+w.segmentsPath); err != nil { - return err - } - if err := w.waitForSegmentsToShowUp(); err != nil { - return err - } - } - w.closed = true - - return nil -} - -func (w *writer) Cancel(ctx context.Context) error { - if w.closed { - return fmt.Errorf("already closed") - } else if w.committed { - return fmt.Errorf("already committed") - } - w.cancelled = true - return w.driver.Delete(ctx, w.path) -} - -func (w *writer) Commit() error { - if w.closed { - return fmt.Errorf("already closed") - } else if w.committed { - return fmt.Errorf("already committed") - } else if w.cancelled { - return fmt.Errorf("already cancelled") - } - - if err := w.bw.Flush(); err != nil { - return err - } - - if err := w.driver.createManifest(w.path, w.driver.Container+"/"+w.segmentsPath); err != nil { - return err - } - - w.committed = true - return w.waitForSegmentsToShowUp() -} - -func (w *writer) waitForSegmentsToShowUp() error { - var err error - waitingTime := readAfterWriteWait - endTime := time.Now().Add(readAfterWriteTimeout) - - for { - var info swift.Object - if info, _, err = w.driver.Conn.Object(w.driver.Container, w.driver.swiftPath(w.path)); err == nil { - if info.Bytes == w.size { - break - } - err = fmt.Errorf("timeout expired while waiting for segments of %s to show up", w.path) - } - if time.Now().Add(waitingTime).After(endTime) { - break - } - time.Sleep(waitingTime) - waitingTime *= 2 - } - - return err -} - -type segmentWriter struct { - conn *swift.Connection - container string - segmentsPath string - segmentNumber int - maxChunkSize int -} - -func (sw *segmentWriter) Write(p []byte) (int, error) { - n := 0 - for offset := 0; offset < len(p); offset += sw.maxChunkSize { - chunkSize := sw.maxChunkSize - if offset+chunkSize > len(p) { - chunkSize = len(p) - offset - } - _, err := sw.conn.ObjectPut(sw.container, getSegmentPath(sw.segmentsPath, sw.segmentNumber), bytes.NewReader(p[offset:offset+chunkSize]), false, "", contentType, nil) - if err != nil { - return n, err - } - - sw.segmentNumber++ - n += chunkSize - } - - return n, nil -} diff --git a/registry/storage/driver/swift/swift_test.go b/registry/storage/driver/swift/swift_test.go deleted file mode 100644 index 6b4342dd0..000000000 --- a/registry/storage/driver/swift/swift_test.go +++ /dev/null @@ -1,257 +0,0 @@ -package swift - -import ( - "os" - "reflect" - "strconv" - "strings" - "testing" - - "github.com/ncw/swift/swifttest" - - "github.com/distribution/distribution/v3/context" - storagedriver "github.com/distribution/distribution/v3/registry/storage/driver" - "github.com/distribution/distribution/v3/registry/storage/driver/testsuites" - - "gopkg.in/check.v1" -) - -// Hook up gocheck into the "go test" runner. -func Test(t *testing.T) { check.TestingT(t) } - -var swiftDriverConstructor func(prefix string) (*Driver, error) - -func init() { - var ( - username = os.Getenv("SWIFT_USERNAME") - password = os.Getenv("SWIFT_PASSWORD") - authURL = os.Getenv("SWIFT_AUTH_URL") - tenant = os.Getenv("SWIFT_TENANT_NAME") - tenantID = os.Getenv("SWIFT_TENANT_ID") - domain = os.Getenv("SWIFT_DOMAIN_NAME") - domainID = os.Getenv("SWIFT_DOMAIN_ID") - tenantDomain = os.Getenv("SWIFT_DOMAIN_NAME") - tenantDomainID = os.Getenv("SWIFT_DOMAIN_ID") - trustID = os.Getenv("SWIFT_TRUST_ID") - container = os.Getenv("SWIFT_CONTAINER_NAME") - region = os.Getenv("SWIFT_REGION_NAME") - AuthVersion, _ = strconv.Atoi(os.Getenv("SWIFT_AUTH_VERSION")) - endpointType = os.Getenv("SWIFT_ENDPOINT_TYPE") - insecureSkipVerify, _ = strconv.ParseBool(os.Getenv("SWIFT_INSECURESKIPVERIFY")) - secretKey = os.Getenv("SWIFT_SECRET_KEY") - accessKey = os.Getenv("SWIFT_ACCESS_KEY") - containerKey, _ = strconv.ParseBool(os.Getenv("SWIFT_TEMPURL_CONTAINERKEY")) - tempURLMethods = strings.Split(os.Getenv("SWIFT_TEMPURL_METHODS"), ",") - - swiftServer *swifttest.SwiftServer - err error - ) - - if username == "" || password == "" || authURL == "" || container == "" { - if swiftServer, err = swifttest.NewSwiftServer("localhost"); err != nil { - panic(err) - } - username = "swifttest" - password = "swifttest" - authURL = swiftServer.AuthURL - container = "test" - } - - prefix, err := os.MkdirTemp("", "driver-") - if err != nil { - panic(err) - } - defer os.Remove(prefix) - - swiftDriverConstructor = func(root string) (*Driver, error) { - parameters := Parameters{ - username, - password, - authURL, - tenant, - tenantID, - domain, - domainID, - tenantDomain, - tenantDomainID, - trustID, - region, - AuthVersion, - container, - root, - endpointType, - insecureSkipVerify, - defaultChunkSize, - secretKey, - accessKey, - containerKey, - tempURLMethods, - } - - return New(parameters) - } - - driverConstructor := func() (storagedriver.StorageDriver, error) { - return swiftDriverConstructor(prefix) - } - - testsuites.RegisterSuite(driverConstructor, testsuites.NeverSkip) -} - -func TestEmptyRootList(t *testing.T) { - validRoot := t.TempDir() - - rootedDriver, err := swiftDriverConstructor(validRoot) - if err != nil { - t.Fatalf("unexpected error creating rooted driver: %v", err) - } - - emptyRootDriver, err := swiftDriverConstructor("") - if err != nil { - t.Fatalf("unexpected error creating empty root driver: %v", err) - } - - slashRootDriver, err := swiftDriverConstructor("/") - if err != nil { - t.Fatalf("unexpected error creating slash root driver: %v", err) - } - - filename := "/test" - contents := []byte("contents") - ctx := context.Background() - err = rootedDriver.PutContent(ctx, filename, contents) - if err != nil { - t.Fatalf("unexpected error creating content: %v", err) - } - - keys, _ := emptyRootDriver.List(ctx, "/") - for _, path := range keys { - if !storagedriver.PathRegexp.MatchString(path) { - t.Fatalf("unexpected string in path: %q != %q", path, storagedriver.PathRegexp) - } - } - - keys, _ = slashRootDriver.List(ctx, "/") - for _, path := range keys { - if !storagedriver.PathRegexp.MatchString(path) { - t.Fatalf("unexpected string in path: %q != %q", path, storagedriver.PathRegexp) - } - } - - // Create an object with a path nested under the existing object - err = rootedDriver.PutContent(ctx, filename+"/file1", contents) - if err != nil { - t.Fatalf("unexpected error creating content: %v", err) - } - - err = rootedDriver.Delete(ctx, filename) - if err != nil { - t.Fatalf("failed to delete: %v", err) - } - - keys, err = rootedDriver.List(ctx, "/") - if err != nil { - t.Fatalf("failed to list objects after deletion: %v", err) - } - - if len(keys) != 0 { - t.Fatal("delete did not remove nested objects") - } -} - -func TestFilenameChunking(t *testing.T) { - // Test valid input and sizes - input := []string{"a", "b", "c", "d", "e"} - expecteds := [][][]string{ - { - {"a"}, - {"b"}, - {"c"}, - {"d"}, - {"e"}, - }, - { - {"a", "b"}, - {"c", "d"}, - {"e"}, - }, - { - {"a", "b", "c"}, - {"d", "e"}, - }, - { - {"a", "b", "c", "d"}, - {"e"}, - }, - { - {"a", "b", "c", "d", "e"}, - }, - { - {"a", "b", "c", "d", "e"}, - }, - } - for i, expected := range expecteds { - actual, err := chunkFilenames(input, i+1) - if !reflect.DeepEqual(actual, expected) { - t.Fatalf("chunk %v didn't match expected value %v", actual, expected) - } - if err != nil { - t.Fatalf("unexpected error chunking filenames: %v", err) - } - } - - // Test nil input - actual, err := chunkFilenames(nil, 5) - if len(actual) != 0 { - t.Fatal("chunks were returned when passed nil") - } - if err != nil { - t.Fatalf("unexpected error chunking filenames: %v", err) - } - - // Test 0 and < 0 sizes - _, err = chunkFilenames(nil, 0) - if err == nil { - t.Fatal("expected error for size = 0") - } - _, err = chunkFilenames(nil, -1) - if err == nil { - t.Fatal("expected error for size = -1") - } -} - -func TestSwiftSegmentPath(t *testing.T) { - d := &driver{ - Prefix: "/test/segment/path", - } - - s1, err := d.swiftSegmentPath("foo-baz") - if err != nil { - t.Fatalf("unexpected error generating segment path: %v", err) - } - - s2, err := d.swiftSegmentPath("foo-baz") - if err != nil { - t.Fatalf("unexpected error generating segment path: %v", err) - } - - if !strings.HasPrefix(s1, "test/segment/path/segments/") { - t.Fatalf("expected to be prefixed: %s", s1) - } - - if !strings.HasPrefix(s1, "test/segment/path/segments/") { - t.Fatalf("expected to be prefixed: %s", s2) - } - - if len(s1) != 68 { - t.Fatalf("unexpected segment path length, %d != %d", len(s1), 68) - } - - if len(s2) != 68 { - t.Fatalf("unexpected segment path length, %d != %d", len(s2), 68) - } - - if s1 == s2 { - t.Fatalf("expected segment paths to differ, %s == %s", s1, s2) - } -} diff --git a/vendor/github.com/ncw/swift/.gitignore b/vendor/github.com/ncw/swift/.gitignore deleted file mode 100644 index 5cdbab794..000000000 --- a/vendor/github.com/ncw/swift/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -*~ -*.pyc -test-env* -junk/ \ No newline at end of file diff --git a/vendor/github.com/ncw/swift/.travis.yml b/vendor/github.com/ncw/swift/.travis.yml deleted file mode 100644 index e0a61643b..000000000 --- a/vendor/github.com/ncw/swift/.travis.yml +++ /dev/null @@ -1,33 +0,0 @@ -language: go -sudo: false - -go: - - 1.2.x - - 1.3.x - - 1.4.x - - 1.5.x - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - - 1.11.x - - 1.12.x - - master - -matrix: - include: - - go: 1.12.x - env: TEST_REAL_SERVER=rackspace - - go: 1.12.x - env: TEST_REAL_SERVER=memset - allow_failures: - - go: 1.12.x - env: TEST_REAL_SERVER=rackspace - - go: 1.12.x - env: TEST_REAL_SERVER=memset -install: go test -i ./... -script: - - test -z "$(go fmt ./...)" - - go test - - ./travis_realserver.sh diff --git a/vendor/github.com/ncw/swift/COPYING b/vendor/github.com/ncw/swift/COPYING deleted file mode 100644 index 8c27c67fd..000000000 --- a/vendor/github.com/ncw/swift/COPYING +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (C) 2012 by Nick Craig-Wood http://www.craig-wood.com/nick/ - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - diff --git a/vendor/github.com/ncw/swift/README.md b/vendor/github.com/ncw/swift/README.md deleted file mode 100644 index 0a09293d8..000000000 --- a/vendor/github.com/ncw/swift/README.md +++ /dev/null @@ -1,156 +0,0 @@ -Swift -===== - -This package provides an easy to use library for interfacing with -Swift / Openstack Object Storage / Rackspace cloud files from the Go -Language - -See here for package docs - - http://godoc.org/github.com/ncw/swift - -[![Build Status](https://api.travis-ci.org/ncw/swift.svg?branch=master)](https://travis-ci.org/ncw/swift) [![GoDoc](https://godoc.org/github.com/ncw/swift?status.svg)](https://godoc.org/github.com/ncw/swift) - -Install -------- - -Use go to install the library - - go get github.com/ncw/swift - -Usage ------ - -See here for full package docs - -- http://godoc.org/github.com/ncw/swift - -Here is a short example from the docs -```go -import "github.com/ncw/swift" - -// Create a connection -c := swift.Connection{ - UserName: "user", - ApiKey: "key", - AuthUrl: "auth_url", - Domain: "domain", // Name of the domain (v3 auth only) - Tenant: "tenant", // Name of the tenant (v2 auth only) -} -// Authenticate -err := c.Authenticate() -if err != nil { - panic(err) -} -// List all the containers -containers, err := c.ContainerNames(nil) -fmt.Println(containers) -// etc... -``` - -Additions ---------- - -The `rs` sub project contains a wrapper for the Rackspace specific CDN Management interface. - -Testing -------- - -To run the tests you can either use an embedded fake Swift server -either use a real Openstack Swift server or a Rackspace Cloud files account. - -When using a real Swift server, you need to set these environment variables -before running the tests - - export SWIFT_API_USER='user' - export SWIFT_API_KEY='key' - export SWIFT_AUTH_URL='https://url.of.auth.server/v1.0' - -And optionally these if using v2 authentication - - export SWIFT_TENANT='TenantName' - export SWIFT_TENANT_ID='TenantId' - -And optionally these if using v3 authentication - - export SWIFT_TENANT='TenantName' - export SWIFT_TENANT_ID='TenantId' - export SWIFT_API_DOMAIN_ID='domain id' - export SWIFT_API_DOMAIN='domain name' - -And optionally these if using v3 trust - - export SWIFT_TRUST_ID='TrustId' - -And optionally this if you want to skip server certificate validation - - export SWIFT_AUTH_INSECURE=1 - -And optionally this to configure the connect channel timeout, in seconds - - export SWIFT_CONNECTION_CHANNEL_TIMEOUT=60 - -And optionally this to configure the data channel timeout, in seconds - - export SWIFT_DATA_CHANNEL_TIMEOUT=60 - -Then run the tests with `go test` - -License -------- - -This is free software under the terms of MIT license (check COPYING file -included in this package). - -Contact and support -------------------- - -The project website is at: - -- https://github.com/ncw/swift - -There you can file bug reports, ask for help or contribute patches. - -Authors -------- - -- Nick Craig-Wood - -Contributors ------------- - -- Brian "bojo" Jones -- Janika Liiv -- Yamamoto, Hirotaka -- Stephen -- platformpurple -- Paul Querna -- Livio Soares -- thesyncim -- lsowen -- Sylvain Baubeau -- Chris Kastorff -- Dai HaoJun -- Hua Wang -- Fabian Ruff -- Arturo Reuschenbach Puncernau -- Petr Kotek -- Stefan Majewsky -- Cezar Sa Espinola -- Sam Gunaratne -- Richard Scothern -- Michel Couillard -- Christopher Waldon -- dennis -- hag -- Alexander Neumann -- eclipseo <30413512+eclipseo@users.noreply.github.com> -- Yuri Per -- Falk Reimann -- Arthur Paim Arnold -- Bruno Michel -- Charles Hsu -- Omar Ali -- Andreas Andersen -- kayrus -- CodeLingo Bot diff --git a/vendor/github.com/ncw/swift/auth.go b/vendor/github.com/ncw/swift/auth.go deleted file mode 100644 index 25654f429..000000000 --- a/vendor/github.com/ncw/swift/auth.go +++ /dev/null @@ -1,335 +0,0 @@ -package swift - -import ( - "bytes" - "encoding/json" - "net/http" - "net/url" - "strings" - "time" -) - -// Auth defines the operations needed to authenticate with swift -// -// This encapsulates the different authentication schemes in use -type Authenticator interface { - // Request creates an http.Request for the auth - return nil if not needed - Request(*Connection) (*http.Request, error) - // Response parses the http.Response - Response(resp *http.Response) error - // The public storage URL - set Internal to true to read - // internal/service net URL - StorageUrl(Internal bool) string - // The access token - Token() string - // The CDN url if available - CdnUrl() string -} - -// Expireser is an optional interface to read the expiration time of the token -type Expireser interface { - Expires() time.Time -} - -type CustomEndpointAuthenticator interface { - StorageUrlForEndpoint(endpointType EndpointType) string -} - -type EndpointType string - -const ( - // Use public URL as storage URL - EndpointTypePublic = EndpointType("public") - - // Use internal URL as storage URL - EndpointTypeInternal = EndpointType("internal") - - // Use admin URL as storage URL - EndpointTypeAdmin = EndpointType("admin") -) - -// newAuth - create a new Authenticator from the AuthUrl -// -// A hint for AuthVersion can be provided -func newAuth(c *Connection) (Authenticator, error) { - AuthVersion := c.AuthVersion - if AuthVersion == 0 { - if strings.Contains(c.AuthUrl, "v3") { - AuthVersion = 3 - } else if strings.Contains(c.AuthUrl, "v2") { - AuthVersion = 2 - } else if strings.Contains(c.AuthUrl, "v1") { - AuthVersion = 1 - } else { - return nil, newErrorf(500, "Can't find AuthVersion in AuthUrl - set explicitly") - } - } - switch AuthVersion { - case 1: - return &v1Auth{}, nil - case 2: - return &v2Auth{ - // Guess as to whether using API key or - // password it will try both eventually so - // this is just an optimization. - useApiKey: len(c.ApiKey) >= 32, - }, nil - case 3: - return &v3Auth{}, nil - } - return nil, newErrorf(500, "Auth Version %d not supported", AuthVersion) -} - -// ------------------------------------------------------------ - -// v1 auth -type v1Auth struct { - Headers http.Header // V1 auth: the authentication headers so extensions can access them -} - -// v1 Authentication - make request -func (auth *v1Auth) Request(c *Connection) (*http.Request, error) { - req, err := http.NewRequest("GET", c.AuthUrl, nil) - if err != nil { - return nil, err - } - req.Header.Set("User-Agent", c.UserAgent) - req.Header.Set("X-Auth-Key", c.ApiKey) - req.Header.Set("X-Auth-User", c.UserName) - return req, nil -} - -// v1 Authentication - read response -func (auth *v1Auth) Response(resp *http.Response) error { - auth.Headers = resp.Header - return nil -} - -// v1 Authentication - read storage url -func (auth *v1Auth) StorageUrl(Internal bool) string { - storageUrl := auth.Headers.Get("X-Storage-Url") - if Internal { - newUrl, err := url.Parse(storageUrl) - if err != nil { - return storageUrl - } - newUrl.Host = "snet-" + newUrl.Host - storageUrl = newUrl.String() - } - return storageUrl -} - -// v1 Authentication - read auth token -func (auth *v1Auth) Token() string { - return auth.Headers.Get("X-Auth-Token") -} - -// v1 Authentication - read cdn url -func (auth *v1Auth) CdnUrl() string { - return auth.Headers.Get("X-CDN-Management-Url") -} - -// ------------------------------------------------------------ - -// v2 Authentication -type v2Auth struct { - Auth *v2AuthResponse - Region string - useApiKey bool // if set will use API key not Password - useApiKeyOk bool // if set won't change useApiKey any more - notFirst bool // set after first run -} - -// v2 Authentication - make request -func (auth *v2Auth) Request(c *Connection) (*http.Request, error) { - auth.Region = c.Region - // Toggle useApiKey if not first run and not OK yet - if auth.notFirst && !auth.useApiKeyOk { - auth.useApiKey = !auth.useApiKey - } - auth.notFirst = true - // Create a V2 auth request for the body of the connection - var v2i interface{} - if !auth.useApiKey { - // Normal swift authentication - v2 := v2AuthRequest{} - v2.Auth.PasswordCredentials.UserName = c.UserName - v2.Auth.PasswordCredentials.Password = c.ApiKey - v2.Auth.Tenant = c.Tenant - v2.Auth.TenantId = c.TenantId - v2i = v2 - } else { - // Rackspace special with API Key - v2 := v2AuthRequestRackspace{} - v2.Auth.ApiKeyCredentials.UserName = c.UserName - v2.Auth.ApiKeyCredentials.ApiKey = c.ApiKey - v2.Auth.Tenant = c.Tenant - v2.Auth.TenantId = c.TenantId - v2i = v2 - } - body, err := json.Marshal(v2i) - if err != nil { - return nil, err - } - url := c.AuthUrl - if !strings.HasSuffix(url, "/") { - url += "/" - } - url += "tokens" - req, err := http.NewRequest("POST", url, bytes.NewBuffer(body)) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", c.UserAgent) - return req, nil -} - -// v2 Authentication - read response -func (auth *v2Auth) Response(resp *http.Response) error { - auth.Auth = new(v2AuthResponse) - err := readJson(resp, auth.Auth) - // If successfully read Auth then no need to toggle useApiKey any more - if err == nil { - auth.useApiKeyOk = true - } - return err -} - -// Finds the Endpoint Url of "type" from the v2AuthResponse using the -// Region if set or defaulting to the first one if not -// -// Returns "" if not found -func (auth *v2Auth) endpointUrl(Type string, endpointType EndpointType) string { - for _, catalog := range auth.Auth.Access.ServiceCatalog { - if catalog.Type == Type { - for _, endpoint := range catalog.Endpoints { - if auth.Region == "" || (auth.Region == endpoint.Region) { - switch endpointType { - case EndpointTypeInternal: - return endpoint.InternalUrl - case EndpointTypePublic: - return endpoint.PublicUrl - case EndpointTypeAdmin: - return endpoint.AdminUrl - default: - return "" - } - } - } - } - } - return "" -} - -// v2 Authentication - read storage url -// -// If Internal is true then it reads the private (internal / service -// net) URL. -func (auth *v2Auth) StorageUrl(Internal bool) string { - endpointType := EndpointTypePublic - if Internal { - endpointType = EndpointTypeInternal - } - return auth.StorageUrlForEndpoint(endpointType) -} - -// v2 Authentication - read storage url -// -// Use the indicated endpointType to choose a URL. -func (auth *v2Auth) StorageUrlForEndpoint(endpointType EndpointType) string { - return auth.endpointUrl("object-store", endpointType) -} - -// v2 Authentication - read auth token -func (auth *v2Auth) Token() string { - return auth.Auth.Access.Token.Id -} - -// v2 Authentication - read expires -func (auth *v2Auth) Expires() time.Time { - t, err := time.Parse(time.RFC3339, auth.Auth.Access.Token.Expires) - if err != nil { - return time.Time{} // return Zero if not parsed - } - return t -} - -// v2 Authentication - read cdn url -func (auth *v2Auth) CdnUrl() string { - return auth.endpointUrl("rax:object-cdn", EndpointTypePublic) -} - -// ------------------------------------------------------------ - -// V2 Authentication request -// -// http://docs.openstack.org/developer/keystone/api_curl_examples.html -// http://docs.rackspace.com/servers/api/v2/cs-gettingstarted/content/curl_auth.html -// http://docs.openstack.org/api/openstack-identity-service/2.0/content/POST_authenticate_v2.0_tokens_.html -type v2AuthRequest struct { - Auth struct { - PasswordCredentials struct { - UserName string `json:"username"` - Password string `json:"password"` - } `json:"passwordCredentials"` - Tenant string `json:"tenantName,omitempty"` - TenantId string `json:"tenantId,omitempty"` - } `json:"auth"` -} - -// V2 Authentication request - Rackspace variant -// -// http://docs.openstack.org/developer/keystone/api_curl_examples.html -// http://docs.rackspace.com/servers/api/v2/cs-gettingstarted/content/curl_auth.html -// http://docs.openstack.org/api/openstack-identity-service/2.0/content/POST_authenticate_v2.0_tokens_.html -type v2AuthRequestRackspace struct { - Auth struct { - ApiKeyCredentials struct { - UserName string `json:"username"` - ApiKey string `json:"apiKey"` - } `json:"RAX-KSKEY:apiKeyCredentials"` - Tenant string `json:"tenantName,omitempty"` - TenantId string `json:"tenantId,omitempty"` - } `json:"auth"` -} - -// V2 Authentication reply -// -// http://docs.openstack.org/developer/keystone/api_curl_examples.html -// http://docs.rackspace.com/servers/api/v2/cs-gettingstarted/content/curl_auth.html -// http://docs.openstack.org/api/openstack-identity-service/2.0/content/POST_authenticate_v2.0_tokens_.html -type v2AuthResponse struct { - Access struct { - ServiceCatalog []struct { - Endpoints []struct { - InternalUrl string - PublicUrl string - AdminUrl string - Region string - TenantId string - } - Name string - Type string - } - Token struct { - Expires string - Id string - Tenant struct { - Id string - Name string - } - } - User struct { - DefaultRegion string `json:"RAX-AUTH:defaultRegion"` - Id string - Name string - Roles []struct { - Description string - Id string - Name string - TenantId string - } - } - } -} diff --git a/vendor/github.com/ncw/swift/auth_v3.go b/vendor/github.com/ncw/swift/auth_v3.go deleted file mode 100644 index 1e34ad814..000000000 --- a/vendor/github.com/ncw/swift/auth_v3.go +++ /dev/null @@ -1,300 +0,0 @@ -package swift - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" - "strings" - "time" -) - -const ( - v3AuthMethodToken = "token" - v3AuthMethodPassword = "password" - v3AuthMethodApplicationCredential = "application_credential" - v3CatalogTypeObjectStore = "object-store" -) - -// V3 Authentication request -// http://docs.openstack.org/developer/keystone/api_curl_examples.html -// http://developer.openstack.org/api-ref-identity-v3.html -type v3AuthRequest struct { - Auth struct { - Identity struct { - Methods []string `json:"methods"` - Password *v3AuthPassword `json:"password,omitempty"` - Token *v3AuthToken `json:"token,omitempty"` - ApplicationCredential *v3AuthApplicationCredential `json:"application_credential,omitempty"` - } `json:"identity"` - Scope *v3Scope `json:"scope,omitempty"` - } `json:"auth"` -} - -type v3Scope struct { - Project *v3Project `json:"project,omitempty"` - Domain *v3Domain `json:"domain,omitempty"` - Trust *v3Trust `json:"OS-TRUST:trust,omitempty"` -} - -type v3Domain struct { - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` -} - -type v3Project struct { - Name string `json:"name,omitempty"` - Id string `json:"id,omitempty"` - Domain *v3Domain `json:"domain,omitempty"` -} - -type v3Trust struct { - Id string `json:"id"` -} - -type v3User struct { - Domain *v3Domain `json:"domain,omitempty"` - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Password string `json:"password,omitempty"` -} - -type v3AuthToken struct { - Id string `json:"id"` -} - -type v3AuthPassword struct { - User v3User `json:"user"` -} - -type v3AuthApplicationCredential struct { - Id string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Secret string `json:"secret,omitempty"` - User *v3User `json:"user,omitempty"` -} - -// V3 Authentication response -type v3AuthResponse struct { - Token struct { - ExpiresAt string `json:"expires_at"` - IssuedAt string `json:"issued_at"` - Methods []string - Roles []struct { - Id, Name string - Links struct { - Self string - } - } - - Project struct { - Domain struct { - Id, Name string - } - Id, Name string - } - - Catalog []struct { - Id, Namem, Type string - Endpoints []struct { - Id, Region_Id, Url, Region string - Interface EndpointType - } - } - - User struct { - Id, Name string - Domain struct { - Id, Name string - Links struct { - Self string - } - } - } - - Audit_Ids []string - } -} - -type v3Auth struct { - Region string - Auth *v3AuthResponse - Headers http.Header -} - -func (auth *v3Auth) Request(c *Connection) (*http.Request, error) { - auth.Region = c.Region - - var v3i interface{} - - v3 := v3AuthRequest{} - - if (c.ApplicationCredentialId != "" || c.ApplicationCredentialName != "") && c.ApplicationCredentialSecret != "" { - var user *v3User - - if c.ApplicationCredentialId != "" { - c.ApplicationCredentialName = "" - user = &v3User{} - } - - if user == nil && c.UserId != "" { - // UserID could be used without the domain information - user = &v3User{ - Id: c.UserId, - } - } - - if user == nil && c.UserName == "" { - // Make sure that Username or UserID are provided - return nil, fmt.Errorf("UserID or Name should be provided") - } - - if user == nil && c.DomainId != "" { - user = &v3User{ - Name: c.UserName, - Domain: &v3Domain{ - Id: c.DomainId, - }, - } - } - - if user == nil && c.Domain != "" { - user = &v3User{ - Name: c.UserName, - Domain: &v3Domain{ - Name: c.Domain, - }, - } - } - - // Make sure that DomainID or DomainName are provided among Username - if user == nil { - return nil, fmt.Errorf("DomainID or Domain should be provided") - } - - v3.Auth.Identity.Methods = []string{v3AuthMethodApplicationCredential} - v3.Auth.Identity.ApplicationCredential = &v3AuthApplicationCredential{ - Id: c.ApplicationCredentialId, - Name: c.ApplicationCredentialName, - Secret: c.ApplicationCredentialSecret, - User: user, - } - } else if c.UserName == "" && c.UserId == "" { - v3.Auth.Identity.Methods = []string{v3AuthMethodToken} - v3.Auth.Identity.Token = &v3AuthToken{Id: c.ApiKey} - } else { - v3.Auth.Identity.Methods = []string{v3AuthMethodPassword} - v3.Auth.Identity.Password = &v3AuthPassword{ - User: v3User{ - Name: c.UserName, - Id: c.UserId, - Password: c.ApiKey, - }, - } - - var domain *v3Domain - - if c.Domain != "" { - domain = &v3Domain{Name: c.Domain} - } else if c.DomainId != "" { - domain = &v3Domain{Id: c.DomainId} - } - v3.Auth.Identity.Password.User.Domain = domain - } - - if v3.Auth.Identity.Methods[0] != v3AuthMethodApplicationCredential { - if c.TrustId != "" { - v3.Auth.Scope = &v3Scope{Trust: &v3Trust{Id: c.TrustId}} - } else if c.TenantId != "" || c.Tenant != "" { - - v3.Auth.Scope = &v3Scope{Project: &v3Project{}} - - if c.TenantId != "" { - v3.Auth.Scope.Project.Id = c.TenantId - } else if c.Tenant != "" { - v3.Auth.Scope.Project.Name = c.Tenant - switch { - case c.TenantDomain != "": - v3.Auth.Scope.Project.Domain = &v3Domain{Name: c.TenantDomain} - case c.TenantDomainId != "": - v3.Auth.Scope.Project.Domain = &v3Domain{Id: c.TenantDomainId} - case c.Domain != "": - v3.Auth.Scope.Project.Domain = &v3Domain{Name: c.Domain} - case c.DomainId != "": - v3.Auth.Scope.Project.Domain = &v3Domain{Id: c.DomainId} - default: - v3.Auth.Scope.Project.Domain = &v3Domain{Name: "Default"} - } - } - } - } - - v3i = v3 - - body, err := json.Marshal(v3i) - - if err != nil { - return nil, err - } - - url := c.AuthUrl - if !strings.HasSuffix(url, "/") { - url += "/" - } - url += "auth/tokens" - req, err := http.NewRequest("POST", url, bytes.NewBuffer(body)) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", c.UserAgent) - return req, nil -} - -func (auth *v3Auth) Response(resp *http.Response) error { - auth.Auth = &v3AuthResponse{} - auth.Headers = resp.Header - err := readJson(resp, auth.Auth) - return err -} - -func (auth *v3Auth) endpointUrl(Type string, endpointType EndpointType) string { - for _, catalog := range auth.Auth.Token.Catalog { - if catalog.Type == Type { - for _, endpoint := range catalog.Endpoints { - if endpoint.Interface == endpointType && (auth.Region == "" || (auth.Region == endpoint.Region)) { - return endpoint.Url - } - } - } - } - return "" -} - -func (auth *v3Auth) StorageUrl(Internal bool) string { - endpointType := EndpointTypePublic - if Internal { - endpointType = EndpointTypeInternal - } - return auth.StorageUrlForEndpoint(endpointType) -} - -func (auth *v3Auth) StorageUrlForEndpoint(endpointType EndpointType) string { - return auth.endpointUrl("object-store", endpointType) -} - -func (auth *v3Auth) Token() string { - return auth.Headers.Get("X-Subject-Token") -} - -func (auth *v3Auth) Expires() time.Time { - t, err := time.Parse(time.RFC3339, auth.Auth.Token.ExpiresAt) - if err != nil { - return time.Time{} // return Zero if not parsed - } - return t -} - -func (auth *v3Auth) CdnUrl() string { - return "" -} diff --git a/vendor/github.com/ncw/swift/compatibility_1_0.go b/vendor/github.com/ncw/swift/compatibility_1_0.go deleted file mode 100644 index 7b69a757a..000000000 --- a/vendor/github.com/ncw/swift/compatibility_1_0.go +++ /dev/null @@ -1,28 +0,0 @@ -// Go 1.0 compatibility functions - -// +build !go1.1 - -package swift - -import ( - "log" - "net/http" - "time" -) - -// Cancel the request - doesn't work under < go 1.1 -func cancelRequest(transport http.RoundTripper, req *http.Request) { - log.Printf("Tried to cancel a request but couldn't - recompile with go 1.1") -} - -// Reset a timer - Doesn't work properly < go 1.1 -// -// This is quite hard to do properly under go < 1.1 so we do a crude -// approximation and hope that everyone upgrades to go 1.1 quickly -func resetTimer(t *time.Timer, d time.Duration) { - t.Stop() - // Very likely this doesn't actually work if we are already - // selecting on t.C. However we've stopped the original timer - // so won't break transfers but may not time them out :-( - *t = *time.NewTimer(d) -} diff --git a/vendor/github.com/ncw/swift/compatibility_1_1.go b/vendor/github.com/ncw/swift/compatibility_1_1.go deleted file mode 100644 index a4f9c3ab2..000000000 --- a/vendor/github.com/ncw/swift/compatibility_1_1.go +++ /dev/null @@ -1,24 +0,0 @@ -// Go 1.1 and later compatibility functions -// -// +build go1.1 - -package swift - -import ( - "net/http" - "time" -) - -// Cancel the request -func cancelRequest(transport http.RoundTripper, req *http.Request) { - if tr, ok := transport.(interface { - CancelRequest(*http.Request) - }); ok { - tr.CancelRequest(req) - } -} - -// Reset a timer -func resetTimer(t *time.Timer, d time.Duration) { - t.Reset(d) -} diff --git a/vendor/github.com/ncw/swift/compatibility_1_6.go b/vendor/github.com/ncw/swift/compatibility_1_6.go deleted file mode 100644 index b443d01d2..000000000 --- a/vendor/github.com/ncw/swift/compatibility_1_6.go +++ /dev/null @@ -1,23 +0,0 @@ -// +build go1.6 - -package swift - -import ( - "net/http" - "time" -) - -const IS_AT_LEAST_GO_16 = true - -func SetExpectContinueTimeout(tr *http.Transport, t time.Duration) { - tr.ExpectContinueTimeout = t -} - -func AddExpectAndTransferEncoding(req *http.Request, hasContentLength bool) { - if req.Body != nil { - req.Header.Add("Expect", "100-continue") - } - if !hasContentLength { - req.TransferEncoding = []string{"chunked"} - } -} diff --git a/vendor/github.com/ncw/swift/compatibility_not_1_6.go b/vendor/github.com/ncw/swift/compatibility_not_1_6.go deleted file mode 100644 index aabb44e2b..000000000 --- a/vendor/github.com/ncw/swift/compatibility_not_1_6.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !go1.6 - -package swift - -import ( - "net/http" - "time" -) - -const IS_AT_LEAST_GO_16 = false - -func SetExpectContinueTimeout(tr *http.Transport, t time.Duration) {} -func AddExpectAndTransferEncoding(req *http.Request, hasContentLength bool) {} diff --git a/vendor/github.com/ncw/swift/dlo.go b/vendor/github.com/ncw/swift/dlo.go deleted file mode 100644 index e2e2aa97e..000000000 --- a/vendor/github.com/ncw/swift/dlo.go +++ /dev/null @@ -1,136 +0,0 @@ -package swift - -import ( - "os" -) - -// DynamicLargeObjectCreateFile represents an open static large object -type DynamicLargeObjectCreateFile struct { - largeObjectCreateFile -} - -// DynamicLargeObjectCreateFile creates a dynamic large object -// returning an object which satisfies io.Writer, io.Seeker, io.Closer -// and io.ReaderFrom. The flags are as passes to the -// largeObjectCreate method. -func (c *Connection) DynamicLargeObjectCreateFile(opts *LargeObjectOpts) (LargeObjectFile, error) { - lo, err := c.largeObjectCreate(opts) - if err != nil { - return nil, err - } - - return withBuffer(opts, &DynamicLargeObjectCreateFile{ - largeObjectCreateFile: *lo, - }), nil -} - -// DynamicLargeObjectCreate creates or truncates an existing dynamic -// large object returning a writeable object. This sets opts.Flags to -// an appropriate value before calling DynamicLargeObjectCreateFile -func (c *Connection) DynamicLargeObjectCreate(opts *LargeObjectOpts) (LargeObjectFile, error) { - opts.Flags = os.O_TRUNC | os.O_CREATE - return c.DynamicLargeObjectCreateFile(opts) -} - -// DynamicLargeObjectDelete deletes a dynamic large object and all of its segments. -func (c *Connection) DynamicLargeObjectDelete(container string, path string) error { - return c.LargeObjectDelete(container, path) -} - -// DynamicLargeObjectMove moves a dynamic large object from srcContainer, srcObjectName to dstContainer, dstObjectName -func (c *Connection) DynamicLargeObjectMove(srcContainer string, srcObjectName string, dstContainer string, dstObjectName string) error { - info, headers, err := c.Object(dstContainer, srcObjectName) - if err != nil { - return err - } - - segmentContainer, segmentPath := parseFullPath(headers["X-Object-Manifest"]) - if err := c.createDLOManifest(dstContainer, dstObjectName, segmentContainer+"/"+segmentPath, info.ContentType); err != nil { - return err - } - - if err := c.ObjectDelete(srcContainer, srcObjectName); err != nil { - return err - } - - return nil -} - -// createDLOManifest creates a dynamic large object manifest -func (c *Connection) createDLOManifest(container string, objectName string, prefix string, contentType string) error { - headers := make(Headers) - headers["X-Object-Manifest"] = prefix - manifest, err := c.ObjectCreate(container, objectName, false, "", contentType, headers) - if err != nil { - return err - } - - if err := manifest.Close(); err != nil { - return err - } - - return nil -} - -// Close satisfies the io.Closer interface -func (file *DynamicLargeObjectCreateFile) Close() error { - return file.Flush() -} - -func (file *DynamicLargeObjectCreateFile) Flush() error { - err := file.conn.createDLOManifest(file.container, file.objectName, file.segmentContainer+"/"+file.prefix, file.contentType) - if err != nil { - return err - } - return file.conn.waitForSegmentsToShowUp(file.container, file.objectName, file.Size()) -} - -func (c *Connection) getAllDLOSegments(segmentContainer, segmentPath string) ([]Object, error) { - //a simple container listing works 99.9% of the time - segments, err := c.ObjectsAll(segmentContainer, &ObjectsOpts{Prefix: segmentPath}) - if err != nil { - return nil, err - } - - hasObjectName := make(map[string]struct{}) - for _, segment := range segments { - hasObjectName[segment.Name] = struct{}{} - } - - //The container listing might be outdated (i.e. not contain all existing - //segment objects yet) because of temporary inconsistency (Swift is only - //eventually consistent!). Check its completeness. - segmentNumber := 0 - for { - segmentNumber++ - segmentName := getSegment(segmentPath, segmentNumber) - if _, seen := hasObjectName[segmentName]; seen { - continue - } - - //This segment is missing in the container listing. Use a more reliable - //request to check its existence. (HEAD requests on segments are - //guaranteed to return the correct metadata, except for the pathological - //case of an outage of large parts of the Swift cluster or its network, - //since every segment is only written once.) - segment, _, err := c.Object(segmentContainer, segmentName) - switch err { - case nil: - //found new segment -> add it in the correct position and keep - //going, more might be missing - if segmentNumber <= len(segments) { - segments = append(segments[:segmentNumber], segments[segmentNumber-1:]...) - segments[segmentNumber-1] = segment - } else { - segments = append(segments, segment) - } - continue - case ObjectNotFound: - //This segment is missing. Since we upload segments sequentially, - //there won't be any more segments after it. - return segments, nil - default: - return nil, err //unexpected error - } - } -} diff --git a/vendor/github.com/ncw/swift/doc.go b/vendor/github.com/ncw/swift/doc.go deleted file mode 100644 index 44efde7bf..000000000 --- a/vendor/github.com/ncw/swift/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Package swift provides an easy to use interface to Swift / Openstack Object Storage / Rackspace Cloud Files - -Standard Usage - -Most of the work is done through the Container*() and Object*() methods. - -All methods are safe to use concurrently in multiple go routines. - -Object Versioning - -As defined by http://docs.openstack.org/api/openstack-object-storage/1.0/content/Object_Versioning-e1e3230.html#d6e983 one can create a container which allows for version control of files. The suggested method is to create a version container for holding all non-current files, and a current container for holding the latest version that the file points to. The container and objects inside it can be used in the standard manner, however, pushing a file multiple times will result in it being copied to the version container and the new file put in it's place. If the current file is deleted, the previous file in the version container will replace it. This means that if a file is updated 5 times, it must be deleted 5 times to be completely removed from the system. - -Rackspace Sub Module - -This module specifically allows the enabling/disabling of Rackspace Cloud File CDN management on a container. This is specific to the Rackspace API and not Swift/Openstack, therefore it has been placed in a submodule. One can easily create a RsConnection and use it like the standard Connection to access and manipulate containers and objects. - -*/ -package swift diff --git a/vendor/github.com/ncw/swift/largeobjects.go b/vendor/github.com/ncw/swift/largeobjects.go deleted file mode 100644 index bec640b00..000000000 --- a/vendor/github.com/ncw/swift/largeobjects.go +++ /dev/null @@ -1,448 +0,0 @@ -package swift - -import ( - "bufio" - "bytes" - "crypto/rand" - "crypto/sha1" - "encoding/hex" - "errors" - "fmt" - "io" - "os" - gopath "path" - "strconv" - "strings" - "time" -) - -// NotLargeObject is returned if an operation is performed on an object which isn't large. -var NotLargeObject = errors.New("Not a large object") - -// readAfterWriteTimeout defines the time we wait before an object appears after having been uploaded -var readAfterWriteTimeout = 15 * time.Second - -// readAfterWriteWait defines the time to sleep between two retries -var readAfterWriteWait = 200 * time.Millisecond - -// largeObjectCreateFile represents an open static or dynamic large object -type largeObjectCreateFile struct { - conn *Connection - container string - objectName string - currentLength int64 - filePos int64 - chunkSize int64 - segmentContainer string - prefix string - contentType string - checkHash bool - segments []Object - headers Headers - minChunkSize int64 -} - -func swiftSegmentPath(path string) (string, error) { - checksum := sha1.New() - random := make([]byte, 32) - if _, err := rand.Read(random); err != nil { - return "", err - } - path = hex.EncodeToString(checksum.Sum(append([]byte(path), random...))) - return strings.TrimLeft(strings.TrimRight("segments/"+path[0:3]+"/"+path[3:], "/"), "/"), nil -} - -func getSegment(segmentPath string, partNumber int) string { - return fmt.Sprintf("%s/%016d", segmentPath, partNumber) -} - -func parseFullPath(manifest string) (container string, prefix string) { - components := strings.SplitN(manifest, "/", 2) - container = components[0] - if len(components) > 1 { - prefix = components[1] - } - return container, prefix -} - -func (headers Headers) IsLargeObjectDLO() bool { - _, isDLO := headers["X-Object-Manifest"] - return isDLO -} - -func (headers Headers) IsLargeObjectSLO() bool { - _, isSLO := headers["X-Static-Large-Object"] - return isSLO -} - -func (headers Headers) IsLargeObject() bool { - return headers.IsLargeObjectSLO() || headers.IsLargeObjectDLO() -} - -func (c *Connection) getAllSegments(container string, path string, headers Headers) (string, []Object, error) { - if manifest, isDLO := headers["X-Object-Manifest"]; isDLO { - segmentContainer, segmentPath := parseFullPath(manifest) - segments, err := c.getAllDLOSegments(segmentContainer, segmentPath) - return segmentContainer, segments, err - } - if headers.IsLargeObjectSLO() { - return c.getAllSLOSegments(container, path) - } - return "", nil, NotLargeObject -} - -// LargeObjectOpts describes how a large object should be created -type LargeObjectOpts struct { - Container string // Name of container to place object - ObjectName string // Name of object - Flags int // Creation flags - CheckHash bool // If set Check the hash - Hash string // If set use this hash to check - ContentType string // Content-Type of the object - Headers Headers // Additional headers to upload the object with - ChunkSize int64 // Size of chunks of the object, defaults to 10MB if not set - MinChunkSize int64 // Minimum chunk size, automatically set for SLO's based on info - SegmentContainer string // Name of the container to place segments - SegmentPrefix string // Prefix to use for the segments - NoBuffer bool // Prevents using a bufio.Writer to write segments -} - -type LargeObjectFile interface { - io.Writer - io.Seeker - io.Closer - Size() int64 - Flush() error -} - -// largeObjectCreate creates a large object at opts.Container, opts.ObjectName. -// -// opts.Flags can have the following bits set -// os.TRUNC - remove the contents of the large object if it exists -// os.APPEND - write at the end of the large object -func (c *Connection) largeObjectCreate(opts *LargeObjectOpts) (*largeObjectCreateFile, error) { - var ( - segmentPath string - segmentContainer string - segments []Object - currentLength int64 - err error - ) - - if opts.SegmentPrefix != "" { - segmentPath = opts.SegmentPrefix - } else if segmentPath, err = swiftSegmentPath(opts.ObjectName); err != nil { - return nil, err - } - - if info, headers, err := c.Object(opts.Container, opts.ObjectName); err == nil { - if opts.Flags&os.O_TRUNC != 0 { - c.LargeObjectDelete(opts.Container, opts.ObjectName) - } else { - currentLength = info.Bytes - if headers.IsLargeObject() { - segmentContainer, segments, err = c.getAllSegments(opts.Container, opts.ObjectName, headers) - if err != nil { - return nil, err - } - if len(segments) > 0 { - segmentPath = gopath.Dir(segments[0].Name) - } - } else { - if err = c.ObjectMove(opts.Container, opts.ObjectName, opts.Container, getSegment(segmentPath, 1)); err != nil { - return nil, err - } - segments = append(segments, info) - } - } - } else if err != ObjectNotFound { - return nil, err - } - - // segmentContainer is not empty when the manifest already existed - if segmentContainer == "" { - if opts.SegmentContainer != "" { - segmentContainer = opts.SegmentContainer - } else { - segmentContainer = opts.Container + "_segments" - } - } - - file := &largeObjectCreateFile{ - conn: c, - checkHash: opts.CheckHash, - container: opts.Container, - objectName: opts.ObjectName, - chunkSize: opts.ChunkSize, - minChunkSize: opts.MinChunkSize, - headers: opts.Headers, - segmentContainer: segmentContainer, - prefix: segmentPath, - segments: segments, - currentLength: currentLength, - } - - if file.chunkSize == 0 { - file.chunkSize = 10 * 1024 * 1024 - } - - if file.minChunkSize > file.chunkSize { - file.chunkSize = file.minChunkSize - } - - if opts.Flags&os.O_APPEND != 0 { - file.filePos = currentLength - } - - return file, nil -} - -// LargeObjectDelete deletes the large object named by container, path -func (c *Connection) LargeObjectDelete(container string, objectName string) error { - _, headers, err := c.Object(container, objectName) - if err != nil { - return err - } - - var objects [][]string - if headers.IsLargeObject() { - segmentContainer, segments, err := c.getAllSegments(container, objectName, headers) - if err != nil { - return err - } - for _, obj := range segments { - objects = append(objects, []string{segmentContainer, obj.Name}) - } - } - objects = append(objects, []string{container, objectName}) - - info, err := c.cachedQueryInfo() - if err == nil && info.SupportsBulkDelete() && len(objects) > 0 { - filenames := make([]string, len(objects)) - for i, obj := range objects { - filenames[i] = obj[0] + "/" + obj[1] - } - _, err = c.doBulkDelete(filenames) - // Don't fail on ObjectNotFound because eventual consistency - // makes this situation normal. - if err != nil && err != Forbidden && err != ObjectNotFound { - return err - } - } else { - for _, obj := range objects { - if err := c.ObjectDelete(obj[0], obj[1]); err != nil { - return err - } - } - } - - return nil -} - -// LargeObjectGetSegments returns all the segments that compose an object -// If the object is a Dynamic Large Object (DLO), it just returns the objects -// that have the prefix as indicated by the manifest. -// If the object is a Static Large Object (SLO), it retrieves the JSON content -// of the manifest and return all the segments of it. -func (c *Connection) LargeObjectGetSegments(container string, path string) (string, []Object, error) { - _, headers, err := c.Object(container, path) - if err != nil { - return "", nil, err - } - - return c.getAllSegments(container, path, headers) -} - -// Seek sets the offset for the next write operation -func (file *largeObjectCreateFile) Seek(offset int64, whence int) (int64, error) { - switch whence { - case 0: - file.filePos = offset - case 1: - file.filePos += offset - case 2: - file.filePos = file.currentLength + offset - default: - return -1, fmt.Errorf("invalid value for whence") - } - if file.filePos < 0 { - return -1, fmt.Errorf("negative offset") - } - return file.filePos, nil -} - -func (file *largeObjectCreateFile) Size() int64 { - return file.currentLength -} - -func withLORetry(expectedSize int64, fn func() (Headers, int64, error)) (err error) { - endTimer := time.NewTimer(readAfterWriteTimeout) - defer endTimer.Stop() - waitingTime := readAfterWriteWait - for { - var headers Headers - var sz int64 - if headers, sz, err = fn(); err == nil { - if !headers.IsLargeObjectDLO() || (expectedSize == 0 && sz > 0) || expectedSize == sz { - return - } - } else { - return - } - waitTimer := time.NewTimer(waitingTime) - select { - case <-endTimer.C: - waitTimer.Stop() - err = fmt.Errorf("Timeout expired while waiting for object to have size == %d, got: %d", expectedSize, sz) - return - case <-waitTimer.C: - waitingTime *= 2 - } - } -} - -func (c *Connection) waitForSegmentsToShowUp(container, objectName string, expectedSize int64) (err error) { - err = withLORetry(expectedSize, func() (Headers, int64, error) { - var info Object - var headers Headers - info, headers, err = c.objectBase(container, objectName) - if err != nil { - return headers, 0, err - } - return headers, info.Bytes, nil - }) - return -} - -// Write satisfies the io.Writer interface -func (file *largeObjectCreateFile) Write(buf []byte) (int, error) { - var sz int64 - var relativeFilePos int - writeSegmentIdx := 0 - for i, obj := range file.segments { - if file.filePos < sz+obj.Bytes || (i == len(file.segments)-1 && file.filePos < sz+file.minChunkSize) { - relativeFilePos = int(file.filePos - sz) - break - } - writeSegmentIdx++ - sz += obj.Bytes - } - sizeToWrite := len(buf) - for offset := 0; offset < sizeToWrite; { - newSegment, n, err := file.writeSegment(buf[offset:], writeSegmentIdx, relativeFilePos) - if err != nil { - return 0, err - } - if writeSegmentIdx < len(file.segments) { - file.segments[writeSegmentIdx] = *newSegment - } else { - file.segments = append(file.segments, *newSegment) - } - offset += n - writeSegmentIdx++ - relativeFilePos = 0 - } - file.filePos += int64(sizeToWrite) - file.currentLength = 0 - for _, obj := range file.segments { - file.currentLength += obj.Bytes - } - return sizeToWrite, nil -} - -func (file *largeObjectCreateFile) writeSegment(buf []byte, writeSegmentIdx int, relativeFilePos int) (*Object, int, error) { - var ( - readers []io.Reader - existingSegment *Object - segmentSize int - ) - segmentName := getSegment(file.prefix, writeSegmentIdx+1) - sizeToRead := int(file.chunkSize) - if writeSegmentIdx < len(file.segments) { - existingSegment = &file.segments[writeSegmentIdx] - if writeSegmentIdx != len(file.segments)-1 { - sizeToRead = int(existingSegment.Bytes) - } - if relativeFilePos > 0 { - headers := make(Headers) - headers["Range"] = "bytes=0-" + strconv.FormatInt(int64(relativeFilePos-1), 10) - existingSegmentReader, _, err := file.conn.ObjectOpen(file.segmentContainer, segmentName, true, headers) - if err != nil { - return nil, 0, err - } - defer existingSegmentReader.Close() - sizeToRead -= relativeFilePos - segmentSize += relativeFilePos - readers = []io.Reader{existingSegmentReader} - } - } - if sizeToRead > len(buf) { - sizeToRead = len(buf) - } - segmentSize += sizeToRead - readers = append(readers, bytes.NewReader(buf[:sizeToRead])) - if existingSegment != nil && segmentSize < int(existingSegment.Bytes) { - headers := make(Headers) - headers["Range"] = "bytes=" + strconv.FormatInt(int64(segmentSize), 10) + "-" - tailSegmentReader, _, err := file.conn.ObjectOpen(file.segmentContainer, segmentName, true, headers) - if err != nil { - return nil, 0, err - } - defer tailSegmentReader.Close() - segmentSize = int(existingSegment.Bytes) - readers = append(readers, tailSegmentReader) - } - segmentReader := io.MultiReader(readers...) - headers, err := file.conn.ObjectPut(file.segmentContainer, segmentName, segmentReader, true, "", file.contentType, nil) - if err != nil { - return nil, 0, err - } - return &Object{Name: segmentName, Bytes: int64(segmentSize), Hash: headers["Etag"]}, sizeToRead, nil -} - -func withBuffer(opts *LargeObjectOpts, lo LargeObjectFile) LargeObjectFile { - if !opts.NoBuffer { - return &bufferedLargeObjectFile{ - LargeObjectFile: lo, - bw: bufio.NewWriterSize(lo, int(opts.ChunkSize)), - } - } - return lo -} - -type bufferedLargeObjectFile struct { - LargeObjectFile - bw *bufio.Writer -} - -func (blo *bufferedLargeObjectFile) Close() error { - err := blo.bw.Flush() - if err != nil { - return err - } - return blo.LargeObjectFile.Close() -} - -func (blo *bufferedLargeObjectFile) Write(p []byte) (n int, err error) { - return blo.bw.Write(p) -} - -func (blo *bufferedLargeObjectFile) Seek(offset int64, whence int) (int64, error) { - err := blo.bw.Flush() - if err != nil { - return 0, err - } - return blo.LargeObjectFile.Seek(offset, whence) -} - -func (blo *bufferedLargeObjectFile) Size() int64 { - return blo.LargeObjectFile.Size() + int64(blo.bw.Buffered()) -} - -func (blo *bufferedLargeObjectFile) Flush() error { - err := blo.bw.Flush() - if err != nil { - return err - } - return blo.LargeObjectFile.Flush() -} diff --git a/vendor/github.com/ncw/swift/meta.go b/vendor/github.com/ncw/swift/meta.go deleted file mode 100644 index 7e149e139..000000000 --- a/vendor/github.com/ncw/swift/meta.go +++ /dev/null @@ -1,174 +0,0 @@ -// Metadata manipulation in and out of Headers - -package swift - -import ( - "fmt" - "net/http" - "strconv" - "strings" - "time" -) - -// Metadata stores account, container or object metadata. -type Metadata map[string]string - -// Metadata gets the Metadata starting with the metaPrefix out of the Headers. -// -// The keys in the Metadata will be converted to lower case -func (h Headers) Metadata(metaPrefix string) Metadata { - m := Metadata{} - metaPrefix = http.CanonicalHeaderKey(metaPrefix) - for key, value := range h { - if strings.HasPrefix(key, metaPrefix) { - metaKey := strings.ToLower(key[len(metaPrefix):]) - m[metaKey] = value - } - } - return m -} - -// AccountMetadata converts Headers from account to a Metadata. -// -// The keys in the Metadata will be converted to lower case. -func (h Headers) AccountMetadata() Metadata { - return h.Metadata("X-Account-Meta-") -} - -// ContainerMetadata converts Headers from container to a Metadata. -// -// The keys in the Metadata will be converted to lower case. -func (h Headers) ContainerMetadata() Metadata { - return h.Metadata("X-Container-Meta-") -} - -// ObjectMetadata converts Headers from object to a Metadata. -// -// The keys in the Metadata will be converted to lower case. -func (h Headers) ObjectMetadata() Metadata { - return h.Metadata("X-Object-Meta-") -} - -// Headers convert the Metadata starting with the metaPrefix into a -// Headers. -// -// The keys in the Metadata will be converted from lower case to http -// Canonical (see http.CanonicalHeaderKey). -func (m Metadata) Headers(metaPrefix string) Headers { - h := Headers{} - for key, value := range m { - key = http.CanonicalHeaderKey(metaPrefix + key) - h[key] = value - } - return h -} - -// AccountHeaders converts the Metadata for the account. -func (m Metadata) AccountHeaders() Headers { - return m.Headers("X-Account-Meta-") -} - -// ContainerHeaders converts the Metadata for the container. -func (m Metadata) ContainerHeaders() Headers { - return m.Headers("X-Container-Meta-") -} - -// ObjectHeaders converts the Metadata for the object. -func (m Metadata) ObjectHeaders() Headers { - return m.Headers("X-Object-Meta-") -} - -// Turns a number of ns into a floating point string in seconds -// -// Trims trailing zeros and guaranteed to be perfectly accurate -func nsToFloatString(ns int64) string { - if ns < 0 { - return "-" + nsToFloatString(-ns) - } - result := fmt.Sprintf("%010d", ns) - split := len(result) - 9 - result, decimals := result[:split], result[split:] - decimals = strings.TrimRight(decimals, "0") - if decimals != "" { - result += "." - result += decimals - } - return result -} - -// Turns a floating point string in seconds into a ns integer -// -// Guaranteed to be perfectly accurate -func floatStringToNs(s string) (int64, error) { - const zeros = "000000000" - if point := strings.IndexRune(s, '.'); point >= 0 { - tail := s[point+1:] - if fill := 9 - len(tail); fill < 0 { - tail = tail[:9] - } else { - tail += zeros[:fill] - } - s = s[:point] + tail - } else if len(s) > 0 { // Make sure empty string produces an error - s += zeros - } - return strconv.ParseInt(s, 10, 64) -} - -// FloatStringToTime converts a floating point number string to a time.Time -// -// The string is floating point number of seconds since the epoch -// (Unix time). The number should be in fixed point format (not -// exponential), eg "1354040105.123456789" which represents the time -// "2012-11-27T18:15:05.123456789Z" -// -// Some care is taken to preserve all the accuracy in the time.Time -// (which wouldn't happen with a naive conversion through float64) so -// a round trip conversion won't change the data. -// -// If an error is returned then time will be returned as the zero time. -func FloatStringToTime(s string) (t time.Time, err error) { - ns, err := floatStringToNs(s) - if err != nil { - return - } - t = time.Unix(0, ns) - return -} - -// TimeToFloatString converts a time.Time object to a floating point string -// -// The string is floating point number of seconds since the epoch -// (Unix time). The number is in fixed point format (not -// exponential), eg "1354040105.123456789" which represents the time -// "2012-11-27T18:15:05.123456789Z". Trailing zeros will be dropped -// from the output. -// -// Some care is taken to preserve all the accuracy in the time.Time -// (which wouldn't happen with a naive conversion through float64) so -// a round trip conversion won't change the data. -func TimeToFloatString(t time.Time) string { - return nsToFloatString(t.UnixNano()) -} - -// GetModTime reads a modification time (mtime) from a Metadata object -// -// This is a defacto standard (used in the official python-swiftclient -// amongst others) for storing the modification time (as read using -// os.Stat) for an object. It is stored using the key 'mtime', which -// for example when written to an object will be 'X-Object-Meta-Mtime'. -// -// If an error is returned then time will be returned as the zero time. -func (m Metadata) GetModTime() (t time.Time, err error) { - return FloatStringToTime(m["mtime"]) -} - -// SetModTime writes an modification time (mtime) to a Metadata object -// -// This is a defacto standard (used in the official python-swiftclient -// amongst others) for storing the modification time (as read using -// os.Stat) for an object. It is stored using the key 'mtime', which -// for example when written to an object will be 'X-Object-Meta-Mtime'. -func (m Metadata) SetModTime(t time.Time) { - m["mtime"] = TimeToFloatString(t) -} diff --git a/vendor/github.com/ncw/swift/notes.txt b/vendor/github.com/ncw/swift/notes.txt deleted file mode 100644 index f738552cd..000000000 --- a/vendor/github.com/ncw/swift/notes.txt +++ /dev/null @@ -1,55 +0,0 @@ -Notes on Go Swift -================= - -Make a builder style interface like the Google Go APIs? Advantages -are that it is easy to add named methods to the service object to do -specific things. Slightly less efficient. Not sure about how to -return extra stuff though - in an object? - -Make a container struct so these could be methods on it? - -Make noResponse check for 204? - -Make storage public so it can be extended easily? - -Rename to go-swift to match user agent string? - -Reconnect on auth error - 401 when token expires isn't tested - -Make more api compatible with python cloudfiles? - -Retry operations on timeout / network errors? -- also 408 error -- GET requests only? - -Make Connection thread safe - whenever it is changed take a write lock whenever it is read from a read lock - -Add extra headers field to Connection (for via etc) - -Make errors use an error heirachy then can catch them with a type assertion - - Error(...) - ObjectCorrupted{ Error } - -Make a Debug flag in connection for logging stuff - -Object If-Match, If-None-Match, If-Modified-Since, If-Unmodified-Since etc - -Object range - -Object create, update with X-Delete-At or X-Delete-After - -Large object support -- check uploads are less than 5GB in normal mode? - -Access control CORS? - -Swift client retries and backs off for all types of errors - -Implement net error interface? - -type Error interface { - error - Timeout() bool // Is the error a timeout? - Temporary() bool // Is the error temporary? -} diff --git a/vendor/github.com/ncw/swift/slo.go b/vendor/github.com/ncw/swift/slo.go deleted file mode 100644 index 6a10ddfc0..000000000 --- a/vendor/github.com/ncw/swift/slo.go +++ /dev/null @@ -1,171 +0,0 @@ -package swift - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/url" - "os" -) - -// StaticLargeObjectCreateFile represents an open static large object -type StaticLargeObjectCreateFile struct { - largeObjectCreateFile -} - -var SLONotSupported = errors.New("SLO not supported") - -type swiftSegment struct { - Path string `json:"path,omitempty"` - Etag string `json:"etag,omitempty"` - Size int64 `json:"size_bytes,omitempty"` - // When uploading a manifest, the attributes must be named `path`, `etag` and `size_bytes` - // but when querying the JSON content of a manifest with the `multipart-manifest=get` - // parameter, Swift names those attributes `name`, `hash` and `bytes`. - // We use all the different attributes names in this structure to be able to use - // the same structure for both uploading and retrieving. - Name string `json:"name,omitempty"` - Hash string `json:"hash,omitempty"` - Bytes int64 `json:"bytes,omitempty"` - ContentType string `json:"content_type,omitempty"` - LastModified string `json:"last_modified,omitempty"` -} - -// StaticLargeObjectCreateFile creates a static large object returning -// an object which satisfies io.Writer, io.Seeker, io.Closer and -// io.ReaderFrom. The flags are as passed to the largeObjectCreate -// method. -func (c *Connection) StaticLargeObjectCreateFile(opts *LargeObjectOpts) (LargeObjectFile, error) { - info, err := c.cachedQueryInfo() - if err != nil || !info.SupportsSLO() { - return nil, SLONotSupported - } - realMinChunkSize := info.SLOMinSegmentSize() - if realMinChunkSize > opts.MinChunkSize { - opts.MinChunkSize = realMinChunkSize - } - lo, err := c.largeObjectCreate(opts) - if err != nil { - return nil, err - } - return withBuffer(opts, &StaticLargeObjectCreateFile{ - largeObjectCreateFile: *lo, - }), nil -} - -// StaticLargeObjectCreate creates or truncates an existing static -// large object returning a writeable object. This sets opts.Flags to -// an appropriate value before calling StaticLargeObjectCreateFile -func (c *Connection) StaticLargeObjectCreate(opts *LargeObjectOpts) (LargeObjectFile, error) { - opts.Flags = os.O_TRUNC | os.O_CREATE - return c.StaticLargeObjectCreateFile(opts) -} - -// StaticLargeObjectDelete deletes a static large object and all of its segments. -func (c *Connection) StaticLargeObjectDelete(container string, path string) error { - info, err := c.cachedQueryInfo() - if err != nil || !info.SupportsSLO() { - return SLONotSupported - } - return c.LargeObjectDelete(container, path) -} - -// StaticLargeObjectMove moves a static large object from srcContainer, srcObjectName to dstContainer, dstObjectName -func (c *Connection) StaticLargeObjectMove(srcContainer string, srcObjectName string, dstContainer string, dstObjectName string) error { - swiftInfo, err := c.cachedQueryInfo() - if err != nil || !swiftInfo.SupportsSLO() { - return SLONotSupported - } - info, headers, err := c.Object(srcContainer, srcObjectName) - if err != nil { - return err - } - - container, segments, err := c.getAllSegments(srcContainer, srcObjectName, headers) - if err != nil { - return err - } - - //copy only metadata during move (other headers might not be safe for copying) - headers = headers.ObjectMetadata().ObjectHeaders() - - if err := c.createSLOManifest(dstContainer, dstObjectName, info.ContentType, container, segments, headers); err != nil { - return err - } - - if err := c.ObjectDelete(srcContainer, srcObjectName); err != nil { - return err - } - - return nil -} - -// createSLOManifest creates a static large object manifest -func (c *Connection) createSLOManifest(container string, path string, contentType string, segmentContainer string, segments []Object, h Headers) error { - sloSegments := make([]swiftSegment, len(segments)) - for i, segment := range segments { - sloSegments[i].Path = fmt.Sprintf("%s/%s", segmentContainer, segment.Name) - sloSegments[i].Etag = segment.Hash - sloSegments[i].Size = segment.Bytes - } - - content, err := json.Marshal(sloSegments) - if err != nil { - return err - } - - values := url.Values{} - values.Set("multipart-manifest", "put") - if _, err := c.objectPut(container, path, bytes.NewBuffer(content), false, "", contentType, h, values); err != nil { - return err - } - - return nil -} - -func (file *StaticLargeObjectCreateFile) Close() error { - return file.Flush() -} - -func (file *StaticLargeObjectCreateFile) Flush() error { - if err := file.conn.createSLOManifest(file.container, file.objectName, file.contentType, file.segmentContainer, file.segments, file.headers); err != nil { - return err - } - return file.conn.waitForSegmentsToShowUp(file.container, file.objectName, file.Size()) -} - -func (c *Connection) getAllSLOSegments(container, path string) (string, []Object, error) { - var ( - segmentList []swiftSegment - segments []Object - segPath string - segmentContainer string - ) - - values := url.Values{} - values.Set("multipart-manifest", "get") - - file, _, err := c.objectOpen(container, path, true, nil, values) - if err != nil { - return "", nil, err - } - - content, err := ioutil.ReadAll(file) - if err != nil { - return "", nil, err - } - - json.Unmarshal(content, &segmentList) - for _, segment := range segmentList { - segmentContainer, segPath = parseFullPath(segment.Name[1:]) - segments = append(segments, Object{ - Name: segPath, - Bytes: segment.Bytes, - Hash: segment.Hash, - }) - } - - return segmentContainer, segments, nil -} diff --git a/vendor/github.com/ncw/swift/swift.go b/vendor/github.com/ncw/swift/swift.go deleted file mode 100644 index 72ede2493..000000000 --- a/vendor/github.com/ncw/swift/swift.go +++ /dev/null @@ -1,2243 +0,0 @@ -package swift - -import ( - "bufio" - "bytes" - "crypto/hmac" - "crypto/md5" - "crypto/sha1" - "encoding/hex" - "encoding/json" - "fmt" - "hash" - "io" - "io/ioutil" - "mime" - "net/http" - "net/url" - "os" - "path" - "strconv" - "strings" - "sync" - "time" -) - -const ( - DefaultUserAgent = "goswift/1.0" // Default user agent - DefaultRetries = 3 // Default number of retries on token expiry - TimeFormat = "2006-01-02T15:04:05" // Python date format for json replies parsed as UTC - UploadTar = "tar" // Data format specifier for Connection.BulkUpload(). - UploadTarGzip = "tar.gz" // Data format specifier for Connection.BulkUpload(). - UploadTarBzip2 = "tar.bz2" // Data format specifier for Connection.BulkUpload(). - allContainersLimit = 10000 // Number of containers to fetch at once - allObjectsLimit = 10000 // Number objects to fetch at once - allObjectsChanLimit = 1000 // ...when fetching to a channel -) - -// ObjectType is the type of the swift object, regular, static large, -// or dynamic large. -type ObjectType int - -// Values that ObjectType can take -const ( - RegularObjectType ObjectType = iota - StaticLargeObjectType - DynamicLargeObjectType -) - -// Connection holds the details of the connection to the swift server. -// -// You need to provide UserName, ApiKey and AuthUrl when you create a -// connection then call Authenticate on it. -// -// The auth version in use will be detected from the AuthURL - you can -// override this with the AuthVersion parameter. -// -// If using v2 auth you can also set Region in the Connection -// structure. If you don't set Region you will get the default region -// which may not be what you want. -// -// For reference some common AuthUrls looks like this: -// -// Rackspace US https://auth.api.rackspacecloud.com/v1.0 -// Rackspace UK https://lon.auth.api.rackspacecloud.com/v1.0 -// Rackspace v2 https://identity.api.rackspacecloud.com/v2.0 -// Memset Memstore UK https://auth.storage.memset.com/v1.0 -// Memstore v2 https://auth.storage.memset.com/v2.0 -// -// When using Google Appengine you must provide the Connection with an -// appengine-specific Transport: -// -// import ( -// "appengine/urlfetch" -// "fmt" -// "github.com/ncw/swift" -// ) -// -// func handler(w http.ResponseWriter, r *http.Request) { -// ctx := appengine.NewContext(r) -// tr := urlfetch.Transport{Context: ctx} -// c := swift.Connection{ -// UserName: "user", -// ApiKey: "key", -// AuthUrl: "auth_url", -// Transport: tr, -// } -// _ := c.Authenticate() -// containers, _ := c.ContainerNames(nil) -// fmt.Fprintf(w, "containers: %q", containers) -// } -// -// If you don't supply a Transport, one is made which relies on -// http.ProxyFromEnvironment (http://golang.org/pkg/net/http/#ProxyFromEnvironment). -// This means that the connection will respect the HTTP proxy specified by the -// environment variables $HTTP_PROXY and $NO_PROXY. -type Connection struct { - // Parameters - fill these in before calling Authenticate - // They are all optional except UserName, ApiKey and AuthUrl - Domain string // User's domain name - DomainId string // User's domain Id - UserName string // UserName for api - UserId string // User Id - ApiKey string // Key for api access - ApplicationCredentialId string // Application Credential ID - ApplicationCredentialName string // Application Credential Name - ApplicationCredentialSecret string // Application Credential Secret - AuthUrl string // Auth URL - Retries int // Retries on error (default is 3) - UserAgent string // Http User agent (default goswift/1.0) - ConnectTimeout time.Duration // Connect channel timeout (default 10s) - Timeout time.Duration // Data channel timeout (default 60s) - Region string // Region to use eg "LON", "ORD" - default is use first region (v2,v3 auth only) - AuthVersion int // Set to 1, 2 or 3 or leave at 0 for autodetect - Internal bool // Set this to true to use the the internal / service network - Tenant string // Name of the tenant (v2,v3 auth only) - TenantId string // Id of the tenant (v2,v3 auth only) - EndpointType EndpointType // Endpoint type (v2,v3 auth only) (default is public URL unless Internal is set) - TenantDomain string // Name of the tenant's domain (v3 auth only), only needed if it differs from the user domain - TenantDomainId string // Id of the tenant's domain (v3 auth only), only needed if it differs the from user domain - TrustId string // Id of the trust (v3 auth only) - Transport http.RoundTripper `json:"-" xml:"-"` // Optional specialised http.Transport (eg. for Google Appengine) - // These are filled in after Authenticate is called as are the defaults for above - StorageUrl string - AuthToken string - Expires time.Time // time the token expires, may be Zero if unknown - client *http.Client - Auth Authenticator `json:"-" xml:"-"` // the current authenticator - authLock sync.Mutex // lock when R/W StorageUrl, AuthToken, Auth - // swiftInfo is filled after QueryInfo is called - swiftInfo SwiftInfo -} - -// setFromEnv reads the value that param points to (it must be a -// pointer), if it isn't the zero value then it reads the environment -// variable name passed in, parses it according to the type and writes -// it to the pointer. -func setFromEnv(param interface{}, name string) (err error) { - val := os.Getenv(name) - if val == "" { - return - } - switch result := param.(type) { - case *string: - if *result == "" { - *result = val - } - case *int: - if *result == 0 { - *result, err = strconv.Atoi(val) - } - case *bool: - if *result == false { - *result, err = strconv.ParseBool(val) - } - case *time.Duration: - if *result == 0 { - *result, err = time.ParseDuration(val) - } - case *EndpointType: - if *result == EndpointType("") { - *result = EndpointType(val) - } - default: - return newErrorf(0, "can't set var of type %T", param) - } - return err -} - -// ApplyEnvironment reads environment variables and applies them to -// the Connection structure. It won't overwrite any parameters which -// are already set in the Connection struct. -// -// To make a new Connection object entirely from the environment you -// would do: -// -// c := new(Connection) -// err := c.ApplyEnvironment() -// if err != nil { log.Fatal(err) } -// -// The naming of these variables follows the official Openstack naming -// scheme so it should be compatible with OpenStack rc files. -// -// For v1 authentication (obsolete) -// ST_AUTH - Auth URL -// ST_USER - UserName for api -// ST_KEY - Key for api access -// -// For v2 authentication -// OS_AUTH_URL - Auth URL -// OS_USERNAME - UserName for api -// OS_PASSWORD - Key for api access -// OS_TENANT_NAME - Name of the tenant -// OS_TENANT_ID - Id of the tenant -// OS_REGION_NAME - Region to use - default is use first region -// -// For v3 authentication -// OS_AUTH_URL - Auth URL -// OS_USERNAME - UserName for api -// OS_USER_ID - User Id -// OS_PASSWORD - Key for api access -// OS_APPLICATION_CREDENTIAL_ID - Application Credential ID -// OS_APPLICATION_CREDENTIAL_NAME - Application Credential Name -// OS_APPLICATION_CREDENTIAL_SECRET - Application Credential Secret -// OS_USER_DOMAIN_NAME - User's domain name -// OS_USER_DOMAIN_ID - User's domain Id -// OS_PROJECT_NAME - Name of the project -// OS_PROJECT_DOMAIN_NAME - Name of the tenant's domain, only needed if it differs from the user domain -// OS_PROJECT_DOMAIN_ID - Id of the tenant's domain, only needed if it differs the from user domain -// OS_TRUST_ID - If of the trust -// OS_REGION_NAME - Region to use - default is use first region -// -// Other -// OS_ENDPOINT_TYPE - Endpoint type public, internal or admin -// ST_AUTH_VERSION - Choose auth version - 1, 2 or 3 or leave at 0 for autodetect -// -// For manual authentication -// OS_STORAGE_URL - storage URL from alternate authentication -// OS_AUTH_TOKEN - Auth Token from alternate authentication -// -// Library specific -// GOSWIFT_RETRIES - Retries on error (default is 3) -// GOSWIFT_USER_AGENT - HTTP User agent (default goswift/1.0) -// GOSWIFT_CONNECT_TIMEOUT - Connect channel timeout with unit, eg "10s", "100ms" (default "10s") -// GOSWIFT_TIMEOUT - Data channel timeout with unit, eg "10s", "100ms" (default "60s") -// GOSWIFT_INTERNAL - Set this to "true" to use the the internal network (obsolete - use OS_ENDPOINT_TYPE) -func (c *Connection) ApplyEnvironment() (err error) { - for _, item := range []struct { - result interface{} - name string - }{ - // Environment variables - keep in same order as Connection - {&c.Domain, "OS_USER_DOMAIN_NAME"}, - {&c.DomainId, "OS_USER_DOMAIN_ID"}, - {&c.UserName, "OS_USERNAME"}, - {&c.UserId, "OS_USER_ID"}, - {&c.ApiKey, "OS_PASSWORD"}, - {&c.ApplicationCredentialId, "OS_APPLICATION_CREDENTIAL_ID"}, - {&c.ApplicationCredentialName, "OS_APPLICATION_CREDENTIAL_NAME"}, - {&c.ApplicationCredentialSecret, "OS_APPLICATION_CREDENTIAL_SECRET"}, - {&c.AuthUrl, "OS_AUTH_URL"}, - {&c.Retries, "GOSWIFT_RETRIES"}, - {&c.UserAgent, "GOSWIFT_USER_AGENT"}, - {&c.ConnectTimeout, "GOSWIFT_CONNECT_TIMEOUT"}, - {&c.Timeout, "GOSWIFT_TIMEOUT"}, - {&c.Region, "OS_REGION_NAME"}, - {&c.AuthVersion, "ST_AUTH_VERSION"}, - {&c.Internal, "GOSWIFT_INTERNAL"}, - {&c.Tenant, "OS_TENANT_NAME"}, //v2 - {&c.Tenant, "OS_PROJECT_NAME"}, // v3 - {&c.TenantId, "OS_TENANT_ID"}, - {&c.EndpointType, "OS_ENDPOINT_TYPE"}, - {&c.TenantDomain, "OS_PROJECT_DOMAIN_NAME"}, - {&c.TenantDomainId, "OS_PROJECT_DOMAIN_ID"}, - {&c.TrustId, "OS_TRUST_ID"}, - {&c.StorageUrl, "OS_STORAGE_URL"}, - {&c.AuthToken, "OS_AUTH_TOKEN"}, - // v1 auth alternatives - {&c.ApiKey, "ST_KEY"}, - {&c.UserName, "ST_USER"}, - {&c.AuthUrl, "ST_AUTH"}, - } { - err = setFromEnv(item.result, item.name) - if err != nil { - return newErrorf(0, "failed to read env var %q: %v", item.name, err) - } - } - return nil -} - -// Error - all errors generated by this package are of this type. Other error -// may be passed on from library functions though. -type Error struct { - StatusCode int // HTTP status code if relevant or 0 if not - Text string -} - -// Error satisfy the error interface. -func (e *Error) Error() string { - return e.Text -} - -// newError make a new error from a string. -func newError(StatusCode int, Text string) *Error { - return &Error{ - StatusCode: StatusCode, - Text: Text, - } -} - -// newErrorf makes a new error from sprintf parameters. -func newErrorf(StatusCode int, Text string, Parameters ...interface{}) *Error { - return newError(StatusCode, fmt.Sprintf(Text, Parameters...)) -} - -// errorMap defines http error codes to error mappings. -type errorMap map[int]error - -var ( - // Specific Errors you might want to check for equality - NotModified = newError(304, "Not Modified") - BadRequest = newError(400, "Bad Request") - AuthorizationFailed = newError(401, "Authorization Failed") - ContainerNotFound = newError(404, "Container Not Found") - ContainerNotEmpty = newError(409, "Container Not Empty") - ObjectNotFound = newError(404, "Object Not Found") - ObjectCorrupted = newError(422, "Object Corrupted") - TimeoutError = newError(408, "Timeout when reading or writing data") - Forbidden = newError(403, "Operation forbidden") - TooLargeObject = newError(413, "Too Large Object") - RateLimit = newError(498, "Rate Limit") - TooManyRequests = newError(429, "TooManyRequests") - - // Mappings for authentication errors - authErrorMap = errorMap{ - 400: BadRequest, - 401: AuthorizationFailed, - 403: Forbidden, - } - - // Mappings for container errors - ContainerErrorMap = errorMap{ - 400: BadRequest, - 403: Forbidden, - 404: ContainerNotFound, - 409: ContainerNotEmpty, - 498: RateLimit, - } - - // Mappings for object errors - objectErrorMap = errorMap{ - 304: NotModified, - 400: BadRequest, - 403: Forbidden, - 404: ObjectNotFound, - 413: TooLargeObject, - 422: ObjectCorrupted, - 429: TooManyRequests, - 498: RateLimit, - } -) - -// checkClose is used to check the return from Close in a defer -// statement. -func checkClose(c io.Closer, err *error) { - cerr := c.Close() - if *err == nil { - *err = cerr - } -} - -// drainAndClose discards all data from rd and closes it. -// If an error occurs during Read, it is discarded. -func drainAndClose(rd io.ReadCloser, err *error) { - if rd == nil { - return - } - - _, _ = io.Copy(ioutil.Discard, rd) - cerr := rd.Close() - if err != nil && *err == nil { - *err = cerr - } -} - -// parseHeaders checks a response for errors and translates into -// standard errors if necessary. If an error is returned, resp.Body -// has been drained and closed. -func (c *Connection) parseHeaders(resp *http.Response, errorMap errorMap) error { - if errorMap != nil { - if err, ok := errorMap[resp.StatusCode]; ok { - drainAndClose(resp.Body, nil) - return err - } - } - if resp.StatusCode < 200 || resp.StatusCode > 299 { - drainAndClose(resp.Body, nil) - return newErrorf(resp.StatusCode, "HTTP Error: %d: %s", resp.StatusCode, resp.Status) - } - return nil -} - -// readHeaders returns a Headers object from the http.Response. -// -// If it receives multiple values for a key (which should never -// happen) it will use the first one -func readHeaders(resp *http.Response) Headers { - headers := Headers{} - for key, values := range resp.Header { - headers[key] = values[0] - } - return headers -} - -// Headers stores HTTP headers (can only have one of each header like Swift). -type Headers map[string]string - -// Does an http request using the running timer passed in -func (c *Connection) doTimeoutRequest(timer *time.Timer, req *http.Request) (*http.Response, error) { - // Do the request in the background so we can check the timeout - type result struct { - resp *http.Response - err error - } - done := make(chan result, 1) - go func() { - resp, err := c.client.Do(req) - done <- result{resp, err} - }() - // Wait for the read or the timeout - select { - case r := <-done: - return r.resp, r.err - case <-timer.C: - // Kill the connection on timeout so we don't leak sockets or goroutines - cancelRequest(c.Transport, req) - return nil, TimeoutError - } - panic("unreachable") // For Go 1.0 -} - -// Set defaults for any unset values -// -// Call with authLock held -func (c *Connection) setDefaults() { - if c.UserAgent == "" { - c.UserAgent = DefaultUserAgent - } - if c.Retries == 0 { - c.Retries = DefaultRetries - } - if c.ConnectTimeout == 0 { - c.ConnectTimeout = 10 * time.Second - } - if c.Timeout == 0 { - c.Timeout = 60 * time.Second - } - if c.Transport == nil { - t := &http.Transport{ - // TLSClientConfig: &tls.Config{RootCAs: pool}, - // DisableCompression: true, - Proxy: http.ProxyFromEnvironment, - // Half of linux's default open files limit (1024). - MaxIdleConnsPerHost: 512, - } - SetExpectContinueTimeout(t, 5*time.Second) - c.Transport = t - } - if c.client == nil { - c.client = &http.Client{ - // CheckRedirect: redirectPolicyFunc, - Transport: c.Transport, - } - } -} - -// Authenticate connects to the Swift server. -// -// If you don't call it before calling one of the connection methods -// then it will be called for you on the first access. -func (c *Connection) Authenticate() (err error) { - c.authLock.Lock() - defer c.authLock.Unlock() - return c.authenticate() -} - -// Internal implementation of Authenticate -// -// Call with authLock held -func (c *Connection) authenticate() (err error) { - c.setDefaults() - - // Flush the keepalives connection - if we are - // re-authenticating then stuff has gone wrong - flushKeepaliveConnections(c.Transport) - - if c.Auth == nil { - c.Auth, err = newAuth(c) - if err != nil { - return - } - } - - retries := 1 -again: - var req *http.Request - req, err = c.Auth.Request(c) - if err != nil { - return - } - if req != nil { - timer := time.NewTimer(c.ConnectTimeout) - defer timer.Stop() - var resp *http.Response - resp, err = c.doTimeoutRequest(timer, req) - if err != nil { - return - } - defer func() { - drainAndClose(resp.Body, &err) - // Flush the auth connection - we don't want to keep - // it open if keepalives were enabled - flushKeepaliveConnections(c.Transport) - }() - if err = c.parseHeaders(resp, authErrorMap); err != nil { - // Try again for a limited number of times on - // AuthorizationFailed or BadRequest. This allows us - // to try some alternate forms of the request - if (err == AuthorizationFailed || err == BadRequest) && retries > 0 { - retries-- - goto again - } - return - } - err = c.Auth.Response(resp) - if err != nil { - return - } - } - if customAuth, isCustom := c.Auth.(CustomEndpointAuthenticator); isCustom && c.EndpointType != "" { - c.StorageUrl = customAuth.StorageUrlForEndpoint(c.EndpointType) - } else { - c.StorageUrl = c.Auth.StorageUrl(c.Internal) - } - c.AuthToken = c.Auth.Token() - if do, ok := c.Auth.(Expireser); ok { - c.Expires = do.Expires() - } else { - c.Expires = time.Time{} - } - - if !c.authenticated() { - err = newError(0, "Response didn't have storage url and auth token") - return - } - return -} - -// Get an authToken and url -// -// The Url may be updated if it needed to authenticate using the OnReAuth function -func (c *Connection) getUrlAndAuthToken(targetUrlIn string, OnReAuth func() (string, error)) (targetUrlOut, authToken string, err error) { - c.authLock.Lock() - defer c.authLock.Unlock() - targetUrlOut = targetUrlIn - if !c.authenticated() { - err = c.authenticate() - if err != nil { - return - } - if OnReAuth != nil { - targetUrlOut, err = OnReAuth() - if err != nil { - return - } - } - } - authToken = c.AuthToken - return -} - -// flushKeepaliveConnections is called to flush pending requests after an error. -func flushKeepaliveConnections(transport http.RoundTripper) { - if tr, ok := transport.(interface { - CloseIdleConnections() - }); ok { - tr.CloseIdleConnections() - } -} - -// UnAuthenticate removes the authentication from the Connection. -func (c *Connection) UnAuthenticate() { - c.authLock.Lock() - c.StorageUrl = "" - c.AuthToken = "" - c.authLock.Unlock() -} - -// Authenticated returns a boolean to show if the current connection -// is authenticated. -// -// Doesn't actually check the credentials against the server. -func (c *Connection) Authenticated() bool { - c.authLock.Lock() - defer c.authLock.Unlock() - return c.authenticated() -} - -// Internal version of Authenticated() -// -// Call with authLock held -func (c *Connection) authenticated() bool { - if c.StorageUrl == "" || c.AuthToken == "" { - return false - } - if c.Expires.IsZero() { - return true - } - timeUntilExpiry := c.Expires.Sub(time.Now()) - return timeUntilExpiry >= 60*time.Second -} - -// SwiftInfo contains the JSON object returned by Swift when the /info -// route is queried. The object contains, among others, the Swift version, -// the enabled middlewares and their configuration -type SwiftInfo map[string]interface{} - -func (i SwiftInfo) SupportsBulkDelete() bool { - _, val := i["bulk_delete"] - return val -} - -func (i SwiftInfo) SupportsSLO() bool { - _, val := i["slo"] - return val -} - -func (i SwiftInfo) SLOMinSegmentSize() int64 { - if slo, ok := i["slo"].(map[string]interface{}); ok { - val, _ := slo["min_segment_size"].(float64) - return int64(val) - } - return 1 -} - -// Discover Swift configuration by doing a request against /info -func (c *Connection) QueryInfo() (infos SwiftInfo, err error) { - infoUrl, err := url.Parse(c.StorageUrl) - if err != nil { - return nil, err - } - infoUrl.Path = path.Join(infoUrl.Path, "..", "..", "info") - resp, err := c.client.Get(infoUrl.String()) - if err == nil { - if resp.StatusCode != http.StatusOK { - drainAndClose(resp.Body, nil) - return nil, fmt.Errorf("Invalid status code for info request: %d", resp.StatusCode) - } - err = readJson(resp, &infos) - if err == nil { - c.authLock.Lock() - c.swiftInfo = infos - c.authLock.Unlock() - } - return infos, err - } - return nil, err -} - -func (c *Connection) cachedQueryInfo() (infos SwiftInfo, err error) { - c.authLock.Lock() - infos = c.swiftInfo - c.authLock.Unlock() - if infos == nil { - infos, err = c.QueryInfo() - if err != nil { - return - } - } - return infos, nil -} - -// RequestOpts contains parameters for Connection.storage. -type RequestOpts struct { - Container string - ObjectName string - Operation string - Parameters url.Values - Headers Headers - ErrorMap errorMap - NoResponse bool - Body io.Reader - Retries int - // if set this is called on re-authentication to refresh the targetUrl - OnReAuth func() (string, error) -} - -// Call runs a remote command on the targetUrl, returns a -// response, headers and possible error. -// -// operation is GET, HEAD etc -// container is the name of a container -// Any other parameters (if not None) are added to the targetUrl -// -// Returns a response or an error. If response is returned then -// the resp.Body must be read completely and -// resp.Body.Close() must be called on it, unless noResponse is set in -// which case the body will be closed in this function -// -// If "Content-Length" is set in p.Headers it will be used - this can -// be used to override the default chunked transfer encoding for -// uploads. -// -// This will Authenticate if necessary, and re-authenticate if it -// receives a 401 error which means the token has expired -// -// This method is exported so extensions can call it. -func (c *Connection) Call(targetUrl string, p RequestOpts) (resp *http.Response, headers Headers, err error) { - c.authLock.Lock() - c.setDefaults() - c.authLock.Unlock() - retries := p.Retries - if retries == 0 { - retries = c.Retries - } - var req *http.Request - for { - var authToken string - if targetUrl, authToken, err = c.getUrlAndAuthToken(targetUrl, p.OnReAuth); err != nil { - return //authentication failure - } - var URL *url.URL - URL, err = url.Parse(targetUrl) - if err != nil { - return - } - if p.Container != "" { - URL.Path += "/" + p.Container - if p.ObjectName != "" { - URL.Path += "/" + p.ObjectName - } - } - if p.Parameters != nil { - URL.RawQuery = p.Parameters.Encode() - } - timer := time.NewTimer(c.ConnectTimeout) - defer timer.Stop() - reader := p.Body - if reader != nil { - reader = newWatchdogReader(reader, c.Timeout, timer) - } - req, err = http.NewRequest(p.Operation, URL.String(), reader) - if err != nil { - return - } - if p.Headers != nil { - for k, v := range p.Headers { - // Set ContentLength in req if the user passed it in in the headers - if k == "Content-Length" { - req.ContentLength, err = strconv.ParseInt(v, 10, 64) - if err != nil { - err = fmt.Errorf("Invalid %q header %q: %v", k, v, err) - return - } - } else { - req.Header.Add(k, v) - } - } - } - req.Header.Add("User-Agent", c.UserAgent) - req.Header.Add("X-Auth-Token", authToken) - - _, hasCL := p.Headers["Content-Length"] - AddExpectAndTransferEncoding(req, hasCL) - - resp, err = c.doTimeoutRequest(timer, req) - if err != nil { - if (p.Operation == "HEAD" || p.Operation == "GET") && retries > 0 { - retries-- - continue - } - return - } - // Check to see if token has expired - if resp.StatusCode == 401 && retries > 0 { - drainAndClose(resp.Body, nil) - c.UnAuthenticate() - retries-- - } else { - break - } - } - - headers = readHeaders(resp) - if err = c.parseHeaders(resp, p.ErrorMap); err != nil { - return - } - if p.NoResponse { - drainAndClose(resp.Body, &err) - if err != nil { - return - } - } else { - // Cancel the request on timeout - cancel := func() { - cancelRequest(c.Transport, req) - } - // Wrap resp.Body to make it obey an idle timeout - resp.Body = newTimeoutReader(resp.Body, c.Timeout, cancel) - } - return -} - -// storage runs a remote command on a the storage url, returns a -// response, headers and possible error. -// -// operation is GET, HEAD etc -// container is the name of a container -// Any other parameters (if not None) are added to the storage url -// -// Returns a response or an error. If response is returned then -// resp.Body.Close() must be called on it, unless noResponse is set in -// which case the body will be closed in this function -// -// This will Authenticate if necessary, and re-authenticate if it -// receives a 401 error which means the token has expired -func (c *Connection) storage(p RequestOpts) (resp *http.Response, headers Headers, err error) { - p.OnReAuth = func() (string, error) { - return c.StorageUrl, nil - } - c.authLock.Lock() - url := c.StorageUrl - c.authLock.Unlock() - return c.Call(url, p) -} - -// readLines reads the response into an array of strings. -// -// Closes the response when done -func readLines(resp *http.Response) (lines []string, err error) { - defer drainAndClose(resp.Body, &err) - reader := bufio.NewReader(resp.Body) - buffer := bytes.NewBuffer(make([]byte, 0, 128)) - var part []byte - var prefix bool - for { - if part, prefix, err = reader.ReadLine(); err != nil { - break - } - buffer.Write(part) - if !prefix { - lines = append(lines, buffer.String()) - buffer.Reset() - } - } - if err == io.EOF { - err = nil - } - return -} - -// readJson reads the response into the json type passed in -// -// Closes the response when done -func readJson(resp *http.Response, result interface{}) (err error) { - defer drainAndClose(resp.Body, &err) - decoder := json.NewDecoder(resp.Body) - return decoder.Decode(result) -} - -/* ------------------------------------------------------------ */ - -// ContainersOpts is options for Containers() and ContainerNames() -type ContainersOpts struct { - Limit int // For an integer value n, limits the number of results to at most n values. - Prefix string // Given a string value x, return container names matching the specified prefix. - Marker string // Given a string value x, return container names greater in value than the specified marker. - EndMarker string // Given a string value x, return container names less in value than the specified marker. - Headers Headers // Any additional HTTP headers - can be nil -} - -// parse the ContainerOpts -func (opts *ContainersOpts) parse() (url.Values, Headers) { - v := url.Values{} - var h Headers - if opts != nil { - if opts.Limit > 0 { - v.Set("limit", strconv.Itoa(opts.Limit)) - } - if opts.Prefix != "" { - v.Set("prefix", opts.Prefix) - } - if opts.Marker != "" { - v.Set("marker", opts.Marker) - } - if opts.EndMarker != "" { - v.Set("end_marker", opts.EndMarker) - } - h = opts.Headers - } - return v, h -} - -// ContainerNames returns a slice of names of containers in this account. -func (c *Connection) ContainerNames(opts *ContainersOpts) ([]string, error) { - v, h := opts.parse() - resp, _, err := c.storage(RequestOpts{ - Operation: "GET", - Parameters: v, - ErrorMap: ContainerErrorMap, - Headers: h, - }) - if err != nil { - return nil, err - } - lines, err := readLines(resp) - return lines, err -} - -// Container contains information about a container -type Container struct { - Name string // Name of the container - Count int64 // Number of objects in the container - Bytes int64 // Total number of bytes used in the container -} - -// Containers returns a slice of structures with full information as -// described in Container. -func (c *Connection) Containers(opts *ContainersOpts) ([]Container, error) { - v, h := opts.parse() - v.Set("format", "json") - resp, _, err := c.storage(RequestOpts{ - Operation: "GET", - Parameters: v, - ErrorMap: ContainerErrorMap, - Headers: h, - }) - if err != nil { - return nil, err - } - var containers []Container - err = readJson(resp, &containers) - return containers, err -} - -// containersAllOpts makes a copy of opts if set or makes a new one and -// overrides Limit and Marker -func containersAllOpts(opts *ContainersOpts) *ContainersOpts { - var newOpts ContainersOpts - if opts != nil { - newOpts = *opts - } - if newOpts.Limit == 0 { - newOpts.Limit = allContainersLimit - } - newOpts.Marker = "" - return &newOpts -} - -// ContainersAll is like Containers but it returns all the Containers -// -// It calls Containers multiple times using the Marker parameter -// -// It has a default Limit parameter but you may pass in your own -func (c *Connection) ContainersAll(opts *ContainersOpts) ([]Container, error) { - opts = containersAllOpts(opts) - containers := make([]Container, 0) - for { - newContainers, err := c.Containers(opts) - if err != nil { - return nil, err - } - containers = append(containers, newContainers...) - if len(newContainers) < opts.Limit { - break - } - opts.Marker = newContainers[len(newContainers)-1].Name - } - return containers, nil -} - -// ContainerNamesAll is like ContainerNamess but it returns all the Containers -// -// It calls ContainerNames multiple times using the Marker parameter -// -// It has a default Limit parameter but you may pass in your own -func (c *Connection) ContainerNamesAll(opts *ContainersOpts) ([]string, error) { - opts = containersAllOpts(opts) - containers := make([]string, 0) - for { - newContainers, err := c.ContainerNames(opts) - if err != nil { - return nil, err - } - containers = append(containers, newContainers...) - if len(newContainers) < opts.Limit { - break - } - opts.Marker = newContainers[len(newContainers)-1] - } - return containers, nil -} - -/* ------------------------------------------------------------ */ - -// ObjectOpts is options for Objects() and ObjectNames() -type ObjectsOpts struct { - Limit int // For an integer value n, limits the number of results to at most n values. - Marker string // Given a string value x, return object names greater in value than the specified marker. - EndMarker string // Given a string value x, return object names less in value than the specified marker - Prefix string // For a string value x, causes the results to be limited to object names beginning with the substring x. - Path string // For a string value x, return the object names nested in the pseudo path - Delimiter rune // For a character c, return all the object names nested in the container - Headers Headers // Any additional HTTP headers - can be nil -} - -// parse reads values out of ObjectsOpts -func (opts *ObjectsOpts) parse() (url.Values, Headers) { - v := url.Values{} - var h Headers - if opts != nil { - if opts.Limit > 0 { - v.Set("limit", strconv.Itoa(opts.Limit)) - } - if opts.Marker != "" { - v.Set("marker", opts.Marker) - } - if opts.EndMarker != "" { - v.Set("end_marker", opts.EndMarker) - } - if opts.Prefix != "" { - v.Set("prefix", opts.Prefix) - } - if opts.Path != "" { - v.Set("path", opts.Path) - } - if opts.Delimiter != 0 { - v.Set("delimiter", string(opts.Delimiter)) - } - h = opts.Headers - } - return v, h -} - -// ObjectNames returns a slice of names of objects in a given container. -func (c *Connection) ObjectNames(container string, opts *ObjectsOpts) ([]string, error) { - v, h := opts.parse() - resp, _, err := c.storage(RequestOpts{ - Container: container, - Operation: "GET", - Parameters: v, - ErrorMap: ContainerErrorMap, - Headers: h, - }) - if err != nil { - return nil, err - } - return readLines(resp) -} - -// Object contains information about an object -type Object struct { - Name string `json:"name"` // object name - ContentType string `json:"content_type"` // eg application/directory - Bytes int64 `json:"bytes"` // size in bytes - ServerLastModified string `json:"last_modified"` // Last modified time, eg '2011-06-30T08:20:47.736680' as a string supplied by the server - LastModified time.Time // Last modified time converted to a time.Time - Hash string `json:"hash"` // MD5 hash, eg "d41d8cd98f00b204e9800998ecf8427e" - SLOHash string `json:"slo_etag"` // MD5 hash of all segments' MD5 hash, eg "d41d8cd98f00b204e9800998ecf8427e" - PseudoDirectory bool // Set when using delimiter to show that this directory object does not really exist - SubDir string `json:"subdir"` // returned only when using delimiter to mark "pseudo directories" - ObjectType ObjectType // type of this object -} - -// Objects returns a slice of Object with information about each -// object in the container. -// -// If Delimiter is set in the opts then PseudoDirectory may be set, -// with ContentType 'application/directory'. These are not real -// objects but represent directories of objects which haven't had an -// object created for them. -func (c *Connection) Objects(container string, opts *ObjectsOpts) ([]Object, error) { - v, h := opts.parse() - v.Set("format", "json") - resp, _, err := c.storage(RequestOpts{ - Container: container, - Operation: "GET", - Parameters: v, - ErrorMap: ContainerErrorMap, - Headers: h, - }) - if err != nil { - return nil, err - } - var objects []Object - err = readJson(resp, &objects) - // Convert Pseudo directories and dates - for i := range objects { - object := &objects[i] - if object.SubDir != "" { - object.Name = object.SubDir - object.PseudoDirectory = true - object.ContentType = "application/directory" - } - if object.ServerLastModified != "" { - // 2012-11-11T14:49:47.887250 - // - // Remove fractional seconds if present. This - // then keeps it consistent with Object - // which can only return timestamps accurate - // to 1 second - // - // The TimeFormat will parse fractional - // seconds if desired though - datetime := strings.SplitN(object.ServerLastModified, ".", 2)[0] - object.LastModified, err = time.Parse(TimeFormat, datetime) - if err != nil { - return nil, err - } - } - if object.SLOHash != "" { - object.ObjectType = StaticLargeObjectType - } - } - return objects, err -} - -// objectsAllOpts makes a copy of opts if set or makes a new one and -// overrides Limit and Marker -func objectsAllOpts(opts *ObjectsOpts, Limit int) *ObjectsOpts { - var newOpts ObjectsOpts - if opts != nil { - newOpts = *opts - } - if newOpts.Limit == 0 { - newOpts.Limit = Limit - } - newOpts.Marker = "" - return &newOpts -} - -// A closure defined by the caller to iterate through all objects -// -// Call Objects or ObjectNames from here with the *ObjectOpts passed in -// -// Do whatever is required with the results then return them -type ObjectsWalkFn func(*ObjectsOpts) (interface{}, error) - -// ObjectsWalk is uses to iterate through all the objects in chunks as -// returned by Objects or ObjectNames using the Marker and Limit -// parameters in the ObjectsOpts. -// -// Pass in a closure `walkFn` which calls Objects or ObjectNames with -// the *ObjectsOpts passed to it and does something with the results. -// -// Errors will be returned from this function -// -// It has a default Limit parameter but you may pass in your own -func (c *Connection) ObjectsWalk(container string, opts *ObjectsOpts, walkFn ObjectsWalkFn) error { - opts = objectsAllOpts(opts, allObjectsChanLimit) - for { - objects, err := walkFn(opts) - if err != nil { - return err - } - var n int - var last string - switch objects := objects.(type) { - case []string: - n = len(objects) - if n > 0 { - last = objects[len(objects)-1] - } - case []Object: - n = len(objects) - if n > 0 { - last = objects[len(objects)-1].Name - } - default: - panic("Unknown type returned to ObjectsWalk") - } - if n < opts.Limit { - break - } - opts.Marker = last - } - return nil -} - -// ObjectsAll is like Objects but it returns an unlimited number of Objects in a slice -// -// It calls Objects multiple times using the Marker parameter -func (c *Connection) ObjectsAll(container string, opts *ObjectsOpts) ([]Object, error) { - objects := make([]Object, 0) - err := c.ObjectsWalk(container, opts, func(opts *ObjectsOpts) (interface{}, error) { - newObjects, err := c.Objects(container, opts) - if err == nil { - objects = append(objects, newObjects...) - } - return newObjects, err - }) - return objects, err -} - -// ObjectNamesAll is like ObjectNames but it returns all the Objects -// -// It calls ObjectNames multiple times using the Marker parameter -// -// It has a default Limit parameter but you may pass in your own -func (c *Connection) ObjectNamesAll(container string, opts *ObjectsOpts) ([]string, error) { - objects := make([]string, 0) - err := c.ObjectsWalk(container, opts, func(opts *ObjectsOpts) (interface{}, error) { - newObjects, err := c.ObjectNames(container, opts) - if err == nil { - objects = append(objects, newObjects...) - } - return newObjects, err - }) - return objects, err -} - -// Account contains information about this account. -type Account struct { - BytesUsed int64 // total number of bytes used - Containers int64 // total number of containers - Objects int64 // total number of objects -} - -// getInt64FromHeader is a helper function to decode int64 from header. -func getInt64FromHeader(resp *http.Response, header string) (result int64, err error) { - value := resp.Header.Get(header) - result, err = strconv.ParseInt(value, 10, 64) - if err != nil { - err = newErrorf(0, "Bad Header '%s': '%s': %s", header, value, err) - } - return -} - -// Account returns info about the account in an Account struct. -func (c *Connection) Account() (info Account, headers Headers, err error) { - var resp *http.Response - resp, headers, err = c.storage(RequestOpts{ - Operation: "HEAD", - ErrorMap: ContainerErrorMap, - NoResponse: true, - }) - if err != nil { - return - } - // Parse the headers into a dict - // - // {'Accept-Ranges': 'bytes', - // 'Content-Length': '0', - // 'Date': 'Tue, 05 Jul 2011 16:37:06 GMT', - // 'X-Account-Bytes-Used': '316598182', - // 'X-Account-Container-Count': '4', - // 'X-Account-Object-Count': '1433'} - if info.BytesUsed, err = getInt64FromHeader(resp, "X-Account-Bytes-Used"); err != nil { - return - } - if info.Containers, err = getInt64FromHeader(resp, "X-Account-Container-Count"); err != nil { - return - } - if info.Objects, err = getInt64FromHeader(resp, "X-Account-Object-Count"); err != nil { - return - } - return -} - -// AccountUpdate adds, replaces or remove account metadata. -// -// Add or update keys by mentioning them in the Headers. -// -// Remove keys by setting them to an empty string. -func (c *Connection) AccountUpdate(h Headers) error { - _, _, err := c.storage(RequestOpts{ - Operation: "POST", - ErrorMap: ContainerErrorMap, - NoResponse: true, - Headers: h, - }) - return err -} - -// ContainerCreate creates a container. -// -// If you don't want to add Headers just pass in nil -// -// No error is returned if it already exists but the metadata if any will be updated. -func (c *Connection) ContainerCreate(container string, h Headers) error { - _, _, err := c.storage(RequestOpts{ - Container: container, - Operation: "PUT", - ErrorMap: ContainerErrorMap, - NoResponse: true, - Headers: h, - }) - return err -} - -// ContainerDelete deletes a container. -// -// May return ContainerDoesNotExist or ContainerNotEmpty -func (c *Connection) ContainerDelete(container string) error { - _, _, err := c.storage(RequestOpts{ - Container: container, - Operation: "DELETE", - ErrorMap: ContainerErrorMap, - NoResponse: true, - }) - return err -} - -// Container returns info about a single container including any -// metadata in the headers. -func (c *Connection) Container(container string) (info Container, headers Headers, err error) { - var resp *http.Response - resp, headers, err = c.storage(RequestOpts{ - Container: container, - Operation: "HEAD", - ErrorMap: ContainerErrorMap, - NoResponse: true, - }) - if err != nil { - return - } - // Parse the headers into the struct - info.Name = container - if info.Bytes, err = getInt64FromHeader(resp, "X-Container-Bytes-Used"); err != nil { - return - } - if info.Count, err = getInt64FromHeader(resp, "X-Container-Object-Count"); err != nil { - return - } - return -} - -// ContainerUpdate adds, replaces or removes container metadata. -// -// Add or update keys by mentioning them in the Metadata. -// -// Remove keys by setting them to an empty string. -// -// Container metadata can only be read with Container() not with Containers(). -func (c *Connection) ContainerUpdate(container string, h Headers) error { - _, _, err := c.storage(RequestOpts{ - Container: container, - Operation: "POST", - ErrorMap: ContainerErrorMap, - NoResponse: true, - Headers: h, - }) - return err -} - -// ------------------------------------------------------------ - -// ObjectCreateFile represents a swift object open for writing -type ObjectCreateFile struct { - checkHash bool // whether we are checking the hash - pipeReader *io.PipeReader // pipe for the caller to use - pipeWriter *io.PipeWriter - hash hash.Hash // hash being build up as we go along - done chan struct{} // signals when the upload has finished - resp *http.Response // valid when done has signalled - err error // ditto - headers Headers // ditto -} - -// Write bytes to the object - see io.Writer -func (file *ObjectCreateFile) Write(p []byte) (n int, err error) { - n, err = file.pipeWriter.Write(p) - if err == io.ErrClosedPipe { - if file.err != nil { - return 0, file.err - } - return 0, newError(500, "Write on closed file") - } - if err == nil && file.checkHash { - _, _ = file.hash.Write(p) - } - return -} - -// Close the object and checks the md5sum if it was required. -// -// Also returns any other errors from the server (eg container not -// found) so it is very important to check the errors on this method. -func (file *ObjectCreateFile) Close() error { - // Close the body - err := file.pipeWriter.Close() - if err != nil { - return err - } - - // Wait for the HTTP operation to complete - <-file.done - - // Check errors - if file.err != nil { - return file.err - } - if file.checkHash { - receivedMd5 := strings.ToLower(file.headers["Etag"]) - calculatedMd5 := fmt.Sprintf("%x", file.hash.Sum(nil)) - if receivedMd5 != calculatedMd5 { - return ObjectCorrupted - } - } - return nil -} - -// Headers returns the response headers from the created object if the upload -// has been completed. The Close() method must be called on an ObjectCreateFile -// before this method. -func (file *ObjectCreateFile) Headers() (Headers, error) { - // error out if upload is not complete. - select { - case <-file.done: - default: - return nil, fmt.Errorf("Cannot get metadata, object upload failed or has not yet completed.") - } - return file.headers, nil -} - -// Check it satisfies the interface -var _ io.WriteCloser = &ObjectCreateFile{} - -// objectPutHeaders create a set of headers for a PUT -// -// It guesses the contentType from the objectName if it isn't set -// -// checkHash may be changed -func objectPutHeaders(objectName string, checkHash *bool, Hash string, contentType string, h Headers) Headers { - if contentType == "" { - contentType = mime.TypeByExtension(path.Ext(objectName)) - if contentType == "" { - contentType = "application/octet-stream" - } - } - // Meta stuff - extraHeaders := map[string]string{ - "Content-Type": contentType, - } - for key, value := range h { - extraHeaders[key] = value - } - if Hash != "" { - extraHeaders["Etag"] = Hash - *checkHash = false // the server will do it - } - return extraHeaders -} - -// ObjectCreate creates or updates the object in the container. It -// returns an io.WriteCloser you should write the contents to. You -// MUST call Close() on it and you MUST check the error return from -// Close(). -// -// If checkHash is True then it will calculate the MD5 Hash of the -// file as it is being uploaded and check it against that returned -// from the server. If it is wrong then it will return -// ObjectCorrupted on Close() -// -// If you know the MD5 hash of the object ahead of time then set the -// Hash parameter and it will be sent to the server (as an Etag -// header) and the server will check the MD5 itself after the upload, -// and this will return ObjectCorrupted on Close() if it is incorrect. -// -// If you don't want any error protection (not recommended) then set -// checkHash to false and Hash to "". -// -// If contentType is set it will be used, otherwise one will be -// guessed from objectName using mime.TypeByExtension -func (c *Connection) ObjectCreate(container string, objectName string, checkHash bool, Hash string, contentType string, h Headers) (file *ObjectCreateFile, err error) { - extraHeaders := objectPutHeaders(objectName, &checkHash, Hash, contentType, h) - pipeReader, pipeWriter := io.Pipe() - file = &ObjectCreateFile{ - hash: md5.New(), - checkHash: checkHash, - pipeReader: pipeReader, - pipeWriter: pipeWriter, - done: make(chan struct{}), - } - // Run the PUT in the background piping it data - go func() { - opts := RequestOpts{ - Container: container, - ObjectName: objectName, - Operation: "PUT", - Headers: extraHeaders, - Body: pipeReader, - NoResponse: true, - ErrorMap: objectErrorMap, - } - file.resp, file.headers, file.err = c.storage(opts) - // Signal finished - pipeReader.Close() - close(file.done) - }() - return -} - -func (c *Connection) objectPut(container string, objectName string, contents io.Reader, checkHash bool, Hash string, contentType string, h Headers, parameters url.Values) (headers Headers, err error) { - extraHeaders := objectPutHeaders(objectName, &checkHash, Hash, contentType, h) - hash := md5.New() - var body io.Reader = contents - if checkHash { - body = io.TeeReader(contents, hash) - } - _, headers, err = c.storage(RequestOpts{ - Container: container, - ObjectName: objectName, - Operation: "PUT", - Headers: extraHeaders, - Body: body, - NoResponse: true, - ErrorMap: objectErrorMap, - Parameters: parameters, - }) - if err != nil { - return - } - if checkHash { - receivedMd5 := strings.ToLower(headers["Etag"]) - calculatedMd5 := fmt.Sprintf("%x", hash.Sum(nil)) - if receivedMd5 != calculatedMd5 { - err = ObjectCorrupted - return - } - } - return -} - -// ObjectPut creates or updates the path in the container from -// contents. contents should be an open io.Reader which will have all -// its contents read. -// -// This is a low level interface. -// -// If checkHash is True then it will calculate the MD5 Hash of the -// file as it is being uploaded and check it against that returned -// from the server. If it is wrong then it will return -// ObjectCorrupted. -// -// If you know the MD5 hash of the object ahead of time then set the -// Hash parameter and it will be sent to the server (as an Etag -// header) and the server will check the MD5 itself after the upload, -// and this will return ObjectCorrupted if it is incorrect. -// -// If you don't want any error protection (not recommended) then set -// checkHash to false and Hash to "". -// -// If contentType is set it will be used, otherwise one will be -// guessed from objectName using mime.TypeByExtension -func (c *Connection) ObjectPut(container string, objectName string, contents io.Reader, checkHash bool, Hash string, contentType string, h Headers) (headers Headers, err error) { - return c.objectPut(container, objectName, contents, checkHash, Hash, contentType, h, nil) -} - -// ObjectPutBytes creates an object from a []byte in a container. -// -// This is a simplified interface which checks the MD5. -func (c *Connection) ObjectPutBytes(container string, objectName string, contents []byte, contentType string) (err error) { - buf := bytes.NewBuffer(contents) - h := Headers{"Content-Length": strconv.Itoa(len(contents))} - _, err = c.ObjectPut(container, objectName, buf, true, "", contentType, h) - return -} - -// ObjectPutString creates an object from a string in a container. -// -// This is a simplified interface which checks the MD5 -func (c *Connection) ObjectPutString(container string, objectName string, contents string, contentType string) (err error) { - buf := strings.NewReader(contents) - h := Headers{"Content-Length": strconv.Itoa(len(contents))} - _, err = c.ObjectPut(container, objectName, buf, true, "", contentType, h) - return -} - -// ObjectOpenFile represents a swift object open for reading -type ObjectOpenFile struct { - connection *Connection // stored copy of Connection used in Open - container string // stored copy of container used in Open - objectName string // stored copy of objectName used in Open - headers Headers // stored copy of headers used in Open - resp *http.Response // http connection - body io.Reader // read data from this - checkHash bool // true if checking MD5 - hash hash.Hash // currently accumulating MD5 - bytes int64 // number of bytes read on this connection - eof bool // whether we have read end of file - pos int64 // current position when reading - lengthOk bool // whether length is valid - length int64 // length of the object if read - seeked bool // whether we have seeked this file or not - overSeeked bool // set if we have seeked to the end or beyond -} - -// Read bytes from the object - see io.Reader -func (file *ObjectOpenFile) Read(p []byte) (n int, err error) { - if file.overSeeked { - return 0, io.EOF - } - n, err = file.body.Read(p) - file.bytes += int64(n) - file.pos += int64(n) - if err == io.EOF { - file.eof = true - } - return -} - -// Seek sets the offset for the next Read to offset, interpreted -// according to whence: 0 means relative to the origin of the file, 1 -// means relative to the current offset, and 2 means relative to the -// end. Seek returns the new offset and an Error, if any. -// -// Seek uses HTTP Range headers which, if the file pointer is moved, -// will involve reopening the HTTP connection. -// -// Note that you can't seek to the end of a file or beyond; HTTP Range -// requests don't support the file pointer being outside the data, -// unlike os.File -// -// Seek(0, 1) will return the current file pointer. -func (file *ObjectOpenFile) Seek(offset int64, whence int) (newPos int64, err error) { - file.overSeeked = false - switch whence { - case 0: // relative to start - newPos = offset - case 1: // relative to current - newPos = file.pos + offset - case 2: // relative to end - if !file.lengthOk { - return file.pos, newError(0, "Length of file unknown so can't seek from end") - } - newPos = file.length + offset - if offset >= 0 { - file.overSeeked = true - return - } - default: - panic("Unknown whence in ObjectOpenFile.Seek") - } - // If at correct position (quite likely), do nothing - if newPos == file.pos { - return - } - // Close the file... - file.seeked = true - err = file.Close() - if err != nil { - return - } - // ...and re-open with a Range header - if file.headers == nil { - file.headers = Headers{} - } - if newPos > 0 { - file.headers["Range"] = fmt.Sprintf("bytes=%d-", newPos) - } else { - delete(file.headers, "Range") - } - newFile, _, err := file.connection.ObjectOpen(file.container, file.objectName, false, file.headers) - if err != nil { - return - } - // Update the file - file.resp = newFile.resp - file.body = newFile.body - file.checkHash = false - file.pos = newPos - return -} - -// Length gets the objects content length either from a cached copy or -// from the server. -func (file *ObjectOpenFile) Length() (int64, error) { - if !file.lengthOk { - info, _, err := file.connection.Object(file.container, file.objectName) - file.length = info.Bytes - file.lengthOk = (err == nil) - return file.length, err - } - return file.length, nil -} - -// Close the object and checks the length and md5sum if it was -// required and all the object was read -func (file *ObjectOpenFile) Close() (err error) { - // Close the body at the end - defer checkClose(file.resp.Body, &err) - - // If not end of file or seeked then can't check anything - if !file.eof || file.seeked { - return - } - - // Check the MD5 sum if requested - if file.checkHash { - receivedMd5 := strings.ToLower(file.resp.Header.Get("Etag")) - calculatedMd5 := fmt.Sprintf("%x", file.hash.Sum(nil)) - if receivedMd5 != calculatedMd5 { - err = ObjectCorrupted - return - } - } - - // Check to see we read the correct number of bytes - if file.lengthOk && file.length != file.bytes { - err = ObjectCorrupted - return - } - return -} - -// Check it satisfies the interfaces -var _ io.ReadCloser = &ObjectOpenFile{} -var _ io.Seeker = &ObjectOpenFile{} - -func (c *Connection) objectOpenBase(container string, objectName string, checkHash bool, h Headers, parameters url.Values) (file *ObjectOpenFile, headers Headers, err error) { - var resp *http.Response - opts := RequestOpts{ - Container: container, - ObjectName: objectName, - Operation: "GET", - ErrorMap: objectErrorMap, - Headers: h, - Parameters: parameters, - } - resp, headers, err = c.storage(opts) - if err != nil { - return - } - // Can't check MD5 on an object with X-Object-Manifest or X-Static-Large-Object set - if checkHash && headers.IsLargeObject() { - // log.Printf("swift: turning off md5 checking on object with manifest %v", objectName) - checkHash = false - } - file = &ObjectOpenFile{ - connection: c, - container: container, - objectName: objectName, - headers: h, - resp: resp, - checkHash: checkHash, - body: resp.Body, - } - if checkHash { - file.hash = md5.New() - file.body = io.TeeReader(resp.Body, file.hash) - } - // Read Content-Length - if resp.Header.Get("Content-Length") != "" { - file.length, err = getInt64FromHeader(resp, "Content-Length") - file.lengthOk = (err == nil) - } - return -} - -func (c *Connection) objectOpen(container string, objectName string, checkHash bool, h Headers, parameters url.Values) (file *ObjectOpenFile, headers Headers, err error) { - err = withLORetry(0, func() (Headers, int64, error) { - file, headers, err = c.objectOpenBase(container, objectName, checkHash, h, parameters) - if err != nil { - return headers, 0, err - } - return headers, file.length, nil - }) - return -} - -// ObjectOpen returns an ObjectOpenFile for reading the contents of -// the object. This satisfies the io.ReadCloser and the io.Seeker -// interfaces. -// -// You must call Close() on contents when finished -// -// Returns the headers of the response. -// -// If checkHash is true then it will calculate the md5sum of the file -// as it is being received and check it against that returned from the -// server. If it is wrong then it will return ObjectCorrupted. It -// will also check the length returned. No checking will be done if -// you don't read all the contents. -// -// Note that objects with X-Object-Manifest or X-Static-Large-Object -// set won't ever have their md5sum's checked as the md5sum reported -// on the object is actually the md5sum of the md5sums of the -// parts. This isn't very helpful to detect a corrupted download as -// the size of the parts aren't known without doing more operations. -// If you want to ensure integrity of an object with a manifest then -// you will need to download everything in the manifest separately. -// -// headers["Content-Type"] will give the content type if desired. -func (c *Connection) ObjectOpen(container string, objectName string, checkHash bool, h Headers) (file *ObjectOpenFile, headers Headers, err error) { - return c.objectOpen(container, objectName, checkHash, h, nil) -} - -// ObjectGet gets the object into the io.Writer contents. -// -// Returns the headers of the response. -// -// If checkHash is true then it will calculate the md5sum of the file -// as it is being received and check it against that returned from the -// server. If it is wrong then it will return ObjectCorrupted. -// -// headers["Content-Type"] will give the content type if desired. -func (c *Connection) ObjectGet(container string, objectName string, contents io.Writer, checkHash bool, h Headers) (headers Headers, err error) { - file, headers, err := c.ObjectOpen(container, objectName, checkHash, h) - if err != nil { - return - } - defer checkClose(file, &err) - _, err = io.Copy(contents, file) - return -} - -// ObjectGetBytes returns an object as a []byte. -// -// This is a simplified interface which checks the MD5 -func (c *Connection) ObjectGetBytes(container string, objectName string) (contents []byte, err error) { - var buf bytes.Buffer - _, err = c.ObjectGet(container, objectName, &buf, true, nil) - contents = buf.Bytes() - return -} - -// ObjectGetString returns an object as a string. -// -// This is a simplified interface which checks the MD5 -func (c *Connection) ObjectGetString(container string, objectName string) (contents string, err error) { - var buf bytes.Buffer - _, err = c.ObjectGet(container, objectName, &buf, true, nil) - contents = buf.String() - return -} - -// ObjectDelete deletes the object. -// -// May return ObjectNotFound if the object isn't found -func (c *Connection) ObjectDelete(container string, objectName string) error { - _, _, err := c.storage(RequestOpts{ - Container: container, - ObjectName: objectName, - Operation: "DELETE", - ErrorMap: objectErrorMap, - }) - return err -} - -// ObjectTempUrl returns a temporary URL for an object -func (c *Connection) ObjectTempUrl(container string, objectName string, secretKey string, method string, expires time.Time) string { - mac := hmac.New(sha1.New, []byte(secretKey)) - prefix, _ := url.Parse(c.StorageUrl) - body := fmt.Sprintf("%s\n%d\n%s/%s/%s", method, expires.Unix(), prefix.Path, container, objectName) - mac.Write([]byte(body)) - sig := hex.EncodeToString(mac.Sum(nil)) - return fmt.Sprintf("%s/%s/%s?temp_url_sig=%s&temp_url_expires=%d", c.StorageUrl, container, objectName, sig, expires.Unix()) -} - -// parseResponseStatus parses string like "200 OK" and returns Error. -// -// For status codes beween 200 and 299, this returns nil. -func parseResponseStatus(resp string, errorMap errorMap) error { - code := 0 - reason := resp - t := strings.SplitN(resp, " ", 2) - if len(t) == 2 { - ncode, err := strconv.Atoi(t[0]) - if err == nil { - code = ncode - reason = t[1] - } - } - if errorMap != nil { - if err, ok := errorMap[code]; ok { - return err - } - } - if 200 <= code && code <= 299 { - return nil - } - return newError(code, reason) -} - -// BulkDeleteResult stores results of BulkDelete(). -// -// Individual errors may (or may not) be returned by Errors. -// Errors is a map whose keys are a full path of where the object was -// to be deleted, and whose values are Error objects. A full path of -// object looks like "/API_VERSION/USER_ACCOUNT/CONTAINER/OBJECT_PATH". -type BulkDeleteResult struct { - NumberNotFound int64 // # of objects not found. - NumberDeleted int64 // # of deleted objects. - Errors map[string]error // Mapping between object name and an error. - Headers Headers // Response HTTP headers. -} - -func (c *Connection) doBulkDelete(objects []string) (result BulkDeleteResult, err error) { - var buffer bytes.Buffer - for _, s := range objects { - u := url.URL{Path: s} - buffer.WriteString(u.String() + "\n") - } - resp, headers, err := c.storage(RequestOpts{ - Operation: "DELETE", - Parameters: url.Values{"bulk-delete": []string{"1"}}, - Headers: Headers{ - "Accept": "application/json", - "Content-Type": "text/plain", - "Content-Length": strconv.Itoa(buffer.Len()), - }, - ErrorMap: ContainerErrorMap, - Body: &buffer, - }) - if err != nil { - return - } - var jsonResult struct { - NotFound int64 `json:"Number Not Found"` - Status string `json:"Response Status"` - Errors [][]string - Deleted int64 `json:"Number Deleted"` - } - err = readJson(resp, &jsonResult) - if err != nil { - return - } - - err = parseResponseStatus(jsonResult.Status, objectErrorMap) - result.NumberNotFound = jsonResult.NotFound - result.NumberDeleted = jsonResult.Deleted - result.Headers = headers - el := make(map[string]error, len(jsonResult.Errors)) - for _, t := range jsonResult.Errors { - if len(t) != 2 { - continue - } - el[t[0]] = parseResponseStatus(t[1], objectErrorMap) - } - result.Errors = el - return -} - -// BulkDelete deletes multiple objectNames from container in one operation. -// -// Some servers may not accept bulk-delete requests since bulk-delete is -// an optional feature of swift - these will return the Forbidden error. -// -// See also: -// * http://docs.openstack.org/trunk/openstack-object-storage/admin/content/object-storage-bulk-delete.html -// * http://docs.rackspace.com/files/api/v1/cf-devguide/content/Bulk_Delete-d1e2338.html -func (c *Connection) BulkDelete(container string, objectNames []string) (result BulkDeleteResult, err error) { - if len(objectNames) == 0 { - result.Errors = make(map[string]error) - return - } - fullPaths := make([]string, len(objectNames)) - for i, name := range objectNames { - fullPaths[i] = fmt.Sprintf("/%s/%s", container, name) - } - return c.doBulkDelete(fullPaths) -} - -// BulkUploadResult stores results of BulkUpload(). -// -// Individual errors may (or may not) be returned by Errors. -// Errors is a map whose keys are a full path of where an object was -// to be created, and whose values are Error objects. A full path of -// object looks like "/API_VERSION/USER_ACCOUNT/CONTAINER/OBJECT_PATH". -type BulkUploadResult struct { - NumberCreated int64 // # of created objects. - Errors map[string]error // Mapping between object name and an error. - Headers Headers // Response HTTP headers. -} - -// BulkUpload uploads multiple files in one operation. -// -// uploadPath can be empty, a container name, or a pseudo-directory -// within a container. If uploadPath is empty, new containers may be -// automatically created. -// -// Files are read from dataStream. The format of the stream is specified -// by the format parameter. Available formats are: -// * UploadTar - Plain tar stream. -// * UploadTarGzip - Gzip compressed tar stream. -// * UploadTarBzip2 - Bzip2 compressed tar stream. -// -// Some servers may not accept bulk-upload requests since bulk-upload is -// an optional feature of swift - these will return the Forbidden error. -// -// See also: -// * http://docs.openstack.org/trunk/openstack-object-storage/admin/content/object-storage-extract-archive.html -// * http://docs.rackspace.com/files/api/v1/cf-devguide/content/Extract_Archive-d1e2338.html -func (c *Connection) BulkUpload(uploadPath string, dataStream io.Reader, format string, h Headers) (result BulkUploadResult, err error) { - extraHeaders := Headers{"Accept": "application/json"} - for key, value := range h { - extraHeaders[key] = value - } - // The following code abuses Container parameter intentionally. - // The best fix might be to rename Container to UploadPath. - resp, headers, err := c.storage(RequestOpts{ - Container: uploadPath, - Operation: "PUT", - Parameters: url.Values{"extract-archive": []string{format}}, - Headers: extraHeaders, - ErrorMap: ContainerErrorMap, - Body: dataStream, - }) - if err != nil { - return - } - // Detect old servers which don't support this feature - if headers["Content-Type"] != "application/json" { - err = Forbidden - return - } - var jsonResult struct { - Created int64 `json:"Number Files Created"` - Status string `json:"Response Status"` - Errors [][]string - } - err = readJson(resp, &jsonResult) - if err != nil { - return - } - - err = parseResponseStatus(jsonResult.Status, objectErrorMap) - result.NumberCreated = jsonResult.Created - result.Headers = headers - el := make(map[string]error, len(jsonResult.Errors)) - for _, t := range jsonResult.Errors { - if len(t) != 2 { - continue - } - el[t[0]] = parseResponseStatus(t[1], objectErrorMap) - } - result.Errors = el - return -} - -// Object returns info about a single object including any metadata in the header. -// -// May return ObjectNotFound. -// -// Use headers.ObjectMetadata() to read the metadata in the Headers. -func (c *Connection) Object(container string, objectName string) (info Object, headers Headers, err error) { - err = withLORetry(0, func() (Headers, int64, error) { - info, headers, err = c.objectBase(container, objectName) - if err != nil { - return headers, 0, err - } - return headers, info.Bytes, nil - }) - return -} - -func (c *Connection) objectBase(container string, objectName string) (info Object, headers Headers, err error) { - var resp *http.Response - resp, headers, err = c.storage(RequestOpts{ - Container: container, - ObjectName: objectName, - Operation: "HEAD", - ErrorMap: objectErrorMap, - NoResponse: true, - }) - if err != nil { - return - } - // Parse the headers into the struct - // HTTP/1.1 200 OK - // Date: Thu, 07 Jun 2010 20:59:39 GMT - // Server: Apache - // Last-Modified: Fri, 12 Jun 2010 13:40:18 GMT - // ETag: 8a964ee2a5e88be344f36c22562a6486 - // Content-Length: 512000 - // Content-Type: text/plain; charset=UTF-8 - // X-Object-Meta-Meat: Bacon - // X-Object-Meta-Fruit: Bacon - // X-Object-Meta-Veggie: Bacon - // X-Object-Meta-Dairy: Bacon - info.Name = objectName - info.ContentType = resp.Header.Get("Content-Type") - if resp.Header.Get("Content-Length") != "" { - if info.Bytes, err = getInt64FromHeader(resp, "Content-Length"); err != nil { - return - } - } - // Currently ceph doesn't return a Last-Modified header for DLO manifests without any segments - // See ceph http://tracker.ceph.com/issues/15812 - if resp.Header.Get("Last-Modified") != "" { - info.ServerLastModified = resp.Header.Get("Last-Modified") - if info.LastModified, err = time.Parse(http.TimeFormat, info.ServerLastModified); err != nil { - return - } - } - - info.Hash = resp.Header.Get("Etag") - if resp.Header.Get("X-Object-Manifest") != "" { - info.ObjectType = DynamicLargeObjectType - } else if resp.Header.Get("X-Static-Large-Object") != "" { - info.ObjectType = StaticLargeObjectType - } - - return -} - -// ObjectUpdate adds, replaces or removes object metadata. -// -// Add or Update keys by mentioning them in the Metadata. Use -// Metadata.ObjectHeaders and Headers.ObjectMetadata to convert your -// Metadata to and from normal HTTP headers. -// -// This removes all metadata previously added to the object and -// replaces it with that passed in so to delete keys, just don't -// mention them the headers you pass in. -// -// Object metadata can only be read with Object() not with Objects(). -// -// This can also be used to set headers not already assigned such as -// X-Delete-At or X-Delete-After for expiring objects. -// -// You cannot use this to change any of the object's other headers -// such as Content-Type, ETag, etc. -// -// Refer to copying an object when you need to update metadata or -// other headers such as Content-Type or CORS headers. -// -// May return ObjectNotFound. -func (c *Connection) ObjectUpdate(container string, objectName string, h Headers) error { - _, _, err := c.storage(RequestOpts{ - Container: container, - ObjectName: objectName, - Operation: "POST", - ErrorMap: objectErrorMap, - NoResponse: true, - Headers: h, - }) - return err -} - -// urlPathEscape escapes URL path the in string using URL escaping rules -// -// This mimics url.PathEscape which only available from go 1.8 -func urlPathEscape(in string) string { - var u url.URL - u.Path = in - return u.String() -} - -// ObjectCopy does a server side copy of an object to a new position -// -// All metadata is preserved. If metadata is set in the headers then -// it overrides the old metadata on the copied object. -// -// The destination container must exist before the copy. -// -// You can use this to copy an object to itself - this is the only way -// to update the content type of an object. -func (c *Connection) ObjectCopy(srcContainer string, srcObjectName string, dstContainer string, dstObjectName string, h Headers) (headers Headers, err error) { - // Meta stuff - extraHeaders := map[string]string{ - "Destination": urlPathEscape(dstContainer + "/" + dstObjectName), - } - for key, value := range h { - extraHeaders[key] = value - } - _, headers, err = c.storage(RequestOpts{ - Container: srcContainer, - ObjectName: srcObjectName, - Operation: "COPY", - ErrorMap: objectErrorMap, - NoResponse: true, - Headers: extraHeaders, - }) - return -} - -// ObjectMove does a server side move of an object to a new position -// -// This is a convenience method which calls ObjectCopy then ObjectDelete -// -// All metadata is preserved. -// -// The destination container must exist before the copy. -func (c *Connection) ObjectMove(srcContainer string, srcObjectName string, dstContainer string, dstObjectName string) (err error) { - _, err = c.ObjectCopy(srcContainer, srcObjectName, dstContainer, dstObjectName, nil) - if err != nil { - return - } - return c.ObjectDelete(srcContainer, srcObjectName) -} - -// ObjectUpdateContentType updates the content type of an object -// -// This is a convenience method which calls ObjectCopy -// -// All other metadata is preserved. -func (c *Connection) ObjectUpdateContentType(container string, objectName string, contentType string) (err error) { - h := Headers{"Content-Type": contentType} - _, err = c.ObjectCopy(container, objectName, container, objectName, h) - return -} - -// ------------------------------------------------------------ - -// VersionContainerCreate is a helper method for creating and enabling version controlled containers. -// -// It builds the current object container, the non-current object version container, and enables versioning. -// -// If the server doesn't support versioning then it will return -// Forbidden however it will have created both the containers at that point. -func (c *Connection) VersionContainerCreate(current, version string) error { - if err := c.ContainerCreate(version, nil); err != nil { - return err - } - if err := c.ContainerCreate(current, nil); err != nil { - return err - } - if err := c.VersionEnable(current, version); err != nil { - return err - } - return nil -} - -// VersionEnable enables versioning on the current container with version as the tracking container. -// -// May return Forbidden if this isn't supported by the server -func (c *Connection) VersionEnable(current, version string) error { - h := Headers{"X-Versions-Location": version} - if err := c.ContainerUpdate(current, h); err != nil { - return err - } - // Check to see if the header was set properly - _, headers, err := c.Container(current) - if err != nil { - return err - } - // If failed to set versions header, return Forbidden as the server doesn't support this - if headers["X-Versions-Location"] != version { - return Forbidden - } - return nil -} - -// VersionDisable disables versioning on the current container. -func (c *Connection) VersionDisable(current string) error { - h := Headers{"X-Versions-Location": ""} - if err := c.ContainerUpdate(current, h); err != nil { - return err - } - return nil -} - -// VersionObjectList returns a list of older versions of the object. -// -// Objects are returned in the format / -func (c *Connection) VersionObjectList(version, object string) ([]string, error) { - opts := &ObjectsOpts{ - // <3-character zero-padded hexadecimal character length>/ - Prefix: fmt.Sprintf("%03x", len(object)) + object + "/", - } - return c.ObjectNames(version, opts) -} diff --git a/vendor/github.com/ncw/swift/swifttest/server.go b/vendor/github.com/ncw/swift/swifttest/server.go deleted file mode 100644 index 6ec50f609..000000000 --- a/vendor/github.com/ncw/swift/swifttest/server.go +++ /dev/null @@ -1,1107 +0,0 @@ -// This implements a very basic Swift server -// Everything is stored in memory -// -// This comes from the https://github.com/mitchellh/goamz -// and was adapted for Swift -// -package swifttest - -import ( - "bytes" - "crypto/hmac" - "crypto/md5" - "crypto/rand" - "crypto/sha1" - "encoding/hex" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "log" - "mime" - "net" - "net/http" - "net/http/httptest" - "net/url" - "path" - "regexp" - "sort" - "strconv" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "github.com/ncw/swift" -) - -const ( - DEBUG = false - TEST_ACCOUNT = "swifttest" -) - -type HandlerOverrideFunc func(w http.ResponseWriter, r *http.Request, recorder *httptest.ResponseRecorder) - -type SwiftServer struct { - // `sync/atomic` expects the first word in an allocated struct to be 64-bit - // aligned on both ARM and x86-32. - // See https://golang.org/pkg/sync/atomic/#pkg-note-BUG for more details. - reqId int64 - sync.RWMutex - t *testing.T - mu sync.Mutex - Listener net.Listener - AuthURL string - URL string - Accounts map[string]*account - Sessions map[string]*session - override map[string]HandlerOverrideFunc -} - -// The Folder type represents a container stored in an account -type Folder struct { - Count int64 `json:"count"` - Bytes int64 `json:"bytes"` - Name string `json:"name"` -} - -// The Key type represents an item stored in an container. -type Key struct { - Key string `json:"name"` - LastModified string `json:"last_modified"` - Size int64 `json:"bytes"` - // ETag gives the hex-encoded MD5 sum of the contents, - // surrounded with double-quotes. - ETag string `json:"hash"` - ContentType string `json:"content_type"` - // Owner Owner -} - -type Subdir struct { - Subdir string `json:"subdir"` -} - -type swiftError struct { - statusCode int - Code string - Message string -} - -type action struct { - srv *SwiftServer - w http.ResponseWriter - req *http.Request - reqId string - user *account -} - -type session struct { - username string -} - -type metadata struct { - meta http.Header // metadata to return with requests. -} - -type account struct { - sync.RWMutex - swift.Account - metadata - password string - ContainersLock sync.RWMutex - Containers map[string]*container -} - -type object struct { - sync.RWMutex - metadata - name string - mtime time.Time - checksum []byte // also held as ETag in meta. - data []byte - content_type string -} - -type container struct { - // `sync/atomic` expects the first word in an allocated struct to be 64-bit - // aligned on both ARM and x86-32. - // See https://golang.org/pkg/sync/atomic/#pkg-note-BUG for more details. - bytes int64 - sync.RWMutex - metadata - name string - ctime time.Time - objects map[string]*object -} - -type segment struct { - Path string `json:"path,omitempty"` - Hash string `json:"hash,omitempty"` - Size int64 `json:"size_bytes,omitempty"` - // When uploading a manifest, the attributes must be named `path`, `hash` and `size` - // but when querying the JSON content of a manifest with the `multipart-manifest=get` - // parameter, Swift names those attributes `name`, `etag` and `bytes`. - // We use all the different attributes names in this structure to be able to use - // the same structure for both uploading and retrieving. - Name string `json:"name,omitempty"` - Etag string `json:"etag,omitempty"` - Bytes int64 `json:"bytes,omitempty"` - ContentType string `json:"content_type,omitempty"` - LastModified string `json:"last_modified,omitempty"` -} - -// A resource encapsulates the subject of an HTTP request. -// The resource referred to may or may not exist -// when the request is made. -type resource interface { - put(a *action) interface{} - get(a *action) interface{} - post(a *action) interface{} - delete(a *action) interface{} - copy(a *action) interface{} -} - -type objectResource struct { - name string - version string - container *container // always non-nil. - object *object // may be nil. -} - -type containerResource struct { - name string - container *container // non-nil if the container already exists. -} - -var responseParams = map[string]bool{ - "content-type": true, - "content-language": true, - "expires": true, - "cache-control": true, - "content-disposition": true, - "content-encoding": true, -} - -func fatalf(code int, codeStr string, errf string, a ...interface{}) { - panic(&swiftError{ - statusCode: code, - Code: codeStr, - Message: fmt.Sprintf(errf, a...), - }) -} - -func (m metadata) setMetadata(a *action, resource string) { - for key, values := range a.req.Header { - key = http.CanonicalHeaderKey(key) - if metaHeaders[key] || strings.HasPrefix(key, "X-"+strings.Title(resource)+"-Meta-") { - if values[0] != "" || resource == "object" { - m.meta[key] = values - } else { - m.meta.Del(key) - } - } - } -} - -func (m metadata) getMetadata(a *action) { - h := a.w.Header() - for name, d := range m.meta { - h[name] = d - } -} - -func (c *container) list(delimiter string, marker string, prefix string, parent string) (resp []interface{}) { - var tmp orderedObjects - - c.RLock() - defer c.RUnlock() - - // first get all matching objects and arrange them in alphabetical order. - for _, obj := range c.objects { - if strings.HasPrefix(obj.name, prefix) { - tmp = append(tmp, obj) - } - } - sort.Sort(tmp) - - var prefixes []string - for _, obj := range tmp { - if !strings.HasPrefix(obj.name, prefix) { - continue - } - - isPrefix := false - name := obj.name - if parent != "" { - if path.Dir(obj.name) != path.Clean(parent) { - continue - } - } else if delimiter != "" { - if i := strings.Index(obj.name[len(prefix):], delimiter); i >= 0 { - name = obj.name[:len(prefix)+i+len(delimiter)] - if prefixes != nil && prefixes[len(prefixes)-1] == name { - continue - } - isPrefix = true - } - } - - if name <= marker { - continue - } - - if isPrefix { - prefixes = append(prefixes, name) - - resp = append(resp, Subdir{ - Subdir: name, - }) - } else { - resp = append(resp, obj) - } - } - - return -} - -// GET on a container lists the objects in the container. -func (r containerResource) get(a *action) interface{} { - if r.container == nil { - fatalf(404, "NoSuchContainer", "The specified container does not exist") - } - - r.container.RLock() - - delimiter := a.req.Form.Get("delimiter") - marker := a.req.Form.Get("marker") - prefix := a.req.Form.Get("prefix") - format := a.req.URL.Query().Get("format") - parent := a.req.Form.Get("path") - - a.w.Header().Set("X-Container-Bytes-Used", strconv.Itoa(int(r.container.bytes))) - a.w.Header().Set("X-Container-Object-Count", strconv.Itoa(len(r.container.objects))) - r.container.getMetadata(a) - - if a.req.Method == "HEAD" { - r.container.RUnlock() - return nil - } - r.container.RUnlock() - - objects := r.container.list(delimiter, marker, prefix, parent) - - if format == "json" { - a.w.Header().Set("Content-Type", "application/json") - var resp []interface{} - for _, item := range objects { - if obj, ok := item.(*object); ok { - resp = append(resp, obj.Key()) - } else { - resp = append(resp, item) - } - } - return resp - } else { - for _, item := range objects { - if obj, ok := item.(*object); ok { - a.w.Write([]byte(obj.name + "\n")) - } else if subdir, ok := item.(Subdir); ok { - a.w.Write([]byte(subdir.Subdir + "\n")) - } - } - return nil - } -} - -// orderedContainers holds a slice of containers that can be sorted -// by name. -type orderedContainers []*container - -func (s orderedContainers) Len() int { - return len(s) -} -func (s orderedContainers) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s orderedContainers) Less(i, j int) bool { - return s[i].name < s[j].name -} - -func (r containerResource) delete(a *action) interface{} { - b := r.container - if b == nil { - fatalf(404, "NoSuchContainer", "The specified container does not exist") - } - if len(b.objects) > 0 { - fatalf(409, "Conflict", "The container you tried to delete is not empty") - } - a.user.Lock() - delete(a.user.Containers, b.name) - a.user.Account.Containers-- - a.user.Unlock() - return nil -} - -func (r containerResource) put(a *action) interface{} { - if a.req.URL.Query().Get("extract-archive") != "" { - fatalf(403, "Operation forbidden", "Bulk upload is not supported") - } - - if r.container == nil { - if !validContainerName(r.name) { - fatalf(400, "InvalidContainerName", "The specified container is not valid") - } - r.container = &container{ - name: r.name, - objects: make(map[string]*object), - metadata: metadata{ - meta: make(http.Header), - }, - } - r.container.setMetadata(a, "container") - - a.user.Lock() - a.user.Containers[r.name] = r.container - a.user.Account.Containers++ - a.user.Unlock() - } - - return nil -} - -func (r containerResource) post(a *action) interface{} { - if r.container == nil { - fatalf(400, "Method", "The resource could not be found.") - } else { - r.container.RLock() - defer r.container.RUnlock() - - r.container.setMetadata(a, "container") - a.w.WriteHeader(201) - jsonMarshal(a.w, Folder{ - Count: int64(len(r.container.objects)), - Bytes: r.container.bytes, - Name: r.container.name, - }) - } - return nil -} - -func (containerResource) copy(a *action) interface{} { return notAllowed() } - -// validContainerName returns whether name is a valid bucket name. -// Here are the rules, from: -// http://docs.openstack.org/api/openstack-object-storage/1.0/content/ch_object-storage-dev-api-storage.html -// -// Container names cannot exceed 256 bytes and cannot contain the / character. -// -func validContainerName(name string) bool { - if len(name) == 0 || len(name) > 256 { - return false - } - for _, r := range name { - switch { - case r == '/': - return false - default: - } - } - return true -} - -// orderedObjects holds a slice of objects that can be sorted -// by name. -type orderedObjects []*object - -func (s orderedObjects) Len() int { - return len(s) -} -func (s orderedObjects) Swap(i, j int) { - s[i], s[j] = s[j], s[i] -} -func (s orderedObjects) Less(i, j int) bool { - return s[i].name < s[j].name -} - -func (obj *object) Key() Key { - return Key{ - Key: obj.name, - LastModified: obj.mtime.Format("2006-01-02T15:04:05"), - Size: int64(len(obj.data)), - ETag: fmt.Sprintf("%x", obj.checksum), - ContentType: obj.content_type, - } -} - -var metaHeaders = map[string]bool{ - "Content-Type": true, - "Content-Encoding": true, - "Content-Disposition": true, - "X-Object-Manifest": true, - "X-Static-Large-Object": true, -} - -var rangeRegexp = regexp.MustCompile("(bytes=)?([0-9]*)-([0-9]*)") - -// GET on an object gets the contents of the object. -func (objr objectResource) get(a *action) interface{} { - var ( - etag []byte - reader io.Reader - start int - end int = -1 - ) - obj := objr.object - if obj == nil { - fatalf(404, "Not Found", "The resource could not be found.") - } - - obj.RLock() - defer obj.RUnlock() - - h := a.w.Header() - // add metadata - obj.getMetadata(a) - - if r := a.req.Header.Get("Range"); r != "" { - m := rangeRegexp.FindStringSubmatch(r) - if m[2] != "" { - start, _ = strconv.Atoi(m[2]) - } - if m[3] != "" { - end, _ = strconv.Atoi(m[3]) - } - } - - max := func(a int, b int) int { - if a > b { - return a - } - return b - } - - if manifest, ok := obj.meta["X-Object-Manifest"]; ok { - var segments []io.Reader - components := strings.SplitN(manifest[0], "/", 2) - a.user.RLock() - segContainer := a.user.Containers[components[0]] - a.user.RUnlock() - prefix := components[1] - resp := segContainer.list("", "", prefix, "") - sum := md5.New() - cursor := 0 - size := 0 - for _, item := range resp { - if obj, ok := item.(*object); ok { - length := len(obj.data) - size += length - sum.Write([]byte(hex.EncodeToString(obj.checksum))) - if start >= cursor+length { - continue - } - segments = append(segments, bytes.NewReader(obj.data[max(0, start-cursor):])) - cursor += length - } - } - etag = sum.Sum(nil) - if end == -1 { - end = size - 1 - } - reader = io.LimitReader(io.MultiReader(segments...), int64(end-start+1)) - } else if value, ok := obj.meta["X-Static-Large-Object"]; ok && value[0] == "True" && a.req.URL.Query().Get("multipart-manifest") != "get" { - var segments []io.Reader - var segmentList []segment - json.Unmarshal(obj.data, &segmentList) - cursor := 0 - size := 0 - sum := md5.New() - for _, segment := range segmentList { - components := strings.SplitN(segment.Name[1:], "/", 2) - a.user.RLock() - segContainer := a.user.Containers[components[0]] - a.user.RUnlock() - objectName := components[1] - segObject := segContainer.objects[objectName] - length := len(segObject.data) - size += length - sum.Write([]byte(hex.EncodeToString(segObject.checksum))) - if start >= cursor+length { - continue - } - segments = append(segments, bytes.NewReader(segObject.data[max(0, start-cursor):])) - cursor += length - } - etag = sum.Sum(nil) - if end == -1 { - end = size - 1 - } - reader = io.LimitReader(io.MultiReader(segments...), int64(end-start+1)) - } else { - if end == -1 { - end = len(obj.data) - 1 - } - etag = obj.checksum - reader = bytes.NewReader(obj.data[start : end+1]) - } - - etagHex := hex.EncodeToString(etag) - - if a.req.Header.Get("If-None-Match") == etagHex { - a.w.WriteHeader(http.StatusNotModified) - return nil - } - - h.Set("Content-Length", fmt.Sprint(end-start+1)) - h.Set("ETag", etagHex) - h.Set("Last-Modified", obj.mtime.Format(http.TimeFormat)) - - if a.req.Method == "HEAD" { - return nil - } - - // TODO avoid holding the lock when writing data. - _, err := io.Copy(a.w, reader) - if err != nil { - // we can't do much except just log the fact. - log.Printf("error writing data: %v", err) - } - return nil -} - -// PUT on an object creates the object. -func (objr objectResource) put(a *action) interface{} { - var expectHash []byte - if c := a.req.Header.Get("ETag"); c != "" { - var err error - expectHash, err = hex.DecodeString(c) - if err != nil || len(expectHash) != md5.Size { - fatalf(400, "InvalidDigest", "The ETag you specified was invalid") - } - } - sum := md5.New() - // TODO avoid holding lock while reading data. - data, err := ioutil.ReadAll(io.TeeReader(a.req.Body, sum)) - if err != nil { - fatalf(400, "TODO", "read error") - } - gotHash := sum.Sum(nil) - if expectHash != nil && bytes.Compare(gotHash, expectHash) != 0 { - fatalf(422, "Bad ETag", "The ETag you specified did not match what we received") - } - if a.req.ContentLength >= 0 && int64(len(data)) != a.req.ContentLength { - fatalf(400, "IncompleteBody", "You did not provide the number of bytes specified by the Content-Length HTTP header") - } - - // TODO is this correct, or should we erase all previous metadata? - obj := objr.object - if obj == nil { - obj = &object{ - name: objr.name, - metadata: metadata{ - meta: make(http.Header), - }, - } - atomic.AddInt64(&a.user.Objects, 1) - } else { - atomic.AddInt64(&objr.container.bytes, -int64(len(obj.data))) - atomic.AddInt64(&a.user.BytesUsed, -int64(len(obj.data))) - } - - var content_type string - if content_type = a.req.Header.Get("Content-Type"); content_type == "" { - content_type = mime.TypeByExtension(obj.name) - if content_type == "" { - content_type = "application/octet-stream" - } - } - - if a.req.URL.Query().Get("multipart-manifest") == "put" { - // TODO: check the content of the SLO - a.req.Header.Set("X-Static-Large-Object", "True") - - var segments []segment - json.Unmarshal(data, &segments) - for i := range segments { - segments[i].Name = "/" + segments[i].Path - segments[i].Path = "" - segments[i].Hash = segments[i].Etag - segments[i].Etag = "" - segments[i].Bytes = segments[i].Size - segments[i].Size = 0 - } - - data, _ = json.Marshal(segments) - sum = md5.New() - sum.Write(data) - gotHash = sum.Sum(nil) - } - - // PUT request has been successful - save data and metadata - obj.setMetadata(a, "object") - obj.content_type = content_type - obj.data = data - obj.checksum = gotHash - obj.mtime = time.Now().UTC() - objr.container.Lock() - objr.container.objects[objr.name] = obj - objr.container.bytes += int64(len(data)) - objr.container.Unlock() - - atomic.AddInt64(&a.user.BytesUsed, int64(len(data))) - - h := a.w.Header() - h.Set("ETag", hex.EncodeToString(obj.checksum)) - - return nil -} - -func (objr objectResource) delete(a *action) interface{} { - if objr.object == nil { - fatalf(404, "NoSuchKey", "The specified key does not exist.") - } - - objr.container.Lock() - defer objr.container.Unlock() - - objr.object.Lock() - defer objr.object.Unlock() - - objr.container.bytes -= int64(len(objr.object.data)) - delete(objr.container.objects, objr.name) - - atomic.AddInt64(&a.user.BytesUsed, -int64(len(objr.object.data))) - atomic.AddInt64(&a.user.Objects, -1) - - return nil -} - -func (objr objectResource) post(a *action) interface{} { - objr.object.Lock() - defer objr.object.Unlock() - - obj := objr.object - obj.setMetadata(a, "object") - return nil -} - -func (objr objectResource) copy(a *action) interface{} { - if objr.object == nil { - fatalf(404, "NoSuchKey", "The specified key does not exist.") - } - - obj := objr.object - obj.RLock() - defer obj.RUnlock() - - destination := a.req.Header.Get("Destination") - if destination == "" { - fatalf(400, "Bad Request", "You must provide a Destination header") - } - - var ( - obj2 *object - objr2 objectResource - ) - - destURL, _ := url.Parse("/v1/AUTH_" + TEST_ACCOUNT + "/" + destination) - r := a.srv.resourceForURL(destURL) - switch t := r.(type) { - case objectResource: - objr2 = t - if objr2.object == nil { - obj2 = &object{ - name: objr2.name, - metadata: metadata{ - meta: make(http.Header), - }, - } - atomic.AddInt64(&a.user.Objects, 1) - } else { - obj2 = objr2.object - atomic.AddInt64(&objr2.container.bytes, -int64(len(obj2.data))) - atomic.AddInt64(&a.user.BytesUsed, -int64(len(obj2.data))) - } - default: - fatalf(400, "Bad Request", "Destination must point to a valid object path") - } - - if objr2.container.name != objr2.container.name && obj2.name != obj.name { - obj2.Lock() - defer obj2.Unlock() - } - - obj2.content_type = obj.content_type - obj2.data = obj.data - obj2.checksum = obj.checksum - obj2.mtime = time.Now() - - for key, values := range obj.metadata.meta { - obj2.metadata.meta[key] = values - } - obj2.setMetadata(a, "object") - - objr2.container.Lock() - objr2.container.objects[objr2.name] = obj2 - objr2.container.bytes += int64(len(obj.data)) - objr2.container.Unlock() - - atomic.AddInt64(&a.user.BytesUsed, int64(len(obj.data))) - - return nil -} - -func (s *SwiftServer) serveHTTP(w http.ResponseWriter, req *http.Request) { - // ignore error from ParseForm as it's usually spurious. - req.ParseForm() - - if fn := s.override[req.URL.Path]; fn != nil { - originalRW := w - recorder := httptest.NewRecorder() - w = recorder - defer func() { - fn(originalRW, req, recorder) - }() - } - - if DEBUG { - log.Printf("swifttest %q %q", req.Method, req.URL) - } - a := &action{ - srv: s, - w: w, - req: req, - reqId: fmt.Sprintf("%09X", atomic.LoadInt64(&s.reqId)), - } - atomic.AddInt64(&s.reqId, 1) - - var r resource - defer func() { - switch err := recover().(type) { - case *swiftError: - w.Header().Set("Content-Type", `text/plain; charset=utf-8`) - http.Error(w, err.Message, err.statusCode) - case nil: - default: - panic(err) - } - }() - - var resp interface{} - - if req.URL.String() == "/v1.0" { - username := req.Header.Get("x-auth-user") - key := req.Header.Get("x-auth-key") - s.Lock() - defer s.Unlock() - if acct, ok := s.Accounts[username]; ok { - if acct.password == key { - r := make([]byte, 16) - _, _ = rand.Read(r) - id := fmt.Sprintf("%X", r) - w.Header().Set("X-Storage-Url", s.URL+"/AUTH_"+username) - w.Header().Set("X-Auth-Token", "AUTH_tk"+string(id)) - w.Header().Set("X-Storage-Token", "AUTH_tk"+string(id)) - s.Sessions[id] = &session{ - username: username, - } - return - } - } - panic(notAuthorized()) - } - - if req.URL.String() == "/info" { - jsonMarshal(w, &swift.SwiftInfo{ - "swift": map[string]interface{}{ - "version": "1.2", - }, - "tempurl": map[string]interface{}{ - "methods": []string{"GET", "HEAD", "PUT"}, - }, - "slo": map[string]interface{}{ - "max_manifest_segments": 1000, - "max_manifest_size": 2097152, - "min_segment_size": 1, - }, - }) - return - } - - r = s.resourceForURL(req.URL) - - key := req.Header.Get("x-auth-token") - signature := req.URL.Query().Get("temp_url_sig") - expires := req.URL.Query().Get("temp_url_expires") - if key == "" && signature != "" && expires != "" { - accountName, _, _, _ := s.parseURL(req.URL) - secretKey := "" - s.RLock() - if account, ok := s.Accounts[accountName]; ok { - secretKey = account.meta.Get("X-Account-Meta-Temp-Url-Key") - } - s.RUnlock() - - get_hmac := func(method string) string { - mac := hmac.New(sha1.New, []byte(secretKey)) - body := fmt.Sprintf("%s\n%s\n%s", method, expires, req.URL.Path) - mac.Write([]byte(body)) - return hex.EncodeToString(mac.Sum(nil)) - } - - if req.Method == "HEAD" { - if signature != get_hmac("GET") && signature != get_hmac("POST") && signature != get_hmac("PUT") { - panic(notAuthorized()) - } - } else if signature != get_hmac(req.Method) { - panic(notAuthorized()) - } - } else { - s.RLock() - session, ok := s.Sessions[key[7:]] - if !ok { - s.RUnlock() - panic(notAuthorized()) - return - } - - a.user = s.Accounts[session.username] - s.RUnlock() - } - - switch req.Method { - case "PUT": - resp = r.put(a) - case "GET", "HEAD": - resp = r.get(a) - case "DELETE": - resp = r.delete(a) - case "POST": - resp = r.post(a) - case "COPY": - resp = r.copy(a) - default: - fatalf(400, "MethodNotAllowed", "unknown http request method %q", req.Method) - } - - content_type := req.Header.Get("Content-Type") - if resp != nil && req.Method != "HEAD" { - if strings.HasPrefix(content_type, "application/json") || - req.URL.Query().Get("format") == "json" { - jsonMarshal(w, resp) - } else { - switch r := resp.(type) { - case string: - w.Write([]byte(r)) - default: - w.Write(resp.([]byte)) - } - } - } -} - -func (s *SwiftServer) SetOverride(path string, fn HandlerOverrideFunc) { - s.override[path] = fn -} - -func (s *SwiftServer) UnsetOverride(path string) { - delete(s.override, path) -} - -func jsonMarshal(w io.Writer, x interface{}) { - if err := json.NewEncoder(w).Encode(x); err != nil { - panic(fmt.Errorf("error marshalling %#v: %v", x, err)) - } -} - -var pathRegexp = regexp.MustCompile("/v1/AUTH_([a-zA-Z0-9]+)(/([^/]+)(/(.*))?)?") - -func (srv *SwiftServer) parseURL(u *url.URL) (account string, container string, object string, err error) { - m := pathRegexp.FindStringSubmatch(u.Path) - if m == nil { - return "", "", "", fmt.Errorf("Couldn't parse the specified URI") - } - account = m[1] - container = m[3] - object = m[5] - return -} - -// resourceForURL returns a resource object for the given URL. -func (srv *SwiftServer) resourceForURL(u *url.URL) (r resource) { - accountName, containerName, objectName, err := srv.parseURL(u) - - if err != nil { - fatalf(404, "InvalidURI", err.Error()) - } - - srv.RLock() - account, ok := srv.Accounts[accountName] - if !ok { - //srv.RUnlock() - fatalf(404, "NoSuchAccount", "The specified account does not exist") - } - srv.RUnlock() - - account.RLock() - if containerName == "" { - account.RUnlock() - return rootResource{} - } - account.RUnlock() - - b := containerResource{ - name: containerName, - container: account.Containers[containerName], - } - - if objectName == "" { - return b - } - - if b.container == nil { - fatalf(404, "NoSuchContainer", "The specified container does not exist") - } - - objr := objectResource{ - name: objectName, - version: u.Query().Get("versionId"), - container: b.container, - } - - objr.container.RLock() - defer objr.container.RUnlock() - if obj := objr.container.objects[objr.name]; obj != nil { - objr.object = obj - } - return objr -} - -// nullResource has error stubs for all resource methods. -type nullResource struct{} - -func notAllowed() interface{} { - fatalf(400, "MethodNotAllowed", "The specified method is not allowed against this resource") - return nil -} - -func notAuthorized() interface{} { - fatalf(401, "Unauthorized", "This server could not verify that you are authorized to access the document you requested.") - return nil -} - -func (nullResource) put(a *action) interface{} { return notAllowed() } -func (nullResource) get(a *action) interface{} { return notAllowed() } -func (nullResource) post(a *action) interface{} { return notAllowed() } -func (nullResource) delete(a *action) interface{} { return notAllowed() } -func (nullResource) copy(a *action) interface{} { return notAllowed() } - -type rootResource struct{} - -func (rootResource) put(a *action) interface{} { return notAllowed() } -func (rootResource) get(a *action) interface{} { - marker := a.req.Form.Get("marker") - prefix := a.req.Form.Get("prefix") - format := a.req.URL.Query().Get("format") - - h := a.w.Header() - - h.Set("X-Account-Bytes-Used", strconv.Itoa(int(atomic.LoadInt64(&a.user.BytesUsed)))) - h.Set("X-Account-Container-Count", strconv.Itoa(int(atomic.LoadInt64(&a.user.Account.Containers)))) - h.Set("X-Account-Object-Count", strconv.Itoa(int(atomic.LoadInt64(&a.user.Objects)))) - - a.user.RLock() - defer a.user.RUnlock() - - // add metadata - a.user.metadata.getMetadata(a) - - if a.req.Method == "HEAD" { - return nil - } - - var tmp orderedContainers - // first get all matching objects and arrange them in alphabetical order. - for _, container := range a.user.Containers { - if strings.HasPrefix(container.name, prefix) { - tmp = append(tmp, container) - } - } - sort.Sort(tmp) - - resp := make([]Folder, 0) - for _, container := range tmp { - if container.name <= marker { - continue - } - if format == "json" { - resp = append(resp, Folder{ - Count: int64(len(container.objects)), - Bytes: container.bytes, - Name: container.name, - }) - } else { - a.w.Write([]byte(container.name + "\n")) - } - } - - if format == "json" { - return resp - } else { - return nil - } -} - -func (r rootResource) post(a *action) interface{} { - a.user.Lock() - a.user.metadata.setMetadata(a, "account") - a.user.Unlock() - return nil -} - -func (rootResource) delete(a *action) interface{} { - if a.req.URL.Query().Get("bulk-delete") == "1" { - fatalf(403, "Operation forbidden", "Bulk delete is not supported") - } - - return notAllowed() -} - -func (rootResource) copy(a *action) interface{} { return notAllowed() } - -func NewSwiftServer(address string) (*SwiftServer, error) { - if strings.Index(address, ":") == -1 { - address += ":0" - } - l, err := net.Listen("tcp", address) - if err != nil { - return nil, fmt.Errorf("cannot listen on %s: %v", address, err) - } - - server := &SwiftServer{ - Listener: l, - AuthURL: "http://" + l.Addr().String() + "/v1.0", - URL: "http://" + l.Addr().String() + "/v1", - Accounts: make(map[string]*account), - Sessions: make(map[string]*session), - override: make(map[string]HandlerOverrideFunc), - } - - server.Accounts[TEST_ACCOUNT] = &account{ - password: TEST_ACCOUNT, - metadata: metadata{ - meta: make(http.Header), - }, - Containers: make(map[string]*container), - } - - go http.Serve(l, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - server.serveHTTP(w, req) - })) - - return server, nil -} - -func (srv *SwiftServer) Close() { - srv.Listener.Close() -} diff --git a/vendor/github.com/ncw/swift/timeout_reader.go b/vendor/github.com/ncw/swift/timeout_reader.go deleted file mode 100644 index 88ae73328..000000000 --- a/vendor/github.com/ncw/swift/timeout_reader.go +++ /dev/null @@ -1,59 +0,0 @@ -package swift - -import ( - "io" - "time" -) - -// An io.ReadCloser which obeys an idle timeout -type timeoutReader struct { - reader io.ReadCloser - timeout time.Duration - cancel func() -} - -// Returns a wrapper around the reader which obeys an idle -// timeout. The cancel function is called if the timeout happens -func newTimeoutReader(reader io.ReadCloser, timeout time.Duration, cancel func()) *timeoutReader { - return &timeoutReader{ - reader: reader, - timeout: timeout, - cancel: cancel, - } -} - -// Read reads up to len(p) bytes into p -// -// Waits at most for timeout for the read to complete otherwise returns a timeout -func (t *timeoutReader) Read(p []byte) (int, error) { - // FIXME limit the amount of data read in one chunk so as to not exceed the timeout? - // Do the read in the background - type result struct { - n int - err error - } - done := make(chan result, 1) - go func() { - n, err := t.reader.Read(p) - done <- result{n, err} - }() - // Wait for the read or the timeout - timer := time.NewTimer(t.timeout) - defer timer.Stop() - select { - case r := <-done: - return r.n, r.err - case <-timer.C: - t.cancel() - return 0, TimeoutError - } - panic("unreachable") // for Go 1.0 -} - -// Close the channel -func (t *timeoutReader) Close() error { - return t.reader.Close() -} - -// Check it satisfies the interface -var _ io.ReadCloser = &timeoutReader{} diff --git a/vendor/github.com/ncw/swift/travis_realserver.sh b/vendor/github.com/ncw/swift/travis_realserver.sh deleted file mode 100644 index 970e94c0d..000000000 --- a/vendor/github.com/ncw/swift/travis_realserver.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/bin/bash -set -e - -if [ "${TRAVIS_PULL_REQUEST}" = "true" ]; then - exit 0 -fi - -if [ "${TEST_REAL_SERVER}" = "rackspace" ] && [ ! -z "${RACKSPACE_APIKEY}" ]; then - echo "Running tests pointing to Rackspace" - export SWIFT_API_KEY=$RACKSPACE_APIKEY - export SWIFT_API_USER=$RACKSPACE_USER - export SWIFT_AUTH_URL=$RACKSPACE_AUTH - go test ./... -fi - -if [ "${TEST_REAL_SERVER}" = "memset" ] && [ ! -z "${MEMSET_APIKEY}" ]; then - echo "Running tests pointing to Memset" - export SWIFT_API_KEY=$MEMSET_APIKEY - export SWIFT_API_USER=$MEMSET_USER - export SWIFT_AUTH_URL=$MEMSET_AUTH - go test -fi diff --git a/vendor/github.com/ncw/swift/watchdog_reader.go b/vendor/github.com/ncw/swift/watchdog_reader.go deleted file mode 100644 index 2714c9e1a..000000000 --- a/vendor/github.com/ncw/swift/watchdog_reader.go +++ /dev/null @@ -1,55 +0,0 @@ -package swift - -import ( - "io" - "time" -) - -var watchdogChunkSize = 1 << 20 // 1 MiB - -// An io.Reader which resets a watchdog timer whenever data is read -type watchdogReader struct { - timeout time.Duration - reader io.Reader - timer *time.Timer - chunkSize int -} - -// Returns a new reader which will kick the watchdog timer whenever data is read -func newWatchdogReader(reader io.Reader, timeout time.Duration, timer *time.Timer) *watchdogReader { - return &watchdogReader{ - timeout: timeout, - reader: reader, - timer: timer, - chunkSize: watchdogChunkSize, - } -} - -// Read reads up to len(p) bytes into p -func (t *watchdogReader) Read(p []byte) (int, error) { - //read from underlying reader in chunks not larger than t.chunkSize - //while resetting the watchdog timer before every read; the small chunk - //size ensures that the timer does not fire when reading a large amount of - //data from a slow connection - start := 0 - end := len(p) - for start < end { - length := end - start - if length > t.chunkSize { - length = t.chunkSize - } - - resetTimer(t.timer, t.timeout) - n, err := t.reader.Read(p[start : start+length]) - start += n - if n == 0 || err != nil { - return start, err - } - } - - resetTimer(t.timer, t.timeout) - return start, nil -} - -// Check it satisfies the interface -var _ io.Reader = &watchdogReader{} diff --git a/vendor/modules.txt b/vendor/modules.txt index a6bf22b11..c577f9692 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -268,10 +268,6 @@ github.com/matttproud/golang_protobuf_extensions/pbutil github.com/mitchellh/mapstructure # github.com/mitchellh/osext v0.0.0-20151018003038-5e2d6d41470f ## explicit -# github.com/ncw/swift v1.0.47 -## explicit -github.com/ncw/swift -github.com/ncw/swift/swifttest # github.com/opencontainers/go-digest v1.0.0 ## explicit; go 1.13 github.com/opencontainers/go-digest