blob: a16235cd1c447b1fe4abe5a0f5e084eb297a7ed3 [file] [log] [blame]
Brian O'Connor0fed5752015-05-04 18:15:29 -07001#!/usr/bin/env python
Brian O'Connor6b30e1b2015-03-11 16:44:16 -07002"""
3Upload a file to S3
4"""
5
6from sys import argv, stdout
7from time import time
8from os.path import basename
9from optparse import OptionParser
10
11from boto.s3.key import Key
12from boto.s3.connection import S3Connection
13
14
Brian O'Connor0fed5752015-05-04 18:15:29 -070015def uploadFile( filename, dest=None, bucket=None, overwrite=False ):
Brian O'Connor6b30e1b2015-03-11 16:44:16 -070016 "Upload a file to a bucket"
17 if not bucket:
18 bucket = 'onos'
19 if not dest:
20 key = basename( filename )
21 else:
22 key = dest + basename( filename ) #FIXME add the /
23 print '* Uploading', filename, 'to bucket', bucket, 'as', key
24 stdout.flush()
25 start = time()
26 def callback( transmitted, size ):
27 "Progress callback for set_contents_from_filename"
28 elapsed = time() - start
29 percent = 100.0 * transmitted / size
30 kbps = .001 * transmitted / elapsed
31 print ( '\r%d bytes transmitted of %d (%.2f%%),'
32 ' %.2f KB/sec ' %
33 ( transmitted, size, percent, kbps ) ),
34 stdout.flush()
35 conn = S3Connection()
36 bucket = conn.get_bucket( bucket )
37 k = Key( bucket )
38 k.key = key
Brian O'Connor0fed5752015-05-04 18:15:29 -070039 if overwrite or not k.exists():
40 k.set_contents_from_filename( filename, cb=callback, num_cb=100 )
41 print
42 elapsed = time() - start
43 print "* elapsed time: %.2f seconds" % elapsed
44 else:
45 print 'file', basename( filename ), 'already exists in', bucket.name
Brian O'Connor6b30e1b2015-03-11 16:44:16 -070046
47if __name__ == '__main__':
48 usage = "Usage: %prog [options] <file to upload>"
49 parser = OptionParser(usage=usage)
50 parser.add_option("-b", "--bucket", dest="bucket",
51 help="Bucket on S3")
52 parser.add_option("-d", "--dest", dest="dest",
53 help="Destination path in bucket")
54 parser.add_option("-k", "--key", dest="awsKey",
55 help="Bucket on S3")
56 parser.add_option("-s", "--secret", dest="awsSecret",
57 help="Bucket on S3")
Brian O'Connor0fed5752015-05-04 18:15:29 -070058 parser.add_option("-f", "--force", dest="overwrite",
59 help="Overwrite existing file")
Brian O'Connor6b30e1b2015-03-11 16:44:16 -070060 (options, args) = parser.parse_args()
61
62 if len( args ) == 0:
63 parser.error("missing filenames")
64 for file in args:
Brian O'Connor0fed5752015-05-04 18:15:29 -070065 uploadFile( file, options.dest, options.bucket, options.overwrite )
Brian O'Connor6b30e1b2015-03-11 16:44:16 -070066
67 #FIXME key and secret are unused