Completed
Pull Request — master (#552)
by
unknown
02:27
created

Client.setup_connection()   A

Complexity

Conditions 4

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
cc 4
c 2
b 2
f 0
dl 0
loc 20
rs 9.2
1
import json
2
import urllib
3
import signal
4
import sys
5
import time
6
import pycurl
7
8
POST_PARAMS = {}
9
MAX_ATTEMPTS = 3
10
11
12
class Client:
13
    def __init__(self, action, api_url, api_user, api_password, method):
14
        self.conn = None
15
        self.action = action
16
        self.keep_trying = 1
17
        self.api_url = api_url
18
        self.api_user = api_user
19
        self.api_password = api_password
20
        self.method = method
21
        self.buffer = ''
22
        signal.signal(signal.SIGINT, self.handle_ctrl_c)
23
24
    def handle_ctrl_c(self, signal, frame):
25
        sys.stderr.write('SIGINT receivied')
26
        sys.stderr.write('You pressed Ctrl+C?!')
27
        self.abort_session()
28
29
    def abort_session(self):
30
        self.keep_trying = 0
31
        self.conn.close()
32
33
    def setup_connection(self):
34
35
        if self.conn:
36
            self.conn.close()
37
        self.headers = ['Accept: application/json', 'Expect:', 'Connection: close']
38
        self.conn = pycurl.Curl()
39
        self.conn.setopt(pycurl.SSL_VERIFYHOST, False)
40
        self.conn.setopt(pycurl.SSL_VERIFYPEER, False)
41
        self.conn.setopt(pycurl.USERPWD, "%s:%s" % (self.api_user, self.api_password))
42
        self.conn.setopt(pycurl.URL, self.api_url)
43
        self.conn.setopt(pycurl.VERBOSE, 0)
44
        self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
45
        self.conn.setopt(pycurl.NOSIGNAL, 1)
46
        self.conn.setopt(pycurl.NOPROGRESS, 1)
47
        self.conn.setopt(pycurl.HTTPHEADER, self.headers)
48
        if self.method == 'post':
49
            self.conn.setopt(pycurl.POST, 1)
50
            self.conn.setopt(pycurl.POSTFIELDS, urllib.urlencode(POST_PARAMS))
51
        elif self.method == 'get':
52
            self.conn.setopt(pycurl.POST, 0)
53
54
    def on_receive(self, data):
55
        # self.action.logger.debug('Icinga2GetStatus: client on_receive, data: %s', data)
56
        # complete message received
57
        self.buffer += data
58
        # sys.stderr.write(data)
59
        try:
60
            event = json.loads(self.buffer)
61
            update_body = True
62
        except:
63
            # no json found
64
            update_body = False
65
66
        if update_body:
67
            if self.action is not None:
68
                # sys.stderr.write('Updating body\n')
69
                self.action.set_body(event)
70
            else:
71
                print event
72
73
    def __del__(self):
74
        self.conn.close()
75
76
    def make_call(self):
77
        backoff_network_error = 0.25
78
        backoff_http_error = 1
79
        backoff_rate_limit = 60
80
        attempt = 0
81
        while True and self.keep_trying == 1 and attempt < MAX_ATTEMPTS:
82
            attempt += 1
83
            self.setup_connection()
84
            try:
85
                self.conn.perform()
86
            except:
87
                # Network error, use linear back off up to 16 seconds
88
                if self.keep_trying == 0:
89
                    continue
90
                sys.stderr.write('Network error: %s' % self.conn.errstr())
91
                sys.stderr.write('Waiting %s seconds before trying again' % backoff_network_error)
92
                time.sleep(backoff_network_error)
93
                backoff_network_error = min(backoff_network_error + 1, 16)
94
                continue
95
            # HTTP Error
96
            sc = self.conn.getinfo(pycurl.HTTP_CODE)
97
            if sc == 200:
98
                # sys.stderr.write('HTTP request successful.')
99
                self.conn.close()
100
                break
101
            elif sc == 420:
102
                # Rate limit, use exponential back off starting with 1 minute then doubling
103
                sys.stderr.write('Rate limit, waiting %s seconds' % backoff_rate_limit)
104
                time.sleep(backoff_rate_limit)
105
                backoff_rate_limit *= 2
106
            elif sc == 401:
107
                # Authentication error
108
                sys.stderr.write('Authentication error, check user/password.')
109
                self.action.error = 1
110
                break
111
            elif sc == 404:
112
                # Authorization error
113
                sys.stderr.write('Object not found. Verify request and/or check permissions.')
114
                self.action.error = 2
115
                break
116
            elif sc == 400:
117
                # Authorization error
118
                sys.stderr.write('Bad request.')
119
                self.action.error = 3
120
                break
121
            else:
122
                # HTTP error, use exponential back off up to 320 seconds
123
                sys.stderr.write('HTTP error %s, %s' % (sc, self.conn.errstr()))
124
                sys.stderr.write('Waiting %s seconds' % backoff_http_error)
125
                time.sleep(backoff_http_error)
126
                backoff_http_error = min(backoff_http_error * 2, 10)
127