blob: 1a1b96580d2cf7060af2e5cede3362f5313d1849 [file] [log] [blame]
Patrick Williamsc124f4f2015-09-15 14:41:29 -05001#!/usr/bin/env python
2
3# Sends an error report (if the report-error class was enabled) to a
4# remote server.
5#
6# Copyright (C) 2013 Intel Corporation
7# Author: Andreea Proca <andreea.b.proca@intel.com>
8# Author: Michael Wood <michael.g.wood@intel.com>
9
10import urllib2
11import sys
12import json
13import os
14import subprocess
15import argparse
16import logging
17
18version = "0.3"
19
20log = logging.getLogger("send-error-report")
21logging.basicConfig(format='%(levelname)s: %(message)s')
22
23def getPayloadLimit(url):
24 req = urllib2.Request(url, None)
25 try:
26 response = urllib2.urlopen(req)
27 except urllib2.URLError as e:
28 # Use this opportunity to bail out if we can't even contact the server
29 log.error("Could not contact server: " + url)
30 log.error(e.reason)
31 sys.exit(1)
32 try:
33 ret = json.loads(response.read())
34 max_log_size = ret.get('max_log_size', 0)
35 return int(max_log_size)
36 except:
37 pass
38
39 return 0
40
41def ask_for_contactdetails():
42 print("Please enter your name and your email (optionally), they'll be saved in the file you send.")
43 username = raw_input("Name (required): ")
44 email = raw_input("E-mail (not required): ")
45 return username, email
46
47def edit_content(json_file_path):
48 edit = raw_input("Review information before sending? (y/n): ")
49 if 'y' in edit or 'Y' in edit:
50 editor = os.environ.get('EDITOR', None)
51 if editor:
52 subprocess.check_call([editor, json_file_path])
53 else:
54 log.error("Please set your EDITOR value")
55 sys.exit(1)
56 return True
57 return False
58
59def prepare_data(args):
60 # attempt to get the max_log_size from the server's settings
61 max_log_size = getPayloadLimit("http://"+args.server+"/ClientPost/JSON")
62
63 if not os.path.isfile(args.error_file):
64 log.error("No data file found.")
65 sys.exit(1)
66
67 home = os.path.expanduser("~")
68 userfile = os.path.join(home, ".oe-send-error")
69
70 try:
71 with open(userfile, 'r') as userfile_fp:
72 if len(args.name) == 0:
73 args.name = userfile_fp.readline()
74 else:
75 #use empty readline to increment the fp
76 userfile_fp.readline()
77
78 if len(args.email) == 0:
79 args.email = userfile_fp.readline()
80 except:
81 pass
82
83 if args.assume_yes == True and len(args.name) == 0:
84 log.error("Name needs to be provided either via "+userfile+" or as an argument (-n).")
85 sys.exit(1)
86
87 while len(args.name) <= 0 and len(args.name) < 50:
88 print("\nName needs to be given and must not more than 50 characters.")
89 args.name, args.email = ask_for_contactdetails()
90
91 with open(userfile, 'w') as userfile_fp:
92 userfile_fp.write(args.name.strip() + "\n")
93 userfile_fp.write(args.email.strip() + "\n")
94
95 with open(args.error_file, 'r') as json_fp:
96 data = json_fp.read()
97
98 jsondata = json.loads(data)
99 jsondata['username'] = args.name.strip()
100 jsondata['email'] = args.email.strip()
101 jsondata['link_back'] = args.link_back.strip()
102 # If we got a max_log_size then use this to truncate to get the last
103 # max_log_size bytes from the end
104 if max_log_size != 0:
105 for fail in jsondata['failures']:
106 if len(fail['log']) > max_log_size:
107 print "Truncating log to allow for upload"
108 fail['log'] = fail['log'][-max_log_size:]
109
110 data = json.dumps(jsondata, indent=4, sort_keys=True)
111
112 # Write back the result which will contain all fields filled in and
113 # any post processing done on the log data
114 with open(args.error_file, "w") as json_fp:
115 if data:
116 json_fp.write(data)
117
118
119 if args.assume_yes == False and edit_content(args.error_file):
120 #We'll need to re-read the content if we edited it
121 with open(args.error_file, 'r') as json_fp:
122 data = json_fp.read()
123
124 return data
125
126
127def send_data(data, args):
128 headers={'Content-type': 'application/json', 'User-Agent': "send-error-report/"+version}
129
130 if args.json:
131 url = "http://"+args.server+"/ClientPost/JSON/"
132 else:
133 url = "http://"+args.server+"/ClientPost/"
134
135 req = urllib2.Request(url, data=data, headers=headers)
136 try:
137 response = urllib2.urlopen(req)
138 except urllib2.HTTPError, e:
139 logging.error(e.reason)
140 sys.exit(1)
141
142 print response.read()
143
144
145if __name__ == '__main__':
146 arg_parse = argparse.ArgumentParser(description="This scripts will send an error report to your specified error-report-web server.")
147
148 arg_parse.add_argument("error_file",
149 help="Generated error report file location",
150 type=str)
151
152 arg_parse.add_argument("-y",
153 "--assume-yes",
154 help="Assume yes to all queries and do not prompt",
155 action="store_true")
156
157 arg_parse.add_argument("-s",
158 "--server",
159 help="Server to send error report to",
160 type=str,
161 default="errors.yoctoproject.org")
162
163 arg_parse.add_argument("-e",
164 "--email",
165 help="Email address to be used for contact",
166 type=str,
167 default="")
168
169 arg_parse.add_argument("-n",
170 "--name",
171 help="Submitter name used to identify your error report",
172 type=str,
173 default="")
174
175 arg_parse.add_argument("-l",
176 "--link-back",
177 help="A url to link back to this build from the error report server",
178 type=str,
179 default="")
180
181 arg_parse.add_argument("-j",
182 "--json",
183 help="Return the result in json format, silences all other output",
184 action="store_true")
185
186
187
188 args = arg_parse.parse_args()
189
190 if (args.json == False):
191 print "Preparing to send errors to: "+args.server
192
193 data = prepare_data(args)
194 send_data(data, args)
195
196 sys.exit(0)