Compare commits

...
15 Commits
13 changed files with 1355 additions and 933 deletions

No files matched your search

+2 -1
View File
@@ -1,5 +1,6 @@
*~
*.pyc
test-env*
junk/
_junk/
rclone
upload
-14
View File
@@ -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)
}
-78
View File
@@ -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
}
+110 -88
View File
@@ -1,8 +1,8 @@
// 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?
@@ -22,8 +22,6 @@ package main
// * files with / in name
import (
"code.google.com/p/goauth2/oauth"
"code.google.com/p/google-api-go-client/drive/v2"
"errors"
"flag"
"fmt"
@@ -33,12 +31,45 @@ import (
"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"
)
// Register with Fs
func init() {
fs.Register(&fs.FsInfo{
Name: "drive",
NewFs: NewFs,
Options: []fs.Option{{
Name: "client_id",
Help: "Google Application Client Id.",
Examples: []fs.OptionExample{{
Value: "202264815644.apps.googleusercontent.com",
Help: "rclone's client id - use this or your own if you want",
}},
}, {
Name: "client_secret",
Help: "Google Application Client Secret.",
Examples: []fs.OptionExample{{
Value: "X4Z3ca8xfWDb1Voo-F9a7ZxJ",
Help: "rclone's client secret - use this or your own if you want",
}},
}, {
Name: "token_file",
Help: "Path to store token file.",
Examples: []fs.OptionExample{{
Value: path.Join(fs.HomeDir, ".gdrive-token-file"),
Help: "Suggested path for token file",
}},
}},
})
}
// FsDrive represents a remote drive server
type FsDrive struct {
svc *drive.Service // the connection to the drive server
@@ -119,11 +150,8 @@ const (
// 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.")
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
@@ -131,18 +159,9 @@ 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
}
@@ -215,27 +234,30 @@ func MakeNewToken(t *oauth.Transport) error {
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")
// NewFs contstructs an FsDrive from the path, container:path
func NewFs(name, path string) (fs.Fs, error) {
clientId := fs.ConfigFile.MustValue(name, "client_id")
if clientId == "" {
return nil, errors.New("client_id not found")
}
if *driveClientSecret == "" {
return nil, errors.New("Need -drive-client-secret or environmental variable GDRIVE_CLIENT_SECRET")
clientSecret := fs.ConfigFile.MustValue(name, "client_secret")
if clientSecret == "" {
return nil, errors.New("client_secret not found")
}
if *driveTokenFile == "" {
return nil, errors.New("Need -drive-token-file or environmental variable GDRIVE_TOKEN_FILE")
tokenFile := fs.ConfigFile.MustValue(name, "token_file")
if tokenFile == "" {
return nil, errors.New("token-file not found")
}
// 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: oauth.CacheFile(tokenFile),
}
root, err := parseDrivePath(path)
@@ -287,7 +309,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 +319,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 +329,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 +339,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 +377,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 +567,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 +582,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 +591,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 +611,7 @@ func (f *FsDrive) ListDir() FsDirChan {
return false
})
if err != nil {
stats.Error()
fs.Stats.Error()
log.Printf("ListDir failed: %s", err)
}
}
@@ -602,7 +624,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 +732,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 +779,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 +790,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 +817,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 +845,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{}
+45 -31
View File
@@ -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?
}
+260
View File
@@ -0,0 +1,260 @@
// 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
// Config file path
ConfigPath string
// Global config
Config = &ConfigInfo{}
// Home directory
HomeDir string
// 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.")
)
// Filesystem config options
type ConfigInfo struct {
Verbose bool
Quiet bool
ModifyWindow time.Duration
Checkers int
Transfers int
}
// 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
// Find users home directory
usr, err := user.Current()
if err != nil {
log.Printf("Couldn't find home directory: %v", err)
return
}
HomeDir = usr.HomeDir
ConfigPath = path.Join(HomeDir, configFileName)
// Load configuration file.
ConfigFile, err = goconfig.LoadConfigFile(ConfigPath)
if err != nil {
log.Printf("Failed to load config file %v - using defaults", ConfigPath)
}
}
// Save configuration file.
func SaveConfig() {
err := goconfig.SaveConfigFile(ConfigFile, ConfigPath)
if err != nil {
log.Fatalf("Failed to save config file: %v", err)
}
}
// Show an overview of the config file
func ShowConfig() {
remotes := ConfigFile.GetSectionList()
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) int {
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 i
}
}
}
// 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 0:
return true
case 1:
return false
case 2:
ConfigFile.DeleteSection(name)
return true
default:
log.Printf("Bad choice %d", i)
}
return false
}
// 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())
}
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)
}
}
if OkRemote(name) {
break
}
}
SaveConfig()
}
// Edit the config file interactively
func EditConfig() {
for {
fmt.Printf("Current remotes:\n\n")
ShowConfig()
fmt.Printf("\n")
switch i := Command([]string{"eEdit existing remote", "nNew remote", "dDelete remote", "qQuit config"}); i {
case 0:
name := ChooseRemote()
EditRemote(name)
case 1:
fmt.Printf("name> ")
name := ReadLine()
NewRemote(name)
case 2:
name := ChooseRemote()
ConfigFile.DeleteSection(name)
case 3:
return
}
}
}
+126 -52
View File
@@ -1,34 +1,85 @@
// 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
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 +95,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 +130,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 +215,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 +249,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 +259,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 +271,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 +279,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 +299,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")
}
-363
View File
@@ -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{}
+61 -51
View File
@@ -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{}
+9
View File
@@ -1,3 +1,8 @@
Make a config setting
* everything can be set on command line, env vars or config file
* make a config mode to edit the config
* make it so you can make aliases memstore: home: etc
Names
* rclone - domain ok, apt ok
@@ -75,3 +80,7 @@ local & drive need to delete directories
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
+201 -178
View File
@@ -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)
+435
View File
@@ -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
View File
@@ -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{}