File: servicebusservice.py

package info (click to toggle)
python-azure 2.0.0~rc6%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 269,052 kB
  • ctags: 9,428
  • sloc: python: 81,857; makefile: 149
file content (1301 lines) | stat: -rw-r--r-- 51,932 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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
#-------------------------------------------------------------------------
# Copyright (c) Microsoft.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#--------------------------------------------------------------------------
import datetime
import os
import time

import requests

from azure.common import (
    AzureHttpError,
)
from .constants import (
    AZURE_SERVICEBUS_NAMESPACE,
    AZURE_SERVICEBUS_ACCESS_KEY,
    AZURE_SERVICEBUS_ISSUER,
    DEFAULT_HTTP_TIMEOUT,
    SERVICE_BUS_HOST_BASE,
    _USER_AGENT_STRING,
)
from ._common_error import (
    _dont_fail_not_exist,
    _dont_fail_on_exist,
    _validate_not_none,
)
from ._common_models import (
    _unicode_type,
)
from ._common_conversion import (
    _encode_base64,
    _int_or_none,
    _sign_string,
    _str,
)
from ._common_serialization import (
    _ETreeXmlToObject,
    _get_request_body,
    _get_request_body_bytes_only,
    url_quote,
    url_unquote,
)
from ._http import (
    HTTPError,
    HTTPRequest,
)
from ._http.httpclient import _HTTPClient
from ._serialization import (
    _convert_event_hub_to_xml,
    _convert_topic_to_xml,
    _convert_response_to_topic,
    _convert_queue_to_xml,
    _convert_response_to_queue,
    _convert_subscription_to_xml,
    _convert_response_to_subscription,
    _convert_rule_to_xml,
    _convert_response_to_rule,
    _convert_response_to_event_hub,
    _convert_etree_element_to_queue,
    _convert_etree_element_to_topic,
    _convert_etree_element_to_subscription,
    _convert_etree_element_to_rule,
    _create_message,
    _service_bus_error_handler,
)


