forked from mnemonic-no/act-workers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.py
81 lines (64 loc) · 2.48 KB
/
worker.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
"""Common worker library"""
import socket
from email.mime.text import MIMEText
import smtplib
from logging import error
import argparse
import requests
import urllib3
class UnknownResult(Exception):
"""UnknownResult is used in API request (not 200 result)"""
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
def parseargs(description):
""" Parse arguments """
parser = argparse.ArgumentParser(description=description)
parser.add_argument('--http-timeout', dest='timeout', type=int,
default=120, help="Timeout")
parser.add_argument('--proxy-string', dest='proxy_string', help="Proxy to use for external queries")
parser.add_argument('--userid', dest='user_id',
help="User ID")
parser.add_argument('--act-baseurl', dest='act_baseurl',
help='ACT API URI')
parser.add_argument("--logfile", dest="logfile",
help="Log to file (default = stdout)")
parser.add_argument("--loglevel", dest="loglevel", default="info",
help="Loglevel (default = info)")
return parser
def fetch_json(url, proxy_string, timeout=60, verify_https=False):
"""Fetch remote URL as JSON
url (string): URL to fetch
proxy_string (string, optional): Optional proxy string on format host:port
timeout (int, optional): Timeout value for query (default=60 seconds)
"""
proxies = {
'http': proxy_string,
'https': proxy_string
}
options = {
"verify": verify_https,
"timeout": timeout,
"proxies": proxies,
"params": {}
}
if not verify_https:
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
try:
req = requests.get(url, **options)
except (urllib3.exceptions.ReadTimeoutError,
requests.exceptions.ReadTimeout,
socket.timeout) as err:
error("Timeout ({0.__class__.__name__}), query: {1}".format(err, req.url))
if not req.status_code == 200:
errmsg = "status_code: {0.status_code}: {0.content}"
raise UnknownResult(errmsg.format(req))
return req.json()
def sendmail(smtphost, sender, recipient, subject, body):
"""Send email"""
msg = MIMEText(body, "plain", "utf-8")
msg['Subject'] = subject
msg['From'] = sender
msg['To'] = recipient
s = smtplib.SMTP(smtphost)
s.sendmail(sender, [recipient], msg.as_string())
s.quit()