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        self.rest = RestConnection(server_info)
105        uri = "http://%s:%s/nodes/self" % (server_info["ip"], server_info["port"])
106        status, content = self.rest._http_request(uri)
107        quotaUnused = -1
108        if status:
109            try:
110                json_parsed = json.loads(content)
111                quotaTotal = json_parsed["storageTotals"]["ram"]["quotaTotal"]
112                quotaUnused = quotaTotal - json_parsed["storageTotals"]["ram"]["quotaUsed"]
113            except:
114                pass
115        quotaUnused = quotaUnused / 1024.0
116        if quotaUnused > 0 and quotaUnused < self.options.ram_quota:
117            print "RAM quota specified is too large to be provisioned into this cluster"
118            print "Available RAM quota: %d, requested: %d" % (quotaUnused, self.options.ram_quota)
119            sys.exit()
120
121        if not RestHelper(self.rest).bucket_exists(self.options.bucket):
122            self.rest.create_bucket(bucket=self.options.bucket,
123                                    ramQuotaMB=self.options.ram_quota,
124                                    authType='sasl')
125            time.sleep(10)
126
127    def save_doc(self, dockey, datafile):
128        raw_data = datafile.read()
129        try:
130            doc = json.loads(raw_data)
131            if '_id' not in doc:
132                self.bucket.set(dockey, 0, 0, raw_data)
133            else:
134                doc['_id'] = doc['_id'].encode('UTF-8')
135                self.bucket.save(doc)
136                for view in doc.get('views', []):
137                    self.views.append(doc['_id'] + '/_view/' + view)
138        except ValueError, error:
139            print error
140
141    def gen_dockey(self, filename):
142        return os.path.splitext(os.path.basename(filename))[0]
143
144    def enumerate_and_save(self, subdir=None):
145        if not subdir:
146            subdir = self.args[0]
147        subdirlist = list()
148        viewdirs = list()
149        for item in os.listdir(subdir):
150            if os.path.isfile(os.path.join(subdir, item)):
151                try:
152                    fp = open(os.path.join(subdir, item), 'r')
153                    dockey = self.gen_dockey(item)
154                    self.save_doc(dockey, fp)
155                    fp.close()
156                except IOError, error:
157                    print error
158            else:
159                if item.find("design_docs") > 0:
160                    viewdirs.append(os.path.join(subdir, item))
161                else:
162                    subdirlist.append(os.path.join(subdir, item))
163        for dir in subdirlist:
164            self.enumerate_and_save(dir)
165        for dir in viewdirs:
166            self.enumerate_and_save(dir)
167
168    def unzip_file_and_upload(self):
169        zfobj = zipfile.ZipFile(self.args[0])
170
171        working_dir = tempfile.mkdtemp()
172        ZipUtil(zfobj).extractall(working_dir)
173
174        self.enumerate_and_save(working_dir)
175        shutil.rmtree(working_dir)
176
177    def populate_docs(self):
178        cb = client.Couchbase(self.options.node,
179                              self.options.username,
180                              self.options.password)
181
182        self.bucket = cb[self.options.bucket]
183
184        #Retrieve and reset couchbase_api_base from server
185        self.bucket.server.couch_api_base = self.retrive_couch_api_base(cb)
186
187        self.views = list()
188
189        if self.args[0].endswith('.zip'):
190            self.unzip_file_and_upload()
191        else:
192            self.enumerate_and_save()
193
194    def retrive_couch_api_base(self, cb):
195        if (':' in self.options.node):
196            ip, port = self.options.node.split(':')
197        else:
198            ip, port = self.options.node, 8091
199
200        server_config_uri = "http://%s:%s/pools/default/buckets/%s" % (ip, port, self.options.bucket)
201        config = client.ServerHelper.parse_server_config(server_config_uri,
202                                                         self.options.username,
203                                                         self.options.password)
204        couch_api_base = config["nodes"][0].get("couchApiBase")
205
206        #Remove bucket suffix because it is added when saving design docs
207        couch_api_base = "/".join(couch_api_base.split("/")[:-1]) + "/"
208
209        return couch_api_base
210
211    def verify_queries(self):
212        for view in self.views:
213            print "View:", view
214            self.bucket.view(view, stale="update_after")
215
216def main():
217    if os.name == 'nt':
218        mydir = os.path.dirname(sys.argv[0])
219        bin_dir = os.path.join(mydir, '..')
220        path = [mydir, bin_dir, os.environ['PATH']]
221        os.environ['PATH'] = ';'.join(path)
222
223    docloader = DocLoader()
224
225    # parse options and arguments
226    docloader.parse_args()
227
228    # create new bucket if it doesn't exist
229    docloader.init_bucket()
230
231    # upload documents
232    docloader.populate_docs()
233
234    # execute views at least once
235    docloader.verify_queries()
236
237    sys.stderr.write("done\n")
238
239if __name__ == '__main__':
240    main()
241    os._exit(0)
242