1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
|
package objects
import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack/objectstorage/v1/containers"
"github.com/gophercloud/gophercloud/openstack/objectstorage/v1/objects"
"github.com/gophercloud/gophercloud/pagination"
)
// DownloadOpts represents options used for downloading an object.
type DownloadOpts struct {
// Delimiter is a delimiter to specify for listing objects.
Delimiter string
// IgnoreMtime won't update the downloaded file's mtime.
IgnoreMtime bool
// NoDownload won't actually download the object.
NoDownload bool
// OutDirectory is a directory to save the objects to.
OutDirectory string
// OutFile is a file to save the object to.
OutFile string
// Prefix is a prefix string for a container.
Prefix string
// RemovePrefix will remove the prefix from the container.
RemovePrefix bool
// SkipIdentical will skip identical objects already downloaded.
SkipIdentical bool
// YesAll will download everything.
YesAll bool
}
// Download downloads one or more objects from an Object Storage account.
// It is roughly based on the python-swiftclient implementation:
//
// https://github.com/openstack/python-swiftclient/blob/e65070964c7b1e04119c87e5f344d39358780d18/swiftclient/service.py#L1024
func Download(client *gophercloud.ServiceClient, containerName string, objectNames []string, opts *DownloadOpts) ([]DownloadResult, error) {
var downloadResults []DownloadResult
if strings.Contains(containerName, "/") {
return nil, fmt.Errorf("container name %s contains a /", containerName)
}
if containerName == "" {
if opts.YesAll {
// Download everything
listOpts := containers.ListOpts{
Full: true,
Delimiter: opts.Delimiter,
Prefix: opts.Prefix,
}
err := containers.List(client, listOpts).EachPage(func(page pagination.Page) (bool, error) {
containerList, err := containers.ExtractInfo(page)
if err != nil {
return false, fmt.Errorf("error listing containers: %s", err)
}
for _, c := range containerList {
results, err := downloadContainer(client, c.Name, opts)
if err != nil {
return false, fmt.Errorf("error downloading container %s: %s", c.Name, err)
}
downloadResults = append(downloadResults, results...)
}
return true, nil
})
if err != nil {
return nil, fmt.Errorf("error downloading container %s: %s", containerName, err)
}
return downloadResults, nil
}
}
if len(objectNames) == 0 {
results, err := downloadContainer(client, containerName, opts)
if err != nil {
return nil, fmt.Errorf("error downloading container %s: %s", containerName, err)
}
downloadResults = append(downloadResults, results...)
return downloadResults, nil
}
for _, objectName := range objectNames {
result, err := downloadObject(client, containerName, objectName, opts)
if err != nil {
return nil, fmt.Errorf("error downloading object %s/%s: %s", containerName, objectName, err)
}
downloadResults = append(downloadResults, *result)
}
return downloadResults, nil
}
// downloadObject will download a specified object.
func downloadObject(client *gophercloud.ServiceClient, containerName string, objectName string, opts *DownloadOpts) (*DownloadResult, error) {
var objectDownloadOpts objects.DownloadOpts
var pseudoDir bool
// Perform a get on the object in order to get its metadata.
originalObject := objects.Get(client, containerName, objectName, nil)
if originalObject.Err != nil {
return nil, fmt.Errorf("error retrieving object %s/%s: %s", containerName, objectName, originalObject.Err)
}
originalMetadata, err := originalObject.ExtractMetadata()
if err != nil {
return nil, fmt.Errorf("error extracting object metadata for %s/%s: %s", containerName, objectName, err)
}
objectPath := objectName
if opts.YesAll {
objectPath = path.Join(containerName, objectName)
}
// SkipIdentical is not possible when stdout has been specified.
opts.SkipIdentical = opts.SkipIdentical && opts.OutFile != "-"
if opts.Prefix != "" && opts.RemovePrefix {
objectPath = string(objectPath[len(opts.Prefix):])
}
if opts.OutDirectory != "" {
objectPath = path.Join(opts.OutDirectory, objectName)
}
filename := objectPath
if opts.OutFile != "" && opts.OutFile != "-" {
filename = opts.OutFile
}
// SkipIdentical will get the md5sum of the existing local file.
// It'll use it in the If-None-Match header.
if opts.SkipIdentical {
objectDownloadOpts.MultipartManifest = "get"
md5, err := FileMD5Sum(filename)
if err != nil && !os.IsNotExist(err) {
return nil, fmt.Errorf("error getting md5sum of file %s: %s", filename, err)
}
if md5 != "" {
objectDownloadOpts.IfNoneMatch = md5
}
}
// Attempt to download the object
res := objects.Download(client, containerName, objectName, objectDownloadOpts)
if res.Err != nil {
// Ignore the error if SkipIdentical is set.
// This is because a second attempt to download the object will happen later.
if !opts.SkipIdentical {
return nil, fmt.Errorf("error getting object %s/%s: %s", containerName, objectName, res.Err)
}
}
headers, err := res.Extract()
if err != nil {
return nil, fmt.Errorf("error extracting headers from %s: %s", objectName, err)
}
if opts.SkipIdentical {
// Determine if the downloaded object has a manifest or is a Static Large
// Object.
//
// This is a little odd. It should be doing the same thing that
// python-swiftclient is doing, though.
var hasManifest bool
var manifest string
if headers.ObjectManifest != "" {
hasManifest = true
manifest = ""
}
if headers.StaticLargeObject {
hasManifest = true
manifest = "[]"
}
if hasManifest {
mo := GetManifestOpts{
ContainerName: containerName,
ContentLength: headers.ContentLength,
ETag: headers.ETag,
ObjectName: objectName,
ObjectManifest: headers.ObjectManifest,
Manifest: manifest,
StaticLargeObject: headers.StaticLargeObject,
}
manifestData, err := GetManifest(client, mo)
if err != nil {
return nil, fmt.Errorf("unable to get manifest for %s/%s: %s", containerName, objectName, err)
}
if len(manifestData) > 0 {
ok, err := IsIdentical(manifestData, filename)
if err != nil {
return nil, fmt.Errorf("error comparing object %s/%s and path %s: %s", containerName, objectName, filename, err)
}
if ok {
downloadResult := &DownloadResult{
Action: "download_object",
Container: containerName,
Object: objectName,
Path: objectPath,
PseudoDir: pseudoDir,
Success: true,
}
return downloadResult, nil
}
// This is a Large object
objectDownloadOpts.MultipartManifest = ""
res = objects.Download(client, containerName, objectName, objectDownloadOpts)
if res.Err != nil {
return nil, fmt.Errorf("error downloading object %s/%s: %s", containerName, objectName, err)
}
}
}
}
if opts.OutFile == "-" && !opts.NoDownload {
downloadResult := &DownloadResult{
Action: "download_object",
Container: containerName,
Content: res.Body,
Object: objectName,
Path: objectPath,
PseudoDir: pseudoDir,
Success: true,
}
return downloadResult, nil
}
contentType := GetContentType(headers.ContentType)
var ctMatch bool
for _, kdm := range knownDirMarkers {
if contentType == kdm {
pseudoDir = true
ctMatch = true
}
}
// I'm not sure if 0777 is appropriate here.
// It looks to be what python-swiftclient and python os.makedirs is doing.
if ctMatch && opts.OutFile != "-" && !opts.NoDownload {
if err := os.MkdirAll(objectPath, 0777); err != nil {
return nil, fmt.Errorf("error creating directory %s: %s", objectPath, err)
}
} else {
mkdir := !(opts.NoDownload || opts.OutFile == "")
if mkdir {
dir := filepath.Dir(objectPath)
if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0777); err != nil {
return nil, fmt.Errorf("error creating directory %s: %s", dir, err)
}
}
}
var file string
if !opts.NoDownload {
if opts.OutFile != "" {
file = opts.OutFile
} else {
if strings.HasSuffix(objectPath, "/") {
pseudoDir = true
} else {
file = objectPath
}
}
}
if file != "" {
f, err := os.Create(file)
if err != nil {
return nil, fmt.Errorf("error creating file %s: %s", file, err)
}
defer f.Close()
buf := make([]byte, diskBuffer)
for {
chunk, err := res.Body.Read(buf)
if err != nil && err != io.EOF {
return nil, fmt.Errorf("error reading object %s/%s: %s", containerName, objectName, err)
}
if chunk == 0 {
break
}
if _, err := f.Write(buf[:chunk]); err != nil {
return nil, fmt.Errorf("error writing file %s: %s", file, err)
}
}
f.Close()
}
if !opts.NoDownload && !opts.IgnoreMtime {
if v, ok := originalMetadata["Mtime"]; ok {
epoch, err := strconv.ParseInt(v, 10, 64)
if err == nil {
epoch = epoch * 1000000000
mtime := time.Unix(epoch, 0)
if err := os.Chtimes(file, mtime, mtime); err != nil {
return nil, fmt.Errorf("error updating mtime for %s: %s", file, err)
}
}
}
}
}
downloadResult := &DownloadResult{
Action: "download_object",
Success: true,
Container: containerName,
Object: objectName,
Path: objectPath,
PseudoDir: pseudoDir,
}
return downloadResult, nil
}
// downloadContainer will download all objects in a given container.
func downloadContainer(client *gophercloud.ServiceClient, containerName string, opts *DownloadOpts) ([]DownloadResult, error) {
listOpts := objects.ListOpts{
Full: true,
Prefix: opts.Prefix,
Delimiter: opts.Delimiter,
}
var downloadResults []DownloadResult
err := objects.List(client, containerName, listOpts).EachPage(func(page pagination.Page) (bool, error) {
objectList, err := objects.ExtractNames(page)
if err != nil {
return false, fmt.Errorf("error listing container %s: %s", containerName, err)
}
for _, objectName := range objectList {
result, err := downloadObject(client, containerName, objectName, opts)
if err != nil {
return false, fmt.Errorf("error downloading object %s/%s: %s", containerName, objectName, err)
}
downloadResults = append(downloadResults, *result)
}
return true, nil
})
if err != nil {
return nil, fmt.Errorf("error downloading container %s: %s", containerName, err)
}
return downloadResults, nil
}
|