File: pdb_upload

package info (click to toggle)
python-boto 1.9b-4
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 1,820 kB
  • ctags: 2,583
  • sloc: python: 16,337; makefile: 106
file content (172 lines) | stat: -rwxr-xr-x 7,411 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
#!/usr/bin/env python
# Copyright (c) 2006-2008 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import queuetools, os, signal, sys
import subprocess
import time
from optparse import OptionParser
from boto.mapreduce.partitiondb import PartitionDB, Partition, Version
from lqs import LQSServer, LQSHandler
from boto.exception import SDBPersistenceError
from boto.sdb.persist import get_manager

USAGE = """
  SYNOPSIS
    %prog [options]
  DESCRIPTION
    Upload partition files to a PartitionDB.
    Called with no options, all PartitionDB objects defined in your default
    domain (as specified in the "default_domain" option in the "[Persist]"
    section of your boto config file) will be listed.
    When called with a particular PartitionDB name (using -p option) all
    Version objects of that PartitionDB object will be listed.
    When called with the -p option and a particular Version name specified
    (using the -v option) all Partitions in that Version object will be listed.
"""
class Client:

    def __init__(self, queue_name):
        self.q = queuetools.get_queue(queue_name)
        self.q.connect()
        self.manager = get_manager()
        self.process()

    def process(self):
        m = self.q.get()
        if m['item']:
            v = Version(m['args']['v_id'], self.manager)
            bucket_name = v.pdb.bucket_name
        while m['item']:
            print 'Uploading: %s' % m['item']
            p = v.add_partition(name=m['item'])
            p.upload(os.path.join(m['args']['path'], m['item']), bucket_name)
            self.q.delete(m)
            m = self.q.get()
        print 'client processing complete'

class Server:

    def __init__(self, path, pdb_name, bucket_name=None, domain_name=None):
        self.path = path
        self.pdb_name = pdb_name
        self.bucket_name = bucket_name
        self.manager = get_manager(domain_name)
        self.get_pdb()
        self.serve()

    def get_pdb(self):
        try:
            self.pdb = PartitionDB.get(name=self.pdb_name)
        except SDBPersistenceError:
            self.pdb = PartitionDB(manager=self.manager, name=self.pdb_name, bucket_name=self.bucket_name)
            self.pdb.save()
            
    def serve(self):
        v = self.pdb.add_version()
        args = {'path' : self.path,
                'v_id' : v.id}
        l = os.listdir(self.path)
        s = LQSServer('', LQSHandler, iter(l), args)
        s.serve_forever()
    
class Upload:

    Usage = "usage: %prog [options] command"

    Commands = {'client' : 'Start an Upload client',
                'server' : 'Start an Upload server'}

    def __init__(self):
        self.parser = OptionParser(usage=self.Usage)
        self.parser.add_option("--help-commands", action="store_true", dest="help_commands",
                               help="provides help on the available commands")
        self.parser.add_option('-d', '--domain-name', action='store', type='string',
                               help='name of the SimpleDB domain where PDB objects are stored')
        self.parser.add_option('-n', '--num-processes', action='store', type='int', dest='num_processes',
                               help='the number of client processes launched')
        self.parser.set_defaults(num_processes=2)
        self.parser.add_option('-i', '--input-path', action='store', type='string',
                               help='the path to directory to upload')
        self.parser.add_option('-p', '--pdb-name', action='store', type='string',
                               help='name of the PDB in which to store files (will create if necessary)')
        self.parser.add_option('-b', '--bucket-name', action='store', type='string',
                               help='name of S3 bucket (only needed if creating new PDB)')
        self.options, self.args = self.parser.parse_args()
        self.prog_name = sys.argv[0]

    def print_command_help(self):
        print '\nCommands:'
        for key in self.Commands.keys():
            print '  %s\t\t%s' % (key, self.Commands[key])

    def do_server(self):
        if not self.options.input_path:
            self.parser.error('No path provided')
        if not os.path.isdir(self.options.input_path):
            self.parser.error('Invalid path (%s)' % self.options.input_path)
        if not self.options.pdb_name:
            self.parser.error('No PDB name provided')
        s = Server(self.options.input_path, self.options.pdb_name,
                   self.options.bucket_name, self.options.domain_name)

    def do_client(self):
        c = Client('localhost')
        
    def main(self):
        if self.options.help_commands:
            self.print_command_help()
            sys.exit(0)
        if len(self.args) == 0:
            if not self.options.input_path:
                self.parser.error('No path provided')
            if not os.path.isdir(self.options.input_path):
                self.parser.error('Invalid path (%s)' % self.options.input_path)
            if not self.options.pdb_name:
                self.parser.error('No PDB name provided')
            server_command = '%s -p %s -i %s' % (self.prog_name, self.options.pdb_name, self.options.input_path)
            if self.options.bucket_name:
                server_command += ' -b %s' % self.options.bucket_name
            server_command += ' server'
            client_command = '%s client' % self.prog_name
            server = subprocess.Popen(server_command, shell=True)
            print 'server pid: %s' % server.pid
            time.sleep(5)
            clients = []
            for i in range(0, self.options.num_processes):
                client = subprocess.Popen(client_command, shell=True)
                clients.append(client)
            print 'waiting for clients to finish'
            for client in clients:
                client.wait()
            os.kill(server.pid, signal.SIGTERM)
        elif len(self.args) == 1:
            self.command = self.args[0]
            if hasattr(self, 'do_%s' % self.command):
                method = getattr(self, 'do_%s' % self.command)
                method()
            else:
                self.parser.error('command (%s) not recognized' % self.command)
        else:
            self.parser.error('unrecognized commands')
            
if __name__ == "__main__":
    upload = Upload()
    upload.main()