Completed
Pull Request — master (#469)
by
unknown
02:24
created

Client.make_call()   D

Complexity

Conditions 10

Size

Total Lines 51

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 51
rs 4.2352
cc 10

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like Client.make_call() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import pycurl, json
2
from StringIO import StringIO
3
import urllib
4
import signal
5
import sys
6
import time
7
8
POST_PARAMS = {}
9
MAX_ATTEMPTS = 3
10
11
class Client:
12
  def __init__(self, action, api_url, api_user, api_password, method):
13
    self.conn = None
14
    self.action = action
15
    self.keep_trying = 1
16
    self.api_url = api_url
17
    self.api_user = api_user
18
    self.api_password = api_password
19
    self.method = method
20
    self.buffer = ''
21
    signal.signal(signal.SIGINT, self.handle_ctrl_c)
22
23
  def handle_ctrl_c(self, signal, frame):
24
    sys.stderr.write('SIGINT receivied')
25
    sys.stderr.write('You pressed Ctrl+C?!')
26
    self.abort_session()
27
28
  def abort_session(self):
29
    self.keep_trying = 0
30
    self.conn.close()
31
32
  def setup_connection(self):
33
34
    if self.conn:
35
      self.conn.close()
36
    self.headers = ['Accept: application/json', 'Expect:', 'Connection: close']
37
    self.conn = pycurl.Curl()
38
    self.conn.setopt(pycurl.SSL_VERIFYHOST, False)
39
    self.conn.setopt(pycurl.SSL_VERIFYPEER, False)
40
    self.conn.setopt(pycurl.USERPWD, "%s:%s" % (self.api_user, self.api_password))
41
    self.conn.setopt(pycurl.URL, self.api_url)
42
    self.conn.setopt(pycurl.VERBOSE, 0)
43
    self.conn.setopt(pycurl.WRITEFUNCTION, self.on_receive)
44
    self.conn.setopt(pycurl.NOSIGNAL, 1)
45
    self.conn.setopt(pycurl.NOPROGRESS, 1)
46
    self.conn.setopt(pycurl.HTTPHEADER, self.headers)
47
    if self.method == 'post':
48
      self.conn.setopt(pycurl.POST, 1)
49
      self.conn.setopt(pycurl.POSTFIELDS, urllib.urlencode(POST_PARAMS))
50
    elif self.method == 'get':
51
      self.conn.setopt(pycurl.POST, 0)
52
    
53
  def on_receive(self, data):
54
    #self.action.logger.debug('Icinga2GetStatus: client on_receive, data: %s', data)
55
    # complete message received
56
    self.buffer += data
57
    # sys.stderr.write(data)
58
    try:
59
      event = json.loads(self.buffer)
60
      update_body = True
61
    except:
62
      # no json found
63
      update_body = False
64
65
    if update_body:
66
      if self.action is not None:
67
        #sys.stderr.write('Updating body\n')
68
        self.action.set_body(event)
69
      else:
70
        print event
71
      
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 and double each attempt
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, or authorization error. Verify request of 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
128
129