Commit f91bfc04 authored by Benjamin Schwenker's avatar Benjamin Schwenker
Browse files

Merge branch '40-http-exception-not-caught' into 'master'

Added additional catching of exceptions as well as retries when it fails. I...

Closes #40

See merge request !43
parents 42163636 59f9e4c8
......@@ -9,10 +9,12 @@
import getpass
import time
import traceback
import requests
import datetime
import pytz
from bs4 import BeautifulSoup
import logging
class elog():
......@@ -113,8 +115,7 @@ class elog():
self._b2rc_session = None
self.usernameb2rc = ''
self.passwordb2rc = ''
self.alias = ''
self.avatar = 'https://owncloud.gwdg.de/index.php/apps/files_sharing/ajax/publicpreview.php?x=1848&y=593&a=true&file=Selection_111.png&t=WiMaxhyNuewsmMy&scalingup=0'
if self.postMessageOfReport:
self._b2rc_session = requests.Session()
self._b2rc_session.auth = requests.auth.HTTPBasicAuth('cosmic', 'running')
......@@ -126,7 +127,7 @@ class elog():
try:
self.alias = lines[2]
except BaseException:
self.alias = ''
self.alias = 'BGNet Bot'
else:
self.usernameb2rc = input("Username:")
self.passwordb2rc = getpass.getpass("Password:")
......@@ -180,10 +181,14 @@ class elog():
if isinstance(requestToElog, requests.Request):
with requests.Session() as s:
s.auth = requestToElog.auth
s.request("GET", requestToElog.url)
prep = s.prepare_request(requestToElog)
settings = s.merge_environment_settings(prep.url, {}, None, None, None)
resp = s.send(prep, **settings)
try:
s.request("GET", requestToElog.url)
prep = s.prepare_request(requestToElog)
settings = s.merge_environment_settings(prep.url, {}, None, None, None)
resp = s.send(prep, **settings)
except Exception as e:
logging.error(traceback.format_exc())
return False
if resp.ok:
print("Elog Entry successfully transmitted to:")
print("{}".format(requestToElog.url))
......@@ -207,14 +212,45 @@ class elog():
# #################################
def api_get(self, name, params=None):
"""Send GET request."""
result = self._b2rc_session.get(self._b2rc_url + name, params=params)
result.raise_for_status()
result = None
success = False
retries = 0
while True:
try:
result = self._b2rc_session.get(self._b2rc_url + name, params=params)
result.raise_for_status()
success = True
except Exception as e:
logging.error(traceback.format_exc())
time.sleep(10)
retries += 1
if success:
break
if retries >=10:
logging.warning('Elog timeout')
break
return result
def api_post(self, name, data, files=None):
"""Send POST request."""
result = self._b2rc_session.post(self._b2rc_url + name,
result = None
success = False
retries = 0
while True:
try:
result = self._b2rc_session.post(self._b2rc_url + name,
data=data, files=files)
result.raise_for_status()
success = True
except Exception as e:
logging.error(traceback.format_exc())
time.sleep(10)
retries += 1
if success:
break
if retries >=10:
logging.warning('Elog timeout')
break
return result
def logout(self):
......@@ -233,8 +269,11 @@ class elog():
result = self.api_post('/api/v1/login', data={'resume': token})
else:
result = self.api_post('/api/v1/login', data={'user': self.usernameb2rc, 'password': self.passwordb2rc})
if not result:
logging.warning('Could not reach b2rc login')
return False
if result.status_code != 200 or result.json()['status'] != 'success':
print('B2rc api: Invalid authentication')
logging.warning('B2rc api: Invalid authentication')
return False
self._resume = (token is not None)
self._b2rc_token = result.json()['data']['authToken']
......@@ -246,6 +285,9 @@ class elog():
def get_ref_from_html(self, html):
'''Clean html file to retrieve latest report URL.'''
if html == []:
logging.info('Elog empty or not reachable, no URL for b2rc posting')
return ''
soup = BeautifulSoup(html, "html.parser")
hrefs = soup.find_all("a", href=True)
cleaned_hrefs = []
......@@ -276,8 +318,22 @@ class elog():
with requests.Session() as s:
s.auth = requests.auth.HTTPBasicAuth(self.username, self.password)
url_str = "{}://{}:{}/{}/".format(self.prefix, self.hostname, self.port, self.logbook)
result = s.get(url_str)
result.raise_for_status()
success = False
retries = 0
while True:
try:
result = s.get(url_str)
result.raise_for_status()
success = True
except Exception as e:
logging.error(traceback.format_exc())
time.sleep(10)
retries += 1
if success:
break
if retries >=10:
logging.warning('B2rc posting timeout')
break
return result.text
def postMessage(self, msg, ch, alias=None, avatar=None, emoji=None):
......@@ -287,23 +343,24 @@ class elog():
data = {'channel': ch, 'text': msg}
if self.alias:
data['alias'] = self.alias
if alias:
data['alias'] = str(alias)
if emoji and emoji.startswith(':'):
data['emoji'] = ':'.join(('', str(emoji).strip(':'), ''))
if avatar and avatar.startswith('http'):
data['avatar'] = avatar
if self.avatar and self.avatar.startswith('http'):
data['avatar'] = self.avatar
result = self.api_post('/api/v1/chat.postMessage', data)
result.raise_for_status()
return result.json()
if not result:
logging.warning('Could not reach b2rc login')
return False
return result.json()['success']
def postReport(self, url):
'''Define message text and channel.'''
text = '{} {}\n[{}]({})'.format(
self.starttime, self.type, url, url)
result = self.postMessage(text, '#bgnet')
if result['success'] is not True:
if result is not True:
raise RuntimeError('postReport: Sending shift report to b2rc failed')
return result
......@@ -315,12 +372,13 @@ class elog():
try:
html = self.search_elog()
except Exception as e:
print('search elog failed: {}' % e)
logging.error(traceback.format_exc())
continue
last_report_url = self.get_ref_from_html(html)
# TODO get time information and reference to uploaded report. Cant be sure that last report is this one
try:
self.postReport(last_report_url)
except Exception as e:
print('RocketChat: Sending shift report to b2rc failed: {}'.format(e))
logging.warning('RocketChat: Sending shift report to b2rc failed: {}'.format(e))
return False
return True
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment