1#!/usr/bin/env python
2# -*- python -*-
3
4import sys
5import time
6import zipfile
7import os
8import os.path
9import shutil
10import simplejson as json
11import tempfile
12
13from optparse import OptionParser
14
15from couchbase import client
16from couchbase.rest_client import RestConnection, RestHelper
17
18class ZipUtil:
19    def __init__(self, zipobj):
20        self.zipobj = zipobj
21
22    def extractall(self, path=None):
23        if path is None:
24            path = os.getcwd()
25        if (path[-1] in (os.path.sep, os.path.altsep)
26            and len(os.path.splitdrive(path)[1]) > 1):
27            path = path[:-1]
28
29        for member in self.zipobj.namelist():
30            if not isinstance(member, zipfile.ZipInfo):
31                member = self.zipobj.getinfo(member)
32
33            # don't include leading "/" from file name if present
34            if member.filename[0] == '/':
35                targetpath = os.path.join(path, member.filename[1:])
36            else:
37                targetpath = os.path.join(path, member.filename)
38
39            targetpath = os.path.normpath(targetpath)
40
41            # Create all parent directories if necessary.
42            upperdirs = os.path.dirname(targetpath)
43            if upperdirs and not os.path.exists(upperdirs):
44                try:
45                    os.makedirs(upperdirs)
46                except:
47                    print "Unexpected error:", sys.exc_info()[0]
48                    return upperdirs
49
50            if member.filename[-1] == '/':
51                if not os.path.isdir(targetpath):
52                    try:
53                        os.mkdir(targetpath)
54                    except:
55                        print "Fail to create directory:", targetpath
56                continue
57
58            target = file(targetpath, "wb")
59            target.write(self.zipobj.read(member.filename))
60            target.close()
61
62        return path
63
64class DocLoader:
65
66    def parse_args(self):
67        usage = "usage: %prog [options] <directory>|zipfile\n\n" + \
68                "Example: %prog -u Administrator -p password -n 127.0.0.1:8091 " + \
69                "-b mybucket -s 100 gamesim-sample.zip"
70
71        parser = OptionParser(usage)
72
73        username = os.environ.get('REST_USERNAME', None)
74        password = os.environ.get('REST_PASSWORD', None)
75
76        parser.add_option('-u', dest='username', default=username,
77                          help='Username', metavar='Administrator')
78        parser.add_option('-p', dest='password', default=password,
79                          help='Password', metavar='password')
80        parser.add_option('-b', dest='bucket',
81                          help='Bucket', metavar='mybucket')
82        parser.add_option('-n', dest='node', default='127.0.0.1:8091',
83                          help='Node address', metavar='127.0.0.1:8091')
84        parser.add_option('-s', dest='ram_quota', default=100, type='int',
85                          help='RAM quota in MB', metavar=100)
86
87        self.options, self.args = parser.parse_args()
88
89        if not self.args or not self.options.bucket:
90            parser.print_help()
91            sys.exit()
92
93        # check if the uploaded file exists
94        if not os.path.exists(self.args[0]):
95            print "Invalid path: %s" % self.args[0]
96            sys.exit()
97
98    def init_bucket(self):
99        server_info = {'ip': self.options.node.split(':')[0],
100                       'port': self.options.node.split(':')[1],
101                       'username': self.options.username,
102                       'password': self.options.password}
103
104        rest = RestConnection(server_info)
105
106        if not RestHelper(rest).bucket_exists(self.options.bucket):
107            uri = "http://%s:%s/nodes/self" % (server_info["ip"], server_info["port"])
108            status, content = rest._http_request(uri)
109            quotaUnused = -1
110            if status:
111                try:
112                    json_parsed = json.loads(content)
113                    quotaTotal = json_parsed["storageTotals"]["ram"]["quotaTotal"]
114                    quotaUnused = quotaTotal - json_parsed["storageTotals"]["ram"]["quotaUsed"]
115                except:
116                    pass
117            quotaUnused = quotaUnused / 1024.0
118            if quotaUnused > 0 and quotaUnused < self.options.ram_quota:
119                print "RAM quota specified is too large to be provisioned into this cluster"
120                print "Available RAM quota: %d, requested: %d" % (quotaUnused, self.options.ram_quota)
121                sys.exit()
122
123            rest.create_bucket(bucket=self.options.bucket,
124                               ramQuotaMB=self.options.ram_quota,
125                               authType='sasl')
126            time.sleep(10)
127
128    def save_doc(self, dockey, datafile):
129        raw_data = datafile.read()
130        try:
131            doc = json.loads(raw_data)
132            if '_id' not in doc:
133                self.bucket.set(dockey, 0, 0, raw_data)
134            else:
135                doc['_id'] = doc['_id'].encode('UTF-8')
136                self.bucket.save(doc)
137                for view in doc.get('views', []):
138                    self.views.append(doc['_id'] + '/_view/' + view)
139        except ValueError, error:
140            print error
141
142    def gen_dockey(self, filename):
143        return os.path.splitext(os.path.basename(filename))[0]
144
145    def enumerate_and_save(self, subdir=None):
146        if not subdir:
147            subdir = self.args[0]
148        subdirlist = list()
149        viewdirs = list()
150        for item in os.listdir(subdir):
151            if os.path.isfile(os.path.join(subdir, item)):
152                try:
153                    fp = open(os.path.join(subdir, item), 'r')
154                    dockey = self.gen_dockey(item)
155                    self.save_doc(dockey, fp)
156                    fp.close()
157                except IOError, error:
158                    print error
159            else:
160                if item.find("design_docs") > 0:
161                    viewdirs.append(os.path.join(subdir, item))
162                else:
163                    subdirlist.append(os.path.join(subdir, item))
164        for dir in subdirlist:
165            self.enumerate_and_save(dir)
166        for dir in viewdirs:
167            self.enumerate_and_save(dir)
168
169    def unzip_file_and_upload(self):
170        zfobj = zipfile.ZipFile(self.args[0])
171
172        working_dir = tempfile.mkdtemp()
173        ZipUtil(zfobj).extractall(working_dir)
174
175        self.enumerate_and_save(working_dir)
176        shutil.rmtree(working_dir)
177
178    def populate_docs(self):
179        cb = client.Couchbase(self.options.node,
180                              self.options.username,
181                              self.options.password)
182
183        self.bucket = cb[self.options.bucket]
184
185        #Retrieve and reset couchbase_api_base from server
186        self.bucket.server.couch_api_base = self.retrive_couch_api_base(cb)
187
188        self.views = list()
189
190        if self.args[0].endswith('.zip'):
191            self.unzip_file_and_upload()
192        else:
193            self.enumerate_and_save()
194
195    def retrive_couch_api_base(self, cb):
196        if (':' in self.options.node):
197            ip, port = self.options.node.split(':')
198        else:
199            ip, port = self.options.node, 8091
200
201        server_config_uri = "http://%s:%s/pools/default/buckets/%s" % (ip, port, self.options.bucket)
202        config = client.ServerHelper.parse_server_config(server_config_uri,
203                                                         self.options.username,
204                                                         self.options.password)
205        couch_api_base = config["nodes"][0].get("couchApiBase")
206
207        #Remove bucket suffix because it is added when saving design docs
208        couch_api_base = "/".join(couch_api_base.split("/")[:-1]) + "/"
209
210        return couch_api_base
211
212    def verify_queries(self):
213        for view in self.views:
214            print "View:", view
215            self.bucket.view(view, stale="update_after")
216
217def main():
218    if os.name == 'nt':
219        mydir = os.path.dirname(sys.argv[0])
220        bin_dir = os.path.join(mydir, '..')
221        path = [mydir, bin_dir, os.environ['PATH']]
222        os.environ['PATH'] = ';'.join(path)
223
224    docloader = DocLoader()
225
226    # parse options and arguments
227    docloader.parse_args()
228
229    # create new bucket if it doesn't exist
230    docloader.init_bucket()
231
232    # upload documents
233    docloader.populate_docs()
234
235    # execute views at least once
236    docloader.verify_queries()
237
238    sys.stderr.write("done\n")
239
240if __name__ == '__main__':
241    main()
242    os._exit(0)
243