Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b4dd693d23 | ||
|
|
1b3a49929b | ||
|
|
1ea9972be7 | ||
|
|
2e5f0ef258 | ||
|
|
dc0e9383a8 | ||
|
|
5575ee2933 | ||
|
|
fec3661fe1 | ||
|
|
2a4c721794 | ||
|
|
7d786204b4 | ||
|
|
b3f1a45bbf | ||
|
|
0a108832e2 | ||
|
|
8fd43a52e7 | ||
|
|
eefe789fc2 | ||
|
|
a34bf2ae5e | ||
|
|
90738f4081 | ||
|
|
754c54b64f | ||
|
|
7153b05342 | ||
|
|
43be26d1f8 | ||
|
|
b98923a20f | ||
|
|
025e5f3f0c | ||
|
|
37d59db94e | ||
|
|
f1a08ad6bf | ||
|
|
b1f681b912 | ||
|
|
6085dc1b5a | ||
|
|
2bca3a45bd |
No files matched your search
+2
-1
@@ -1,5 +1,6 @@
|
||||
*~
|
||||
*.pyc
|
||||
test-env*
|
||||
junk/
|
||||
_junk/
|
||||
rclone
|
||||
upload
|
||||
@@ -1,16 +1,28 @@
|
||||
Rclone
|
||||
======
|
||||
|
||||
[](http://rclone.org/)
|
||||
|
||||
Sync files and directories to and from
|
||||
|
||||
* Openstack Swift
|
||||
* Rackspace cloud files
|
||||
* Amazon S3
|
||||
* Google Drive
|
||||
* Amazon S3
|
||||
* Openstack Swift / Rackspace cloud files / Memset Memstore
|
||||
* The local filesystem
|
||||
|
||||
FIXME
|
||||
Features
|
||||
|
||||
* MD5SUMs checked at all times for file integrity
|
||||
* Timestamps preserved on files
|
||||
* Partial syncs supported on a whole file basis
|
||||
* Copy mode to just copy new/changed files
|
||||
* Sync mode to make a directory identical
|
||||
* Check mode to check all MD5SUMs
|
||||
* Can sync to and from network, eg two different Drive accounts
|
||||
|
||||
Home page
|
||||
|
||||
* http://rclone.org/
|
||||
|
||||
Install
|
||||
-------
|
||||
@@ -19,19 +31,269 @@ Rclone is a Go program and comes as a single binary file.
|
||||
|
||||
Download the relevant binary from
|
||||
|
||||
- http://www.craig-wood.com/nick/pub/rclone/
|
||||
* http://www.craig-wood.com/nick/pub/rclone/
|
||||
|
||||
Or alternatively if you have Go installed use
|
||||
|
||||
go get github.com/ncw/rclone
|
||||
|
||||
and this will build the binary in `$GOPATH/bin`. You can then modify
|
||||
the source and submit patches.
|
||||
and this will build the binary in `$GOPATH/bin`.
|
||||
|
||||
You can then modify the source and submit patches.
|
||||
|
||||
Configure
|
||||
---------
|
||||
|
||||
First you'll need to configure rclone. As the object storage systems
|
||||
have quite complicated authentication these are kept in a config file
|
||||
`.rclone.conf` in your home directory by default. (You can use the
|
||||
-config option to choose a different config file.)
|
||||
|
||||
The easiest way to make the config is to run rclone with the config
|
||||
option, Eg
|
||||
|
||||
rclone config
|
||||
|
||||
Here is an example of making an s3 configuration
|
||||
|
||||
```
|
||||
$ rclone config
|
||||
No remotes found - make a new one
|
||||
n) New remote
|
||||
q) Quit config
|
||||
n/q> n
|
||||
name> remote
|
||||
What type of source is it?
|
||||
Choose a number from below
|
||||
1) swift
|
||||
2) s3
|
||||
3) local
|
||||
4) drive
|
||||
type> 2
|
||||
AWS Access Key ID.
|
||||
access_key_id> accesskey
|
||||
AWS Secret Access Key (password).
|
||||
secret_access_key> secretaccesskey
|
||||
Endpoint for S3 API.
|
||||
Choose a number from below, or type in your own value
|
||||
* The default endpoint - a good choice if you are unsure.
|
||||
* US Region, Northern Virginia or Pacific Northwest.
|
||||
* Leave location constraint empty.
|
||||
1) https://s3.amazonaws.com/
|
||||
* US Region, Northern Virginia only.
|
||||
* Leave location constraint empty.
|
||||
2) https://s3-external-1.amazonaws.com
|
||||
[snip]
|
||||
* South America (Sao Paulo) Region
|
||||
* Needs location constraint sa-east-1.
|
||||
9) https://s3-sa-east-1.amazonaws.com
|
||||
endpoint> 1
|
||||
Location constraint - must be set to match the Endpoint.
|
||||
Choose a number from below, or type in your own value
|
||||
* Empty for US Region, Northern Virginia or Pacific Northwest.
|
||||
1)
|
||||
* US West (Oregon) Region.
|
||||
2) us-west-2
|
||||
[snip]
|
||||
* South America (Sao Paulo) Region.
|
||||
9) sa-east-1
|
||||
location_constraint> 1
|
||||
--------------------
|
||||
[remote]
|
||||
access_key_id = accesskey
|
||||
secret_access_key = secretaccesskey
|
||||
endpoint = https://s3.amazonaws.com/
|
||||
location_constraint =
|
||||
--------------------
|
||||
y) Yes this is OK
|
||||
e) Edit this remote
|
||||
d) Delete this remote
|
||||
y/e/d> y
|
||||
Current remotes:
|
||||
|
||||
Name Type
|
||||
==== ====
|
||||
remote s3
|
||||
|
||||
e) Edit existing remote
|
||||
n) New remote
|
||||
d) Delete remote
|
||||
q) Quit config
|
||||
e/n/d/q> q
|
||||
```
|
||||
|
||||
This can now be used like this
|
||||
|
||||
```
|
||||
rclone lsd remote:// - see all buckets/containers
|
||||
rclone ls remote:// - list a bucket
|
||||
rclone sync /home/local/directory remote://bucket
|
||||
```
|
||||
|
||||
See the next section for more details.
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
FIXME
|
||||
Rclone syncs a directory tree from local to remote.
|
||||
|
||||
Its basic syntax is like this
|
||||
|
||||
Syntax: [options] subcommand <parameters> <parameters...>
|
||||
|
||||
See below for how to specify the source and destination paths.
|
||||
|
||||
Subcommands
|
||||
-----------
|
||||
|
||||
rclone copy source://path dest://path
|
||||
|
||||
Copy the source to the destination. Doesn't transfer
|
||||
unchanged files, testing first by modification time then by
|
||||
MD5SUM. Doesn't delete files from the destination.
|
||||
|
||||
rclone sync source://path dest://path
|
||||
|
||||
Sync the source to the destination. Doesn't transfer
|
||||
unchanged files, testing first by modification time then by
|
||||
MD5SUM. Deletes any files that exist in source that don't
|
||||
exist in destination. Since this can cause data loss, test
|
||||
first with the -dry-run flag.
|
||||
|
||||
rclone ls [remote://path]
|
||||
|
||||
List all the objects in the the path.
|
||||
|
||||
rclone lsd [remote://path]
|
||||
|
||||
List all directoryes/objects/buckets in the the path.
|
||||
|
||||
rclone mkdir remote://path
|
||||
|
||||
Make the path if it doesn't already exist
|
||||
|
||||
rclone rmdir remote://path
|
||||
|
||||
Remove the path. Note that you can't remove a path with
|
||||
objects in it, use purge for that.
|
||||
|
||||
rclone purge remote://path
|
||||
|
||||
Remove the path and all of its contents.
|
||||
|
||||
rclone check source://path dest://path
|
||||
|
||||
Checks the files in the source and destination match. It
|
||||
compares sizes and MD5SUMs and prints a report of files which
|
||||
don't match. It doesn't alter the source or destination.
|
||||
|
||||
General options:
|
||||
* `-config` Location of the config file
|
||||
* `-transfers=4`: Number of file transfers to run in parallel.
|
||||
* `-checkers=8`: Number of MD5SUM checkers to run in parallel.
|
||||
* `-dry-run=false`: Do a trial run with no permanent changes
|
||||
* `-modify-window=1ns`: Max time difference to be considered the same - this is automatically set usually
|
||||
* `-quiet=false`: Print as little stuff as possible
|
||||
* `-stats=1m0s`: Interval to print stats
|
||||
* `-verbose=false`: Print lots more stuff
|
||||
|
||||
Developer options:
|
||||
* `-cpuprofile=""`: Write cpu profile to file
|
||||
|
||||
Local Filesystem
|
||||
----------------
|
||||
|
||||
Paths are specified as normal filesystem paths, so
|
||||
|
||||
rclone sync /home/source /tmp/destination
|
||||
|
||||
Will sync source to destination
|
||||
|
||||
Swift / Rackspace cloudfiles / Memset Memstore
|
||||
----------------------------------------------
|
||||
|
||||
Paths are specified as remote://container (or remote:// for the `lsd`
|
||||
command.)
|
||||
|
||||
So to copy a local directory to a swift container called backup:
|
||||
|
||||
rclone sync /home/source swift://backup
|
||||
|
||||
The modified time is stored as metadata on the object as
|
||||
`X-Object-Meta-Mtime` as floating point since the epoch.
|
||||
|
||||
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.
|
||||
|
||||
Amazon S3
|
||||
---------
|
||||
|
||||
Paths are specified as remote://bucket
|
||||
|
||||
So to copy a local directory to a s3 container called backup
|
||||
|
||||
rclone sync /home/source s3://backup
|
||||
|
||||
The modified time is stored as metadata on the object as
|
||||
`X-Amz-Meta-Mtime` as floating point since the epoch.
|
||||
|
||||
Google drive
|
||||
------------
|
||||
|
||||
Paths are specified as drive://path Drive paths may be as deep as required.
|
||||
|
||||
The initial setup for drive involves getting a token from Google drive
|
||||
which you need to do in your browser. The `rclone config` walks you
|
||||
through it.
|
||||
|
||||
Here is an example of how to make a remote called `drv`
|
||||
|
||||
```
|
||||
$ ./rclone config
|
||||
n) New remote
|
||||
d) Delete remote
|
||||
q) Quit config
|
||||
e/n/d/q> n
|
||||
name> drv
|
||||
What type of source is it?
|
||||
Choose a number from below
|
||||
1) swift
|
||||
2) s3
|
||||
3) local
|
||||
4) drive
|
||||
type> 4
|
||||
Google Application Client Id - leave blank to use rclone's.
|
||||
client_id>
|
||||
Google Application Client Secret - leave blank to use rclone's.
|
||||
client_secret>
|
||||
Remote config
|
||||
Go to the following link in your browser
|
||||
https://accounts.google.com/o/oauth2/auth?access_type=&approval_prompt=&client_id=XXXXXXXXXXXX.apps.googleusercontent.com&redirect_uri=urn%3XXXXX%3Awg%3Aoauth%3XX.0%3Aoob&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&state=state
|
||||
Log in, then type paste the token that is returned in the browser here
|
||||
Enter verification code> X/XXXXXXXXXXXXXXXXXX-XXXXXXXXX.XXXXXXXXX-XXXXX_XXXXXXX_XXXXXXX
|
||||
--------------------
|
||||
[drv]
|
||||
client_id =
|
||||
client_secret =
|
||||
token = {"AccessToken":"xxxx.xxxxxxx_xxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","RefreshToken":"1/xxxxxxxxxxxxxxxx_xxxxxxxxxxxxxxxxxxxxxxxxxx","Expiry":"2014-03-16T13:57:58.955387075Z","Extra":null}
|
||||
--------------------
|
||||
y) Yes this is OK
|
||||
e) Edit this remote
|
||||
d) Delete this remote
|
||||
y/e/d> y
|
||||
```
|
||||
|
||||
You can then use it like this
|
||||
|
||||
rclone lsd drv://
|
||||
rclone ls drv://
|
||||
|
||||
To copy a local directory to a drive directory called backup
|
||||
|
||||
rclone copy /home/source drv://backup
|
||||
|
||||
Google drive stores modification times accurate to 1 ms.
|
||||
|
||||
License
|
||||
-------
|
||||
@@ -39,21 +301,30 @@ License
|
||||
This is free software under the terms of MIT the license (check the
|
||||
COPYING file included in this package).
|
||||
|
||||
Bugs
|
||||
----
|
||||
|
||||
* Doesn't sync individual files yet, only directories.
|
||||
* Drive: Sometimes get: Failed to copy: Upload failed: googleapi: Error 403: Rate Limit Exceeded
|
||||
* quota is 100.0 requests/second/user
|
||||
* Empty directories left behind with Local and Drive
|
||||
* eg purging a local directory with subdirectories doesn't work
|
||||
|
||||
Contact and support
|
||||
-------------------
|
||||
|
||||
The project website is at:
|
||||
|
||||
- https://github.com/ncw/rclone
|
||||
* https://github.com/ncw/rclone
|
||||
|
||||
There you can file bug reports, ask for help or contribute patches.
|
||||
|
||||
Authors
|
||||
-------
|
||||
|
||||
- Nick Craig-Wood <nick@craig-wood.com>
|
||||
* Nick Craig-Wood <nick@craig-wood.com>
|
||||
|
||||
Contributors
|
||||
------------
|
||||
|
||||
- Your name goes here!
|
||||
* Your name goes here!
|
||||
-14
@@ -1,14 +0,0 @@
|
||||
// Default implementation of Chtimes
|
||||
|
||||
// +build !linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Chtimes(name string, atime time.Time, mtime time.Time) error {
|
||||
return os.Chtimes(name, atime, mtime)
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
// An implementation of Chtimes which preserves nanosecond precision under linux
|
||||
//
|
||||
// Should go in standard library, but here for now
|
||||
|
||||
// +build linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// COPIED from syscall
|
||||
// byteSliceFromString returns a NUL-terminated slice of bytes
|
||||
// containing the text of s. If s contains a NUL byte at any
|
||||
// location, it returns (nil, EINVAL).
|
||||
func byteSliceFromString(s string) ([]byte, error) {
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == 0 {
|
||||
return nil, syscall.EINVAL
|
||||
}
|
||||
}
|
||||
a := make([]byte, len(s)+1)
|
||||
copy(a, s)
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// COPIED from syscall
|
||||
// bytePtrFromString returns a pointer to a NUL-terminated array of
|
||||
// bytes containing the text of s. If s contains a NUL byte at any
|
||||
// location, it returns (nil, EINVAL).
|
||||
func bytePtrFromString(s string) (*byte, error) {
|
||||
a, err := byteSliceFromString(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &a[0], nil
|
||||
}
|
||||
|
||||
// COPIED from syscall auto generated code modified from utimes
|
||||
func utimensat(dirfd int, path string, times *[2]syscall.Timespec) (err error) {
|
||||
var _p0 *byte
|
||||
_p0, err = bytePtrFromString(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, _, e1 := syscall.Syscall(syscall.SYS_UTIMENSAT, uintptr(dirfd), uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(times)))
|
||||
if e1 != 0 {
|
||||
err = e1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// FIXME needs defining properly!
|
||||
const AT_FDCWD = -100
|
||||
|
||||
// COPIED from syscall and modified
|
||||
//sys utimes(path string, times *[2]Timeval) (err error)
|
||||
func Utimensat(dirfd int, path string, ts []syscall.Timespec) (err error) {
|
||||
if len(ts) != 2 {
|
||||
return syscall.EINVAL
|
||||
}
|
||||
return utimensat(dirfd, path, (*[2]syscall.Timespec)(unsafe.Pointer(&ts[0])))
|
||||
}
|
||||
|
||||
// COPIED from syscall and modified
|
||||
func Chtimes(name string, atime time.Time, mtime time.Time) error {
|
||||
var utimes [2]syscall.Timespec
|
||||
utimes[0] = syscall.NsecToTimespec(atime.UnixNano())
|
||||
utimes[1] = syscall.NsecToTimespec(mtime.UnixNano())
|
||||
if e := Utimensat(AT_FDCWD, name, utimes[0:]); e != nil {
|
||||
return &os.PathError{Op: "chtimes", Path: name, Err: e}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/bin/sh
|
||||
|
||||
# This uses gox from https://github.com/mitchellh/gox
|
||||
# Make sure you've run gox -build-toolchain
|
||||
|
||||
rm -rf build
|
||||
|
||||
gox -output "build/{{.OS}}/{{.Arch}}/{{.Dir}}"
|
||||
|
||||
cat <<'#EOF' > build/README.txt
|
||||
This directory contains builds of the rclone program.
|
||||
|
||||
Rclone a program designed to stress test your disks and find
|
||||
failures in them.
|
||||
|
||||
Use it to soak test your new disks / memory cards / USB sticks before
|
||||
trusting your valuable data to it.
|
||||
|
||||
See the project website here: https://github.com/ncw/rclone for
|
||||
more details.
|
||||
|
||||
The files in this directory are organised by OS and processor type
|
||||
|
||||
#EOF
|
||||
|
||||
mv build/darwin build/osx
|
||||
|
||||
( cd build ; tree . >> README.txt )
|
||||
+193
-142
@@ -1,20 +1,14 @@
|
||||
// Drive interface
|
||||
package main
|
||||
package drive
|
||||
|
||||
// FIXME drive code is leaking goroutines somehow - reported bug
|
||||
// https://code.google.com/p/google-api-go-client/issues/detail?id=23
|
||||
// Gets this quite often
|
||||
// Failed to set mtime: googleapi: Error 403: Rate Limit Exceeded
|
||||
|
||||
// FIXME list containers equivalent should list directories?
|
||||
|
||||
// FIXME list directory should list to channel for concurrency not
|
||||
// append to array
|
||||
|
||||
// FIXME perhaps have a drive setup mode where we ask for all the
|
||||
// params interactively and store them all in one file
|
||||
// - don't need to store client* apparently
|
||||
|
||||
// NB permissions of token file is too open
|
||||
|
||||
// FIXME need to deal with some corner cases
|
||||
// * multiple files with the same name
|
||||
// * files can be in multiple directories
|
||||
@@ -22,23 +16,123 @@ package main
|
||||
// * files with / in name
|
||||
|
||||
import (
|
||||
"code.google.com/p/goauth2/oauth"
|
||||
"code.google.com/p/google-api-go-client/drive/v2"
|
||||
"errors"
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"code.google.com/p/goauth2/oauth"
|
||||
"code.google.com/p/google-api-go-client/drive/v2"
|
||||
"github.com/ncw/rclone/fs"
|
||||
)
|
||||
|
||||
// Constants
|
||||
const (
|
||||
rcloneClientId = "202264815644.apps.googleusercontent.com"
|
||||
rcloneClientSecret = "X4Z3ca8xfWDb1Voo-F9a7ZxJ"
|
||||
driveFolderType = "application/vnd.google-apps.folder"
|
||||
)
|
||||
|
||||
// Globals
|
||||
var (
|
||||
// Flags
|
||||
driveFullList = flag.Bool("drive-full-list", true, "Use a full listing for directory list. More data but usually quicker.")
|
||||
)
|
||||
|
||||
// Register with Fs
|
||||
func init() {
|
||||
fs.Register(&fs.FsInfo{
|
||||
Name: "drive",
|
||||
NewFs: NewFs,
|
||||
Config: Config,
|
||||
Options: []fs.Option{{
|
||||
Name: "client_id",
|
||||
Help: "Google Application Client Id - leave blank to use rclone's.",
|
||||
}, {
|
||||
Name: "client_secret",
|
||||
Help: "Google Application Client Secret - leave blank to use rclone's.",
|
||||
}},
|
||||
})
|
||||
}
|
||||
|
||||
// Configuration helper - called after the user has put in the defaults
|
||||
func Config(name string) {
|
||||
// See if already have a token
|
||||
tokenString := fs.ConfigFile.MustValue(name, "token")
|
||||
if tokenString != "" {
|
||||
fmt.Printf("Already have a drive token - refresh?\n")
|
||||
if !fs.Confirm() {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Get a drive transport
|
||||
t, err := newDriveTransport(name)
|
||||
if err != nil {
|
||||
log.Fatalf("Couldn't make drive transport: %v", err)
|
||||
}
|
||||
|
||||
// Generate a URL for the user to visit for authorization.
|
||||
authUrl := t.Config.AuthCodeURL("state")
|
||||
fmt.Printf("Go to the following link in your browser\n")
|
||||
fmt.Printf("%s\n", authUrl)
|
||||
fmt.Printf("Log in, then type paste the token that is returned in the browser here\n")
|
||||
|
||||
// Read the code, and exchange it for a token.
|
||||
fmt.Printf("Enter verification code> ")
|
||||
authCode := fs.ReadLine()
|
||||
_, err = t.Exchange(authCode)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to get token: %v", err)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// A token cache to save the token in the config file section named
|
||||
type tokenCache string
|
||||
|
||||
// Get the token from the config file - returns an error if it isn't present
|
||||
func (name tokenCache) Token() (*oauth.Token, error) {
|
||||
tokenString, err := fs.ConfigFile.GetValue(string(name), "token")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if tokenString == "" {
|
||||
return nil, fmt.Errorf("Empty token found - please reconfigure")
|
||||
}
|
||||
token := new(oauth.Token)
|
||||
err = json.Unmarshal([]byte(tokenString), token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return token, nil
|
||||
|
||||
}
|
||||
|
||||
// Save the token to the config file
|
||||
//
|
||||
// This saves the config file if it changes
|
||||
func (name tokenCache) PutToken(token *oauth.Token) error {
|
||||
tokenBytes, err := json.Marshal(token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tokenString := string(tokenBytes)
|
||||
old := fs.ConfigFile.MustValue(string(name), "token")
|
||||
if tokenString != old {
|
||||
fs.ConfigFile.SetValue(string(name), "token", tokenString)
|
||||
fs.SaveConfig()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// FsDrive represents a remote drive server
|
||||
type FsDrive struct {
|
||||
svc *drive.Service // the connection to the drive server
|
||||
@@ -110,39 +204,14 @@ func (m *dirCache) Flush() {
|
||||
|
||||
// ------------------------------------------------------------
|
||||
|
||||
// Constants
|
||||
const (
|
||||
// defaultDriveTokenFile = ".google-drive-token" // FIXME root in home directory somehow
|
||||
driveFolderType = "application/vnd.google-apps.folder"
|
||||
)
|
||||
|
||||
// Globals
|
||||
var (
|
||||
// Flags
|
||||
driveClientId = flag.String("drive-client-id", os.Getenv("GDRIVE_CLIENT_ID"), "Auth URL for server. Defaults to environment var GDRIVE_CLIENT_ID.")
|
||||
driveClientSecret = flag.String("drive-client-secret", os.Getenv("GDRIVE_CLIENT_SECRET"), "User name. Defaults to environment var GDRIVE_CLIENT_SECRET.")
|
||||
driveTokenFile = flag.String("drive-token-file", os.Getenv("GDRIVE_TOKEN_FILE"), "API key (password). Defaults to environment var GDRIVE_TOKEN_FILE.")
|
||||
driveAuthCode = flag.String("drive-auth-code", "", "Pass in when requested to make the drive token file.")
|
||||
driveFullList = flag.Bool("drive-full-list", true, "Use a full listing for directory list. More data but usually quicker.")
|
||||
)
|
||||
|
||||
// String converts this FsDrive to a string
|
||||
func (f *FsDrive) String() string {
|
||||
return fmt.Sprintf("Google drive root '%s'", f.root)
|
||||
}
|
||||
|
||||
// Pattern to match a drive url
|
||||
var driveMatch = regexp.MustCompile(`^drive://(.*)$`)
|
||||
|
||||
// parseParse parses a drive 'url'
|
||||
func parseDrivePath(path string) (root string, err error) {
|
||||
parts := driveMatch.FindAllStringSubmatch(path, -1)
|
||||
if len(parts) != 1 || len(parts[0]) != 2 {
|
||||
err = fmt.Errorf("Couldn't parse drive url %q", path)
|
||||
} else {
|
||||
root = parts[0][1]
|
||||
root = strings.Trim(root, "/")
|
||||
}
|
||||
root = strings.Trim(root, "/")
|
||||
return
|
||||
}
|
||||
|
||||
@@ -195,47 +264,41 @@ OUTER:
|
||||
return
|
||||
}
|
||||
|
||||
// Ask the user for a new auth
|
||||
func MakeNewToken(t *oauth.Transport) error {
|
||||
if *driveAuthCode == "" {
|
||||
// Generate a URL to visit for authorization.
|
||||
authUrl := t.Config.AuthCodeURL("state")
|
||||
fmt.Fprintf(os.Stderr, "Go to the following link in your browser\n")
|
||||
fmt.Fprintf(os.Stderr, "%s\n", authUrl)
|
||||
fmt.Fprintf(os.Stderr, "Log in, then re-run this program with the -drive-auth-code parameter\n")
|
||||
fmt.Fprintf(os.Stderr, "You only need this parameter once until the drive token file has been created\n")
|
||||
return errors.New("Re-run with --drive-auth-code")
|
||||
// Makes a new drive transport from the config
|
||||
func newDriveTransport(name string) (*oauth.Transport, error) {
|
||||
clientId := fs.ConfigFile.MustValue(name, "client_id")
|
||||
if clientId == "" {
|
||||
clientId = rcloneClientId
|
||||
}
|
||||
|
||||
// Read the code, and exchange it for a token.
|
||||
//fmt.Printf("Enter verification code: ")
|
||||
//var code string
|
||||
//fmt.Scanln(&code)
|
||||
_, err := t.Exchange(*driveAuthCode)
|
||||
return err
|
||||
}
|
||||
|
||||
// NewFsDrive contstructs an FsDrive from the path, container:path
|
||||
func NewFsDrive(path string) (*FsDrive, error) {
|
||||
if *driveClientId == "" {
|
||||
return nil, errors.New("Need -drive-client-id or environmental variable GDRIVE_CLIENT_ID")
|
||||
}
|
||||
if *driveClientSecret == "" {
|
||||
return nil, errors.New("Need -drive-client-secret or environmental variable GDRIVE_CLIENT_SECRET")
|
||||
}
|
||||
if *driveTokenFile == "" {
|
||||
return nil, errors.New("Need -drive-token-file or environmental variable GDRIVE_TOKEN_FILE")
|
||||
clientSecret := fs.ConfigFile.MustValue(name, "client_secret")
|
||||
if clientSecret == "" {
|
||||
clientSecret = rcloneClientSecret
|
||||
}
|
||||
|
||||
// Settings for authorization.
|
||||
var driveConfig = &oauth.Config{
|
||||
ClientId: *driveClientId,
|
||||
ClientSecret: *driveClientSecret,
|
||||
ClientId: clientId,
|
||||
ClientSecret: clientSecret,
|
||||
Scope: "https://www.googleapis.com/auth/drive",
|
||||
RedirectURL: "urn:ietf:wg:oauth:2.0:oob",
|
||||
AuthURL: "https://accounts.google.com/o/oauth2/auth",
|
||||
TokenURL: "https://accounts.google.com/o/oauth2/token",
|
||||
TokenCache: oauth.CacheFile(*driveTokenFile),
|
||||
TokenCache: tokenCache(name),
|
||||
}
|
||||
|
||||
t := &oauth.Transport{
|
||||
Config: driveConfig,
|
||||
Transport: http.DefaultTransport,
|
||||
}
|
||||
|
||||
return t, nil
|
||||
}
|
||||
|
||||
// NewFs contstructs an FsDrive from the path, container:path
|
||||
func NewFs(name, path string) (fs.Fs, error) {
|
||||
t, err := newDriveTransport(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
root, err := parseDrivePath(path)
|
||||
@@ -244,22 +307,10 @@ func NewFsDrive(path string) (*FsDrive, error) {
|
||||
}
|
||||
f := &FsDrive{root: root, dirCache: newDirCache()}
|
||||
|
||||
t := &oauth.Transport{
|
||||
Config: driveConfig,
|
||||
Transport: http.DefaultTransport,
|
||||
}
|
||||
|
||||
// Try to pull the token from the cache; if this fails, we need to get one.
|
||||
token, err := driveConfig.TokenCache.Token()
|
||||
token, err := t.Config.TokenCache.Token()
|
||||
if err != nil {
|
||||
err := MakeNewToken(t)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to authorise: %s", err)
|
||||
}
|
||||
} else {
|
||||
if *driveAuthCode != "" {
|
||||
return nil, fmt.Errorf("Only supply -drive-auth-code once")
|
||||
}
|
||||
return nil, fmt.Errorf("Failed to get token: %s", err)
|
||||
}
|
||||
t.Token = token
|
||||
|
||||
@@ -287,7 +338,7 @@ func NewFsDrive(path string) (*FsDrive, error) {
|
||||
// Return an FsObject from a path
|
||||
//
|
||||
// May return nil if an error occurred
|
||||
func (f *FsDrive) NewFsObjectWithInfo(remote string, info *drive.File) FsObject {
|
||||
func (f *FsDrive) NewFsObjectWithInfo(remote string, info *drive.File) fs.Object {
|
||||
fs := &FsObjectDrive{
|
||||
drive: f,
|
||||
remote: remote,
|
||||
@@ -297,7 +348,7 @@ func (f *FsDrive) NewFsObjectWithInfo(remote string, info *drive.File) FsObject
|
||||
} else {
|
||||
err := fs.readMetaData() // reads info and meta, returning an error
|
||||
if err != nil {
|
||||
// logged already FsDebug("Failed to read info: %s", err)
|
||||
// logged already fs.Debug("Failed to read info: %s", err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -307,7 +358,7 @@ func (f *FsDrive) NewFsObjectWithInfo(remote string, info *drive.File) FsObject
|
||||
// Return an FsObject from a path
|
||||
//
|
||||
// May return nil if an error occurred
|
||||
func (f *FsDrive) NewFsObject(remote string) FsObject {
|
||||
func (f *FsDrive) NewFsObject(remote string) fs.Object {
|
||||
return f.NewFsObjectWithInfo(remote, nil)
|
||||
}
|
||||
|
||||
@@ -317,7 +368,7 @@ func (f *FsDrive) NewFsObject(remote string) FsObject {
|
||||
//
|
||||
// This fetches the minimum amount of stuff but does more API calls
|
||||
// which makes it slow
|
||||
func (f *FsDrive) listDirRecursive(dirId string, path string, out FsObjectsChan) error {
|
||||
func (f *FsDrive) listDirRecursive(dirId string, path string, out fs.ObjectsChan) error {
|
||||
var subError error
|
||||
// Make the API request
|
||||
_, err := f.listAll(dirId, "", false, false, func(item *drive.File) bool {
|
||||
@@ -355,7 +406,7 @@ func (f *FsDrive) listDirRecursive(dirId string, path string, out FsObjectsChan)
|
||||
//
|
||||
// This is fast in terms of number of API calls, but slow in terms of
|
||||
// fetching more data than it needs
|
||||
func (f *FsDrive) listDirFull(dirId string, path string, out FsObjectsChan) error {
|
||||
func (f *FsDrive) listDirFull(dirId string, path string, out fs.ObjectsChan) error {
|
||||
// Orphans waiting for their parent
|
||||
orphans := make(map[string][]*drive.File)
|
||||
|
||||
@@ -545,13 +596,13 @@ func (f *FsDrive) findRoot(create bool) error {
|
||||
}
|
||||
|
||||
// Walk the path returning a channel of FsObjects
|
||||
func (f *FsDrive) List() FsObjectsChan {
|
||||
out := make(FsObjectsChan, *checkers)
|
||||
func (f *FsDrive) List() fs.ObjectsChan {
|
||||
out := make(fs.ObjectsChan, fs.Config.Checkers)
|
||||
go func() {
|
||||
defer close(out)
|
||||
err := f.findRoot(false)
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf("Couldn't find root: %s", err)
|
||||
} else {
|
||||
if *driveFullList {
|
||||
@@ -560,7 +611,7 @@ func (f *FsDrive) List() FsObjectsChan {
|
||||
err = f.listDirRecursive(f.rootId, "", out)
|
||||
}
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf("List failed: %s", err)
|
||||
}
|
||||
}
|
||||
@@ -569,17 +620,17 @@ func (f *FsDrive) List() FsObjectsChan {
|
||||
}
|
||||
|
||||
// Walk the path returning a channel of FsObjects
|
||||
func (f *FsDrive) ListDir() FsDirChan {
|
||||
out := make(FsDirChan, *checkers)
|
||||
func (f *FsDrive) ListDir() fs.DirChan {
|
||||
out := make(fs.DirChan, fs.Config.Checkers)
|
||||
go func() {
|
||||
defer close(out)
|
||||
err := f.findRoot(false)
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf("Couldn't find root: %s", err)
|
||||
} else {
|
||||
_, err := f.listAll(f.rootId, "", true, false, func(item *drive.File) bool {
|
||||
dir := &FsDir{
|
||||
dir := &fs.Dir{
|
||||
Name: item.Title,
|
||||
Bytes: -1,
|
||||
Count: -1,
|
||||
@@ -589,7 +640,7 @@ func (f *FsDrive) ListDir() FsDirChan {
|
||||
return false
|
||||
})
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf("ListDir failed: %s", err)
|
||||
}
|
||||
}
|
||||
@@ -602,7 +653,7 @@ func (f *FsDrive) ListDir() FsDirChan {
|
||||
// Copy the reader in to the new object which is returned
|
||||
//
|
||||
// The new object may have been created
|
||||
func (f *FsDrive) Put(in io.Reader, remote string, modTime time.Time, size int64) (FsObject, error) {
|
||||
func (f *FsDrive) Put(in io.Reader, remote string, modTime time.Time, size int64) (fs.Object, error) {
|
||||
// Temporary FsObject under construction
|
||||
fs := &FsObjectDrive{drive: f, remote: remote}
|
||||
|
||||
@@ -710,45 +761,45 @@ func (f *FsDrive) Purge() error {
|
||||
// ------------------------------------------------------------
|
||||
|
||||
// Return the remote path
|
||||
func (fs *FsObjectDrive) Remote() string {
|
||||
return fs.remote
|
||||
func (o *FsObjectDrive) Remote() string {
|
||||
return o.remote
|
||||
}
|
||||
|
||||
// Md5sum returns the Md5sum of an object returning a lowercase hex string
|
||||
func (fs *FsObjectDrive) Md5sum() (string, error) {
|
||||
return fs.md5sum, nil
|
||||
func (o *FsObjectDrive) Md5sum() (string, error) {
|
||||
return o.md5sum, nil
|
||||
}
|
||||
|
||||
// Size returns the size of an object in bytes
|
||||
func (fs *FsObjectDrive) Size() int64 {
|
||||
return fs.bytes
|
||||
func (o *FsObjectDrive) Size() int64 {
|
||||
return o.bytes
|
||||
}
|
||||
|
||||
// setMetaData sets the fs data from a drive.File
|
||||
func (fs *FsObjectDrive) setMetaData(info *drive.File) {
|
||||
fs.id = info.Id
|
||||
fs.url = info.DownloadUrl
|
||||
fs.md5sum = strings.ToLower(info.Md5Checksum)
|
||||
fs.bytes = info.FileSize
|
||||
fs.modifiedDate = info.ModifiedDate
|
||||
func (o *FsObjectDrive) setMetaData(info *drive.File) {
|
||||
o.id = info.Id
|
||||
o.url = info.DownloadUrl
|
||||
o.md5sum = strings.ToLower(info.Md5Checksum)
|
||||
o.bytes = info.FileSize
|
||||
o.modifiedDate = info.ModifiedDate
|
||||
}
|
||||
|
||||
// readMetaData gets the info if it hasn't already been fetched
|
||||
func (fs *FsObjectDrive) readMetaData() (err error) {
|
||||
if fs.id != "" {
|
||||
func (o *FsObjectDrive) readMetaData() (err error) {
|
||||
if o.id != "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
directory, leaf := splitPath(fs.remote)
|
||||
directoryId, err := fs.drive.findDir(directory, false)
|
||||
directory, leaf := splitPath(o.remote)
|
||||
directoryId, err := o.drive.findDir(directory, false)
|
||||
if err != nil {
|
||||
FsDebug(fs, "Couldn't find directory: %s", err)
|
||||
fs.Debug(o, "Couldn't find directory: %s", err)
|
||||
return fmt.Errorf("Couldn't find directory: %s", err)
|
||||
}
|
||||
|
||||
found, err := fs.drive.listAll(directoryId, leaf, false, true, func(item *drive.File) bool {
|
||||
found, err := o.drive.listAll(directoryId, leaf, false, true, func(item *drive.File) bool {
|
||||
if item.Title == leaf {
|
||||
fs.setMetaData(item)
|
||||
o.setMetaData(item)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -757,7 +808,7 @@ func (fs *FsObjectDrive) readMetaData() (err error) {
|
||||
return err
|
||||
}
|
||||
if !found {
|
||||
FsDebug(fs, "Couldn't find object")
|
||||
fs.Debug(o, "Couldn't find object")
|
||||
return fmt.Errorf("Couldn't find object")
|
||||
}
|
||||
return nil
|
||||
@@ -768,26 +819,26 @@ func (fs *FsObjectDrive) readMetaData() (err error) {
|
||||
//
|
||||
// It attempts to read the objects mtime and if that isn't present the
|
||||
// LastModified returned in the http headers
|
||||
func (fs *FsObjectDrive) ModTime() time.Time {
|
||||
err := fs.readMetaData()
|
||||
func (o *FsObjectDrive) ModTime() time.Time {
|
||||
err := o.readMetaData()
|
||||
if err != nil {
|
||||
FsLog(fs, "Failed to read metadata: %s", err)
|
||||
fs.Log(o, "Failed to read metadata: %s", err)
|
||||
return time.Now()
|
||||
}
|
||||
modTime, err := time.Parse(time.RFC3339, fs.modifiedDate)
|
||||
modTime, err := time.Parse(time.RFC3339, o.modifiedDate)
|
||||
if err != nil {
|
||||
FsLog(fs, "Failed to read mtime from object: %s", err)
|
||||
fs.Log(o, "Failed to read mtime from object: %s", err)
|
||||
return time.Now()
|
||||
}
|
||||
return modTime
|
||||
}
|
||||
|
||||
// Sets the modification time of the local fs object
|
||||
func (fs *FsObjectDrive) SetModTime(modTime time.Time) {
|
||||
err := fs.readMetaData()
|
||||
func (o *FsObjectDrive) SetModTime(modTime time.Time) {
|
||||
err := o.readMetaData()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(fs, "Failed to read metadata: %s", err)
|
||||
fs.Stats.Error()
|
||||
fs.Log(o, "Failed to read metadata: %s", err)
|
||||
return
|
||||
}
|
||||
// New metadata
|
||||
@@ -795,23 +846,23 @@ func (fs *FsObjectDrive) SetModTime(modTime time.Time) {
|
||||
ModifiedDate: modTime.Format(time.RFC3339Nano),
|
||||
}
|
||||
// Set modified date
|
||||
_, err = fs.drive.svc.Files.Update(fs.id, info).SetModifiedDate(true).Do()
|
||||
_, err = o.drive.svc.Files.Update(o.id, info).SetModifiedDate(true).Do()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(fs, "Failed to update remote mtime: %s", err)
|
||||
fs.Stats.Error()
|
||||
fs.Log(o, "Failed to update remote mtime: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Is this object storable
|
||||
func (fs *FsObjectDrive) Storable() bool {
|
||||
func (o *FsObjectDrive) Storable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Open an object for read
|
||||
func (fs *FsObjectDrive) Open() (in io.ReadCloser, err error) {
|
||||
req, _ := http.NewRequest("GET", fs.url, nil)
|
||||
func (o *FsObjectDrive) Open() (in io.ReadCloser, err error) {
|
||||
req, _ := http.NewRequest("GET", o.url, nil)
|
||||
req.Header.Set("User-Agent", "rclone/1.0")
|
||||
res, err := fs.drive.client.Do(req)
|
||||
res, err := o.drive.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -823,11 +874,11 @@ func (fs *FsObjectDrive) Open() (in io.ReadCloser, err error) {
|
||||
}
|
||||
|
||||
// Remove an object
|
||||
func (fs *FsObjectDrive) Remove() error {
|
||||
return fs.drive.svc.Files.Delete(fs.id).Do()
|
||||
func (o *FsObjectDrive) Remove() error {
|
||||
return o.drive.svc.Files.Delete(o.id).Do()
|
||||
}
|
||||
|
||||
// Check the interfaces are satisfied
|
||||
var _ Fs = &FsDrive{}
|
||||
var _ Purger = &FsDrive{}
|
||||
var _ FsObject = &FsObjectDrive{}
|
||||
var _ fs.Fs = &FsDrive{}
|
||||
var _ fs.Purger = &FsDrive{}
|
||||
var _ fs.Object = &FsObjectDrive{}
|
||||
@@ -1,6 +1,6 @@
|
||||
// Accounting and limiting reader
|
||||
|
||||
package main
|
||||
package fs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
// Globals
|
||||
var (
|
||||
stats = NewStats()
|
||||
Stats = NewStats()
|
||||
)
|
||||
|
||||
// Stringset holds some strings
|
||||
@@ -35,7 +35,7 @@ func (ss StringSet) String() string {
|
||||
}
|
||||
|
||||
// Stats limits and accounts all transfers
|
||||
type Stats struct {
|
||||
type StatsInfo struct {
|
||||
lock sync.RWMutex
|
||||
bytes int64
|
||||
errors int64
|
||||
@@ -46,24 +46,24 @@ type Stats struct {
|
||||
start time.Time
|
||||
}
|
||||
|
||||
// NewStats cretates an initialised Stats
|
||||
func NewStats() *Stats {
|
||||
return &Stats{
|
||||
checking: make(StringSet, *checkers),
|
||||
transferring: make(StringSet, *transfers),
|
||||
// NewStats cretates an initialised StatsInfo
|
||||
func NewStats() *StatsInfo {
|
||||
return &StatsInfo{
|
||||
checking: make(StringSet, Config.Checkers),
|
||||
transferring: make(StringSet, Config.Transfers),
|
||||
start: time.Now(),
|
||||
}
|
||||
}
|
||||
|
||||
// String convert the Stats to a string for printing
|
||||
func (s *Stats) String() string {
|
||||
// String convert the StatsInfo to a string for printing
|
||||
func (s *StatsInfo) String() string {
|
||||
s.lock.RLock()
|
||||
defer s.lock.RUnlock()
|
||||
dt := time.Now().Sub(stats.start)
|
||||
dt := time.Now().Sub(s.start)
|
||||
dt_seconds := dt.Seconds()
|
||||
speed := 0.0
|
||||
if dt > 0 {
|
||||
speed = float64(stats.bytes) / 1024 / dt_seconds
|
||||
speed = float64(s.bytes) / 1024 / dt_seconds
|
||||
}
|
||||
buf := &bytes.Buffer{}
|
||||
fmt.Fprintf(buf, `
|
||||
@@ -73,10 +73,10 @@ Checks: %10d
|
||||
Transferred: %10d
|
||||
Elapsed time: %v
|
||||
`,
|
||||
stats.bytes, speed,
|
||||
stats.errors,
|
||||
stats.checks,
|
||||
stats.transfers,
|
||||
s.bytes, speed,
|
||||
s.errors,
|
||||
s.checks,
|
||||
s.transfers,
|
||||
dt)
|
||||
if len(s.checking) > 0 {
|
||||
fmt.Fprintf(buf, "Checking: %s\n", s.checking)
|
||||
@@ -87,59 +87,73 @@ Elapsed time: %v
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// Log outputs the Stats to the log
|
||||
func (s *Stats) Log() {
|
||||
log.Printf("%v\n", stats)
|
||||
// Log outputs the StatsInfo to the log
|
||||
func (s *StatsInfo) Log() {
|
||||
log.Printf("%v\n", s)
|
||||
}
|
||||
|
||||
// Bytes updates the stats for bytes bytes
|
||||
func (s *Stats) Bytes(bytes int64) {
|
||||
func (s *StatsInfo) Bytes(bytes int64) {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
s.bytes += bytes
|
||||
}
|
||||
|
||||
// Errors updates the stats for errors
|
||||
func (s *Stats) Errors(errors int64) {
|
||||
func (s *StatsInfo) Errors(errors int64) {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
s.errors += errors
|
||||
}
|
||||
|
||||
// GetErrors reads the number of errors
|
||||
func (s *StatsInfo) GetErrors() int64 {
|
||||
s.lock.RLock()
|
||||
defer s.lock.RUnlock()
|
||||
return s.errors
|
||||
}
|
||||
|
||||
// Errored returns whether there have been any errors
|
||||
func (s *StatsInfo) Errored() bool {
|
||||
s.lock.RLock()
|
||||
defer s.lock.RUnlock()
|
||||
return s.errors != 0
|
||||
}
|
||||
|
||||
// Error adds a single error into the stats
|
||||
func (s *Stats) Error() {
|
||||
func (s *StatsInfo) Error() {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
s.errors += 1
|
||||
}
|
||||
|
||||
// Checking adds a check into the stats
|
||||
func (s *Stats) Checking(fs FsObject) {
|
||||
func (s *StatsInfo) Checking(o Object) {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
s.checking[fs.Remote()] = true
|
||||
s.checking[o.Remote()] = true
|
||||
}
|
||||
|
||||
// DoneChecking removes a check from the stats
|
||||
func (s *Stats) DoneChecking(fs FsObject) {
|
||||
func (s *StatsInfo) DoneChecking(o Object) {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
delete(s.checking, fs.Remote())
|
||||
delete(s.checking, o.Remote())
|
||||
s.checks += 1
|
||||
}
|
||||
|
||||
// Transferring adds a transfer into the stats
|
||||
func (s *Stats) Transferring(fs FsObject) {
|
||||
func (s *StatsInfo) Transferring(o Object) {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
s.transferring[fs.Remote()] = true
|
||||
s.transferring[o.Remote()] = true
|
||||
}
|
||||
|
||||
// DoneTransferring removes a transfer from the stats
|
||||
func (s *Stats) DoneTransferring(fs FsObject) {
|
||||
func (s *StatsInfo) DoneTransferring(o Object) {
|
||||
s.lock.Lock()
|
||||
defer s.lock.Unlock()
|
||||
delete(s.transferring, fs.Remote())
|
||||
delete(s.transferring, o.Remote())
|
||||
s.transfers += 1
|
||||
}
|
||||
|
||||
@@ -160,7 +174,7 @@ func NewAccount(in io.ReadCloser) *Account {
|
||||
func (file *Account) Read(p []byte) (n int, err error) {
|
||||
n, err = file.in.Read(p)
|
||||
file.bytes += int64(n)
|
||||
stats.Bytes(int64(n))
|
||||
Stats.Bytes(int64(n))
|
||||
if err == io.EOF {
|
||||
// FIXME Do something?
|
||||
}
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
// Read and write the config file
|
||||
package fs
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"os/user"
|
||||
"path"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Unknwon/goconfig"
|
||||
)
|
||||
|
||||
const (
|
||||
configFileName = ".rclone.conf"
|
||||
)
|
||||
|
||||
// Global
|
||||
var (
|
||||
// Config file
|
||||
ConfigFile *goconfig.ConfigFile
|
||||
// Home directory
|
||||
HomeDir = configHome()
|
||||
// Config file path
|
||||
ConfigPath = path.Join(HomeDir, configFileName)
|
||||
// Global config
|
||||
Config = &ConfigInfo{}
|
||||
// Flags
|
||||
verbose = flag.Bool("verbose", false, "Print lots more stuff")
|
||||
quiet = flag.Bool("quiet", false, "Print as little stuff as possible")
|
||||
modifyWindow = flag.Duration("modify-window", time.Nanosecond, "Max time diff to be considered the same")
|
||||
checkers = flag.Int("checkers", 8, "Number of checkers to run in parallel.")
|
||||
transfers = flag.Int("transfers", 4, "Number of file transfers to run in parallel.")
|
||||
configFile = flag.String("config", ConfigPath, "Config file.")
|
||||
)
|
||||
|
||||
// Filesystem config options
|
||||
type ConfigInfo struct {
|
||||
Verbose bool
|
||||
Quiet bool
|
||||
ModifyWindow time.Duration
|
||||
Checkers int
|
||||
Transfers int
|
||||
}
|
||||
|
||||
// Find the config directory
|
||||
func configHome() string {
|
||||
// Find users home directory
|
||||
usr, err := user.Current()
|
||||
if err != nil {
|
||||
log.Printf("Couldn't find home directory: %v", err)
|
||||
return ""
|
||||
}
|
||||
return usr.HomeDir
|
||||
}
|
||||
|
||||
// Loads the config file
|
||||
func LoadConfig() {
|
||||
// Read some flags if set
|
||||
//
|
||||
// FIXME read these from the config file too
|
||||
Config.Verbose = *verbose
|
||||
Config.Quiet = *quiet
|
||||
Config.ModifyWindow = *modifyWindow
|
||||
Config.Checkers = *checkers
|
||||
Config.Transfers = *transfers
|
||||
|
||||
ConfigPath = *configFile
|
||||
|
||||
// Load configuration file.
|
||||
var err error
|
||||
ConfigFile, err = goconfig.LoadConfigFile(ConfigPath)
|
||||
if err != nil {
|
||||
log.Printf("Failed to load config file %v - using defaults", ConfigPath)
|
||||
ConfigFile, err = goconfig.LoadConfigFile(os.DevNull)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to read null config file: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Save configuration file.
|
||||
func SaveConfig() {
|
||||
err := goconfig.SaveConfigFile(ConfigFile, ConfigPath)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to save config file: %v", err)
|
||||
}
|
||||
err = os.Chmod(ConfigPath, 0600)
|
||||
if err != nil {
|
||||
log.Printf("Failed to set permissions on config file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Show an overview of the config file
|
||||
func ShowRemotes() {
|
||||
remotes := ConfigFile.GetSectionList()
|
||||
if len(remotes) == 0 {
|
||||
return
|
||||
}
|
||||
sort.Strings(remotes)
|
||||
fmt.Printf("%-20s %s\n", "Name", "Type")
|
||||
fmt.Printf("%-20s %s\n", "====", "====")
|
||||
for _, remote := range remotes {
|
||||
fmt.Printf("%-20s %s\n", remote, ConfigFile.MustValue(remote, "type"))
|
||||
}
|
||||
}
|
||||
|
||||
// ChooseRemote chooses a remote name
|
||||
func ChooseRemote() string {
|
||||
remotes := ConfigFile.GetSectionList()
|
||||
sort.Strings(remotes)
|
||||
return Choose("remote", remotes, nil, false)
|
||||
}
|
||||
|
||||
// Read some input
|
||||
func ReadLine() string {
|
||||
buf := bufio.NewReader(os.Stdin)
|
||||
line, err := buf.ReadString('\n')
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to read line: %v", err)
|
||||
}
|
||||
return strings.TrimSpace(line)
|
||||
}
|
||||
|
||||
// Command - choose one
|
||||
func Command(commands []string) byte {
|
||||
opts := []string{}
|
||||
for _, text := range commands {
|
||||
fmt.Printf("%c) %s\n", text[0], text[1:])
|
||||
opts = append(opts, text[:1])
|
||||
}
|
||||
optString := strings.Join(opts, "")
|
||||
optHelp := strings.Join(opts, "/")
|
||||
for {
|
||||
fmt.Printf("%s> ", optHelp)
|
||||
result := strings.ToLower(ReadLine())
|
||||
if len(result) != 1 {
|
||||
continue
|
||||
}
|
||||
i := strings.IndexByte(optString, result[0])
|
||||
if i >= 0 {
|
||||
return result[0]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Asks the user for Yes or No and returns true or false
|
||||
func Confirm() bool {
|
||||
return Command([]string{"yYes", "nNo"}) == 'y'
|
||||
}
|
||||
|
||||
// Choose one of the defaults or type a new string if newOk is set
|
||||
func Choose(what string, defaults, help []string, newOk bool) string {
|
||||
fmt.Printf("Choose a number from below")
|
||||
if newOk {
|
||||
fmt.Printf(", or type in your own value")
|
||||
}
|
||||
fmt.Println()
|
||||
for i, text := range defaults {
|
||||
if help != nil {
|
||||
parts := strings.Split(help[i], "\n")
|
||||
for _, part := range parts {
|
||||
fmt.Printf(" * %s\n", part)
|
||||
}
|
||||
}
|
||||
fmt.Printf("%2d) %s\n", i+1, text)
|
||||
}
|
||||
for {
|
||||
fmt.Printf("%s> ", what)
|
||||
result := ReadLine()
|
||||
i, err := strconv.Atoi(result)
|
||||
if err != nil {
|
||||
if newOk {
|
||||
return result
|
||||
}
|
||||
continue
|
||||
}
|
||||
if i >= 1 && i <= len(defaults) {
|
||||
return defaults[i-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Show the contents of the remote
|
||||
func ShowRemote(name string) {
|
||||
fmt.Printf("--------------------\n")
|
||||
fmt.Printf("[%s]\n", name)
|
||||
for _, key := range ConfigFile.GetKeyList(name) {
|
||||
fmt.Printf("%s = %s\n", key, ConfigFile.MustValue(name, key))
|
||||
}
|
||||
fmt.Printf("--------------------\n")
|
||||
}
|
||||
|
||||
// Print the contents of the remote and ask if it is OK
|
||||
func OkRemote(name string) bool {
|
||||
ShowRemote(name)
|
||||
switch i := Command([]string{"yYes this is OK", "eEdit this remote", "dDelete this remote"}); i {
|
||||
case 'y':
|
||||
return true
|
||||
case 'e':
|
||||
return false
|
||||
case 'd':
|
||||
ConfigFile.DeleteSection(name)
|
||||
return true
|
||||
default:
|
||||
log.Printf("Bad choice %d", i)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Runs the config helper for the remote if needed
|
||||
func RemoteConfig(name string) {
|
||||
fmt.Printf("Remote config\n")
|
||||
fsName := ConfigFile.MustValue(name, "type")
|
||||
if fsName == "" {
|
||||
log.Fatalf("Couldn't find type of fs for %q", name)
|
||||
}
|
||||
f, err := Find(fsName)
|
||||
if err != nil {
|
||||
log.Fatalf("Didn't find filing system: %v", err)
|
||||
}
|
||||
if f.Config != nil {
|
||||
f.Config(name)
|
||||
}
|
||||
}
|
||||
|
||||
// Make a new remote
|
||||
func NewRemote(name string) {
|
||||
fmt.Printf("What type of source is it?\n")
|
||||
types := []string{}
|
||||
for _, item := range fsRegistry {
|
||||
types = append(types, item.Name)
|
||||
}
|
||||
newType := Choose("type", types, nil, false)
|
||||
ConfigFile.SetValue(name, "type", newType)
|
||||
fs, err := Find(newType)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to find fs: %v", err)
|
||||
}
|
||||
for _, option := range fs.Options {
|
||||
ConfigFile.SetValue(name, option.Name, option.Choose())
|
||||
}
|
||||
RemoteConfig(name)
|
||||
if OkRemote(name) {
|
||||
SaveConfig()
|
||||
return
|
||||
}
|
||||
EditRemote(name)
|
||||
}
|
||||
|
||||
// Edit a remote
|
||||
func EditRemote(name string) {
|
||||
ShowRemote(name)
|
||||
fmt.Printf("Edit remote\n")
|
||||
for {
|
||||
for _, key := range ConfigFile.GetKeyList(name) {
|
||||
value := ConfigFile.MustValue(name, key)
|
||||
fmt.Printf("Press enter to accept current value, or type in a new one\n")
|
||||
fmt.Printf("%s = %s>", key, value)
|
||||
newValue := ReadLine()
|
||||
if newValue != "" {
|
||||
ConfigFile.SetValue(name, key, newValue)
|
||||
}
|
||||
}
|
||||
RemoteConfig(name)
|
||||
if OkRemote(name) {
|
||||
break
|
||||
}
|
||||
}
|
||||
SaveConfig()
|
||||
}
|
||||
|
||||
// Delete a remote
|
||||
func DeleteRemote(name string) {
|
||||
ConfigFile.DeleteSection(name)
|
||||
SaveConfig()
|
||||
}
|
||||
|
||||
// Edit the config file interactively
|
||||
func EditConfig() {
|
||||
for {
|
||||
haveRemotes := len(ConfigFile.GetSectionList()) != 0
|
||||
what := []string{"eEdit existing remote", "nNew remote", "dDelete remote", "qQuit config"}
|
||||
if haveRemotes {
|
||||
fmt.Printf("Current remotes:\n\n")
|
||||
ShowRemotes()
|
||||
fmt.Printf("\n")
|
||||
} else {
|
||||
fmt.Printf("No remotes found - make a new one\n")
|
||||
what = append(what[1:2], what[3])
|
||||
}
|
||||
switch i := Command(what); i {
|
||||
case 'e':
|
||||
name := ChooseRemote()
|
||||
EditRemote(name)
|
||||
case 'n':
|
||||
fmt.Printf("name> ")
|
||||
name := ReadLine()
|
||||
NewRemote(name)
|
||||
case 'd':
|
||||
name := ChooseRemote()
|
||||
DeleteRemote(name)
|
||||
case 'q':
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
+127
-52
@@ -1,34 +1,86 @@
|
||||
// File system interface
|
||||
|
||||
package main
|
||||
package fs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"regexp"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Globals
|
||||
var (
|
||||
// Filesystem registry
|
||||
fsRegistry []*FsInfo
|
||||
)
|
||||
|
||||
// Filesystem info
|
||||
type FsInfo struct {
|
||||
Name string // name of this fs
|
||||
NewFs func(string, string) (Fs, error) // create a new file system
|
||||
Config func(string) // function to call to help with config
|
||||
Options []Option
|
||||
}
|
||||
|
||||
// An options for a Fs
|
||||
type Option struct {
|
||||
Name string
|
||||
Help string
|
||||
Optional bool
|
||||
Examples []OptionExample
|
||||
}
|
||||
|
||||
// An example for an option
|
||||
type OptionExample struct {
|
||||
Value string
|
||||
Help string
|
||||
}
|
||||
|
||||
// Choose an option
|
||||
func (o *Option) Choose() string {
|
||||
fmt.Println(o.Help)
|
||||
if len(o.Examples) > 0 {
|
||||
var values []string
|
||||
var help []string
|
||||
for _, example := range o.Examples {
|
||||
values = append(values, example.Value)
|
||||
help = append(help, example.Help)
|
||||
}
|
||||
return Choose(o.Name, values, help, true)
|
||||
}
|
||||
fmt.Printf("%s> ", o.Name)
|
||||
return ReadLine()
|
||||
}
|
||||
|
||||
// Register a filesystem
|
||||
//
|
||||
// Fs modules should use this in an init() function
|
||||
func Register(info *FsInfo) {
|
||||
fsRegistry = append(fsRegistry, info)
|
||||
}
|
||||
|
||||
// A Filesystem, describes the local filesystem and the remote object store
|
||||
type Fs interface {
|
||||
// String returns a description of the FS
|
||||
String() string
|
||||
|
||||
// List the Fs into a channel
|
||||
List() FsObjectsChan
|
||||
List() ObjectsChan
|
||||
|
||||
// List the Fs directories/buckets/containers into a channel
|
||||
ListDir() FsDirChan
|
||||
ListDir() DirChan
|
||||
|
||||
// Find the FsObject at remote. Returns nil if can't be found
|
||||
NewFsObject(remote string) FsObject
|
||||
// Find the Object at remote. Returns nil if can't be found
|
||||
NewFsObject(remote string) Object
|
||||
|
||||
// Put in to the remote path with the modTime given of the given size
|
||||
//
|
||||
// May create the object even if it returns an error - if so
|
||||
// will return the object and the error, otherwise will return
|
||||
// nil and the error
|
||||
Put(in io.Reader, remote string, modTime time.Time, size int64) (FsObject, error)
|
||||
Put(in io.Reader, remote string, modTime time.Time, size int64) (Object, error)
|
||||
|
||||
// Make the directory (container, bucket)
|
||||
Mkdir() error
|
||||
@@ -44,7 +96,7 @@ type Fs interface {
|
||||
|
||||
// A filesystem like object which can either be a remote object or a
|
||||
// local file/directory
|
||||
type FsObject interface {
|
||||
type Object interface {
|
||||
// Remote returns the remote path
|
||||
Remote() string
|
||||
|
||||
@@ -79,50 +131,72 @@ type Purger interface {
|
||||
Purge() error
|
||||
}
|
||||
|
||||
// A channel of FsObjects
|
||||
type FsObjectsChan chan FsObject
|
||||
// A channel of Objects
|
||||
type ObjectsChan chan Object
|
||||
|
||||
// A slice of FsObjects
|
||||
type FsObjects []FsObject
|
||||
// A slice of Objects
|
||||
type Objects []Object
|
||||
|
||||
// A structure of directory/container/bucket lists
|
||||
type FsDir struct {
|
||||
type Dir struct {
|
||||
Name string // name of the directory
|
||||
When time.Time // modification or creation time - IsZero for unknown
|
||||
Bytes int64 // size of directory and contents -1 for unknown
|
||||
Count int64 // number of objects -1 for unknown
|
||||
}
|
||||
|
||||
// A channel of FsDir objects
|
||||
type FsDirChan chan *FsDir
|
||||
// A channel of Dir objects
|
||||
type DirChan chan *Dir
|
||||
|
||||
// Pattern to match a url
|
||||
var matcher = regexp.MustCompile(`^([\w_-]+)://(.*)$`)
|
||||
|
||||
// Finds a FsInfo object for the name passed in
|
||||
//
|
||||
// Services are looked up in the config file
|
||||
func Find(name string) (*FsInfo, error) {
|
||||
for _, item := range fsRegistry {
|
||||
if item.Name == name {
|
||||
return item, nil
|
||||
}
|
||||
}
|
||||
return nil, fmt.Errorf("Didn't find filing system for %q", name)
|
||||
}
|
||||
|
||||
// NewFs makes a new Fs object from the path
|
||||
//
|
||||
// FIXME make more generic
|
||||
// The path is of the form service://path
|
||||
//
|
||||
// Services are looked up in the config file
|
||||
func NewFs(path string) (Fs, error) {
|
||||
if swiftMatch.MatchString(path) {
|
||||
return NewFsSwift(path)
|
||||
parts := matcher.FindStringSubmatch(path)
|
||||
fsName, configName, fsPath := "local", "local", path
|
||||
if parts != nil {
|
||||
configName, fsPath = parts[1], parts[2]
|
||||
var err error
|
||||
fsName, err = ConfigFile.GetValue(configName, "type")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Didn't find section in config file for %q", configName)
|
||||
}
|
||||
}
|
||||
if s3Match.MatchString(path) {
|
||||
return NewFsS3(path)
|
||||
fs, err := Find(fsName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if driveMatch.MatchString(path) {
|
||||
return NewFsDrive(path)
|
||||
}
|
||||
return NewFsLocal(path)
|
||||
return fs.NewFs(configName, fsPath)
|
||||
}
|
||||
|
||||
// Write debuging output for this FsObject
|
||||
func FsDebug(fs FsObject, text string, args ...interface{}) {
|
||||
if *verbose {
|
||||
// Write debuging output for this Object
|
||||
func Debug(fs Object, text string, args ...interface{}) {
|
||||
if Config.Verbose {
|
||||
out := fmt.Sprintf(text, args...)
|
||||
log.Printf("%s: %s", fs.Remote(), out)
|
||||
}
|
||||
}
|
||||
|
||||
// Write log output for this FsObject
|
||||
func FsLog(fs FsObject, text string, args ...interface{}) {
|
||||
if !*quiet {
|
||||
// Write log output for this Object
|
||||
func Log(fs Object, text string, args ...interface{}) {
|
||||
if !Config.Quiet {
|
||||
out := fmt.Sprintf(text, args...)
|
||||
log.Printf("%s: %s", fs.Remote(), out)
|
||||
}
|
||||
@@ -142,21 +216,21 @@ func checkClose(c io.Closer, err *error) {
|
||||
// May return an error which will already have been logged
|
||||
//
|
||||
// If an error is returned it will return false
|
||||
func CheckMd5sums(src, dst FsObject) (bool, error) {
|
||||
func CheckMd5sums(src, dst Object) (bool, error) {
|
||||
srcMd5, err := src.Md5sum()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(src, "Failed to calculate src md5: %s", err)
|
||||
Stats.Error()
|
||||
Log(src, "Failed to calculate src md5: %s", err)
|
||||
return false, err
|
||||
}
|
||||
dstMd5, err := dst.Md5sum()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(dst, "Failed to calculate dst md5: %s", err)
|
||||
Stats.Error()
|
||||
Log(dst, "Failed to calculate dst md5: %s", err)
|
||||
return false, err
|
||||
}
|
||||
// FsDebug("Src MD5 %s", srcMd5)
|
||||
// FsDebug("Dst MD5 %s", obj.Hash)
|
||||
// Debug("Src MD5 %s", srcMd5)
|
||||
// Debug("Dst MD5 %s", obj.Hash)
|
||||
return srcMd5 == dstMd5, nil
|
||||
}
|
||||
|
||||
@@ -176,9 +250,9 @@ func CheckMd5sums(src, dst FsObject) (bool, error) {
|
||||
//
|
||||
// Otherwise the file is considered to be not equal including if there
|
||||
// were errors reading info.
|
||||
func Equal(src, dst FsObject) bool {
|
||||
func Equal(src, dst Object) bool {
|
||||
if src.Size() != dst.Size() {
|
||||
FsDebug(src, "Sizes differ")
|
||||
Debug(src, "Sizes differ")
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -186,10 +260,11 @@ func Equal(src, dst FsObject) bool {
|
||||
srcModTime := src.ModTime()
|
||||
dstModTime := dst.ModTime()
|
||||
dt := dstModTime.Sub(srcModTime)
|
||||
if dt >= *modifyWindow || dt <= -*modifyWindow {
|
||||
FsDebug(src, "Modification times differ by %s: %v, %v", dt, srcModTime, dstModTime)
|
||||
ModifyWindow := Config.ModifyWindow
|
||||
if dt >= ModifyWindow || dt <= -ModifyWindow {
|
||||
Debug(src, "Modification times differ by %s: %v, %v", dt, srcModTime, dstModTime)
|
||||
} else {
|
||||
FsDebug(src, "Size and modification time differ by %s (within %s)", dt, *modifyWindow)
|
||||
Debug(src, "Size and modification time differ by %s (within %s)", dt, ModifyWindow)
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -197,7 +272,7 @@ func Equal(src, dst FsObject) bool {
|
||||
// check the MD5SUM
|
||||
same, _ := CheckMd5sums(src, dst)
|
||||
if !same {
|
||||
FsDebug(src, "Md5sums differ")
|
||||
Debug(src, "Md5sums differ")
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -205,16 +280,16 @@ func Equal(src, dst FsObject) bool {
|
||||
// mtime of the dst object here
|
||||
dst.SetModTime(srcModTime)
|
||||
|
||||
FsDebug(src, "Size and MD5SUM of src and dst objects identical")
|
||||
Debug(src, "Size and MD5SUM of src and dst objects identical")
|
||||
return true
|
||||
}
|
||||
|
||||
// Copy src object to f
|
||||
func Copy(f Fs, src FsObject) {
|
||||
func Copy(f Fs, src Object) {
|
||||
in0, err := src.Open()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(src, "Failed to open: %s", err)
|
||||
Stats.Error()
|
||||
Log(src, "Failed to open: %s", err)
|
||||
return
|
||||
}
|
||||
in := NewAccount(in0) // account the transfer
|
||||
@@ -225,17 +300,17 @@ func Copy(f Fs, src FsObject) {
|
||||
err = inErr
|
||||
}
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(src, "Failed to copy: %s", err)
|
||||
Stats.Error()
|
||||
Log(src, "Failed to copy: %s", err)
|
||||
if dst != nil {
|
||||
FsDebug(dst, "Removing failed copy")
|
||||
Debug(dst, "Removing failed copy")
|
||||
removeErr := dst.Remove()
|
||||
if removeErr != nil {
|
||||
stats.Error()
|
||||
FsLog(dst, "Failed to remove failed copy: %s", removeErr)
|
||||
Stats.Error()
|
||||
Log(dst, "Failed to remove failed copy: %s", removeErr)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
FsDebug(src, "Copied")
|
||||
Debug(src, "Copied")
|
||||
}
|
||||
@@ -1,363 +0,0 @@
|
||||
// S3 interface
|
||||
package main
|
||||
|
||||
// FIXME need to prevent anything but ListDir working for s3://
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/ncw/swift"
|
||||
"io"
|
||||
"launchpad.net/goamz/aws"
|
||||
"launchpad.net/goamz/s3"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Constants
|
||||
const (
|
||||
metaMtime = "X-Amz-Meta-Mtime" // the meta key to store mtime in
|
||||
)
|
||||
|
||||
// FsS3 represents a remote s3 server
|
||||
type FsS3 struct {
|
||||
c *s3.S3 // the connection to the s3 server
|
||||
b *s3.Bucket // the connection to the bucket
|
||||
bucket string // the bucket we are working on
|
||||
perm s3.ACL // permissions for new buckets / objects
|
||||
}
|
||||
|
||||
// FsObjectS3 describes a s3 object
|
||||
type FsObjectS3 struct {
|
||||
// Will definitely have everything but meta which may be nil
|
||||
//
|
||||
// List will read everything but meta - to fill that in need to call
|
||||
// readMetaData
|
||||
s3 *FsS3 // what this object is part of
|
||||
remote string // The remote path
|
||||
etag string // md5sum of the object
|
||||
bytes int64 // size of the object
|
||||
lastModified time.Time // Last modified
|
||||
meta s3.Headers // The object metadata if known - may be nil
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------
|
||||
|
||||
// Globals
|
||||
var (
|
||||
// Flags
|
||||
awsAccessKeyId = flag.String("aws-access-key-id", os.Getenv("AWS_ACCESS_KEY_ID"), "AWS Access Key ID. Defaults to environment var AWS_ACCESS_KEY_ID.")
|
||||
awsSecretAccessKey = flag.String("aws-secret-access-key", os.Getenv("AWS_SECRET_ACCESS_KEY"), "AWS Secret Access Key (password). Defaults to environment var AWS_SECRET_ACCESS_KEY.")
|
||||
// AWS endpoints: http://docs.amazonwebservices.com/general/latest/gr/rande.html#s3_region
|
||||
s3Endpoint = flag.String("s3-endpoint", os.Getenv("S3_ENDPOINT"), "S3 Endpoint. Defaults to environment var S3_ENDPOINT then https://s3.amazonaws.com/.")
|
||||
s3LocationConstraint = flag.String("s3-location-constraint", os.Getenv("S3_LOCATION_CONSTRAINT"), "Location constraint for creating buckets only. Defaults to environment var S3_LOCATION_CONSTRAINT.")
|
||||
)
|
||||
|
||||
// String converts this FsS3 to a string
|
||||
func (f *FsS3) String() string {
|
||||
return fmt.Sprintf("S3 bucket %s", f.bucket)
|
||||
}
|
||||
|
||||
// Pattern to match a s3 url
|
||||
var s3Match = regexp.MustCompile(`^s3://([^/]*)(.*)$`)
|
||||
|
||||
// parseParse parses a s3 'url'
|
||||
func s3ParsePath(path string) (bucket, directory string, err error) {
|
||||
parts := s3Match.FindAllStringSubmatch(path, -1)
|
||||
if len(parts) != 1 || len(parts[0]) != 3 {
|
||||
err = fmt.Errorf("Couldn't parse s3 url %q", path)
|
||||
} else {
|
||||
bucket, directory = parts[0][1], parts[0][2]
|
||||
directory = strings.Trim(directory, "/")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// s3Connection makes a connection to s3
|
||||
func s3Connection() (*s3.S3, error) {
|
||||
// Make the auth
|
||||
if *awsAccessKeyId == "" {
|
||||
return nil, errors.New("Need -aws-access-key-id or environmental variable AWS_ACCESS_KEY_ID")
|
||||
}
|
||||
if *awsSecretAccessKey == "" {
|
||||
return nil, errors.New("Need -aws-secret-access-key or environmental variable AWS_SECRET_ACCESS_KEY")
|
||||
}
|
||||
auth := aws.Auth{AccessKey: *awsAccessKeyId, SecretKey: *awsSecretAccessKey}
|
||||
|
||||
// FIXME look through all the regions by name and use one of them if found
|
||||
|
||||
// Synthesize the region
|
||||
if *s3Endpoint == "" {
|
||||
*s3Endpoint = "https://s3.amazonaws.com/"
|
||||
}
|
||||
region := aws.Region{
|
||||
Name: "s3",
|
||||
S3Endpoint: *s3Endpoint,
|
||||
S3LocationConstraint: false,
|
||||
}
|
||||
if *s3LocationConstraint != "" {
|
||||
region.Name = *s3LocationConstraint
|
||||
region.S3LocationConstraint = true
|
||||
}
|
||||
|
||||
c := s3.New(auth, region)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// NewFsS3 contstructs an FsS3 from the path, bucket:path
|
||||
func NewFsS3(path string) (*FsS3, error) {
|
||||
bucket, directory, err := s3ParsePath(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if directory != "" {
|
||||
return nil, fmt.Errorf("Directories not supported yet in %q: %q", path, directory)
|
||||
}
|
||||
c, err := s3Connection()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f := &FsS3{
|
||||
c: c,
|
||||
bucket: bucket,
|
||||
b: c.Bucket(bucket),
|
||||
perm: s3.Private, // FIXME need user to specify
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// Return an FsObject from a path
|
||||
//
|
||||
// May return nil if an error occurred
|
||||
func (f *FsS3) NewFsObjectWithInfo(remote string, info *s3.Key) FsObject {
|
||||
fs := &FsObjectS3{
|
||||
s3: f,
|
||||
remote: remote,
|
||||
}
|
||||
if info != nil {
|
||||
// Set info but not meta
|
||||
var err error
|
||||
fs.lastModified, err = time.Parse(time.RFC3339, info.LastModified)
|
||||
if err != nil {
|
||||
FsLog(fs, "Failed to read last modified: %s", err)
|
||||
fs.lastModified = time.Now()
|
||||
}
|
||||
fs.etag = info.ETag
|
||||
fs.bytes = info.Size
|
||||
} else {
|
||||
err := fs.readMetaData() // reads info and meta, returning an error
|
||||
if err != nil {
|
||||
// logged already FsDebug("Failed to read info: %s", err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fs
|
||||
}
|
||||
|
||||
// Return an FsObject from a path
|
||||
//
|
||||
// May return nil if an error occurred
|
||||
func (f *FsS3) NewFsObject(remote string) FsObject {
|
||||
return f.NewFsObjectWithInfo(remote, nil)
|
||||
}
|
||||
|
||||
// Walk the path returning a channel of FsObjects
|
||||
func (f *FsS3) List() FsObjectsChan {
|
||||
out := make(FsObjectsChan, *checkers)
|
||||
go func() {
|
||||
// FIXME need to implement ALL loop
|
||||
objects, err := f.b.List("", "", "", 10000)
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
log.Printf("Couldn't read bucket %q: %s", f.bucket, err)
|
||||
} else {
|
||||
for i := range objects.Contents {
|
||||
object := &objects.Contents[i]
|
||||
if fs := f.NewFsObjectWithInfo(object.Key, object); fs != nil {
|
||||
out <- fs
|
||||
}
|
||||
}
|
||||
}
|
||||
close(out)
|
||||
}()
|
||||
return out
|
||||
}
|
||||
|
||||
// Lists the buckets
|
||||
func (f *FsS3) ListDir() FsDirChan {
|
||||
out := make(FsDirChan, *checkers)
|
||||
go func() {
|
||||
defer close(out)
|
||||
buckets, err := f.c.ListBuckets()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
log.Printf("Couldn't list buckets: %s", err)
|
||||
} else {
|
||||
for _, bucket := range buckets {
|
||||
out <- &FsDir{
|
||||
Name: bucket.Name,
|
||||
When: bucket.CreationDate,
|
||||
Bytes: -1,
|
||||
Count: -1,
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return out
|
||||
}
|
||||
|
||||
// Put the FsObject into the bucket
|
||||
func (f *FsS3) Put(in io.Reader, remote string, modTime time.Time, size int64) (FsObject, error) {
|
||||
// Temporary FsObject under construction
|
||||
fs := &FsObjectS3{s3: f, remote: remote}
|
||||
|
||||
// Set the mtime in the headers
|
||||
headers := s3.Headers{
|
||||
metaMtime: swift.TimeToFloatString(modTime),
|
||||
}
|
||||
|
||||
// Guess the content type
|
||||
contentType := mime.TypeByExtension(path.Ext(remote))
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
|
||||
_, err := fs.s3.b.PutReaderHeaders(remote, in, size, contentType, f.perm, headers)
|
||||
return fs, err
|
||||
}
|
||||
|
||||
// Mkdir creates the bucket if it doesn't exist
|
||||
func (f *FsS3) Mkdir() error {
|
||||
err := f.b.PutBucket(f.perm)
|
||||
if err, ok := err.(*s3.Error); ok {
|
||||
if err.Code == "BucketAlreadyOwnedByYou" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Rmdir deletes the bucket
|
||||
//
|
||||
// Returns an error if it isn't empty
|
||||
func (f *FsS3) Rmdir() error {
|
||||
return f.b.DelBucket()
|
||||
}
|
||||
|
||||
// Return the precision
|
||||
func (fs *FsS3) Precision() time.Duration {
|
||||
return time.Nanosecond
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------
|
||||
|
||||
// Return the remote path
|
||||
func (fs *FsObjectS3) Remote() string {
|
||||
return fs.remote
|
||||
}
|
||||
|
||||
// Md5sum returns the Md5sum of an object returning a lowercase hex string
|
||||
func (fs *FsObjectS3) Md5sum() (string, error) {
|
||||
return strings.Trim(strings.ToLower(fs.etag), `"`), nil
|
||||
}
|
||||
|
||||
// Size returns the size of an object in bytes
|
||||
func (fs *FsObjectS3) Size() int64 {
|
||||
return fs.bytes
|
||||
}
|
||||
|
||||
// readMetaData gets the metadata if it hasn't already been fetched
|
||||
//
|
||||
// it also sets the info
|
||||
func (fs *FsObjectS3) readMetaData() (err error) {
|
||||
if fs.meta != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
headers, err := fs.s3.b.Head(fs.remote, nil)
|
||||
if err != nil {
|
||||
FsDebug(fs, "Failed to read info: %s", err)
|
||||
return err
|
||||
}
|
||||
size, err := strconv.ParseInt(headers["Content-Length"], 10, 64)
|
||||
if err != nil {
|
||||
FsDebug(fs, "Failed to read size from: %q", headers)
|
||||
return err
|
||||
}
|
||||
fs.etag = headers["Etag"]
|
||||
fs.bytes = size
|
||||
fs.meta = headers
|
||||
if fs.lastModified, err = time.Parse(http.TimeFormat, headers["Last-Modified"]); err != nil {
|
||||
FsLog(fs, "Failed to read last modified from HEAD: %s", err)
|
||||
fs.lastModified = time.Now()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ModTime returns the modification time of the object
|
||||
//
|
||||
// It attempts to read the objects mtime and if that isn't present the
|
||||
// LastModified returned in the http headers
|
||||
func (fs *FsObjectS3) ModTime() time.Time {
|
||||
err := fs.readMetaData()
|
||||
if err != nil {
|
||||
FsLog(fs, "Failed to read metadata: %s", err)
|
||||
return time.Now()
|
||||
}
|
||||
// read mtime out of metadata if available
|
||||
d, ok := fs.meta[metaMtime]
|
||||
if !ok {
|
||||
// FsDebug(fs, "No metadata")
|
||||
return fs.lastModified
|
||||
}
|
||||
modTime, err := swift.FloatStringToTime(d)
|
||||
if err != nil {
|
||||
FsLog(fs, "Failed to read mtime from object: %s", err)
|
||||
return fs.lastModified
|
||||
}
|
||||
return modTime
|
||||
}
|
||||
|
||||
// Sets the modification time of the local fs object
|
||||
func (fs *FsObjectS3) SetModTime(modTime time.Time) {
|
||||
err := fs.readMetaData()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(fs, "Failed to read metadata: %s", err)
|
||||
return
|
||||
}
|
||||
fs.meta[metaMtime] = swift.TimeToFloatString(modTime)
|
||||
_, err = fs.s3.b.Update(fs.remote, fs.s3.perm, fs.meta)
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(fs, "Failed to update remote mtime: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Is this object storable
|
||||
func (fs *FsObjectS3) Storable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Open an object for read
|
||||
func (fs *FsObjectS3) Open() (in io.ReadCloser, err error) {
|
||||
in, err = fs.s3.b.GetReader(fs.remote)
|
||||
return
|
||||
}
|
||||
|
||||
// Remove an object
|
||||
func (fs *FsObjectS3) Remove() error {
|
||||
return fs.s3.b.Del(fs.remote)
|
||||
}
|
||||
|
||||
// Check the interfaces are satisfied
|
||||
var _ Fs = &FsS3{}
|
||||
var _ FsObject = &FsObjectS3{}
|
||||
@@ -1,5 +1,5 @@
|
||||
// Local filesystem interface
|
||||
package main
|
||||
package local
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
@@ -12,8 +12,18 @@ import (
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/ncw/rclone/fs"
|
||||
)
|
||||
|
||||
// Register with Fs
|
||||
func init() {
|
||||
fs.Register(&fs.FsInfo{
|
||||
Name: "local",
|
||||
NewFs: NewFs,
|
||||
})
|
||||
}
|
||||
|
||||
// FsLocal represents a local filesystem rooted at root
|
||||
type FsLocal struct {
|
||||
root string // The root directory
|
||||
@@ -30,8 +40,8 @@ type FsObjectLocal struct {
|
||||
|
||||
// ------------------------------------------------------------
|
||||
|
||||
// NewFsLocal contstructs an FsLocal from the path
|
||||
func NewFsLocal(root string) (*FsLocal, error) {
|
||||
// NewFs contstructs an FsLocal from the path
|
||||
func NewFs(name, root string) (fs.Fs, error) {
|
||||
root = path.Clean(root)
|
||||
f := &FsLocal{root: root}
|
||||
return f, nil
|
||||
@@ -45,42 +55,42 @@ func (f *FsLocal) String() string {
|
||||
// Return an FsObject from a path
|
||||
//
|
||||
// May return nil if an error occurred
|
||||
func (f *FsLocal) NewFsObjectWithInfo(remote string, info os.FileInfo) FsObject {
|
||||
func (f *FsLocal) NewFsObjectWithInfo(remote string, info os.FileInfo) fs.Object {
|
||||
path := filepath.Join(f.root, remote)
|
||||
fs := &FsObjectLocal{remote: remote, path: path}
|
||||
o := &FsObjectLocal{remote: remote, path: path}
|
||||
if info != nil {
|
||||
fs.info = info
|
||||
o.info = info
|
||||
} else {
|
||||
err := fs.lstat()
|
||||
err := o.lstat()
|
||||
if err != nil {
|
||||
FsDebug(fs, "Failed to stat %s: %s", path, err)
|
||||
fs.Debug(o, "Failed to stat %s: %s", path, err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fs
|
||||
return o
|
||||
}
|
||||
|
||||
// Return an FsObject from a path
|
||||
//
|
||||
// May return nil if an error occurred
|
||||
func (f *FsLocal) NewFsObject(remote string) FsObject {
|
||||
func (f *FsLocal) NewFsObject(remote string) fs.Object {
|
||||
return f.NewFsObjectWithInfo(remote, nil)
|
||||
}
|
||||
|
||||
// List the path returning a channel of FsObjects
|
||||
//
|
||||
// Ignores everything which isn't Storable, eg links etc
|
||||
func (f *FsLocal) List() FsObjectsChan {
|
||||
out := make(FsObjectsChan, *checkers)
|
||||
func (f *FsLocal) List() fs.ObjectsChan {
|
||||
out := make(fs.ObjectsChan, fs.Config.Checkers)
|
||||
go func() {
|
||||
err := filepath.Walk(f.root, func(path string, fi os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf("Failed to open directory: %s: %s", path, err)
|
||||
} else {
|
||||
remote, err := filepath.Rel(f.root, path)
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf("Failed to get relative path %s: %s", path, err)
|
||||
return nil
|
||||
}
|
||||
@@ -97,7 +107,7 @@ func (f *FsLocal) List() FsObjectsChan {
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf("Failed to open directory: %s: %s", f.root, err)
|
||||
}
|
||||
close(out)
|
||||
@@ -106,18 +116,18 @@ func (f *FsLocal) List() FsObjectsChan {
|
||||
}
|
||||
|
||||
// Walk the path returning a channel of FsObjects
|
||||
func (f *FsLocal) ListDir() FsDirChan {
|
||||
out := make(FsDirChan, *checkers)
|
||||
func (f *FsLocal) ListDir() fs.DirChan {
|
||||
out := make(fs.DirChan, fs.Config.Checkers)
|
||||
go func() {
|
||||
defer close(out)
|
||||
items, err := ioutil.ReadDir(f.root)
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf("Couldn't find read directory: %s", err)
|
||||
} else {
|
||||
for _, item := range items {
|
||||
if item.IsDir() {
|
||||
dir := &FsDir{
|
||||
dir := &fs.Dir{
|
||||
Name: item.Name(),
|
||||
When: item.ModTime(),
|
||||
Bytes: 0,
|
||||
@@ -127,7 +137,7 @@ func (f *FsLocal) ListDir() FsDirChan {
|
||||
dirpath := path.Join(f.root, item.Name())
|
||||
err := filepath.Walk(dirpath, func(path string, fi os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf("Failed to open directory: %s: %s", path, err)
|
||||
} else {
|
||||
dir.Count += 1
|
||||
@@ -136,7 +146,7 @@ func (f *FsLocal) ListDir() FsDirChan {
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf("Failed to open directory: %s: %s", dirpath, err)
|
||||
}
|
||||
out <- dir
|
||||
@@ -149,7 +159,7 @@ func (f *FsLocal) ListDir() FsDirChan {
|
||||
}
|
||||
|
||||
// Puts the FsObject to the local filesystem
|
||||
func (f *FsLocal) Put(in io.Reader, remote string, modTime time.Time, size int64) (FsObject, error) {
|
||||
func (f *FsLocal) Put(in io.Reader, remote string, modTime time.Time, size int64) (fs.Object, error) {
|
||||
dstPath := filepath.Join(f.root, remote)
|
||||
// Temporary FsObject under construction
|
||||
fs := &FsObjectLocal{remote: remote, path: dstPath}
|
||||
@@ -225,7 +235,7 @@ func (f *FsLocal) readPrecision() (precision time.Duration) {
|
||||
for duration := time.Duration(1); duration < time.Second; duration *= 10 {
|
||||
// Current time with delta
|
||||
t := time.Unix(time.Now().Unix(), int64(duration))
|
||||
err := Chtimes(path, t, t)
|
||||
err := os.Chtimes(path, t, t)
|
||||
if err != nil {
|
||||
// fmt.Println("Failed to Chtimes", err)
|
||||
break
|
||||
@@ -251,78 +261,78 @@ func (f *FsLocal) readPrecision() (precision time.Duration) {
|
||||
// ------------------------------------------------------------
|
||||
|
||||
// Return the remote path
|
||||
func (fs *FsObjectLocal) Remote() string {
|
||||
return fs.remote
|
||||
func (o *FsObjectLocal) Remote() string {
|
||||
return o.remote
|
||||
}
|
||||
|
||||
// Md5sum calculates the Md5sum of a file returning a lowercase hex string
|
||||
func (fs *FsObjectLocal) Md5sum() (string, error) {
|
||||
in, err := os.Open(fs.path)
|
||||
func (o *FsObjectLocal) Md5sum() (string, error) {
|
||||
in, err := os.Open(o.path)
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(fs, "Failed to open: %s", err)
|
||||
fs.Stats.Error()
|
||||
fs.Log(o, "Failed to open: %s", err)
|
||||
return "", err
|
||||
}
|
||||
defer in.Close() // FIXME ignoring error
|
||||
hash := md5.New()
|
||||
_, err = io.Copy(hash, in)
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(fs, "Failed to read: %s", err)
|
||||
fs.Stats.Error()
|
||||
fs.Log(o, "Failed to read: %s", err)
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("%x", hash.Sum(nil)), nil
|
||||
}
|
||||
|
||||
// Size returns the size of an object in bytes
|
||||
func (fs *FsObjectLocal) Size() int64 {
|
||||
return fs.info.Size()
|
||||
func (o *FsObjectLocal) Size() int64 {
|
||||
return o.info.Size()
|
||||
}
|
||||
|
||||
// ModTime returns the modification time of the object
|
||||
func (fs *FsObjectLocal) ModTime() time.Time {
|
||||
return fs.info.ModTime()
|
||||
func (o *FsObjectLocal) ModTime() time.Time {
|
||||
return o.info.ModTime()
|
||||
}
|
||||
|
||||
// Sets the modification time of the local fs object
|
||||
func (fs *FsObjectLocal) SetModTime(modTime time.Time) {
|
||||
err := Chtimes(fs.path, modTime, modTime)
|
||||
func (o *FsObjectLocal) SetModTime(modTime time.Time) {
|
||||
err := os.Chtimes(o.path, modTime, modTime)
|
||||
if err != nil {
|
||||
FsDebug(fs, "Failed to set mtime on file: %s", err)
|
||||
fs.Debug(o, "Failed to set mtime on file: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Is this object storable
|
||||
func (fs *FsObjectLocal) Storable() bool {
|
||||
mode := fs.info.Mode()
|
||||
func (o *FsObjectLocal) Storable() bool {
|
||||
mode := o.info.Mode()
|
||||
if mode&(os.ModeSymlink|os.ModeNamedPipe|os.ModeSocket|os.ModeDevice) != 0 {
|
||||
FsDebug(fs, "Can't transfer non file/directory")
|
||||
fs.Debug(o, "Can't transfer non file/directory")
|
||||
return false
|
||||
} else if mode&os.ModeDir != 0 {
|
||||
FsDebug(fs, "FIXME Skipping directory")
|
||||
fs.Debug(o, "FIXME Skipping directory")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// Open an object for read
|
||||
func (fs *FsObjectLocal) Open() (in io.ReadCloser, err error) {
|
||||
in, err = os.Open(fs.path)
|
||||
func (o *FsObjectLocal) Open() (in io.ReadCloser, err error) {
|
||||
in, err = os.Open(o.path)
|
||||
return
|
||||
}
|
||||
|
||||
// Stat a FsObject into info
|
||||
func (fs *FsObjectLocal) lstat() error {
|
||||
info, err := os.Lstat(fs.path)
|
||||
fs.info = info
|
||||
func (o *FsObjectLocal) lstat() error {
|
||||
info, err := os.Lstat(o.path)
|
||||
o.info = info
|
||||
return err
|
||||
}
|
||||
|
||||
// Remove an object
|
||||
func (fs *FsObjectLocal) Remove() error {
|
||||
return os.Remove(fs.path)
|
||||
func (o *FsObjectLocal) Remove() error {
|
||||
return os.Remove(o.path)
|
||||
}
|
||||
|
||||
// Check the interfaces are satisfied
|
||||
var _ Fs = &FsLocal{}
|
||||
var _ FsObject = &FsObjectLocal{}
|
||||
var _ fs.Fs = &FsLocal{}
|
||||
var _ fs.Object = &FsObjectLocal{}
|
||||
@@ -1,14 +1,10 @@
|
||||
Names
|
||||
* rclone - domain ok, apt ok
|
||||
|
||||
Todo
|
||||
* Make a test suite which can run on all the given types of fs
|
||||
* Copy should use the sync code as it is more efficient at directory listing
|
||||
* Factor fses into own packages
|
||||
* FIXME: ls without an argument for buckets/containers?
|
||||
* FIXME: More -dry-run checks for object transfer
|
||||
* Might be quicker to check md5sums first? for swift <-> swift certainly, and maybe for small files
|
||||
* Ignoring the pseudo directories
|
||||
* swift: Ignoring the pseudo directories
|
||||
* if object.PseudoDirectory {
|
||||
* fmt.Printf("%9s %19s %s\n", "Directory", "-", fs.Remote())
|
||||
* Make Account wrapper
|
||||
@@ -24,36 +20,17 @@ Todo
|
||||
* Add max object size to fs metadata - 5GB for swift, infinite for local, ? for s3
|
||||
* tie into -max-size flag
|
||||
|
||||
Drive
|
||||
* Do we need the secrets or just the code? If just the code then
|
||||
can make a web service which does the request on the clients
|
||||
behalf so don't need to expose the client secrets
|
||||
* Apparently we don't need -drive-client-id or -drive-client-secret once we have a token
|
||||
* Make a cgi which we send the user to
|
||||
* It has the client secrets
|
||||
* It gets google to authenticate
|
||||
* It receives the token back
|
||||
* It displays the token to the user to paste in to the code
|
||||
* Should be https really
|
||||
* Sometimes get: Failed to copy: Upload failed: googleapi: Error 403: Rate Limit Exceeded
|
||||
* quota is 100.0 requests/second/user
|
||||
|
||||
Ideas
|
||||
* could do encryption - put IV into metadata?
|
||||
* optimise remote copy container to another container using remote
|
||||
copy if local is same as remote - use an optional Copier interface
|
||||
* Allow subpaths container:/sub/path
|
||||
* look at auth from env in s3 module - add to swift?
|
||||
* support
|
||||
* sftp
|
||||
* scp
|
||||
* Google cloud storage: https://developers.google.com/storage/
|
||||
* Google drive: https://developers.google.com/drive/
|
||||
* rsync over ssh
|
||||
* dropbox: https://github.com/nickoneill/go-dropbox (no MD5s)
|
||||
* grive seems to have its secrets in the source code which would make things easier!
|
||||
|
||||
|
||||
|
||||
Need to make directory objects otherwise can't upload an empty directory
|
||||
* Or could upload empty directories only?
|
||||
@@ -65,13 +42,6 @@ s3
|
||||
* Otherwise can set metadata
|
||||
* Returns etag and last modified in bucket list
|
||||
|
||||
|
||||
Bugs
|
||||
|
||||
local & drive need to delete directories
|
||||
|
||||
2013/01/18 16:31:32 Waiting for deletions to finish
|
||||
2013/01/18 16:31:32 z3: FIXME Skipping directory
|
||||
2013/01/18 16:31:32 z3/x: Deleted
|
||||
2013/01/18 16:31:32 Deleting path
|
||||
2013/01/18 16:31:32 Rmdir failed: remove z3: directory not empty
|
||||
Non verbose - not sure number transferred got counted up? CHECK
|
||||
@@ -13,32 +13,34 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/ncw/rclone/fs"
|
||||
// Active file systems
|
||||
_ "github.com/ncw/rclone/drive"
|
||||
_ "github.com/ncw/rclone/local"
|
||||
_ "github.com/ncw/rclone/s3"
|
||||
_ "github.com/ncw/rclone/swift"
|
||||
)
|
||||
|
||||
// Globals
|
||||
var (
|
||||
// Flags
|
||||
cpuprofile = flag.String("cpuprofile", "", "Write cpu profile to file")
|
||||
verbose = flag.Bool("verbose", false, "Print lots more stuff")
|
||||
quiet = flag.Bool("quiet", false, "Print as little stuff as possible")
|
||||
dry_run = flag.Bool("dry-run", false, "Do a trial run with no permanent changes")
|
||||
checkers = flag.Int("checkers", 8, "Number of checkers to run in parallel.")
|
||||
transfers = flag.Int("transfers", 4, "Number of file transfers to run in parallel.")
|
||||
statsInterval = flag.Duration("stats", time.Minute*1, "Interval to print stats")
|
||||
modifyWindow = flag.Duration("modify-window", time.Nanosecond, "Max time diff to be considered the same")
|
||||
)
|
||||
|
||||
// A pair of FsObjects
|
||||
// A pair of fs.Objects
|
||||
type PairFsObjects struct {
|
||||
src, dst FsObject
|
||||
src, dst fs.Object
|
||||
}
|
||||
|
||||
type PairFsObjectsChan chan PairFsObjects
|
||||
|
||||
// Check to see if src needs to be copied to dst and if so puts it in out
|
||||
func checkOne(src, dst FsObject, out FsObjectsChan) {
|
||||
func checkOne(src, dst fs.Object, out fs.ObjectsChan) {
|
||||
if dst == nil {
|
||||
FsDebug(src, "Couldn't find local file - download")
|
||||
fs.Debug(src, "Couldn't find local file - download")
|
||||
out <- src
|
||||
return
|
||||
}
|
||||
@@ -47,8 +49,8 @@ func checkOne(src, dst FsObject, out FsObjectsChan) {
|
||||
return
|
||||
}
|
||||
// Check to see if changed or not
|
||||
if Equal(src, dst) {
|
||||
FsDebug(src, "Unchanged skipping")
|
||||
if fs.Equal(src, dst) {
|
||||
fs.Debug(src, "Unchanged skipping")
|
||||
return
|
||||
}
|
||||
out <- src
|
||||
@@ -57,59 +59,59 @@ func checkOne(src, dst FsObject, out FsObjectsChan) {
|
||||
// Read FsObjects~s on in send to out if they need uploading
|
||||
//
|
||||
// FIXME potentially doing lots of MD5SUMS at once
|
||||
func PairChecker(in PairFsObjectsChan, out FsObjectsChan, wg *sync.WaitGroup) {
|
||||
func PairChecker(in PairFsObjectsChan, out fs.ObjectsChan, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
for pair := range in {
|
||||
src := pair.src
|
||||
stats.Checking(src)
|
||||
fs.Stats.Checking(src)
|
||||
checkOne(src, pair.dst, out)
|
||||
stats.DoneChecking(src)
|
||||
fs.Stats.DoneChecking(src)
|
||||
}
|
||||
}
|
||||
|
||||
// Read FsObjects~s on in send to out if they need uploading
|
||||
//
|
||||
// FIXME potentially doing lots of MD5SUMS at once
|
||||
func Checker(in, out FsObjectsChan, fdst Fs, wg *sync.WaitGroup) {
|
||||
func Checker(in, out fs.ObjectsChan, fdst fs.Fs, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
for src := range in {
|
||||
stats.Checking(src)
|
||||
fs.Stats.Checking(src)
|
||||
dst := fdst.NewFsObject(src.Remote())
|
||||
checkOne(src, dst, out)
|
||||
stats.DoneChecking(src)
|
||||
fs.Stats.DoneChecking(src)
|
||||
}
|
||||
}
|
||||
|
||||
// Read FsObjects on in and copy them
|
||||
func Copier(in FsObjectsChan, fdst Fs, wg *sync.WaitGroup) {
|
||||
func Copier(in fs.ObjectsChan, fdst fs.Fs, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
for src := range in {
|
||||
stats.Transferring(src)
|
||||
Copy(fdst, src)
|
||||
stats.DoneTransferring(src)
|
||||
fs.Stats.Transferring(src)
|
||||
fs.Copy(fdst, src)
|
||||
fs.Stats.DoneTransferring(src)
|
||||
}
|
||||
}
|
||||
|
||||
// Copies fsrc into fdst
|
||||
func CopyFs(fdst, fsrc Fs) {
|
||||
func CopyFs(fdst, fsrc fs.Fs) {
|
||||
err := fdst.Mkdir()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Fatal("Failed to make destination")
|
||||
}
|
||||
|
||||
to_be_checked := fsrc.List()
|
||||
to_be_uploaded := make(FsObjectsChan, *transfers)
|
||||
to_be_uploaded := make(fs.ObjectsChan, fs.Config.Transfers)
|
||||
|
||||
var checkerWg sync.WaitGroup
|
||||
checkerWg.Add(*checkers)
|
||||
for i := 0; i < *checkers; i++ {
|
||||
checkerWg.Add(fs.Config.Checkers)
|
||||
for i := 0; i < fs.Config.Checkers; i++ {
|
||||
go Checker(to_be_checked, to_be_uploaded, fdst, &checkerWg)
|
||||
}
|
||||
|
||||
var copierWg sync.WaitGroup
|
||||
copierWg.Add(*transfers)
|
||||
for i := 0; i < *transfers; i++ {
|
||||
copierWg.Add(fs.Config.Transfers)
|
||||
for i := 0; i < fs.Config.Transfers; i++ {
|
||||
go Copier(to_be_uploaded, fdst, &copierWg)
|
||||
}
|
||||
|
||||
@@ -121,24 +123,24 @@ func CopyFs(fdst, fsrc Fs) {
|
||||
}
|
||||
|
||||
// Delete all the files passed in the channel
|
||||
func DeleteFiles(to_be_deleted FsObjectsChan) {
|
||||
func DeleteFiles(to_be_deleted fs.ObjectsChan) {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(*transfers)
|
||||
for i := 0; i < *transfers; i++ {
|
||||
wg.Add(fs.Config.Transfers)
|
||||
for i := 0; i < fs.Config.Transfers; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for dst := range to_be_deleted {
|
||||
if *dry_run {
|
||||
FsDebug(dst, "Not deleting as -dry-run")
|
||||
fs.Debug(dst, "Not deleting as -dry-run")
|
||||
} else {
|
||||
stats.Checking(dst)
|
||||
fs.Stats.Checking(dst)
|
||||
err := dst.Remove()
|
||||
stats.DoneChecking(dst)
|
||||
fs.Stats.DoneChecking(dst)
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(dst, "Couldn't delete: %s", err)
|
||||
fs.Stats.Error()
|
||||
fs.Log(dst, "Couldn't delete: %s", err)
|
||||
} else {
|
||||
FsDebug(dst, "Deleted")
|
||||
fs.Debug(dst, "Deleted")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -150,10 +152,10 @@ func DeleteFiles(to_be_deleted FsObjectsChan) {
|
||||
}
|
||||
|
||||
// Syncs fsrc into fdst
|
||||
func Sync(fdst, fsrc Fs) {
|
||||
func Sync(fdst, fsrc fs.Fs) {
|
||||
err := fdst.Mkdir()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Fatal("Failed to make destination")
|
||||
}
|
||||
|
||||
@@ -161,24 +163,24 @@ func Sync(fdst, fsrc Fs) {
|
||||
|
||||
// Read the destination files first
|
||||
// FIXME could do this in parallel and make it use less memory
|
||||
delFiles := make(map[string]FsObject)
|
||||
delFiles := make(map[string]fs.Object)
|
||||
for dst := range fdst.List() {
|
||||
delFiles[dst.Remote()] = dst
|
||||
}
|
||||
|
||||
// Read source files checking them off against dest files
|
||||
to_be_checked := make(PairFsObjectsChan, *transfers)
|
||||
to_be_uploaded := make(FsObjectsChan, *transfers)
|
||||
to_be_checked := make(PairFsObjectsChan, fs.Config.Transfers)
|
||||
to_be_uploaded := make(fs.ObjectsChan, fs.Config.Transfers)
|
||||
|
||||
var checkerWg sync.WaitGroup
|
||||
checkerWg.Add(*checkers)
|
||||
for i := 0; i < *checkers; i++ {
|
||||
checkerWg.Add(fs.Config.Checkers)
|
||||
for i := 0; i < fs.Config.Checkers; i++ {
|
||||
go PairChecker(to_be_checked, to_be_uploaded, &checkerWg)
|
||||
}
|
||||
|
||||
var copierWg sync.WaitGroup
|
||||
copierWg.Add(*transfers)
|
||||
for i := 0; i < *transfers; i++ {
|
||||
copierWg.Add(fs.Config.Transfers)
|
||||
for i := 0; i < fs.Config.Transfers; i++ {
|
||||
go Copier(to_be_uploaded, fdst, &copierWg)
|
||||
}
|
||||
|
||||
@@ -203,13 +205,13 @@ func Sync(fdst, fsrc Fs) {
|
||||
log.Printf("Waiting for transfers to finish")
|
||||
copierWg.Wait()
|
||||
|
||||
if stats.errors != 0 {
|
||||
if fs.Stats.Errored() {
|
||||
log.Printf("Not deleting files as there were IO errors")
|
||||
return
|
||||
}
|
||||
|
||||
// Delete the spare files
|
||||
toDelete := make(FsObjectsChan, *transfers)
|
||||
toDelete := make(fs.ObjectsChan, fs.Config.Transfers)
|
||||
go func() {
|
||||
for _, fs := range delFiles {
|
||||
toDelete <- fs
|
||||
@@ -220,24 +222,24 @@ func Sync(fdst, fsrc Fs) {
|
||||
}
|
||||
|
||||
// Checks the files in fsrc and fdst according to Size and MD5SUM
|
||||
func Check(fdst, fsrc Fs) {
|
||||
func Check(fdst, fsrc fs.Fs) {
|
||||
log.Printf("Building file list")
|
||||
|
||||
// Read the destination files first
|
||||
// FIXME could do this in parallel and make it use less memory
|
||||
dstFiles := make(map[string]FsObject)
|
||||
dstFiles := make(map[string]fs.Object)
|
||||
for dst := range fdst.List() {
|
||||
dstFiles[dst.Remote()] = dst
|
||||
}
|
||||
|
||||
// Read the source files checking them against dstFiles
|
||||
// FIXME could do this in parallel and make it use less memory
|
||||
srcFiles := make(map[string]FsObject)
|
||||
commonFiles := make(map[string][]FsObject)
|
||||
srcFiles := make(map[string]fs.Object)
|
||||
commonFiles := make(map[string][]fs.Object)
|
||||
for src := range fsrc.List() {
|
||||
remote := src.Remote()
|
||||
if dst, ok := dstFiles[remote]; ok {
|
||||
commonFiles[remote] = []FsObject{dst, src}
|
||||
commonFiles[remote] = []fs.Object{dst, src}
|
||||
delete(dstFiles, remote)
|
||||
} else {
|
||||
srcFiles[remote] = src
|
||||
@@ -246,17 +248,17 @@ func Check(fdst, fsrc Fs) {
|
||||
|
||||
log.Printf("Files in %s but not in %s", fdst, fsrc)
|
||||
for remote := range dstFiles {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf(remote)
|
||||
}
|
||||
|
||||
log.Printf("Files in %s but not in %s", fsrc, fdst)
|
||||
for remote := range srcFiles {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf(remote)
|
||||
}
|
||||
|
||||
checks := make(chan []FsObject, *transfers)
|
||||
checks := make(chan []fs.Object, fs.Config.Transfers)
|
||||
go func() {
|
||||
for _, check := range commonFiles {
|
||||
checks <- check
|
||||
@@ -265,53 +267,53 @@ func Check(fdst, fsrc Fs) {
|
||||
}()
|
||||
|
||||
var checkerWg sync.WaitGroup
|
||||
checkerWg.Add(*checkers)
|
||||
for i := 0; i < *checkers; i++ {
|
||||
checkerWg.Add(fs.Config.Checkers)
|
||||
for i := 0; i < fs.Config.Checkers; i++ {
|
||||
go func() {
|
||||
defer checkerWg.Done()
|
||||
for check := range checks {
|
||||
dst, src := check[0], check[1]
|
||||
stats.Checking(src)
|
||||
fs.Stats.Checking(src)
|
||||
if src.Size() != dst.Size() {
|
||||
stats.DoneChecking(src)
|
||||
stats.Error()
|
||||
FsLog(src, "Sizes differ")
|
||||
fs.Stats.DoneChecking(src)
|
||||
fs.Stats.Error()
|
||||
fs.Log(src, "Sizes differ")
|
||||
continue
|
||||
}
|
||||
same, err := CheckMd5sums(src, dst)
|
||||
stats.DoneChecking(src)
|
||||
same, err := fs.CheckMd5sums(src, dst)
|
||||
fs.Stats.DoneChecking(src)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if !same {
|
||||
stats.Error()
|
||||
FsLog(src, "Md5sums differ")
|
||||
fs.Stats.Error()
|
||||
fs.Log(src, "Md5sums differ")
|
||||
}
|
||||
FsDebug(src, "OK")
|
||||
fs.Debug(src, "OK")
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
log.Printf("Waiting for checks to finish")
|
||||
checkerWg.Wait()
|
||||
log.Printf("%d differences found", stats.errors)
|
||||
log.Printf("%d differences found", fs.Stats.GetErrors())
|
||||
}
|
||||
|
||||
// List the Fs to stdout
|
||||
//
|
||||
// Lists in parallel which may get them out of order
|
||||
func List(f, _ Fs) {
|
||||
func List(f, _ fs.Fs) {
|
||||
in := f.List()
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(*checkers)
|
||||
for i := 0; i < *checkers; i++ {
|
||||
wg.Add(fs.Config.Checkers)
|
||||
for i := 0; i < fs.Config.Checkers; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for fs := range in {
|
||||
stats.Checking(fs)
|
||||
modTime := fs.ModTime()
|
||||
stats.DoneChecking(fs)
|
||||
fmt.Printf("%9d %19s %s\n", fs.Size(), modTime.Format("2006-01-02 15:04:05.00000000"), fs.Remote())
|
||||
for o := range in {
|
||||
fs.Stats.Checking(o)
|
||||
modTime := o.ModTime()
|
||||
fs.Stats.DoneChecking(o)
|
||||
fmt.Printf("%9d %19s %s\n", o.Size(), modTime.Format("2006-01-02 15:04:05.00000000"), o.Remote())
|
||||
}
|
||||
}()
|
||||
}
|
||||
@@ -319,29 +321,29 @@ func List(f, _ Fs) {
|
||||
}
|
||||
|
||||
// List the directories/buckets/containers in the Fs to stdout
|
||||
func ListDir(f, _ Fs) {
|
||||
func ListDir(f, _ fs.Fs) {
|
||||
for dir := range f.ListDir() {
|
||||
fmt.Printf("%12d %13s %9d %s\n", dir.Bytes, dir.When.Format("2006-01-02 15:04:05"), dir.Count, dir.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// Makes a destination directory or container
|
||||
func mkdir(fdst, fsrc Fs) {
|
||||
func mkdir(fdst, fsrc fs.Fs) {
|
||||
err := fdst.Mkdir()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Fatalf("Mkdir failed: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Removes a container but not if not empty
|
||||
func rmdir(fdst, fsrc Fs) {
|
||||
func rmdir(fdst, fsrc fs.Fs) {
|
||||
if *dry_run {
|
||||
log.Printf("Not deleting %s as -dry-run", fdst)
|
||||
} else {
|
||||
err := fdst.Rmdir()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Fatalf("Rmdir failed: %s", err)
|
||||
}
|
||||
}
|
||||
@@ -350,11 +352,11 @@ func rmdir(fdst, fsrc Fs) {
|
||||
// Removes a container and all of its contents
|
||||
//
|
||||
// FIXME doesn't delete local directories
|
||||
func purge(fdst, fsrc Fs) {
|
||||
if f, ok := fdst.(Purger); ok {
|
||||
func purge(fdst, fsrc fs.Fs) {
|
||||
if f, ok := fdst.(fs.Purger); ok {
|
||||
err := f.Purge()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Fatalf("Purge failed: %s", err)
|
||||
}
|
||||
} else {
|
||||
@@ -364,117 +366,128 @@ func purge(fdst, fsrc Fs) {
|
||||
}
|
||||
}
|
||||
|
||||
// Edits the config file
|
||||
func EditConfig(fdst, fsrc fs.Fs) {
|
||||
fs.EditConfig()
|
||||
}
|
||||
|
||||
type Command struct {
|
||||
name string
|
||||
help string
|
||||
run func(fdst, fsrc Fs)
|
||||
minArgs, maxArgs int
|
||||
Name string
|
||||
Help string
|
||||
ArgsHelp string
|
||||
Run func(fdst, fsrc fs.Fs)
|
||||
MinArgs int
|
||||
MaxArgs int
|
||||
NoStats bool
|
||||
}
|
||||
|
||||
// checkArgs checks there are enough arguments and prints a message if not
|
||||
func (cmd *Command) checkArgs(args []string) {
|
||||
if len(args) < cmd.minArgs {
|
||||
if len(args) < cmd.MinArgs {
|
||||
syntaxError()
|
||||
fmt.Fprintf(os.Stderr, "Command %s needs %d arguments mininum\n", cmd.name, cmd.minArgs)
|
||||
fmt.Fprintf(os.Stderr, "Command %s needs %d arguments mininum\n", cmd.Name, cmd.MinArgs)
|
||||
os.Exit(1)
|
||||
} else if len(args) > cmd.maxArgs {
|
||||
} else if len(args) > cmd.MaxArgs {
|
||||
syntaxError()
|
||||
fmt.Fprintf(os.Stderr, "Command %s needs %d arguments maximum\n", cmd.name, cmd.maxArgs)
|
||||
fmt.Fprintf(os.Stderr, "Command %s needs %d arguments maximum\n", cmd.Name, cmd.MaxArgs)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
var Commands = []Command{
|
||||
{
|
||||
"copy",
|
||||
`<source> <destination>
|
||||
|
||||
Name: "copy",
|
||||
ArgsHelp: "source://path dest://path",
|
||||
Help: `
|
||||
Copy the source to the destination. Doesn't transfer
|
||||
unchanged files, testing first by modification time then by
|
||||
MD5SUM. Doesn't delete files from the destination.
|
||||
|
||||
`,
|
||||
CopyFs,
|
||||
2, 2,
|
||||
MD5SUM. Doesn't delete files from the destination.`,
|
||||
Run: CopyFs,
|
||||
MinArgs: 2,
|
||||
MaxArgs: 2,
|
||||
},
|
||||
{
|
||||
"sync",
|
||||
`<source> <destination>
|
||||
|
||||
Name: "sync",
|
||||
ArgsHelp: "source://path dest://path",
|
||||
Help: `
|
||||
Sync the source to the destination. Doesn't transfer
|
||||
unchanged files, testing first by modification time then by
|
||||
MD5SUM. Deletes any files that exist in source that don't
|
||||
exist in destination. Since this can cause data loss, test
|
||||
first with the -dry-run flag.`,
|
||||
|
||||
Sync,
|
||||
2, 2,
|
||||
Run: Sync,
|
||||
MinArgs: 2,
|
||||
MaxArgs: 2,
|
||||
},
|
||||
{
|
||||
"ls",
|
||||
`[<path>]
|
||||
|
||||
Name: "ls",
|
||||
ArgsHelp: "[remote://path]",
|
||||
Help: `
|
||||
List all the objects in the the path.`,
|
||||
|
||||
List,
|
||||
1, 1,
|
||||
Run: List,
|
||||
MinArgs: 1,
|
||||
MaxArgs: 1,
|
||||
},
|
||||
{
|
||||
"lsd",
|
||||
`[<path>]
|
||||
|
||||
Name: "lsd",
|
||||
ArgsHelp: "[remote://path]",
|
||||
Help: `
|
||||
List all directoryes/objects/buckets in the the path.`,
|
||||
|
||||
ListDir,
|
||||
1, 1,
|
||||
Run: ListDir,
|
||||
MinArgs: 1,
|
||||
MaxArgs: 1,
|
||||
},
|
||||
{
|
||||
"mkdir",
|
||||
`<path>
|
||||
|
||||
Name: "mkdir",
|
||||
ArgsHelp: "remote://path",
|
||||
Help: `
|
||||
Make the path if it doesn't already exist`,
|
||||
|
||||
mkdir,
|
||||
1, 1,
|
||||
Run: mkdir,
|
||||
MinArgs: 1,
|
||||
MaxArgs: 1,
|
||||
},
|
||||
{
|
||||
"rmdir",
|
||||
`<path>
|
||||
|
||||
Name: "rmdir",
|
||||
ArgsHelp: "remote://path",
|
||||
Help: `
|
||||
Remove the path. Note that you can't remove a path with
|
||||
objects in it, use purge for that.`,
|
||||
|
||||
rmdir,
|
||||
1, 1,
|
||||
Run: rmdir,
|
||||
MinArgs: 1,
|
||||
MaxArgs: 1,
|
||||
},
|
||||
{
|
||||
"purge",
|
||||
`<path>
|
||||
|
||||
Name: "purge",
|
||||
ArgsHelp: "remote://path",
|
||||
Help: `
|
||||
Remove the path and all of its contents.`,
|
||||
|
||||
purge,
|
||||
1, 1,
|
||||
Run: purge,
|
||||
MinArgs: 1,
|
||||
MaxArgs: 1,
|
||||
},
|
||||
{
|
||||
"check",
|
||||
`<source> <destination>
|
||||
|
||||
Name: "check",
|
||||
ArgsHelp: "source://path dest://path",
|
||||
Help: `
|
||||
Checks the files in the source and destination match. It
|
||||
compares sizes and MD5SUMs and prints a report of files which
|
||||
don't match. It doesn't alter the source or destination.`,
|
||||
|
||||
Check,
|
||||
2, 2,
|
||||
Run: Check,
|
||||
MinArgs: 2,
|
||||
MaxArgs: 2,
|
||||
},
|
||||
{
|
||||
"help",
|
||||
`
|
||||
|
||||
Name: "config",
|
||||
Help: `
|
||||
Enter an interactive configuration session.`,
|
||||
Run: EditConfig,
|
||||
NoStats: true,
|
||||
},
|
||||
{
|
||||
Name: "help",
|
||||
Help: `
|
||||
This help.`,
|
||||
|
||||
nil,
|
||||
0, 0,
|
||||
NoStats: true,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -489,7 +502,8 @@ Subcommands:
|
||||
`)
|
||||
for i := range Commands {
|
||||
cmd := &Commands[i]
|
||||
fmt.Fprintf(os.Stderr, " %s: %s\n\n", cmd.name, cmd.help)
|
||||
fmt.Fprintf(os.Stderr, " %s %s\n", cmd.Name, cmd.ArgsHelp)
|
||||
fmt.Fprintf(os.Stderr, "%s\n\n", cmd.Help)
|
||||
}
|
||||
|
||||
fmt.Fprintf(os.Stderr, "Options:\n")
|
||||
@@ -511,12 +525,13 @@ func main() {
|
||||
flag.Parse()
|
||||
args := flag.Args()
|
||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||
fs.LoadConfig()
|
||||
|
||||
// Setup profiling if desired
|
||||
if *cpuprofile != "" {
|
||||
f, err := os.Create(*cpuprofile)
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Fatal(err)
|
||||
}
|
||||
pprof.StartCPUProfile(f)
|
||||
@@ -535,38 +550,38 @@ func main() {
|
||||
for i := range Commands {
|
||||
command := &Commands[i]
|
||||
// exact command name found - use that
|
||||
if command.name == cmd {
|
||||
if command.Name == cmd {
|
||||
found = command
|
||||
break
|
||||
} else if strings.HasPrefix(command.name, cmd) {
|
||||
} else if strings.HasPrefix(command.Name, cmd) {
|
||||
if found != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Fatalf("Not unique - matches multiple commands %q", cmd)
|
||||
}
|
||||
found = command
|
||||
}
|
||||
}
|
||||
if found == nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Fatalf("Unknown command %q", cmd)
|
||||
}
|
||||
found.checkArgs(args)
|
||||
|
||||
// Make source and destination fs
|
||||
var fdst, fsrc Fs
|
||||
var fdst, fsrc fs.Fs
|
||||
var err error
|
||||
if len(args) >= 1 {
|
||||
fdst, err = NewFs(args[0])
|
||||
fdst, err = fs.NewFs(args[0])
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
log.Fatal("Failed to create file system: ", err)
|
||||
fs.Stats.Error()
|
||||
log.Fatalf("Failed to create file system for %q: %v", args[0], err)
|
||||
}
|
||||
}
|
||||
if len(args) >= 2 {
|
||||
fsrc, err = NewFs(args[1])
|
||||
fsrc, err = fs.NewFs(args[1])
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
log.Fatal("Failed to create destination file system: ", err)
|
||||
fs.Stats.Error()
|
||||
log.Fatalf("Failed to create destination file system for %q: %v", args[1], err)
|
||||
}
|
||||
fsrc, fdst = fdst, fsrc
|
||||
}
|
||||
@@ -575,34 +590,42 @@ func main() {
|
||||
if fsrc != nil {
|
||||
precision := fsrc.Precision()
|
||||
log.Printf("Source precision %s\n", precision)
|
||||
if precision > *modifyWindow {
|
||||
*modifyWindow = precision
|
||||
if precision > fs.Config.ModifyWindow {
|
||||
fs.Config.ModifyWindow = precision
|
||||
}
|
||||
}
|
||||
if fdst != nil {
|
||||
precision := fdst.Precision()
|
||||
log.Printf("Destination precision %s\n", precision)
|
||||
if precision > *modifyWindow {
|
||||
*modifyWindow = precision
|
||||
if precision > fs.Config.ModifyWindow {
|
||||
fs.Config.ModifyWindow = precision
|
||||
}
|
||||
}
|
||||
log.Printf("Modify window is %s\n", *modifyWindow)
|
||||
if fs.Config.Verbose {
|
||||
log.Printf("Modify window is %s\n", fs.Config.ModifyWindow)
|
||||
}
|
||||
|
||||
// Print the stats every statsInterval
|
||||
go func() {
|
||||
ch := time.Tick(*statsInterval)
|
||||
for {
|
||||
<-ch
|
||||
stats.Log()
|
||||
}
|
||||
}()
|
||||
if !found.NoStats {
|
||||
go func() {
|
||||
ch := time.Tick(*statsInterval)
|
||||
for {
|
||||
<-ch
|
||||
fs.Stats.Log()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// Run the actual command
|
||||
if found.run != nil {
|
||||
found.run(fdst, fsrc)
|
||||
fmt.Println(stats)
|
||||
log.Printf("*** Go routines at exit %d\n", runtime.NumGoroutine())
|
||||
if stats.errors > 0 {
|
||||
if found.Run != nil {
|
||||
found.Run(fdst, fsrc)
|
||||
if !found.NoStats {
|
||||
fmt.Println(fs.Stats)
|
||||
}
|
||||
if fs.Config.Verbose {
|
||||
log.Printf("*** Go routines at exit %d\n", runtime.NumGoroutine())
|
||||
}
|
||||
if fs.Stats.Errored() {
|
||||
os.Exit(1)
|
||||
}
|
||||
os.Exit(0)
|
||||
|
||||
@@ -0,0 +1,435 @@
|
||||
// S3 interface
|
||||
package s3
|
||||
|
||||
// FIXME need to prevent anything but ListDir working for s3://
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/ncw/goamz/aws"
|
||||
"github.com/ncw/goamz/s3"
|
||||
"github.com/ncw/rclone/fs"
|
||||
"github.com/ncw/swift"
|
||||
)
|
||||
|
||||
// Register with Fs
|
||||
func init() {
|
||||
fs.Register(&fs.FsInfo{
|
||||
Name: "s3",
|
||||
NewFs: NewFs,
|
||||
// AWS endpoints: http://docs.amazonwebservices.com/general/latest/gr/rande.html#s3_region
|
||||
Options: []fs.Option{{
|
||||
Name: "access_key_id",
|
||||
Help: "AWS Access Key ID.",
|
||||
}, {
|
||||
Name: "secret_access_key",
|
||||
Help: "AWS Secret Access Key (password). ",
|
||||
}, {
|
||||
Name: "endpoint",
|
||||
Help: "Endpoint for S3 API.",
|
||||
Examples: []fs.OptionExample{{
|
||||
Value: "https://s3.amazonaws.com/",
|
||||
Help: "The default endpoint - a good choice if you are unsure.\nUS Region, Northern Virginia or Pacific Northwest.\nLeave location constraint empty.",
|
||||
}, {
|
||||
Value: "https://s3-external-1.amazonaws.com",
|
||||
Help: "US Region, Northern Virginia only.\nLeave location constraint empty.",
|
||||
}, {
|
||||
Value: "https://s3-us-west-2.amazonaws.com",
|
||||
Help: "US West (Oregon) Region\nNeeds location constraint us-west-2.",
|
||||
}, {
|
||||
Value: "https://s3-us-west-1.amazonaws.com",
|
||||
Help: "US West (Northern California) Region\nNeeds location constraint us-west-1.",
|
||||
}, {
|
||||
Value: "https://s3-eu-west-1.amazonaws.com",
|
||||
Help: "EU (Ireland) Region Region\nNeeds location constraint EU or eu-west-1.",
|
||||
}, {
|
||||
Value: "https://s3-ap-southeast-1.amazonaws.com",
|
||||
Help: "Asia Pacific (Singapore) Region\nNeeds location constraint ap-southeast-1.",
|
||||
}, {
|
||||
Value: "https://s3-ap-southeast-2.amazonaws.com",
|
||||
Help: "Asia Pacific (Sydney) Region\nNeeds location constraint .",
|
||||
}, {
|
||||
Value: "https://s3-ap-northeast-1.amazonaws.com",
|
||||
Help: "Asia Pacific (Tokyo) Region\nNeeds location constraint ap-northeast-1.",
|
||||
}, {
|
||||
Value: "https://s3-sa-east-1.amazonaws.com",
|
||||
Help: "South America (Sao Paulo) Region\nNeeds location constraint sa-east-1.",
|
||||
}},
|
||||
}, {
|
||||
Name: "location_constraint",
|
||||
Help: "Location constraint - must be set to match the Endpoint.",
|
||||
Examples: []fs.OptionExample{{
|
||||
Value: "",
|
||||
Help: "Empty for US Region, Northern Virginia or Pacific Northwest.",
|
||||
}, {
|
||||
Value: "us-west-2",
|
||||
Help: "US West (Oregon) Region.",
|
||||
}, {
|
||||
Value: "us-west-1",
|
||||
Help: "US West (Northern California) Region.",
|
||||
}, {
|
||||
Value: "eu-west-1",
|
||||
Help: "EU (Ireland) Region.",
|
||||
}, {
|
||||
Value: "EU",
|
||||
Help: "EU Region.",
|
||||
}, {
|
||||
Value: "ap-southeast-1",
|
||||
Help: "Asia Pacific (Singapore) Region.",
|
||||
}, {
|
||||
Value: "ap-southeast-2",
|
||||
Help: "Asia Pacific (Sydney) Region.",
|
||||
}, {
|
||||
Value: "ap-northeast-1",
|
||||
Help: "Asia Pacific (Tokyo) Region.",
|
||||
}, {
|
||||
Value: "sa-east-1",
|
||||
Help: "South America (Sao Paulo) Region.",
|
||||
}},
|
||||
}},
|
||||
})
|
||||
}
|
||||
|
||||
// Constants
|
||||
const (
|
||||
metaMtime = "X-Amz-Meta-Mtime" // the meta key to store mtime in
|
||||
)
|
||||
|
||||
// FsS3 represents a remote s3 server
|
||||
type FsS3 struct {
|
||||
c *s3.S3 // the connection to the s3 server
|
||||
b *s3.Bucket // the connection to the bucket
|
||||
bucket string // the bucket we are working on
|
||||
perm s3.ACL // permissions for new buckets / objects
|
||||
}
|
||||
|
||||
// FsObjectS3 describes a s3 object
|
||||
type FsObjectS3 struct {
|
||||
// Will definitely have everything but meta which may be nil
|
||||
//
|
||||
// List will read everything but meta - to fill that in need to call
|
||||
// readMetaData
|
||||
s3 *FsS3 // what this object is part of
|
||||
remote string // The remote path
|
||||
etag string // md5sum of the object
|
||||
bytes int64 // size of the object
|
||||
lastModified time.Time // Last modified
|
||||
meta s3.Headers // The object metadata if known - may be nil
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------
|
||||
|
||||
// String converts this FsS3 to a string
|
||||
func (f *FsS3) String() string {
|
||||
return fmt.Sprintf("S3 bucket %s", f.bucket)
|
||||
}
|
||||
|
||||
// Pattern to match a s3 path
|
||||
var matcher = regexp.MustCompile(`^([^/]*)(.*)$`)
|
||||
|
||||
// parseParse parses a s3 'url'
|
||||
func s3ParsePath(path string) (bucket, directory string, err error) {
|
||||
parts := matcher.FindStringSubmatch(path)
|
||||
if parts == nil {
|
||||
err = fmt.Errorf("Couldn't parse bucket out of s3 path %q", path)
|
||||
} else {
|
||||
bucket, directory = parts[1], parts[2]
|
||||
directory = strings.Trim(directory, "/")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// s3Connection makes a connection to s3
|
||||
func s3Connection(name string) (*s3.S3, error) {
|
||||
// Make the auth
|
||||
accessKeyId := fs.ConfigFile.MustValue(name, "access_key_id")
|
||||
if accessKeyId == "" {
|
||||
return nil, errors.New("access_key_id not found")
|
||||
}
|
||||
secretAccessKey := fs.ConfigFile.MustValue(name, "secret_access_key")
|
||||
if secretAccessKey == "" {
|
||||
return nil, errors.New("secret_access_key not found")
|
||||
}
|
||||
auth := aws.Auth{AccessKey: accessKeyId, SecretKey: secretAccessKey}
|
||||
|
||||
// FIXME look through all the regions by name and use one of them if found
|
||||
|
||||
// Synthesize the region
|
||||
s3Endpoint := fs.ConfigFile.MustValue(name, "endpoint")
|
||||
if s3Endpoint == "" {
|
||||
s3Endpoint = "https://s3.amazonaws.com/"
|
||||
}
|
||||
region := aws.Region{
|
||||
Name: "s3",
|
||||
S3Endpoint: s3Endpoint,
|
||||
S3LocationConstraint: false,
|
||||
}
|
||||
s3LocationConstraint := fs.ConfigFile.MustValue(name, "location_constraint")
|
||||
if s3LocationConstraint != "" {
|
||||
region.Name = s3LocationConstraint
|
||||
region.S3LocationConstraint = true
|
||||
}
|
||||
|
||||
c := s3.New(auth, region)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// NewFsS3 contstructs an FsS3 from the path, bucket:path
|
||||
func NewFs(name, path string) (fs.Fs, error) {
|
||||
bucket, directory, err := s3ParsePath(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if directory != "" {
|
||||
return nil, fmt.Errorf("Directories not supported yet in %q: %q", path, directory)
|
||||
}
|
||||
c, err := s3Connection(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f := &FsS3{
|
||||
c: c,
|
||||
bucket: bucket,
|
||||
b: c.Bucket(bucket),
|
||||
perm: s3.Private, // FIXME need user to specify
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// Return an FsObject from a path
|
||||
//
|
||||
// May return nil if an error occurred
|
||||
func (f *FsS3) NewFsObjectWithInfo(remote string, info *s3.Key) fs.Object {
|
||||
o := &FsObjectS3{
|
||||
s3: f,
|
||||
remote: remote,
|
||||
}
|
||||
if info != nil {
|
||||
// Set info but not meta
|
||||
var err error
|
||||
o.lastModified, err = time.Parse(time.RFC3339, info.LastModified)
|
||||
if err != nil {
|
||||
fs.Log(o, "Failed to read last modified: %s", err)
|
||||
o.lastModified = time.Now()
|
||||
}
|
||||
o.etag = info.ETag
|
||||
o.bytes = info.Size
|
||||
} else {
|
||||
err := o.readMetaData() // reads info and meta, returning an error
|
||||
if err != nil {
|
||||
// logged already FsDebug("Failed to read info: %s", err)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
// Return an FsObject from a path
|
||||
//
|
||||
// May return nil if an error occurred
|
||||
func (f *FsS3) NewFsObject(remote string) fs.Object {
|
||||
return f.NewFsObjectWithInfo(remote, nil)
|
||||
}
|
||||
|
||||
// Walk the path returning a channel of FsObjects
|
||||
func (f *FsS3) List() fs.ObjectsChan {
|
||||
out := make(fs.ObjectsChan, fs.Config.Checkers)
|
||||
go func() {
|
||||
// FIXME need to implement ALL loop
|
||||
objects, err := f.b.List("", "", "", 10000)
|
||||
if err != nil {
|
||||
fs.Stats.Error()
|
||||
log.Printf("Couldn't read bucket %q: %s", f.bucket, err)
|
||||
} else {
|
||||
for i := range objects.Contents {
|
||||
object := &objects.Contents[i]
|
||||
if fs := f.NewFsObjectWithInfo(object.Key, object); fs != nil {
|
||||
out <- fs
|
||||
}
|
||||
}
|
||||
}
|
||||
close(out)
|
||||
}()
|
||||
return out
|
||||
}
|
||||
|
||||
// Lists the buckets
|
||||
func (f *FsS3) ListDir() fs.DirChan {
|
||||
out := make(fs.DirChan, fs.Config.Checkers)
|
||||
go func() {
|
||||
defer close(out)
|
||||
buckets, err := f.c.ListBuckets()
|
||||
if err != nil {
|
||||
fs.Stats.Error()
|
||||
log.Printf("Couldn't list buckets: %s", err)
|
||||
} else {
|
||||
for _, bucket := range buckets {
|
||||
out <- &fs.Dir{
|
||||
Name: bucket.Name,
|
||||
When: bucket.CreationDate,
|
||||
Bytes: -1,
|
||||
Count: -1,
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
return out
|
||||
}
|
||||
|
||||
// Put the FsObject into the bucket
|
||||
func (f *FsS3) Put(in io.Reader, remote string, modTime time.Time, size int64) (fs.Object, error) {
|
||||
// Temporary FsObject under construction
|
||||
fs := &FsObjectS3{s3: f, remote: remote}
|
||||
|
||||
// Set the mtime in the headers
|
||||
headers := s3.Headers{
|
||||
metaMtime: swift.TimeToFloatString(modTime),
|
||||
}
|
||||
|
||||
// Guess the content type
|
||||
contentType := mime.TypeByExtension(path.Ext(remote))
|
||||
if contentType == "" {
|
||||
contentType = "application/octet-stream"
|
||||
}
|
||||
|
||||
_, err := fs.s3.b.PutReaderHeaders(remote, in, size, contentType, f.perm, headers)
|
||||
return fs, err
|
||||
}
|
||||
|
||||
// Mkdir creates the bucket if it doesn't exist
|
||||
func (f *FsS3) Mkdir() error {
|
||||
err := f.b.PutBucket(f.perm)
|
||||
if err, ok := err.(*s3.Error); ok {
|
||||
if err.Code == "BucketAlreadyOwnedByYou" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Rmdir deletes the bucket
|
||||
//
|
||||
// Returns an error if it isn't empty
|
||||
func (f *FsS3) Rmdir() error {
|
||||
return f.b.DelBucket()
|
||||
}
|
||||
|
||||
// Return the precision
|
||||
func (f *FsS3) Precision() time.Duration {
|
||||
return time.Nanosecond
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------
|
||||
|
||||
// Return the remote path
|
||||
func (o *FsObjectS3) Remote() string {
|
||||
return o.remote
|
||||
}
|
||||
|
||||
// Md5sum returns the Md5sum of an object returning a lowercase hex string
|
||||
func (o *FsObjectS3) Md5sum() (string, error) {
|
||||
return strings.Trim(strings.ToLower(o.etag), `"`), nil
|
||||
}
|
||||
|
||||
// Size returns the size of an object in bytes
|
||||
func (o *FsObjectS3) Size() int64 {
|
||||
return o.bytes
|
||||
}
|
||||
|
||||
// readMetaData gets the metadata if it hasn't already been fetched
|
||||
//
|
||||
// it also sets the info
|
||||
func (o *FsObjectS3) readMetaData() (err error) {
|
||||
if o.meta != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
headers, err := o.s3.b.Head(o.remote, nil)
|
||||
if err != nil {
|
||||
fs.Debug(o, "Failed to read info: %s", err)
|
||||
return err
|
||||
}
|
||||
size, err := strconv.ParseInt(headers["Content-Length"], 10, 64)
|
||||
if err != nil {
|
||||
fs.Debug(o, "Failed to read size from: %q", headers)
|
||||
return err
|
||||
}
|
||||
o.etag = headers["Etag"]
|
||||
o.bytes = size
|
||||
o.meta = headers
|
||||
if o.lastModified, err = time.Parse(http.TimeFormat, headers["Last-Modified"]); err != nil {
|
||||
fs.Log(o, "Failed to read last modified from HEAD: %s", err)
|
||||
o.lastModified = time.Now()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ModTime returns the modification time of the object
|
||||
//
|
||||
// It attempts to read the objects mtime and if that isn't present the
|
||||
// LastModified returned in the http headers
|
||||
func (o *FsObjectS3) ModTime() time.Time {
|
||||
err := o.readMetaData()
|
||||
if err != nil {
|
||||
fs.Log(o, "Failed to read metadata: %s", err)
|
||||
return time.Now()
|
||||
}
|
||||
// read mtime out of metadata if available
|
||||
d, ok := o.meta[metaMtime]
|
||||
if !ok {
|
||||
// fs.Debug(o, "No metadata")
|
||||
return o.lastModified
|
||||
}
|
||||
modTime, err := swift.FloatStringToTime(d)
|
||||
if err != nil {
|
||||
fs.Log(o, "Failed to read mtime from object: %s", err)
|
||||
return o.lastModified
|
||||
}
|
||||
return modTime
|
||||
}
|
||||
|
||||
// Sets the modification time of the local fs object
|
||||
func (o *FsObjectS3) SetModTime(modTime time.Time) {
|
||||
err := o.readMetaData()
|
||||
if err != nil {
|
||||
fs.Stats.Error()
|
||||
fs.Log(o, "Failed to read metadata: %s", err)
|
||||
return
|
||||
}
|
||||
o.meta[metaMtime] = swift.TimeToFloatString(modTime)
|
||||
_, err = o.s3.b.Update(o.remote, o.s3.perm, o.meta)
|
||||
if err != nil {
|
||||
fs.Stats.Error()
|
||||
fs.Log(o, "Failed to update remote mtime: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Is this object storable
|
||||
func (o *FsObjectS3) Storable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Open an object for read
|
||||
func (o *FsObjectS3) Open() (in io.ReadCloser, err error) {
|
||||
in, err = o.s3.b.GetReader(o.remote)
|
||||
return
|
||||
}
|
||||
|
||||
// Remove an object
|
||||
func (o *FsObjectS3) Remove() error {
|
||||
return o.s3.b.Del(o.remote)
|
||||
}
|
||||
|
||||
// Check the interfaces are satisfied
|
||||
var _ fs.Fs = &FsS3{}
|
||||
var _ fs.Object = &FsObjectS3{}
|
||||
+106
-77
@@ -1,21 +1,57 @@
|
||||
// Swift interface
|
||||
package main
|
||||
package swift
|
||||
|
||||
// FIXME need to prevent anything but ListDir working for swift://
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/ncw/swift"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/ncw/rclone/fs"
|
||||
"github.com/ncw/swift"
|
||||
)
|
||||
|
||||
// Register with Fs
|
||||
func init() {
|
||||
fs.Register(&fs.FsInfo{
|
||||
Name: "swift",
|
||||
NewFs: NewFs,
|
||||
Options: []fs.Option{{
|
||||
Name: "user",
|
||||
Help: "User name to log in.",
|
||||
}, {
|
||||
Name: "key",
|
||||
Help: "API key or password.",
|
||||
}, {
|
||||
Name: "auth",
|
||||
Help: "Authentication URL for server.",
|
||||
Examples: []fs.OptionExample{{
|
||||
Help: "Rackspace US",
|
||||
Value: "https://auth.api.rackspacecloud.com/v1.0",
|
||||
}, {
|
||||
Help: "Rackspace UK",
|
||||
Value: "https://lon.auth.api.rackspacecloud.com/v1.0",
|
||||
}, {
|
||||
Help: "Rackspace v2",
|
||||
Value: "https://identity.api.rackspacecloud.com/v2.0",
|
||||
}, {
|
||||
Help: "Memset Memstore UK",
|
||||
Value: "https://auth.storage.memset.com/v1.0",
|
||||
}, {
|
||||
Help: "Memset Memstore UK v2",
|
||||
Value: "https://auth.storage.memset.com/v2.0",
|
||||
}},
|
||||
},
|
||||
// snet = flag.Bool("swift-snet", false, "Use internal service network") // FIXME not implemented
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// FsSwift represents a remote swift server
|
||||
type FsSwift struct {
|
||||
c swift.Connection // the connection to the swift server
|
||||
@@ -35,51 +71,44 @@ type FsObjectSwift struct {
|
||||
|
||||
// ------------------------------------------------------------
|
||||
|
||||
// Globals
|
||||
var (
|
||||
// Flags
|
||||
// FIXME make these part of swift so we get a standard set of flags?
|
||||
authUrl = flag.String("auth", os.Getenv("ST_AUTH"), "Auth URL for server. Defaults to environment var ST_AUTH.")
|
||||
userName = flag.String("user", os.Getenv("ST_USER"), "User name. Defaults to environment var ST_USER.")
|
||||
apiKey = flag.String("key", os.Getenv("ST_KEY"), "API key (password). Defaults to environment var ST_KEY.")
|
||||
snet = flag.Bool("snet", false, "Use internal service network") // FIXME not implemented
|
||||
)
|
||||
|
||||
// String converts this FsSwift to a string
|
||||
func (f *FsSwift) String() string {
|
||||
return fmt.Sprintf("Swift container %s", f.container)
|
||||
}
|
||||
|
||||
// Pattern to match a swift url
|
||||
var swiftMatch = regexp.MustCompile(`^swift://([^/]*)(.*)$`)
|
||||
// Pattern to match a swift path
|
||||
var matcher = regexp.MustCompile(`^([^/]*)(.*)$`)
|
||||
|
||||
// parseParse parses a swift 'url'
|
||||
func parsePath(path string) (container, directory string, err error) {
|
||||
parts := swiftMatch.FindAllStringSubmatch(path, -1)
|
||||
if len(parts) != 1 || len(parts[0]) != 3 {
|
||||
err = fmt.Errorf("Couldn't parse swift url %q", path)
|
||||
parts := matcher.FindStringSubmatch(path)
|
||||
if parts == nil {
|
||||
err = fmt.Errorf("Couldn't find container in swift path %q", path)
|
||||
} else {
|
||||
container, directory = parts[0][1], parts[0][2]
|
||||
container, directory = parts[1], parts[2]
|
||||
directory = strings.Trim(directory, "/")
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// swiftConnection makes a connection to swift
|
||||
func swiftConnection() (*swift.Connection, error) {
|
||||
if *userName == "" {
|
||||
return nil, errors.New("Need -user or environmental variable ST_USER")
|
||||
func swiftConnection(name string) (*swift.Connection, error) {
|
||||
userName := fs.ConfigFile.MustValue(name, "user")
|
||||
if userName == "" {
|
||||
return nil, errors.New("user not found")
|
||||
}
|
||||
if *apiKey == "" {
|
||||
return nil, errors.New("Need -key or environmental variable ST_KEY")
|
||||
apiKey := fs.ConfigFile.MustValue(name, "key")
|
||||
if apiKey == "" {
|
||||
return nil, errors.New("key not found")
|
||||
}
|
||||
if *authUrl == "" {
|
||||
return nil, errors.New("Need -auth or environmental variable ST_AUTH")
|
||||
authUrl := fs.ConfigFile.MustValue(name, "auth")
|
||||
if authUrl == "" {
|
||||
return nil, errors.New("auth not found")
|
||||
}
|
||||
c := &swift.Connection{
|
||||
UserName: *userName,
|
||||
ApiKey: *apiKey,
|
||||
AuthUrl: *authUrl,
|
||||
UserName: userName,
|
||||
ApiKey: apiKey,
|
||||
AuthUrl: authUrl,
|
||||
}
|
||||
err := c.Authenticate()
|
||||
if err != nil {
|
||||
@@ -88,8 +117,8 @@ func swiftConnection() (*swift.Connection, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// NewFsSwift contstructs an FsSwift from the path, container:path
|
||||
func NewFsSwift(path string) (*FsSwift, error) {
|
||||
// NewFs contstructs an FsSwift from the path, container:path
|
||||
func NewFs(name, path string) (fs.Fs, error) {
|
||||
container, directory, err := parsePath(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -97,7 +126,7 @@ func NewFsSwift(path string) (*FsSwift, error) {
|
||||
if directory != "" {
|
||||
return nil, fmt.Errorf("Directories not supported yet in %q", path)
|
||||
}
|
||||
c, err := swiftConnection()
|
||||
c, err := swiftConnection(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -108,7 +137,7 @@ func NewFsSwift(path string) (*FsSwift, error) {
|
||||
// Return an FsObject from a path
|
||||
//
|
||||
// May return nil if an error occurred
|
||||
func (f *FsSwift) NewFsObjectWithInfo(remote string, info *swift.Object) FsObject {
|
||||
func (f *FsSwift) NewFsObjectWithInfo(remote string, info *swift.Object) fs.Object {
|
||||
fs := &FsObjectSwift{
|
||||
swift: f,
|
||||
remote: remote,
|
||||
@@ -129,13 +158,13 @@ func (f *FsSwift) NewFsObjectWithInfo(remote string, info *swift.Object) FsObjec
|
||||
// Return an FsObject from a path
|
||||
//
|
||||
// May return nil if an error occurred
|
||||
func (f *FsSwift) NewFsObject(remote string) FsObject {
|
||||
func (f *FsSwift) NewFsObject(remote string) fs.Object {
|
||||
return f.NewFsObjectWithInfo(remote, nil)
|
||||
}
|
||||
|
||||
// Walk the path returning a channel of FsObjects
|
||||
func (f *FsSwift) List() FsObjectsChan {
|
||||
out := make(FsObjectsChan, *checkers)
|
||||
func (f *FsSwift) List() fs.ObjectsChan {
|
||||
out := make(fs.ObjectsChan, fs.Config.Checkers)
|
||||
go func() {
|
||||
// FIXME use a smaller limit?
|
||||
err := f.c.ObjectsWalk(f.container, nil, func(opts *swift.ObjectsOpts) (interface{}, error) {
|
||||
@@ -151,7 +180,7 @@ func (f *FsSwift) List() FsObjectsChan {
|
||||
return objects, err
|
||||
})
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf("Couldn't read container %q: %s", f.container, err)
|
||||
}
|
||||
close(out)
|
||||
@@ -160,17 +189,17 @@ func (f *FsSwift) List() FsObjectsChan {
|
||||
}
|
||||
|
||||
// Lists the containers
|
||||
func (f *FsSwift) ListDir() FsDirChan {
|
||||
out := make(FsDirChan, *checkers)
|
||||
func (f *FsSwift) ListDir() fs.DirChan {
|
||||
out := make(fs.DirChan, fs.Config.Checkers)
|
||||
go func() {
|
||||
defer close(out)
|
||||
containers, err := f.c.ContainersAll(nil)
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
fs.Stats.Error()
|
||||
log.Printf("Couldn't list containers: %s", err)
|
||||
} else {
|
||||
for _, container := range containers {
|
||||
out <- &FsDir{
|
||||
out <- &fs.Dir{
|
||||
Name: container.Name,
|
||||
Bytes: container.Bytes,
|
||||
Count: container.Count,
|
||||
@@ -186,7 +215,7 @@ func (f *FsSwift) ListDir() FsDirChan {
|
||||
// Copy the reader in to the new object which is returned
|
||||
//
|
||||
// The new object may have been created
|
||||
func (f *FsSwift) Put(in io.Reader, remote string, modTime time.Time, size int64) (FsObject, error) {
|
||||
func (f *FsSwift) Put(in io.Reader, remote string, modTime time.Time, size int64) (fs.Object, error) {
|
||||
// Temporary FsObject under construction
|
||||
fs := &FsObjectSwift{swift: f, remote: remote}
|
||||
|
||||
@@ -217,35 +246,35 @@ func (fs *FsSwift) Precision() time.Duration {
|
||||
// ------------------------------------------------------------
|
||||
|
||||
// Return the remote path
|
||||
func (fs *FsObjectSwift) Remote() string {
|
||||
return fs.remote
|
||||
func (o *FsObjectSwift) Remote() string {
|
||||
return o.remote
|
||||
}
|
||||
|
||||
// Md5sum returns the Md5sum of an object returning a lowercase hex string
|
||||
func (fs *FsObjectSwift) Md5sum() (string, error) {
|
||||
return strings.ToLower(fs.info.Hash), nil
|
||||
func (o *FsObjectSwift) Md5sum() (string, error) {
|
||||
return strings.ToLower(o.info.Hash), nil
|
||||
}
|
||||
|
||||
// Size returns the size of an object in bytes
|
||||
func (fs *FsObjectSwift) Size() int64 {
|
||||
return fs.info.Bytes
|
||||
func (o *FsObjectSwift) Size() int64 {
|
||||
return o.info.Bytes
|
||||
}
|
||||
|
||||
// readMetaData gets the metadata if it hasn't already been fetched
|
||||
//
|
||||
// it also sets the info
|
||||
func (fs *FsObjectSwift) readMetaData() (err error) {
|
||||
if fs.meta != nil {
|
||||
func (o *FsObjectSwift) readMetaData() (err error) {
|
||||
if o.meta != nil {
|
||||
return nil
|
||||
}
|
||||
info, h, err := fs.swift.c.Object(fs.swift.container, fs.remote)
|
||||
info, h, err := o.swift.c.Object(o.swift.container, o.remote)
|
||||
if err != nil {
|
||||
FsDebug(fs, "Failed to read info: %s", err)
|
||||
fs.Debug(o, "Failed to read info: %s", err)
|
||||
return err
|
||||
}
|
||||
meta := h.ObjectMetadata()
|
||||
fs.info = info
|
||||
fs.meta = &meta
|
||||
o.info = info
|
||||
o.meta = &meta
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -254,52 +283,52 @@ func (fs *FsObjectSwift) readMetaData() (err error) {
|
||||
//
|
||||
// It attempts to read the objects mtime and if that isn't present the
|
||||
// LastModified returned in the http headers
|
||||
func (fs *FsObjectSwift) ModTime() time.Time {
|
||||
err := fs.readMetaData()
|
||||
func (o *FsObjectSwift) ModTime() time.Time {
|
||||
err := o.readMetaData()
|
||||
if err != nil {
|
||||
// FsLog(fs, "Failed to read metadata: %s", err)
|
||||
return fs.info.LastModified
|
||||
// fs.Log(o, "Failed to read metadata: %s", err)
|
||||
return o.info.LastModified
|
||||
}
|
||||
modTime, err := fs.meta.GetModTime()
|
||||
modTime, err := o.meta.GetModTime()
|
||||
if err != nil {
|
||||
// FsLog(fs, "Failed to read mtime from object: %s", err)
|
||||
return fs.info.LastModified
|
||||
// fs.Log(o, "Failed to read mtime from object: %s", err)
|
||||
return o.info.LastModified
|
||||
}
|
||||
return modTime
|
||||
}
|
||||
|
||||
// Sets the modification time of the local fs object
|
||||
func (fs *FsObjectSwift) SetModTime(modTime time.Time) {
|
||||
err := fs.readMetaData()
|
||||
func (o *FsObjectSwift) SetModTime(modTime time.Time) {
|
||||
err := o.readMetaData()
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(fs, "Failed to read metadata: %s", err)
|
||||
fs.Stats.Error()
|
||||
fs.Log(o, "Failed to read metadata: %s", err)
|
||||
return
|
||||
}
|
||||
fs.meta.SetModTime(modTime)
|
||||
err = fs.swift.c.ObjectUpdate(fs.swift.container, fs.remote, fs.meta.ObjectHeaders())
|
||||
o.meta.SetModTime(modTime)
|
||||
err = o.swift.c.ObjectUpdate(o.swift.container, o.remote, o.meta.ObjectHeaders())
|
||||
if err != nil {
|
||||
stats.Error()
|
||||
FsLog(fs, "Failed to update remote mtime: %s", err)
|
||||
fs.Stats.Error()
|
||||
fs.Log(o, "Failed to update remote mtime: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Is this object storable
|
||||
func (fs *FsObjectSwift) Storable() bool {
|
||||
func (o *FsObjectSwift) Storable() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// Open an object for read
|
||||
func (fs *FsObjectSwift) Open() (in io.ReadCloser, err error) {
|
||||
in, _, err = fs.swift.c.ObjectOpen(fs.swift.container, fs.remote, true, nil)
|
||||
func (o *FsObjectSwift) Open() (in io.ReadCloser, err error) {
|
||||
in, _, err = o.swift.c.ObjectOpen(o.swift.container, o.remote, true, nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Remove an object
|
||||
func (fs *FsObjectSwift) Remove() error {
|
||||
return fs.swift.c.ObjectDelete(fs.swift.container, fs.remote)
|
||||
func (o *FsObjectSwift) Remove() error {
|
||||
return o.swift.c.ObjectDelete(o.swift.container, o.remote)
|
||||
}
|
||||
|
||||
// Check the interfaces are satisfied
|
||||
var _ Fs = &FsSwift{}
|
||||
var _ FsObject = &FsObjectSwift{}
|
||||
var _ fs.Fs = &FsSwift{}
|
||||
var _ fs.Object = &FsObjectSwift{}
|
||||
Reference in new issue
Block a user