class ServiceBusService(object):

    def __init__(self, service_namespace=None, account_key=None, issuer=None,
                 x_ms_version='2011-06-01', host_base=SERVICE_BUS_HOST_BASE,
                 shared_access_key_name=None, shared_access_key_value=None,
                 authentication=None, timeout=DEFAULT_HTTP_TIMEOUT,
                 request_session=None):
        '''
        Initializes the service bus service for a namespace with the specified
        authentication settings (SAS or ACS).

        service_namespace:
            Service bus namespace, required for all operations. If None,
            the value is set to the AZURE_SERVICEBUS_NAMESPACE env variable.
        account_key:
            ACS authentication account key. If None, the value is set to the
            AZURE_SERVICEBUS_ACCESS_KEY env variable.
            Note that if both SAS and ACS settings are specified, SAS is used.
        issuer:
            ACS authentication issuer. If None, the value is set to the
            AZURE_SERVICEBUS_ISSUER env variable.
            Note that if both SAS and ACS settings are specified, SAS is used.
        x_ms_version:
            Unused. Kept for backwards compatibility.
        host_base:
            Optional. Live host base url. Defaults to Azure url. Override this
            for on-premise.
        shared_access_key_name:
            SAS authentication key name.
            Note that if both SAS and ACS settings are specified, SAS is used.
        shared_access_key_value:
            SAS authentication key value.
            Note that if both SAS and ACS settings are specified, SAS is used.
        authentication:
            Instance of authentication class. If this is specified, then
            ACS and SAS parameters are ignored.
        timeout:
            Optional. Timeout for the http request, in seconds.
        request_session:
            Optional. Session object to use for http requests.
        '''
        self.requestid = None
        self.service_namespace = service_namespace
        self.host_base = host_base

        if not self.service_namespace:
            self.service_namespace = os.environ.get(AZURE_SERVICEBUS_NAMESPACE)

        if not self.service_namespace:
            raise ValueError('You need to provide servicebus namespace')

        if authentication:
            self.authentication = authentication
        else:
            if not account_key:
                account_key = os.environ.get(AZURE_SERVICEBUS_ACCESS_KEY)
            if not issuer:
                issuer = os.environ.get(AZURE_SERVICEBUS_ISSUER)

            if shared_access_key_name and shared_access_key_value:
                self.authentication = ServiceBusSASAuthentication(
                    shared_access_key_name,
                    shared_access_key_value)
            elif account_key and issuer:
                self.authentication = ServiceBusWrapTokenAuthentication(
                    account_key,
                    issuer)
            else:
                raise ValueError(
                    'You need to provide servicebus access key and Issuer OR shared access key and value')

        self._httpclient = _HTTPClient(
            service_instance=self,
            timeout=timeout,
            request_session=request_session or requests.Session(),
            user_agent=_USER_AGENT_STRING,
        )
        self._filter = self._httpclient.perform_request

    @staticmethod
    def format_dead_letter_queue_name(queue_name):
        """Get the dead letter name of this queue"""
        return queue_name + '/$DeadLetterQueue'

    @staticmethod
    def format_dead_letter_subscription_name(subscription_name):
        """Get the dead letter name of this subscription"""
        return subscription_name + '/$DeadLetterQueue'

    # Backwards compatibility:
    # account_key and issuer used to be stored on the service class, they are
    # now stored on the authentication class.
    @property
    def account_key(self):
        return self.authentication.account_key

    @account_key.setter
    def account_key(self, value):
        self.authentication.account_key = value

    @property
    def issuer(self):
        return self.authentication.issuer

    @issuer.setter
    def issuer(self, value):
        self.authentication.issuer = value

    def with_filter(self, filter):
        '''
        Returns a new service which will process requests with the specified
        filter.  Filtering operations can include logging, automatic retrying,
        etc...  The filter is a lambda which receives the HTTPRequest and
        another lambda.  The filter can perform any pre-processing on the
        request, pass it off to the next lambda, and then perform any
        post-processing on the response.
        '''
        res = ServiceBusService(
            service_namespace=self.service_namespace,
            authentication=self.authentication)

        old_filter = self._filter

        def new_filter(request):
            return filter(request, old_filter)

        res._filter = new_filter
        return res

    def set_proxy(self, host, port, user=None, password=None):
        '''
        Sets the proxy server host and port for the HTTP CONNECT Tunnelling.

        host:
            Address of the proxy. Ex: '192.168.0.100'
        port:
            Port of the proxy. Ex: 6000
        user:
            User for proxy authorization.
        password:
            Password for proxy authorization.
        '''
        self._httpclient.set_proxy(host, port, user, password)

    @property
    def timeout(self):
        return self._httpclient.timeout

    @timeout.setter
    def timeout(self, value):
        self._httpclient.timeout = value

    def create_queue(self, queue_name, queue=None, fail_on_exist=False):
        '''
        Creates a new queue. Once created, this queue's resource manifest is
        immutable.

        queue_name:
            Name of the queue to create.
        queue:
            Queue object to create.
        fail_on_exist:
            Specify whether to throw an exception when the queue exists.
        '''
        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host = self._get_host()
        request.path = '/' + _str(queue_name) + ''
        request.body = _get_request_body(_convert_queue_to_xml(queue))
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        if not fail_on_exist:
            try:
                self._perform_request(request)
                return True
            except AzureHttpError as ex:
                _dont_fail_on_exist(ex)
                return False
        else:
            self._perform_request(request)
            return True

    def delete_queue(self, queue_name, fail_not_exist=False):
        '''
        Deletes an existing queue. This operation will also remove all
        associated state including messages in the queue.

        queue_name:
            Name of the queue to delete.
        fail_not_exist:
            Specify whether to throw an exception if the queue doesn't exist.
        '''
        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'DELETE'
        request.host = self._get_host()
        request.path = '/' + _str(queue_name) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        if not fail_not_exist:
            try:
                self._perform_request(request)
                return True
            except AzureHttpError as ex:
                _dont_fail_not_exist(ex)
                return False
        else:
            self._perform_request(request)
            return True

    def get_queue(self, queue_name):
        '''
        Retrieves an existing queue.

        queue_name:
            Name of the queue.
        '''
        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/' + _str(queue_name) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _convert_response_to_queue(response)

    def list_queues(self):
        '''
        Enumerates the queues in the service namespace.
        '''
        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/$Resources/Queues'
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _ETreeXmlToObject.convert_response_to_feeds(
            response, _convert_etree_element_to_queue)

    def create_topic(self, topic_name, topic=None, fail_on_exist=False):
        '''
        Creates a new topic. Once created, this topic resource manifest is
        immutable.

        topic_name:
            Name of the topic to create.
        topic:
            Topic object to create.
        fail_on_exist:
            Specify whether to throw an exception when the topic exists.
        '''
        _validate_not_none('topic_name', topic_name)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host = self._get_host()
        request.path = '/' + _str(topic_name) + ''
        request.body = _get_request_body(_convert_topic_to_xml(topic))
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        if not fail_on_exist:
            try:
                self._perform_request(request)
                return True
            except AzureHttpError as ex:
                _dont_fail_on_exist(ex)
                return False
        else:
            self._perform_request(request)
            return True

    def delete_topic(self, topic_name, fail_not_exist=False):
        '''
        Deletes an existing topic. This operation will also remove all
        associated state including associated subscriptions.

        topic_name:
            Name of the topic to delete.
        fail_not_exist:
            Specify whether throw exception when topic doesn't exist.
        '''
        _validate_not_none('topic_name', topic_name)
        request = HTTPRequest()
        request.method = 'DELETE'
        request.host = self._get_host()
        request.path = '/' + _str(topic_name) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        if not fail_not_exist:
            try:
                self._perform_request(request)
                return True
            except AzureHttpError as ex:
                _dont_fail_not_exist(ex)
                return False
        else:
            self._perform_request(request)
            return True

    def get_topic(self, topic_name):
        '''
        Retrieves the description for the specified topic.

        topic_name:
            Name of the topic.
        '''
        _validate_not_none('topic_name', topic_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/' + _str(topic_name) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _convert_response_to_topic(response)

    def list_topics(self):
        '''
        Retrieves the topics in the service namespace.
        '''
        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/$Resources/Topics'
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _ETreeXmlToObject.convert_response_to_feeds(
            response, _convert_etree_element_to_topic)

    def create_rule(self, topic_name, subscription_name, rule_name, rule=None,
                    fail_on_exist=False):
        '''
        Creates a new rule. Once created, this rule's resource manifest is
        immutable.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription.
        rule_name:
            Name of the rule.
        fail_on_exist:
            Specify whether to throw an exception when the rule exists.
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('subscription_name', subscription_name)
        _validate_not_none('rule_name', rule_name)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host = self._get_host()
        request.path = '/' + _str(topic_name) + '/subscriptions/' + \
            _str(subscription_name) + \
            '/rules/' + _str(rule_name) + ''
        request.body = _get_request_body(_convert_rule_to_xml(rule))
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        if not fail_on_exist:
            try:
                self._perform_request(request)
                return True
            except AzureHttpError as ex:
                _dont_fail_on_exist(ex)
                return False
        else:
            self._perform_request(request)
            return True

    def delete_rule(self, topic_name, subscription_name, rule_name,
                    fail_not_exist=False):
        '''
        Deletes an existing rule.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription.
        rule_name:
            Name of the rule to delete.  DEFAULT_RULE_NAME=$Default.
            Use DEFAULT_RULE_NAME to delete default rule for the subscription.
        fail_not_exist:
            Specify whether throw exception when rule doesn't exist.
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('subscription_name', subscription_name)
        _validate_not_none('rule_name', rule_name)
        request = HTTPRequest()
        request.method = 'DELETE'
        request.host = self._get_host()
        request.path = '/' + _str(topic_name) + '/subscriptions/' + \
            _str(subscription_name) + \
            '/rules/' + _str(rule_name) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        if not fail_not_exist:
            try:
                self._perform_request(request)
                return True
            except AzureHttpError as ex:
                _dont_fail_not_exist(ex)
                return False
        else:
            self._perform_request(request)
            return True

    def get_rule(self, topic_name, subscription_name, rule_name):
        '''
        Retrieves the description for the specified rule.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription.
        rule_name:
            Name of the rule.
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('subscription_name', subscription_name)
        _validate_not_none('rule_name', rule_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/' + _str(topic_name) + '/subscriptions/' + \
            _str(subscription_name) + \
            '/rules/' + _str(rule_name) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _convert_response_to_rule(response)

    def list_rules(self, topic_name, subscription_name):
        '''
        Retrieves the rules that exist under the specified subscription.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription.
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('subscription_name', subscription_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/' + \
            _str(topic_name) + '/subscriptions/' + \
            _str(subscription_name) + '/rules/'
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _ETreeXmlToObject.convert_response_to_feeds(
            response, _convert_etree_element_to_rule)

    def create_subscription(self, topic_name, subscription_name,
                            subscription=None, fail_on_exist=False):
        '''
        Creates a new subscription. Once created, this subscription resource
        manifest is immutable.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription.
        fail_on_exist:
            Specify whether throw exception when subscription exists.
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('subscription_name', subscription_name)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host = self._get_host()
        request.path = '/' + \
            _str(topic_name) + '/subscriptions/' + _str(subscription_name) + ''
        request.body = _get_request_body(
            _convert_subscription_to_xml(subscription))
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        if not fail_on_exist:
            try:
                self._perform_request(request)
                return True
            except AzureHttpError as ex:
                _dont_fail_on_exist(ex)
                return False
        else:
            self._perform_request(request)
            return True

    def delete_subscription(self, topic_name, subscription_name,
                            fail_not_exist=False):
        '''
        Deletes an existing subscription.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription to delete.
        fail_not_exist:
            Specify whether to throw an exception when the subscription
            doesn't exist.
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('subscription_name', subscription_name)
        request = HTTPRequest()
        request.method = 'DELETE'
        request.host = self._get_host()
        request.path = '/' + \
            _str(topic_name) + '/subscriptions/' + _str(subscription_name) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        if not fail_not_exist:
            try:
                self._perform_request(request)
                return True
            except AzureHttpError as ex:
                _dont_fail_not_exist(ex)
                return False
        else:
            self._perform_request(request)
            return True

    def get_subscription(self, topic_name, subscription_name):
        '''
        Gets an existing subscription.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription.
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('subscription_name', subscription_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/' + \
            _str(topic_name) + '/subscriptions/' + _str(subscription_name) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _convert_response_to_subscription(response)

    def list_subscriptions(self, topic_name):
        '''
        Retrieves the subscriptions in the specified topic.

        topic_name:
            Name of the topic.
        '''
        _validate_not_none('topic_name', topic_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/' + _str(topic_name) + '/subscriptions/'
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _ETreeXmlToObject.convert_response_to_feeds(
            response, _convert_etree_element_to_subscription)

    def send_topic_message(self, topic_name, message=None):
        '''
        Enqueues a message into the specified topic. The limit to the number
        of messages which may be present in the topic is governed by the
        message size in MaxTopicSizeInBytes. If this message causes the topic
        to exceed its quota, a quota exceeded error is returned and the
        message will be rejected.

        topic_name:
            Name of the topic.
        message:
            Message object containing message body and properties.
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('message', message)
        request = HTTPRequest()
        request.method = 'POST'
        request.host = self._get_host()
        request.path = '/' + _str(topic_name) + '/messages'
        request.headers = message.add_headers(request)
        request.body = _get_request_body_bytes_only(
            'message.body', message.body)
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        self._perform_request(request)

    def peek_lock_subscription_message(self, topic_name, subscription_name,
                                       timeout='60'):
        '''
        This operation is used to atomically retrieve and lock a message for
        processing. The message is guaranteed not to be delivered to other
        receivers during the lock duration period specified in buffer
        description. Once the lock expires, the message will be available to
        other receivers (on the same subscription only) during the lock
        duration period specified in the topic description. Once the lock
        expires, the message will be available to other receivers. In order to
        complete processing of the message, the receiver should issue a delete
        command with the lock ID received from this operation. To abandon
        processing of the message and unlock it for other receivers, an Unlock
        Message command should be issued, or the lock duration period can
        expire.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription.
        timeout:
            Optional. The timeout parameter is expressed in seconds.
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('subscription_name', subscription_name)
        request = HTTPRequest()
        request.method = 'POST'
        request.host = self._get_host()
        request.path = '/' + \
            _str(topic_name) + '/subscriptions/' + \
            _str(subscription_name) + '/messages/head'
        request.query = [('timeout', _int_or_none(timeout))]
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _create_message(response, self)

    def unlock_subscription_message(self, topic_name, subscription_name,
                                    sequence_number, lock_token):
        '''
        Unlock a message for processing by other receivers on a given
        subscription. This operation deletes the lock object, causing the
        message to be unlocked. A message must have first been locked by a
        receiver before this operation is called.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription.
        sequence_number:
            The sequence number of the message to be unlocked as returned in
            BrokerProperties['SequenceNumber'] by the Peek Message operation.
        lock_token:
            The ID of the lock as returned by the Peek Message operation in
            BrokerProperties['LockToken']
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('subscription_name', subscription_name)
        _validate_not_none('sequence_number', sequence_number)
        _validate_not_none('lock_token', lock_token)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host = self._get_host()
        request.path = '/' + _str(topic_name) + \
                       '/subscriptions/' + str(subscription_name) + \
                       '/messages/' + _str(sequence_number) + \
                       '/' + _str(lock_token) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        self._perform_request(request)

    def renew_lock_subscription_message(self, topic_name, subscription_name,
                                        sequence_number, lock_token):
        '''
        Renew the lock on an already locked message on a given
        subscription. A message must have first been locked by a
        receiver before this operation is called.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription.
        sequence_number:
            The sequence number of the message to be unlocked as returned in
            BrokerProperties['SequenceNumber'] by the Peek Message operation.
        lock_token:
            The ID of the lock as returned by the Peek Message operation in
            BrokerProperties['LockToken']
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('subscription_name', subscription_name)
        _validate_not_none('sequence_number', sequence_number)
        _validate_not_none('lock_token', lock_token)
        request = HTTPRequest()
        request.method = 'POST'
        request.host = self._get_host()
        request.path = '/' + _str(topic_name) + \
                       '/subscriptions/' + str(subscription_name) + \
                       '/messages/' + _str(sequence_number) + \
                       '/' + _str(lock_token) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        self._perform_request(request)

    def read_delete_subscription_message(self, topic_name, subscription_name,
                                         timeout='60'):
        '''
        Read and delete a message from a subscription as an atomic operation.
        This operation should be used when a best-effort guarantee is
        sufficient for an application; that is, using this operation it is
        possible for messages to be lost if processing fails.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription.
        timeout:
            Optional. The timeout parameter is expressed in seconds.
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('subscription_name', subscription_name)
        request = HTTPRequest()
        request.method = 'DELETE'
        request.host = self._get_host()
        request.path = '/' + _str(topic_name) + \
                       '/subscriptions/' + _str(subscription_name) + \
                       '/messages/head'
        request.query = [('timeout', _int_or_none(timeout))]
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _create_message(response, self)

    def delete_subscription_message(self, topic_name, subscription_name,
                                    sequence_number, lock_token):
        '''
        Completes processing on a locked message and delete it from the
        subscription. This operation should only be called after processing a
        previously locked message is successful to maintain At-Least-Once
        delivery assurances.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription.
        sequence_number:
            The sequence number of the message to be deleted as returned in
            BrokerProperties['SequenceNumber'] by the Peek Message operation.
        lock_token:
            The ID of the lock as returned by the Peek Message operation in
            BrokerProperties['LockToken']
        '''
        _validate_not_none('topic_name', topic_name)
        _validate_not_none('subscription_name', subscription_name)
        _validate_not_none('sequence_number', sequence_number)
        _validate_not_none('lock_token', lock_token)
        request = HTTPRequest()
        request.method = 'DELETE'
        request.host = self._get_host()
        request.path = '/' + _str(topic_name) + \
                       '/subscriptions/' + _str(subscription_name) + \
                       '/messages/' + _str(sequence_number) + \
                       '/' + _str(lock_token) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        self._perform_request(request)

    def send_queue_message(self, queue_name, message=None):
        '''
        Sends a message into the specified queue. The limit to the number of
        messages which may be present in the topic is governed by the message
        size the MaxTopicSizeInMegaBytes. If this message will cause the queue
        to exceed its quota, a quota exceeded error is returned and the
        message will be rejected.

        queue_name:
            Name of the queue.
        message:
            Message object containing message body and properties.
        '''
        _validate_not_none('queue_name', queue_name)
        _validate_not_none('message', message)
        request = HTTPRequest()
        request.method = 'POST'
        request.host = self._get_host()
        request.path = '/' + _str(queue_name) + '/messages'
        request.headers = message.add_headers(request)
        request.body = _get_request_body_bytes_only('message.body',
                                                    message.body)
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        self._perform_request(request)

    def peek_lock_queue_message(self, queue_name, timeout='60'):
        '''
        Automically retrieves and locks a message from a queue for processing.
        The message is guaranteed not to be delivered to other receivers (on
        the same subscription only) during the lock duration period specified
        in the queue description. Once the lock expires, the message will be
        available to other receivers. In order to complete processing of the
        message, the receiver should issue a delete command with the lock ID
        received from this operation. To abandon processing of the message and
        unlock it for other receivers, an Unlock Message command should be
        issued, or the lock duration period can expire.

        queue_name:
            Name of the queue.
        timeout:
            Optional. The timeout parameter is expressed in seconds.
        '''
        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'POST'
        request.host = self._get_host()
        request.path = '/' + _str(queue_name) + '/messages/head'
        request.query = [('timeout', _int_or_none(timeout))]
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _create_message(response, self)

    def unlock_queue_message(self, queue_name, sequence_number, lock_token):
        '''
        Unlocks a message for processing by other receivers on a given
        queue. This operation deletes the lock object, causing the
        message to be unlocked. A message must have first been locked by a
        receiver before this operation is called.

        queue_name:
            Name of the queue.
        sequence_number:
            The sequence number of the message to be unlocked as returned in
            BrokerProperties['SequenceNumber'] by the Peek Message operation.
        lock_token:
            The ID of the lock as returned by the Peek Message operation in
            BrokerProperties['LockToken']
        '''
        _validate_not_none('queue_name', queue_name)
        _validate_not_none('sequence_number', sequence_number)
        _validate_not_none('lock_token', lock_token)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host = self._get_host()
        request.path = '/' + _str(queue_name) + \
                       '/messages/' + _str(sequence_number) + \
                       '/' + _str(lock_token) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        self._perform_request(request)

    def renew_lock_queue_message(self, queue_name, sequence_number, lock_token):
        '''
        Renew lock on an already locked message on a given
        queue. A message must have first been locked by a
        receiver before this operation is called.

        queue_name:
            Name of the queue.
        sequence_number:
            The sequence number of the message to be unlocked as returned in
            BrokerProperties['SequenceNumber'] by the Peek Message operation.
        lock_token:
            The ID of the lock as returned by the Peek Message operation in
            BrokerProperties['LockToken']
        '''
        _validate_not_none('queue_name', queue_name)
        _validate_not_none('sequence_number', sequence_number)
        _validate_not_none('lock_token', lock_token)
        request = HTTPRequest()
        request.method = 'POST'
        request.host = self._get_host()
        request.path = '/' + _str(queue_name) + \
                       '/messages/' + _str(sequence_number) + \
                       '/' + _str(lock_token) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        self._perform_request(request)

    def read_delete_queue_message(self, queue_name, timeout='60'):
        '''
        Reads and deletes a message from a queue as an atomic operation. This
        operation should be used when a best-effort guarantee is sufficient
        for an application; that is, using this operation it is possible for
        messages to be lost if processing fails.

        queue_name:
            Name of the queue.
        timeout:
            Optional. The timeout parameter is expressed in seconds.
        '''
        _validate_not_none('queue_name', queue_name)
        request = HTTPRequest()
        request.method = 'DELETE'
        request.host = self._get_host()
        request.path = '/' + _str(queue_name) + '/messages/head'
        request.query = [('timeout', _int_or_none(timeout))]
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _create_message(response, self)

    def delete_queue_message(self, queue_name, sequence_number, lock_token):
        '''
        Completes processing on a locked message and delete it from the queue.
        This operation should only be called after processing a previously
        locked message is successful to maintain At-Least-Once delivery
        assurances.

        queue_name:
            Name of the queue.
        sequence_number:
            The sequence number of the message to be deleted as returned in
            BrokerProperties['SequenceNumber'] by the Peek Message operation.
        lock_token:
            The ID of the lock as returned by the Peek Message operation in
            BrokerProperties['LockToken']
        '''
        _validate_not_none('queue_name', queue_name)
        _validate_not_none('sequence_number', sequence_number)
        _validate_not_none('lock_token', lock_token)
        request = HTTPRequest()
        request.method = 'DELETE'
        request.host = self._get_host()
        request.path = '/' + _str(queue_name) + \
                       '/messages/' + _str(sequence_number) + \
                       '/' + _str(lock_token) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        self._perform_request(request)

    def receive_queue_message(self, queue_name, peek_lock=True, timeout=60):
        '''
        Receive a message from a queue for processing.

        queue_name:
            Name of the queue.
        peek_lock:
            Optional. True to retrieve and lock the message. False to read and
            delete the message. Default is True (lock).
        timeout:
            Optional. The timeout parameter is expressed in seconds.
        '''
        if peek_lock:
            return self.peek_lock_queue_message(queue_name, timeout)
        else:
            return self.read_delete_queue_message(queue_name, timeout)

    def receive_subscription_message(self, topic_name, subscription_name,
                                     peek_lock=True, timeout=60):
        '''
        Receive a message from a subscription for processing.

        topic_name:
            Name of the topic.
        subscription_name:
            Name of the subscription.
        peek_lock:
            Optional. True to retrieve and lock the message. False to read and
            delete the message. Default is True (lock).
        timeout:
            Optional. The timeout parameter is expressed in seconds.
        '''
        if peek_lock:
            return self.peek_lock_subscription_message(topic_name,
                                                       subscription_name,
                                                       timeout)
        else:
            return self.read_delete_subscription_message(topic_name,
                                                         subscription_name,
                                                         timeout)

    def create_event_hub(self, hub_name, hub=None, fail_on_exist=False):
        '''
        Creates a new Event Hub.

        hub_name:
            Name of event hub.
        hub:
            Optional. Event hub properties. Instance of EventHub class.
        hub.message_retention_in_days:
            Number of days to retain the events for this Event Hub.
        hub.status: Status of the Event Hub (enabled or disabled).
        hub.user_metadata: User metadata.
        hub.partition_count: Number of shards on the Event Hub.
        fail_on_exist:
            Specify whether to throw an exception when the event hub exists.
        '''
        _validate_not_none('hub_name', hub_name)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host = self._get_host()
        request.path = '/' + _str(hub_name) + '?api-version=2014-01'
        request.body = _get_request_body(_convert_event_hub_to_xml(hub))
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        if not fail_on_exist:
            try:
                self._perform_request(request)
                return True
            except AzureHttpError as ex:
                _dont_fail_on_exist(ex)
                return False
        else:
            self._perform_request(request)
            return True

    def update_event_hub(self, hub_name, hub=None):
        '''
        Updates an Event Hub.

        hub_name:
            Name of event hub.
        hub:
            Optional. Event hub properties. Instance of EventHub class.
        hub.message_retention_in_days:
            Number of days to retain the events for this Event Hub.
        '''
        _validate_not_none('hub_name', hub_name)
        request = HTTPRequest()
        request.method = 'PUT'
        request.host = self._get_host()
        request.path = '/' + _str(hub_name) + '?api-version=2014-01'
        request.body = _get_request_body(_convert_event_hub_to_xml(hub))
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers.append(('If-Match', '*'))
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _convert_response_to_event_hub(response)

    def delete_event_hub(self, hub_name, fail_not_exist=False):
        '''
        Deletes an Event Hub. This operation will also remove all associated
        state.

        hub_name:
            Name of the event hub to delete.
        fail_not_exist:
            Specify whether to throw an exception if the event hub doesn't exist.
        '''
        _validate_not_none('hub_name', hub_name)
        request = HTTPRequest()
        request.method = 'DELETE'
        request.host = self._get_host()
        request.path = '/' + _str(hub_name) + '?api-version=2014-01'
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        if not fail_not_exist:
            try:
                self._perform_request(request)
                return True
            except AzureHttpError as ex:
                _dont_fail_not_exist(ex)
                return False
        else:
            self._perform_request(request)
            return True

    def get_event_hub(self, hub_name):
        '''
        Retrieves an existing event hub.

        hub_name:
            Name of the event hub.
        '''
        _validate_not_none('hub_name', hub_name)
        request = HTTPRequest()
        request.method = 'GET'
        request.host = self._get_host()
        request.path = '/' + _str(hub_name) + ''
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        response = self._perform_request(request)

        return _convert_response_to_event_hub(response)

    def send_event(self, hub_name, message, device_id=None,
                   broker_properties=None):
        '''
        Sends a new message event to an Event Hub.
        '''
        _validate_not_none('hub_name', hub_name)
        request = HTTPRequest()
        request.method = 'POST'
        request.host = self._get_host()
        if device_id:
            request.path = '/{0}/publishers/{1}/messages?api-version=2014-01'.format(hub_name, device_id)
        else:
            request.path = '/{0}/messages?api-version=2014-01'.format(hub_name)
        if broker_properties:
            request.headers.append(
                ('BrokerProperties', str(broker_properties)))
        request.body = _get_request_body(message)
        request.path, request.query = self._httpclient._update_request_uri_query(request)
        request.headers = self._update_service_bus_header(request)
        self._perform_request(request)

    def _get_host(self):
        return self.service_namespace + self.host_base

    def _perform_request(self, request):
        try:
            resp = self._filter(request)
        except HTTPError as ex:
            return _service_bus_error_handler(ex)

        return resp

    def _update_service_bus_header(self, request):
        ''' Add additional headers for service bus. '''

        if request.method in ['PUT', 'POST', 'MERGE', 'DELETE']:
            request.headers.append(('Content-Length', str(len(request.body))))

        # if it is not GET or HEAD request, must set content-type.
        if not request.method in ['GET', 'HEAD']:
            for name, _ in request.headers:
                if 'content-type' == name.lower():
                    break
            else:
                request.headers.append(
                    ('Content-Type',
                     'application/atom+xml;type=entry;charset=utf-8'))

        # Adds authorization header for authentication.
        self.authentication.sign_request(request, self._httpclient)

        return request.headers


# Token cache for Authentication
# Shared by the different instances of ServiceBusWrapTokenAuthentication
_tokens = {}


class ServiceBusWrapTokenAuthentication:
    def __init__(self, account_key, issuer):
        self.account_key = account_key
        self.issuer = issuer

    def sign_request(self, request, httpclient):
        request.headers.append(
            ('Authorization', self._get_authorization(request, httpclient)))

    def _get_authorization(self, request, httpclient):
        ''' return the signed string with token. '''
        return 'WRAP access_token="' + \
                self._get_token(request.host, request.path, httpclient) + '"'

    def _token_is_expired(self, token):
        ''' Check if token expires or not. '''
        time_pos_begin = token.find('ExpiresOn=') + len('ExpiresOn=')
        time_pos_end = token.find('&', time_pos_begin)
        token_expire_time = int(token[time_pos_begin:time_pos_end])
        time_now = time.mktime(time.localtime())

        # Adding 30 seconds so the token wouldn't be expired when we send the
        # token to server.
        return (token_expire_time - time_now) < 30

    def _get_token(self, host, path, httpclient):
        '''
        Returns token for the request.

        host:
            the service bus service request.
        path:
            the service bus service request.
        '''
        wrap_scope = 'http://' + host + path + self.issuer + self.account_key

        # Check whether has unexpired cache, return cached token if it is still
        # usable.
        if wrap_scope in _tokens:
            token = _tokens[wrap_scope]
            if not self._token_is_expired(token):
                return token

        # get token from accessconstrol server
        request = HTTPRequest()
        request.protocol_override = 'https'
        request.host = host.replace('.servicebus.', '-sb.accesscontrol.')
        request.method = 'POST'
        request.path = '/WRAPv0.9'
        request.body = ('wrap_name=' + url_quote(self.issuer) +
                        '&wrap_password=' + url_quote(self.account_key) +
                        '&wrap_scope=' +
                        url_quote('http://' + host + path)).encode('utf-8')
        request.headers.append(('Content-Length', str(len(request.body))))
        resp = httpclient.perform_request(request)

        token = resp.body.decode('utf-8-sig')
        token = url_unquote(token[token.find('=') + 1:token.rfind('&')])
        _tokens[wrap_scope] = token

        return token


class ServiceBusSASAuthentication:
    def __init__(self, key_name, key_value):
        self.key_name = key_name
        self.key_value = key_value

    def sign_request(self, request, httpclient):
        request.headers.append(
            ('Authorization', self._get_authorization(request, httpclient)))

    def _get_authorization(self, request, httpclient):
        uri = httpclient.get_uri(request)
        uri = url_quote(uri, '').lower()
        expiry = str(self._get_expiry())

        to_sign = uri + '\n' + expiry
        signature = url_quote(_sign_string(self.key_value, to_sign, False), '')

        auth_format = 'SharedAccessSignature sig={0}&se={1}&skn={2}&sr={3}'
        auth = auth_format.format(signature, expiry, self.key_name, uri)

        return auth

    def _get_expiry(self):
        '''Returns the UTC datetime, in seconds since Epoch, when this signed 
        request expires (5 minutes from now).'''
        return int(round(time.time() + 300))