/
rest_client.py
6590 lines (5943 loc) · 289 KB
/
rest_client.py
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import json
import urllib.request, urllib.parse, urllib.error
import requests
from urllib3._collections import HTTPHeaderDict
from . import httplib2
import logger
import traceback
import socket
import time
import re
import uuid
from copy import deepcopy
from threading import Thread
from TestInput import TestInputSingleton
from testconstants import MIN_KV_QUOTA, INDEX_QUOTA, FTS_QUOTA, CBAS_QUOTA
from testconstants import COUCHBASE_FROM_VERSION_4, IS_CONTAINER, CLUSTER_QUOTA_RATIO
from lib.Cb_constants.CBServer import CbServer
try:
from couchbase_helper.document import DesignDocument, View
except ImportError:
from lib.couchbase_helper.document import DesignDocument, View
from memcached.helper.kvstore import KVStore
from .exception import ServerAlreadyJoinedException, ServerUnavailableException, InvalidArgumentException
from membase.api.exception import BucketCreationException, ServerSelfJoinException, ClusterRemoteException, \
RebalanceFailedException, FailoverFailedException, DesignDocCreationException, QueryViewException, \
ReadDocumentException, GetBucketInfoFailed, CompactViewFailed, SetViewInfoNotFound, AddNodeException, \
BucketFlushFailed, CBRecoveryFailedException, XDCRException, SetRecoveryTypeFailed, BucketCompactionException
log = logger.Logger.get_logger()
# helper library methods built on top of RestConnection interface
class RestHelper(object):
def __init__(self, rest_connection):
self.rest = rest_connection
def is_ns_server_running(self, timeout_in_seconds=360):
log.info("-->is_ns_server_running?")
end_time = time.time() + timeout_in_seconds
while time.time() <= end_time:
try:
status = self.rest.get_nodes_self(5)
if status is not None and status.status == 'healthy':
return True
else:
if status is not None:
log.warn("server {0}:{1} status is {2}"\
.format(self.rest.ip, self.rest.port, status.status))
else:
log.warn("server {0}:{1} status is down"\
.format(self.rest.ip, self.rest.port))
except ServerUnavailableException:
log.error("server {0}:{1} is unavailable"\
.format(self.rest.ip, self.rest.port))
time.sleep(5)
msg = 'unable to connect to the node {0} even after waiting {1} seconds'
log.error(msg.format(self.rest.ip, timeout_in_seconds))
return False
def is_cluster_healthy(self, timeout=120):
# get the nodes and verify that all the nodes.status are healthy
nodes = self.rest.node_statuses(timeout)
return all(node.status == 'healthy' for node in nodes)
def rebalance_reached(self, percentage=100,retry_count=40):
start = time.time()
progress = 0
previous_progress = 0
retry = 0
while progress != -1 and progress < percentage and retry < retry_count:
# -1 is error , -100 means could not retrieve progress
progress = self.rest._rebalance_progress()
if progress == -100:
log.error("unable to retrieve rebalanceProgress.try again in 2 seconds")
retry += 1
else:
if previous_progress == progress:
retry += 0.5
else:
retry = 0
previous_progress = progress
# sleep for 2 seconds
time.sleep(3)
if progress <= 0:
log.error("rebalance progress code : {0}".format(progress))
return False
elif retry >= retry_count:
log.error("rebalance stuck on {0}%".format(progress))
return False
else:
duration = time.time() - start
log.info('rebalance reached >{0}% in {1} seconds '.format(progress, duration))
return True
# return true if cluster balanced, false if it needs rebalance
def is_cluster_rebalanced(self):
command = "ns_orchestrator:needs_rebalance()"
status, content = self.rest.diag_eval(command)
if status:
return content.lower() == "false"
log.error("can't define if cluster balanced")
return None
# this method will rebalance the cluster by passing the remote_node as
# ejected node
def remove_nodes(self, knownNodes, ejectedNodes, wait_for_rebalance=True):
if len(ejectedNodes) == 0:
return False
self.rest.rebalance(knownNodes, ejectedNodes)
if wait_for_rebalance:
return self.rest.monitorRebalance()
else:
return False
def vbucket_map_ready(self, bucket, timeout_in_seconds=360):
end_time = time.time() + timeout_in_seconds
while time.time() <= end_time:
vBuckets = self.rest.get_vbuckets(bucket)
if vBuckets:
return True
else:
time.sleep(0.5)
msg = 'vbucket map is not ready for bucket {0} after waiting {1} seconds'
log.info(msg.format(bucket, timeout_in_seconds))
return False
def bucket_exists(self, bucket):
try:
buckets = self.rest.get_buckets()
names = [item.name for item in buckets]
log.info("node {1} existing buckets : {0}" \
.format(names, self.rest.ip))
for item in buckets:
if item.name == bucket:
log.info("node {1} found bucket {0}" \
.format(bucket, self.rest.ip))
return True
return False
except Exception:
return False
def wait_for_node_status(self, node, expected_status, timeout_in_seconds):
status_reached = False
end_time = time.time() + timeout_in_seconds
while time.time() <= end_time and not status_reached:
nodes = self.rest.node_statuses()
for n in nodes:
if node.id == n.id:
log.info('node {0} status : {1}'.format(node.id, n.status))
if n.status.lower() == expected_status.lower():
status_reached = True
break
if not status_reached:
log.info("sleep for 5 seconds before reading the node.status again")
time.sleep(5)
log.info('node {0} status_reached : {1}'.format(node.id, status_reached))
return status_reached
def _wait_for_task_pid(self, pid, end_time, ddoc_name):
while (time.time() < end_time):
new_pid, _ = self.rest._get_indexer_task_pid(ddoc_name)
if pid == new_pid:
time.sleep(5)
continue
else:
return
def _wait_for_indexer_ddoc(self, servers, ddoc_name, timeout=300):
nodes = self.rest.get_nodes()
servers_to_check = []
for node in nodes:
for server in servers:
if node.ip == server.ip and str(node.port) == str(server.port):
servers_to_check.append(server)
for server in servers_to_check:
try:
rest = RestConnection(server)
log.info('Check index for ddoc %s , server %s' % (ddoc_name, server.ip))
end_time = time.time() + timeout
log.info('Start getting index for ddoc %s , server %s' % (ddoc_name, server.ip))
old_pid, is_pid_blocked = rest._get_indexer_task_pid(ddoc_name)
if not old_pid:
log.info('Index for ddoc %s is not going on, server %s' % (ddoc_name, server.ip))
continue
while is_pid_blocked:
log.info('Index for ddoc %s is blocked, server %s' % (ddoc_name, server.ip))
self._wait_for_task_pid(old_pid, end_time, ddoc_name)
old_pid, is_pid_blocked = rest._get_indexer_task_pid(ddoc_name)
if time.time() > end_time:
log.error("INDEX IS STILL BLOKED node %s ddoc % pid %" % (server, ddoc_name, old_pid))
break
if old_pid:
log.info('Index for ddoc %s is running, server %s' % (ddoc_name, server.ip))
self._wait_for_task_pid(old_pid, end_time, ddoc_name)
except Exception as ex:
log.error('unable to check index on server %s because of %s' % (server.ip, str(ex)))
def _get_vbuckets(self, servers, bucket_name='default'):
vbuckets_servers = {}
for server in servers:
buckets = RestConnection(server).get_buckets()
if not buckets:
return vbuckets_servers
if bucket_name:
bucket_to_check = [bucket for bucket in buckets
if bucket.name == bucket_name][0]
else:
bucket_to_check = [bucket for bucket in buckets][0]
vbuckets_servers[server] = {}
vbs_active = [vb.id for vb in bucket_to_check.vbuckets
if vb.master.startswith(str(server.ip))]
vbs_replica = []
for replica_num in range(0, bucket_to_check.numReplicas):
vbs_replica.extend([vb.id for vb in bucket_to_check.vbuckets
if replica_num in vb.replica
and vb.replica[replica_num].startswith(str(server.ip))])
vbuckets_servers[server]['active_vb'] = vbs_active
vbuckets_servers[server]['replica_vb'] = vbs_replica
return vbuckets_servers
class RestConnection(object):
DELETE = "DELETE"
GET = "GET"
POST = "POST"
PUT = "PUT"
def __new__(cls, serverInfo={}):
# allow port to determine
# behavior of restconnection
port = None
if isinstance(serverInfo, dict):
if 'port' in serverInfo:
port = serverInfo['port']
else:
port = serverInfo.port
if not port:
port = CbServer.port
if CbServer.use_https:
port = CbServer.ssl_port
if int(port) in range(9091, 9100):
# return elastic search rest connection
from membase.api.esrest_client import EsRestConnection
obj = super(EsRestConnection,cls).__new__(cls)
else:
# default
obj = object.__new__(cls)
return obj
def __init__(self, serverInfo):
# serverInfo can be a json object/dictionary
if isinstance(serverInfo, dict):
self.ip = serverInfo["ip"]
self.internal_ip = serverInfo.get("internal_ip")
self.username = serverInfo["username"]
self.password = serverInfo["password"]
self.port = serverInfo["port"]
self.index_port = CbServer.index_port
self.fts_port = CbServer.fts_port
self.query_port = CbServer.n1ql_port
self.eventing_port = CbServer.eventing_port
self.capi_port = CbServer.capi_port
if "index_port" in list(serverInfo.keys()):
self.index_port = serverInfo["index_port"]
if "fts_port" in list(serverInfo.keys()):
if serverInfo['fts_port']:
self.fts_port = serverInfo["fts_port"]
if "eventing_port" in list(serverInfo.keys()):
if serverInfo['eventing_port']:
self.eventing_port = serverInfo["eventing_port"]
self.hostname = ''
self.services = ''
if "hostname" in serverInfo:
self.hostname = serverInfo["hostname"]
if "services" in serverInfo:
self.services = serverInfo["services"]
else:
self.ip = serverInfo.ip
self.internal_ip = serverInfo.internal_ip if hasattr(serverInfo, "internal_ip") else None
self.username = serverInfo.rest_username
self.password = serverInfo.rest_password
self.port = serverInfo.port
self.hostname = ''
self.index_port = CbServer.index_port
self.fts_port = CbServer.fts_port
self.query_port = CbServer.n1ql_port
self.eventing_port = CbServer.eventing_port
self.capi_port = CbServer.capi_port
self.services = "kv"
self.debug_logs = False
if hasattr(serverInfo, "services"):
self.services = serverInfo.services
if hasattr(serverInfo, 'index_port'):
self.index_port = serverInfo.index_port
if hasattr(serverInfo, 'query_port'):
self.query_port = serverInfo.query_port
if hasattr(serverInfo, 'fts_port'):
if serverInfo.fts_port:
self.fts_port = serverInfo.fts_port
if hasattr(serverInfo, 'eventing_port'):
if serverInfo.eventing_port:
self.eventing_port = serverInfo.eventing_port
if hasattr(serverInfo, 'hostname') and serverInfo.hostname and\
serverInfo.hostname.find(self.ip) == -1:
self.hostname = serverInfo.hostname
if hasattr(serverInfo, 'services'):
self.services = serverInfo.services
self.input = TestInputSingleton.input
if self.input is not None:
""" from watson, services param order and format:
new_services=fts-kv-index-n1ql """
self.services_node_init = self.input.param("new_services", None)
self.debug_logs = self.input.param("debug-logs", False)
if CbServer.use_https:
self.port = CbServer.ssl_port_map.get(str(self.port),
str(self.port))
self.index_port = CbServer.ssl_port_map.get(str(self.index_port),
str(self.index_port))
self.query_port = CbServer.ssl_port_map.get(str(self.query_port),
str(self.query_port))
self.fts_port = CbServer.ssl_port_map.get(str(self.fts_port),
str(self.fts_port))
self.eventing_port = CbServer.ssl_port_map.get(str(self.eventing_port),
str(self.eventing_port))
self.capi_port = CbServer.ssl_port_map.get(str(self.capi_port), str(self.capi_port))
http_url = "http://%s:%s/"
https_url = "https://%s:%s/"
generic_url = http_url
if CbServer.use_https:
generic_url = https_url
url_host = "%s" % self.ip
if self.hostname:
url_host = "%s" % self.hostname
self.baseUrl = generic_url % (url_host, self.port)
self.fts_baseUrl = generic_url % (url_host, self.fts_port)
self.index_baseUrl = generic_url % (url_host, self.index_port)
self.query_baseUrl = generic_url % (url_host, self.query_port)
self.capiBaseUrl = generic_url % (url_host, self.capi_port)
self.eventing_baseUrl = generic_url % (url_host, self.eventing_port)
# Initialization of CBAS related params
self.cbas_ip = self.ip
self.cbas_port = CbServer.cbas_port
if hasattr(self.input, 'cbas'):
if self.input.cbas:
self.cbas_node = self.input.cbas
if hasattr(self.cbas_node, 'port'):
self.cbas_port = self.cbas_node.port
if hasattr(self.cbas_node, 'ip'):
self.cbas_ip = self.cbas_node.ip
if CbServer.use_https:
self.cbas_port = CbServer.ssl_cbas_port
self.cbas_base_url = generic_url % (self.cbas_ip, self.cbas_port)
self.cbas_base_url = self.cbas_base_url[:-1]
# for Node is unknown to this cluster error
for iteration in range(5):
http_res, success = self.init_http_request(api=self.baseUrl + "nodes/self")
if not success and isinstance(http_res, str) and\
(http_res.find('Node is unknown to this cluster') > -1 or \
http_res.find('Unexpected server error, request logged') > -1):
log.error("Error {0} was gotten, 5 seconds sleep before retry"\
.format(http_res))
time.sleep(5)
if iteration == 2:
log.error("node {0}:{1} is in a broken state!"\
.format(self.ip, self.port))
raise ServerUnavailableException(self.ip)
continue
else:
break
# determine the real couchApiBase for cluster_run
# couchApiBase appeared in version 2.*
if isinstance(http_res, dict):
if not http_res or http_res["version"][0:2] == "1.":
self.capiBaseUrl = self.baseUrl + "/couchBase"
else:
for iteration in range(5):
if "couchApiBase" not in http_res.keys():
if self.is_cluster_mixed():
self.capiBaseUrl = self.baseUrl + "/couchBase"
return
time.sleep(0.2)
http_res, success = self.init_http_request(self.baseUrl + 'nodes/self')
else:
if CbServer.use_https:
self.capiBaseUrl = http_res["couchApiBaseHTTPS"]
else:
self.capiBaseUrl = http_res["couchApiBase"]
if self.internal_ip and "alternateAddresses" in http_res and "external" in http_res["alternateAddresses"]:
self.capiBaseUrl = self.capiBaseUrl.replace(self.internal_ip, http_res["alternateAddresses"]["external"]["hostname"])
return
raise ServerUnavailableException("couchApiBase doesn't exist in nodes/self: %s " % http_res)
def get_https_base_url(self):
port = CbServer.ssl_port_map.get(str(self.port),
str(self.port))
https_url = "https://%s:%s/"
return https_url % (self.ip, port)
def sasl_streaming_rq(self, bucket, timeout=120,
disable_ssl_certificate_validation=True):
api = self.baseUrl + 'pools/default/bucketsStreaming/{0}'.format(bucket)
if isinstance(bucket, Bucket):
api = self.baseUrl + 'pools/default/bucketsStreaming/{0}'.format(bucket.name)
try:
httplib2.Http(timeout=timeout, disable_ssl_certificate_validation=disable_ssl_certificate_validation).\
request(api, 'GET', '', headers=self._create_capi_headers())
except Exception as ex:
log.warn('Exception while streaming: %s' % str(ex))
def open_sasl_streaming_connection(self, bucket, timeout=1000):
if self.debug_logs:
log.info("Opening sasl streaming connection for bucket {0}"\
.format((bucket, bucket.name)[isinstance(bucket, Bucket)]))
t = Thread(target=self.sasl_streaming_rq,
name="streaming_" + str(uuid.uuid4())[:4],
args=(bucket, timeout))
try:
t.start()
except:
log.warn("thread is not started")
return None
return t
def is_cluster_mixed(self, timeout=120):
http_res, success = self.init_http_request(self.baseUrl + 'pools/default', timeout=timeout)
if http_res == 'unknown pool':
return False
try:
versions = list({node["version"][:1] for node in http_res["nodes"]})
except:
log.error('Error while processing cluster info {0}'.format(http_res))
# not really clear what to return but False see to be a good start until we figure what is happening
return False
if '1' in versions and '2' in versions:
return True
return False
def is_cluster_compat_mode_greater_than(self, version):
"""
curl -v -X POST -u Administrator:welcome http://10.3.4.186:8091/diag/eval
-d 'cluster_compat_mode:get_compat_version().'
Returns : [3,2] if version = 3.2.0
"""
status, content = self.diag_eval('cluster_compat_mode:get_compat_version().')
if status:
json_parsed = json.loads(content)
cluster_ver = float("%s.%s" % (json_parsed[0], json_parsed[1]))
if cluster_ver > version:
return True
return False
def is_enterprise_edition(self):
http_res, success = self.init_http_request(self.baseUrl + 'pools/default')
if http_res == 'unknown pool':
return False
editions = []
community_nodes = []
""" get the last word in node["version"] as in "version": "2.5.1-1073-rel-enterprise" """
for node in http_res["nodes"]:
editions.extend(node["version"].split("-")[-1:])
if "community" in node["version"].split("-")[-1:]:
community_nodes.extend(node["hostname"].split(":")[:1])
if "community" in editions:
log.error("IP(s) for node(s) with community edition {0}".format(community_nodes))
return False
return True
def init_http_request(self, api, timeout=120):
content = None
try:
headers = self._create_capi_headers()
status, content, header = self._http_request(api, 'GET', headers=headers, timeout=timeout)
json_parsed = json.loads(content)
if status:
return json_parsed, True
else:
print("{0} with status {1}: {2}".format(api, status, json_parsed))
return json_parsed, False
except ValueError as e:
if content is not None:
print("{0}: {1}".format(api, content))
else:
print(e)
return content, False
def rename_node(self, hostname, username='Administrator', password='password'):
params = urllib.parse.urlencode({'username': username,
'password': password,
'hostname': hostname})
api = "%snode/controller/rename" % self.baseUrl
status, content, header = self._http_request(api, 'POST', params)
return status, content
def active_tasks(self):
api = self.baseUrl + "pools/default/tasks"
try:
status, content, header = self._http_request(api, 'GET',
headers=self._create_capi_headers())
json_parsed = json.loads(content)
except ValueError as e:
print(e)
return ""
return json_parsed
def ns_server_tasks(self):
api = self.baseUrl + 'pools/default/tasks'
retries = 3
while retries:
try:
status, content, header = self._http_request(api, 'GET', headers=self._create_headers())
return json.loads(content)
except ValueError:
time.sleep(10)
retries -= 1
return ""
# DEPRECATED: use create_ddoc() instead.
def create_view(self, design_doc_name, bucket_name, views, options=None):
return self.create_ddoc(design_doc_name, bucket_name, views, options)
def create_ddoc(self, design_doc_name, bucket, views, options=None):
design_doc = DesignDocument(design_doc_name, views, options=options)
if design_doc.name.find('/') != -1:
design_doc.name = design_doc.name.replace('/', '%2f')
design_doc.id = '_design/{0}'.format(design_doc.name)
return self.create_design_document(bucket, design_doc)
def create_design_document(self, bucket, design_doc):
log.info("-->create_design_document")
try:
design_doc_name = design_doc.id
api = '%s/%s/%s' % (self.capiBaseUrl, bucket, design_doc_name)
if isinstance(bucket, Bucket):
api = '%s/%s/%s' % (self.capiBaseUrl, bucket.name, design_doc_name)
status, content, header = self._http_request(api, 'PUT', str(design_doc),
headers=self._create_capi_headers())
except Exception as e:
traceback.print_exc()
if not status:
raise DesignDocCreationException(design_doc_name, content)
return json.loads(content.decode())
def is_index_triggered(self, ddoc_name, index_type='main'):
run, block = self._get_indexer_task_pid(ddoc_name, index_type=index_type)
if run or block:
return True
else:
return False
def _get_indexer_task_pid(self, ddoc_name, index_type='main'):
active_tasks = self.active_tasks()
if 'error' in active_tasks:
return None
if active_tasks:
for task in active_tasks:
if task['type'] == 'indexer' and task['indexer_type'] == index_type:
for ddoc in task['design_documents']:
if ddoc == ('_design/%s' % ddoc_name):
return task['pid'], False
if task['type'] == 'blocked_indexer' and task['indexer_type'] == index_type:
for ddoc in task['design_documents']:
if ddoc == ('_design/%s' % ddoc_name):
return task['pid'], True
return None, None
def query_view(self, design_doc_name, view_name, bucket, query, timeout=120, invalid_query=False, type="view"):
status, content, header = self._query(design_doc_name, view_name, bucket, type, query, timeout)
if not status and not invalid_query:
stat = 0
if 'status' in header:
stat = int(header['status'])
raise QueryViewException(view_name, content, status=stat)
return json.loads(content)
def _query(self, design_doc_name, view_name, bucket, view_type, query, timeout):
if design_doc_name.find('/') != -1:
design_doc_name = design_doc_name.replace('/', '%2f')
if view_name.find('/') != -1:
view_name = view_name.replace('/', '%2f')
api = self.capiBaseUrl + '%s/_design/%s/_%s/%s?%s' % (bucket,
design_doc_name, view_type,
view_name,
urllib.parse.urlencode(query))
if isinstance(bucket, Bucket):
api = self.capiBaseUrl + '%s/_design/%s/_%s/%s?%s' % (bucket.name,
design_doc_name, view_type,
view_name,
urllib.parse.urlencode(query))
log.info("index query url: {0}".format(api))
status, content, header = self._http_request(api, headers=self._create_capi_headers(),
timeout=timeout)
return status, content, header
def view_results(self, bucket, ddoc_name, params, limit=100, timeout=120,
view_name=None):
status, json = self._index_results(bucket, "view", ddoc_name, params, limit, timeout=timeout, view_name=view_name)
if not status:
raise Exception("unable to obtain view results")
return json
# DEPRECATED: Incorrectly named function kept for backwards compatibility.
def get_view(self, bucket, view):
log.info("DEPRECATED function get_view(" + view + "). use get_ddoc()")
return self.get_ddoc(bucket, view)
def get_data_path(self):
node_info = self.get_nodes_self()
data_path = node_info.storage[0].get_data_path()
return data_path
def get_index_path(self):
node_info = self.get_nodes_self()
data_path = node_info.storage[0].get_index_path()
return data_path
def get_memcached_port(self):
node_info = self.get_nodes_self()
return node_info.memcached
def get_ddoc(self, bucket, ddoc_name):
status, json, meta = self._get_design_doc(bucket, ddoc_name)
if not status:
raise ReadDocumentException(ddoc_name, json)
return json, meta
# the same as Preview a Random Document on UI
def get_random_key(self, bucket):
api = self.baseUrl + 'pools/default/buckets/%s/localRandomKey' % bucket
status, content, header = self._http_request(api, headers=self._create_capi_headers())
json_parsed = json.loads(content)
if not status:
raise Exception("unable to get random document/key for bucket %s" % bucket)
return json_parsed
def create_scope(self, bucket, scope, params=None, num_retries=3):
api = self.baseUrl + 'pools/default/buckets/%s/scopes' % bucket
body = {'name': scope}
if params:
body.update(params)
params = urllib.parse.urlencode(body)
headers = self._create_headers()
while num_retries > 0:
status, content, header = self._http_request(api, 'POST', params=params, headers=headers)
log.info("{0} with params: {1}".format(api, params))
if status:
json_parsed = json.loads(content)
log.info("Scope created {}->{} {}".format(bucket, scope, json_parsed))
break
elif header["status"] == "400":
log.info("Scope already exists. Skipping create {}->{}".format(bucket, scope))
break
else:
time.sleep(10)
num_retries -= 1
else:
raise Exception("Create scope failed : status:{0},content:{1}".format(status, content))
return status
def _create_single_collection(self, bucket, scope, collection, params=None):
api = self.baseUrl + 'pools/default/buckets/%s/scopes/%s/collections' % (bucket, scope)
body = {'name': collection}
if params:
body.update(params)
params = urllib.parse.urlencode(body)
headers = self._create_headers()
status, content, header = self._http_request(api, 'POST', params=params, headers=headers)
log.info("{0} with params: {1}".format(api, params))
return status,content,header
def create_collection(self, bucket, scope, collection, params=None, num_retries=3):
if not isinstance(collection, list):
collection = [collection]
for c in collection:
while num_retries > 0:
status, content, header = self._create_single_collection(bucket, scope, c, params)
if status:
json_parsed = json.loads(content)
log.info("Collection created {}->{}->{} manifest:{}".format(bucket, scope, c, json_parsed))
break
elif header["status"] == "400":
log.info("Collection already exists. Skipping create {}->{}-{}".format(bucket, scope, c))
break
else:
time.sleep(10)
num_retries -= 1
else:
raise Exception("Create collection failed : status:{0},content:{1}".format(status, content))
return status
def put_collection_scope_manifest(self, bucket, manifest, ensure_manifest=True):
""" Put collection scope manifest to bulk update collection/scopes
Args:
ensure_manifest (bool): If set, blocks until the manifest has been applied to all nodes as
the endpoint is asynchronous.
"""
if isinstance(bucket, Bucket):
bucket = bucket.name
params, headers = json.dumps(manifest), self._create_capi_headers()
status, content, _ = self._http_request(f"{self.baseUrl}pools/default/buckets/{bucket}/scopes", 'PUT',
params=params, headers=headers)
if ensure_manifest:
uid = json.loads(content)['uid']
ensure_manifest_status, manifest_content, _ = self._http_request(
f"{self.baseUrl}pools/default/buckets/{bucket}/scopes/@ensureManifest/{uid}", 'POST',
headers=headers)
return status
def get_bucket_manifest(self, bucket):
if isinstance(bucket, Bucket):
bucket = bucket.name
api = '{0}{1}{2}{3}'.format(self.baseUrl, 'pools/default/buckets/', bucket, '/scopes')
status, content, header = self._http_request(api)
if status:
return json.loads(content)
else:
raise Exception(
"Cannot get manifest for bucket {}: status:{}, content:{}".format(bucket, status, content))
def _parse_manifest(self, bucket, extract=None):
try:
manifest = self.get_bucket_manifest(bucket)
scopes = []
collections = []
for scope in manifest["scopes"]:
scopes.append(scope["name"])
for collection in scope["collections"]:
collections.append(collection["name"])
if extract == "scopes":
return scopes
elif extract == "collections":
return collections
except Exception as e:
raise Exception("Cannot extract {} for bucket {} from manifest {}".format(extract, bucket, e.message))
def get_bucket_scopes(self, bucket):
return self._parse_manifest(bucket, "scopes")
def get_bucket_collections(self, bucket):
return self._parse_manifest(bucket, "collections")
def get_scope_collections(self, bucket, scope):
try:
manifest = self.get_bucket_manifest(bucket)
scope_found = False
collections_in_scope = []
for scopes in manifest["scopes"]:
if scopes['name'] == scope:
scope_found = True
for collection in scopes['collections']:
collections_in_scope.append(collection['name'])
if not scope_found:
log.error("Cannot get collections for scope {} because it does not exist".format(scope))
return collections_in_scope
except Exception as e:
raise Exception("Cannot get collections for bucket {}-> scope{} {}".format(bucket, scope, e.message))
def delete_scope(self, bucket, scope):
api = self.baseUrl + 'pools/default/buckets/%s/scopes/%s' % (bucket, scope)
headers = self._create_headers()
status, content, header = self._http_request(api, 'DELETE', headers=headers)
log.info("{0}".format(api))
return status
def get_rest_endpoint_data(self, endpoint=None, ip=None, port=None):
protocol = "http"
if CbServer.use_https:
port = CbServer.ssl_port_map.get(str(port), str(port))
protocol = "https"
endpoint_base_url = "{0}://{1}:{2}/".format(protocol, ip, port)
api = str(endpoint_base_url) + str(endpoint)
print(f'Executing GET on: {api}')
headers = self._create_headers()
status, content, header = self._http_request(api, 'GET', headers=headers)
return status, content
def delete_collection(self, bucket, scope, collection):
api = self.baseUrl + 'pools/default/buckets/%s/scopes/%s/collections/%s' % (bucket, scope, collection)
headers = self._create_headers()
status, content, header = self._http_request(api, 'DELETE', headers=headers)
return status
def get_collection(self, bucket):
api = self.baseUrl + 'pools/default/buckets/%s/scopes' % bucket
headers = self._create_headers()
status, content, header = self._http_request(api, 'GET', headers=headers)
return status, content
def get_collection_uid(self, bucket, scope, collection):
try:
manifest = self.get_bucket_manifest(bucket)
for scopes in manifest["scopes"]:
if scopes['name'] == scope:
for col in scopes['collections']:
if col['name'] == collection:
return col['uid']
log.error("Cannot get collection uid because {0}.{1}.{2} does not exist"
.format(bucket, scope, collection))
except Exception as e:
raise Exception("Exception thrown while getting collection uid {}"
.format(e.message))
def run_view(self, bucket, view, name):
api = self.capiBaseUrl + '/%s/_design/%s/_view/%s' % (bucket, view, name)
status, content, header = self._http_request(api, headers=self._create_capi_headers())
json_parsed = json.loads(content)
if not status:
raise Exception("unable to create view")
return json_parsed
def delete_view(self, bucket, view):
status, json = self._delete_design_doc(bucket, view)
if not status:
raise Exception("unable to delete the view")
return json
def spatial_results(self, bucket, spatial, params, limit=100):
status, json = self._index_results(bucket, "spatial", spatial,
params, limit)
if not status:
raise Exception("unable to obtain spatial view results")
return json
def create_spatial(self, bucket, spatial, function):
status, json = self._create_design_doc(bucket, spatial, function)
if status == False:
raise Exception("unable to create spatial view")
return json
def get_spatial(self, bucket, spatial):
status, json, meta = self._get_design_doc(bucket, spatial)
if not status:
raise Exception("unable to get the spatial view definition")
return json, meta
def delete_spatial(self, bucket, spatial):
status, json = self._delete_design_doc(bucket, spatial)
if not status:
raise Exception("unable to delete the spatial view")
return json
# type_ is "view" or "spatial"
def _index_results(self, bucket, type_, ddoc_name, params, limit, timeout=120,
view_name=None):
if view_name is None:
view_name = ddoc_name
query = '/{0}/_design/{1}/_{2}/{3}'
api = self.capiBaseUrl + query.format(bucket, ddoc_name, type_, view_name)
num_params = 0
if limit != None:
num_params = 1
api += "?limit={0}".format(limit)
for param in params:
if num_params > 0:
api += "&"
else:
api += "?"
num_params += 1
if param in ["key", "startkey", "endkey", "start_range",
"end_range"] or isinstance(params[param], bool):
api += "{0}={1}".format(param,
json.dumps(params[param],
separators=(',', ':')))
else:
api += "{0}={1}".format(param, params[param])
log.info("index query url: {0}".format(api))
status, content, header = self._http_request(api, headers=self._create_capi_headers(), timeout=timeout)
json_parsed = json.loads(content)
return status, json_parsed
def get_couch_doc(self, doc_id, bucket="default", timeout=120):
""" use couchBase uri to retrieve document from a bucket """
api = self.capiBaseUrl + '/%s/%s' % (bucket, doc_id)
status, content, header = self._http_request(api, headers=self._create_capi_headers(),
timeout=timeout)
if not status:
raise ReadDocumentException(doc_id, content)
return json.loads(content)
def _create_design_doc(self, bucket, name, function):
api = self.capiBaseUrl + '/%s/_design/%s' % (bucket, name)
status, content, header = self._http_request(
api, 'PUT', function, headers=self._create_capi_headers())
json_parsed = json.loads(content)
return status, json_parsed
def _get_design_doc(self, bucket, name):
api = self.capiBaseUrl + '/%s/_design/%s' % (bucket, name)
if isinstance(bucket, Bucket):
api = self.capiBaseUrl + '/%s/_design/%s' % (bucket.name, name)
status, content, header = self._http_request(api, headers=self._create_capi_headers())
json_parsed = json.loads(content.decode())
meta_parsed = ""
if status:
# in dp4 builds meta data is in content, not in header
if 'X-Couchbase-Meta' in header:
meta = header['X-Couchbase-Meta']
meta_parsed = json.loads(meta)
elif 'x-couchbase-meta' in header:
meta = header['x-couchbase-meta']
meta_parsed = json.loads(meta)
else:
meta_parsed = {}
try:
meta_parsed["_rev"] = json_parsed["_rev"]
meta_parsed["_id"] = json_parsed["_id"]
except KeyError:
pass
return status, json_parsed, meta_parsed
def _delete_design_doc(self, bucket, name):
status, design_doc, meta = self._get_design_doc(bucket, name)
if not status:
raise Exception("unable to find for deletion design document")
api = self.capiBaseUrl + '/%s/_design/%s' % (bucket, name)
if isinstance(bucket, Bucket):
api = self.capiBaseUrl + '/%s/_design/%s' % (bucket.name, name)
status, content, header = self._http_request(api, 'DELETE',
headers=self._create_capi_headers())
json_parsed = json.loads(content)
return status, json_parsed
def spatial_compaction(self, bucket, design_name):
api = self.capiBaseUrl + '/%s/_design/%s/_spatial/_compact' % (bucket, design_name)
if isinstance(bucket, Bucket):
api = self.capiBaseUrl + \
'/%s/_design/%s/_spatial/_compact' % (bucket.name, design_name)
status, content, header = self._http_request(api, 'POST',
headers=self._create_capi_headers())
json_parsed = json.loads(content)
return status, json_parsed
# Make a _design/_info request
def set_view_info(self, bucket, design_name):
"""Get view diagnostic info (node specific)"""
api = self.capiBaseUrl
if isinstance(bucket, Bucket):
api += '/_set_view/{0}/_design/{1}/_info'.format(bucket.name, design_name)
else:
api += '_set_view/{0}/_design/{1}/_info'.format(bucket, design_name)
status, content, header = self._http_request(api, 'GET',
headers=self._create_capi_headers())
if not status:
raise SetViewInfoNotFound(design_name, content)
json_parsed = json.loads(content)
return status, json_parsed
# Make a _spatial/_info request
def spatial_info(self, bucket, design_name):
api = self.capiBaseUrl + \
'/%s/_design/%s/_spatial/_info' % (bucket, design_name)
status, content, header = self._http_request(
api, 'GET', headers=self._create_capi_headers())
json_parsed = json.loads(content)
return status, json_parsed
def _create_capi_headers(self):
authorization = self.get_authorization(self.username, self.password)
return {'Content-Type': 'application/json',
'Authorization': 'Basic %s' % authorization,
'Accept': '*/*'}
def _create_capi_headers_with_auth(self, username, password):
authorization = self.get_authorization(username, password)
return {'Content-Type': 'application/json',
'Authorization': 'Basic %s' % authorization,
'Accept': '*/*'}
def _create_headers_with_auth(self, username, password):
authorization = self.get_authorization(username, password)