This repository was archived by the owner on Sep 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathrt2jira.py
More file actions
executable file
·606 lines (519 loc) · 31.6 KB
/
rt2jira.py
File metadata and controls
executable file
·606 lines (519 loc) · 31.6 KB
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
#!/usr/bin/env python
from __future__ import print_function
from itertools import izip
from rtkit.resource import RTResource
from rtkit.authenticators import CookieAuthenticator
from rtkit.errors import RTResourceError
from rtkit import set_logging
from jira.client import JIRA
from jira.exceptions import JIRAError
from titlecase import titlecase
import time
import os
import pprint
import re
import sys
import logging
import ConfigParser
import syslog
# Initialize RT library logging
set_logging('error')
rt_logger = logging.getLogger('rtkit')
# Initialize app-level logging
logger = logging.getLogger('rt2jira')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(logging.Formatter('%(asctime)s %(name)s[%(process)s]: [%(levelname)s] - %(message)s', "%b %m %H:%M:%S"))
logger.addHandler(ch)
# Initialize factories
pp = pprint.PrettyPrinter(indent=4)
# Define helper functions
def rt_format_ticket_time(t):
"""
Given a time struct representing the RT ticket's creation timestamp, this
returns a formatted, printable version of this timestamp.
:param t: the time struct of the RT ticket's creation timestamp
"""
return time.strftime("%a %b %d %H:%M:%S %Y", t)
def rt_parse_ticket_time(t):
"""
Given a string representing the RT ticket's creation timestamp, this
returns a parsed time struct version of this timestamp.
:param t: the string of the RT ticket's creation timestamp
"""
return time.strptime(t, "%a %b %d %H:%M:%S %Y")
def rt_format_comment_time(t):
"""
Given a time struct representing the RT ticket's comment timestamp, this
returns a formatted, printable version of this timestamp.
:param t: the time struct of the RT ticket's comment timestamp
"""
return time.strftime("%a %b %d %H:%M:%S %Y UTC", t)
def rt_parse_comment_time(t):
"""
Given a string representing the RT ticket's comment timestamp, this
returns a parsed time struct version of this timestamp.
:param t: the string of the RT ticket's comment timestamp
"""
return time.strptime(t, "%Y-%m-%d %H:%M:%S")
def package(r):
"""
Given an array of tuples, this function returns a dict of mapped
key/value pairs.
:param r: the array of tuples to process
"""
keys, vals = zip(*r)
k = iter(keys)
v = iter(vals)
d = dict(izip(k,v))
return d
def config_get_dict(config, section, option):
"""
Given a configuration section and option, fetch and parse the data
as if it were a dict. Return the resultant data as a dict.
:param config: the parsed configuration object
:param section: the section to extract
:param option: the option to parse
"""
fields_raw = config.get(section, option)
ret_fields = {}
if fields_raw:
regex_iter = re.finditer('\("([a-zA-Z0-9_]*)", "([a-zA-Z0-9_\.\ ]*)"\)', fields_raw)
fields = [(c.group(1), c.group(2)) for c in regex_iter]
ret_fields = package(fields)
return ret_fields
def find_id_range(jira_issue):
"""
Given an existing JIRA ticket, search the ticket and extract out
all corresponding RT ticket IDs referenced in the description and
comments of the JIRA ticket. Then, return an array indicating
the smallest and largest IDs found in this ticket.
:param jira_issue: the JIRA issue to search
"""
ret = None
regex = re.compile('Ticket ID: (.*)\n')
match = regex.search(jira_issue.fields.description)
if match and len(match.groups()) >= 1:
id_list = set([ int(match.group(1).strip()) ])
jira_comments = jira.comments(jira_issue)
for comment in jira_comments:
match = regex.search(comment.body)
if match and len(match.groups()) >= 1:
id_list.add(int(match.group(1).strip()))
id_list = list(id_list)
id_list.sort()
ret = [ id_list[0], id_list[-1] ]
return ret
def resolve(jira_issue, resolution_name, resolve_comment):
"""
Given a JIRA ticket, mark the ticket as resolved.
:param jira_issue: the specified JIRA ticket
:param resolution_name: the specified type of resolution for this ticket
"""
state_name = config.get('jira', 'resolve_transition_name')
state_id = None
resolution_id = None
for transition in jira.transitions(jira_issue):
if state_name in transition['name']:
state_id = transition['id']
break
for resolution in jira.resolutions():
if resolution_name in resolution.name:
resolution_id = resolution.id
break
if state_id and resolution_id:
fields_dict = config_get_dict(config, 'jira', 'resolve_fields')
fields_dict['resolution'] = { 'id': resolution_id }
logger.info('Resolving ticket (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_INFO, 'Resolving ticket (' + jira_issue.key + ')')
jira.transition_issue(jira_issue, state_id, fields=fields_dict, comment=resolve_comment)
def reopen(jira_issue):
"""
Given a JIRA ticket, mark the ticket as reopened.
:param jira_issue: the specified JIRA ticket
"""
state_name = config.get('jira', 'reopen_transition_name')
state_id = None
for transition in jira.transitions(jira_issue):
if state_name in transition['name']:
state_id = transition['id']
break
jira.transition_issue(jira_issue, state_id, comment=config.get('jira', 'reopen_comment'))
def find_user(rt_username, algo_type, project_keys):
"""
Given an RT username, returns the corresponding JIRA username that best
matches this user. None is returned, otherwise.
Two different algorithms are provided:
0 - straight search in JIRA using the specified RT username
1 - search in JIRA where RT usernames are <first_initial><last_name>
and JIRA usernames are <first_name>.<last_name>
:param rt_username: the RT username to use as initial search criteria
:param algo_type: the algorithm type specified (0 or 1)
:param project_keys: comma-separated list of project keys to check for issue assignment permissions
"""
users_dict = config_get_dict(config, 'jira', 'find_user_mapping')
users = None
if algo_type == 1:
if rt_username in users_dict:
users = jira.search_assignable_users_for_projects(users_dict[rt_username], project_keys)
else:
users = jira.search_assignable_users_for_projects(rt_username[1:], project_keys)
else:
users = jira.search_assignable_users_for_projects(rt_username, project_keys)
regex = None
if algo_type == 1:
regex = re.compile('^' + rt_username[0] + '.*\.' + rt_username[1:] + '$', re.IGNORECASE)
else:
regex = re.compile('^' + rt_username + '$', re.IGNORECASE)
ret_user = None
for user in users:
match = regex.search(user.name)
if match:
ret_user = user
break
return ret_user
# Read global configuration settings
config_file = sys.argv[1]
#config = ConfigParser.RawConfigParser(allow_no_value=True)
config = ConfigParser.RawConfigParser()
try:
config.read([config_file])
except:
logger.error("Can't parse " + config_file)
syslog.syslog(syslog.LOG_ERR, "Can't parse " + config_file)
sys.exit(1)
# Sanity check
try:
if not config.getboolean('sanity', 'reviewed'):
logger.error('Please review and change the ' + config_file + ' settings before running this script.')
syslog.syslog(syslog.LOG_ERR, 'Please review and change the ' + config_file + ' settings before running this script.')
sys.exit(1)
except:
sys.exit(1)
# Check for debug setting.
try:
if not config.getboolean('sanity', 'debug'):
logger.setLevel(logging.INFO)
ch.setLevel(logging.INFO)
except:
pass
# Initialize or restore RT state settings
stored_last_updated_activity = time.gmtime(0)
try:
stored_last_updated_activity = rt_parse_ticket_time(config.get('rt', 'last_fetched_timestamp'))
except:
logger.warn('Unable to parse feed timestamp - Defaulting to: ' + rt_format_ticket_time(stored_last_updated_activity) + ' UTC')
syslog.syslog(syslog.LOG_WARNING, 'Unable to parse feed timestamp - Defaulting to: ' + rt_format_ticket_time(stored_last_updated_activity) + ' UTC')
# Initialize web services
# Source RT Feed
resource = None
feed = None
try:
resource = RTResource(config.get('rt', 'api_url_prefix'), config.get('rt', 'username'), config.get('rt', 'password'), CookieAuthenticator)
feed = resource.get(path=config.get('rt', 'api_search_suffix'))
except RTResourceError as e:
logger.error('Cannot connect to RT server')
syslog.syslog(syslog.LOG_ERR, 'Cannot connect to RT server')
logger.error(e.response.status_int)
syslog.syslog(syslog.LOG_ERR, e.response.status_int)
logger.error(e.response.status)
syslog.syslog(syslog.LOG_ERR, e.response.status)
logger.error(e.response.parsed)
syslog.syslog(syslog.LOG_ERR, e.response.parsed)
sys.exit(1)
except:
logger.error('Cannot connect to RT server')
syslog.syslog(syslog.LOG_ERR, 'Cannot connect to RT server')
sys.exit(1)
# Destination JIRA Service
jira = None
try:
jira = JIRA(options={'server': config.get('jira', 'api_url_prefix'), 'verify': config.getboolean('jira', 'verify')}, basic_auth=(config.get('jira', 'username'), config.get('jira', 'password')))
except JIRAError as e:
logger.error("Unable to connect to JIRA server.")
syslog.syslog(syslog.LOG_ERR, "Unable to connect to JIRA server.")
logger.error(e.response.parsed)
syslog.syslog(syslog.LOG_ERR, e.response.parsed)
sys.exit(1)
except:
logger.error("Unable to connect to JIRA server.")
syslog.syslog(syslog.LOG_ERR, "Unable to connect to JIRA server.")
sys.exit(1)
if __name__ == '__main__':
# Process the most recent activity currently stored.
logger.info('Starting - Feed Last Updated: ' + rt_format_ticket_time(stored_last_updated_activity) + ' UTC')
syslog.syslog(syslog.LOG_NOTICE, 'Starting - Feed Last Updated: ' + rt_format_ticket_time(stored_last_updated_activity) + ' UTC')
last_updated_activity = stored_last_updated_activity
try:
# For each ticket found in the source feed
for e in feed.parsed:
t = package(e)
ticket_id = re.sub('ticket\/', '', t['id'])
ticket_requester = re.sub('\@.*', '', t['Requestors'])
ticket_requester_name = titlecase(re.sub('[0-9]', '', re.sub('\.', ' ', ticket_requester)))
ticket_date = rt_parse_ticket_time(t['Created'])
ticket_last_updated = rt_parse_ticket_time(t['LastUpdated'])
# Scrub ticket title to remove 're:' and 'fw:' prefixes
scrubbed_title = re.sub('^(?i)(re|fw|fwd):( |)', '', t['Subject'])
#ticket_summary = ticket_requester_name + ': ' + scrubbed_title
ticket_summary = scrubbed_title
logger.info('Processing Ticket ID (' + ticket_id + ') - ' + ticket_summary)
syslog.syslog(syslog.LOG_INFO, 'Processing Ticket ID (' + ticket_id + ') - ' + ticket_summary)
# If stored timestamp is more recent than the comment, then skip processing the comment.
if stored_last_updated_activity >= ticket_last_updated:
logger.debug('RT ticket older than stored timestamp, skipping')
syslog.syslog(syslog.LOG_DEBUG, 'RT ticket older than stored timestamp, skipping')
continue
sanitized_summary = re.sub('[^0-9A-Za-z\.\- ]', ' ', ticket_summary)
sanitized_summary = ' '.join([item.strip() for item in sanitized_summary.split(' ') if len(item) > 3])
sanitized_summary = re.sub('--', '', sanitized_summary)
sanitized_summary = re.sub(' -', ' ', sanitized_summary)
jira_results = None
if sanitized_summary:
logger.debug('JQL Search Terms: ' + sanitized_summary)
syslog.syslog(syslog.LOG_DEBUG, 'JQL Search Terms: ' + sanitized_summary)
# Check if JIRA ticket already exists.
jira_results = jira.search_issues('project = ' + config.get('jira', 'project') + ' AND component = "' + config.get('jira', 'component') + '" AND summary ~ "' + sanitized_summary + '" ORDER BY created ASC', maxResults=False)
# If the summary wasn't valid or we didn't get any previous search results.
if not sanitized_summary or not jira_results:
# Then search specifically for the Ticket ID reference in the JIRA ticket description.
description = 'Ticket ID: ' + ticket_id
# If the ticket_summary was completely empty, then create an artificial one.
if not ticket_summary:
ticket_summary = description
logger.debug('JQL Search Terms: ' + description)
syslog.syslog(syslog.LOG_DEBUG, 'JQL Search Terms: ' + description)
# Check if JIRA ticket already exists.
jira_results = jira.search_issues('project = ' + config.get('jira', 'project') + ' AND component = "' + config.get('jira', 'component') + '" AND description ~ "' + description + '" ORDER BY created ASC', maxResults=False)
# Check if at least one matching JIRA ticket exists.
jira_issue = None
if jira_results:
# Iterate through the resuling JIRA ticket search results
# Find the first JIRA ticket where the ticket IDs listed in the ticket are within +/- 10 of the RT ticket ID
for result in jira_results:
id_range = find_id_range(result)
original_id = int(ticket_id)
id_correlation_range = config.getint('rt', 'ticket_id_correlation_range')
if id_range and (((id_range[0] - id_correlation_range) <= original_id) and (original_id <= (id_range[-1] + id_correlation_range))):
jira_issue = result
break
if jira_issue:
logger.info('Found existing JIRA ticket (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_INFO, 'Found existing JIRA ticket (' + jira_issue.key + ')')
if not jira_issue:
# If there's no match, then create a new JIRA ticket.
ticket_description = 'Ticket ID: ' + ticket_id + '\n' + config.get('rt', 'url_ticket_display_prefix') + ticket_id + '\nSubject: ' + scrubbed_title + '\nRequester: ' + ticket_requester_name + '\nCreated Date: ' + rt_format_ticket_time(ticket_date)
jira_issue = jira.create_issue(project={'key':config.get('jira', 'project')}, summary=ticket_summary, description=ticket_description, issuetype={'name':config.get('jira', 'issue_type')}, components=[{'name':config.get('jira', 'component')}])
logger.info('Creating new JIRA ticket (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_INFO, 'Creating new JIRA ticket (' + jira_issue.key + ')')
# Update custom fields upon creation, if specified.
fields_dict = config_get_dict(config, 'jira', 'create_fields')
if fields_dict != {}:
for k,v in fields_dict.iteritems():
try:
fields_dict[k] = eval(v)
except:
continue
jira_issue.update(fields=fields_dict)
user = find_user(ticket_requester, config.getint('jira', 'find_user_algo_type_description'), config.get('jira', 'find_user_projects'))
if user:
# Make the ticket requester the reporter of the JIRA ticket.
logger.debug('Making (' + user.name + ') the reporter of (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_DEBUG, 'Making (' + user.name + ') the reporter of (' + jira_issue.key + ')')
jira_issue.update(fields={'reporter':{'name': user.name}})
# Auto-add ticket requester as watcher to the JIRA ticket.
logger.debug('Adding (' + user.name + ') as a watcher to (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_DEBUG, 'Adding (' + user.name + ') as a watcher to (' + jira_issue.key + ')')
jira.add_watcher(jira_issue, user.name)
else:
logger.warn('Unable to find equivalent RT requester in JIRA: ' + ticket_requester)
syslog.syslog(syslog.LOG_WARNING, 'Unable to find equivalent RT requester in JIRA: ' + ticket_requester)
# If global watchers are specified, then add them to the newly created ticket.
create_watchers = config.get('jira', 'create_watchers')
if create_watchers != "None":
for create_watcher in create_watchers.split(','):
logger.debug('Adding (' + create_watcher + ') as a watcher to (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_DEBUG, 'Adding (' + create_watcher + ') as a watcher to (' + jira_issue.key + ')')
jira.add_watcher(jira_issue, create_watcher)
# Once the JIRA ticket is created, should a new label be assigned to the ticket?
new_issue_label = config.get('jira', 'new_issue_label')
if new_issue_label != "None":
logger.debug('Adding label (' + new_issue_label + ') to (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_DEBUG, 'Adding label (' + new_issue_label + ') to (' + jira_issue.key + ')')
jira_issue.fields.labels.append(new_issue_label)
jira_issue.update(fields={"labels": jira_issue.fields.labels})
# Once the JIRA ticket is created, should the security level be modified?
if config.getboolean('jira', 'modify_security_level'):
original_security_level = config.get('jira', 'original_security_level')
original_security_level_mentioned = False
if original_security_level != "None":
if original_security_level in jira_issue.fields.description:
original_security_level_mentioned = True
else:
# Obtain all current comments on the JIRA ticket.
jira_comments = jira.comments(jira_issue)
for existing_comment in jira_comments:
if original_security_level in existing_comment.body:
original_security_level_mentioned = True
break
if original_security_level_mentioned:
logger.debug('Original security level for JIRA ticket (' + jira_issue.key + ') mentioned')
syslog.syslog(syslog.LOG_DEBUG, 'Original security level for JIRA ticket (' + jira_issue.key + ') mentioned')
# If checks passed, then modify the security level.
if not original_security_level_mentioned:
target_security_level = config.get('jira', 'target_security_level')
if target_security_level == "None":
logger.info('Removing security level for JIRA ticket (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_INFO, 'Removing security level for JIRA ticket (' + jira_issue.key + ')')
jira_issue.update(fields={"security": None})
else:
logger.info('Setting security level of JIRA ticket (' + jira_issue.key + ') to (' + target_security_level + ')')
syslog.syslog(syslog.LOG_INFO, 'Setting security level of JIRA ticket (' + jira_issue.key + ') to (' + target_security_level + ')')
jira_issue.update(fields={"security":{'name': target_security_level}})
# Next, obtain all current comments on the JIRA ticket.
jira_comments = jira.comments(jira_issue)
# Finally, loop through all non-system comments currently associated to the RT ticket.
rt_response = resource.get(path='ticket/'+ticket_id+'/history?format=l')
for r in rt_response.parsed:
c = package(r)
comment_date = rt_parse_comment_time(c['Created'])
# Skip system comments.
if c['Creator'] == 'RT_System':
continue
# If stored timestamp is more recent than the comment, then skip processing the comment.
if stored_last_updated_activity >= comment_date:
logger.debug('RT comment older than stored timestamp, skipping')
syslog.syslog(syslog.LOG_DEBUG, 'RT comment older than stored timestamp, skipping')
continue
elif comment_date > last_updated_activity:
# If the comment timestamp is more recent than the current timestamp of most recent activity,
# then update the current timestamp of most recent activity.
last_updated_activity = comment_date
# Check to see if the comment already exists in the JIRA ticket.
comment_creator = re.sub('\@.*', '', c['Creator'])
comment_uuid = 'Date: ' + rt_format_comment_time(comment_date) + '\nFrom: ' + comment_creator
comment_exists = False
for existing_comment in jira_comments:
logger.debug('Searching (' + jira_issue.key + ') comment (' + existing_comment.id + ')')
syslog.syslog(syslog.LOG_DEBUG, 'Searching (' + jira_issue.key + ') comment (' + existing_comment.id + ')')
if comment_uuid in existing_comment.body:
comment_exists = True
logger.debug('RT comment already exists, skipping')
syslog.syslog(syslog.LOG_DEBUG, 'RT comment already exists, skipping')
break
if not comment_exists:
comment_body = 'Date: ' + rt_format_comment_time(comment_date) + '\nFrom: ' + c['Creator'] + '\nTicket ID: ' + ticket_id + '\nSubject: ' + scrubbed_title + '\nAction: ' + c['Description'] + '\n\n' + c['Content']
# JIRA can't store comments more than 32,000 chars in length
truncated_comment = (comment_body[:31997] + '...') if len(comment_body) > 32000 else comment_body
# Only create the JIRA comment if this isn't an internal action to rt2jira
internal_action = 'Comments added by ' + config.get('rt', 'username')
new_comment = None
if internal_action not in c['Description']:
logger.info('Adding new comment to (' + jira_issue.key + ') from (' + comment_creator + ') on (' + rt_format_comment_time(comment_date) + ')')
syslog.syslog(syslog.LOG_INFO, 'Adding new comment to (' + jira_issue.key + ') from (' + comment_creator + ') on (' + rt_format_comment_time(comment_date) + ')')
new_comment = jira.add_comment(jira_issue, truncated_comment)
user = find_user(comment_creator, config.getint('jira', 'find_user_algo_type_comment'), config.get('jira', 'find_user_projects'))
if user:
# Auto-add ticket commenter as watcher to the JIRA ticket.
logger.debug('Adding (' + user.name + ') as a watcher to (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_DEBUG, 'Adding (' + user.name + ') as a watcher to (' + jira_issue.key + ')')
jira.add_watcher(jira_issue, user.name)
else:
logger.debug('Unable to find equivalent RT commenter in JIRA: ' + comment_creator)
syslog.syslog(syslog.LOG_DEBUG, 'Unable to find equivalent RT commenter in JIRA: ' + comment_creator)
# Assign ticket, if RT ticket was taken.
if 'Taken by' in c['Description']:
ticket_owner = re.sub('Taken by ', '', c['Description'])
user = find_user(ticket_owner, config.getint('jira', 'find_user_algo_type_comment'), config.get('jira', 'find_user_projects'))
if user:
logger.debug('Making (' + user.name + ') the assignee of (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_DEBUG, 'Making (' + user.name + ') the assignee of (' + jira_issue.key + ')')
jira_issue.update(fields={'assignee':{'name': user.name}})
else:
logger.warn('Unable to find equivalent RT owner in JIRA: ' + ticket_owner)
syslog.syslog(syslog.LOG_WARNING, 'Unable to find equivalent RT owner in JIRA: ' + ticket_owner)
# Assign ticket, if a dupe RT ticket was created and current ticket is unassigned.
# The assumption here is that whoever has most recently repled to the RT ticket via email is likely the default assignee of the ticket.
fields_dict = config_get_dict(config, 'jira', 'create_fields')
if fields_dict != {} and not jira_issue.fields.assignee and '@' not in c['Creator']:
for k,v in fields_dict.iteritems():
try:
if 'ticket_id' in v and 'Ticket created by' in c['Description'] and eval('jira_issue.fields.' + k) != ticket_id:
user = find_user(comment_creator, config.getint('jira', 'find_user_algo_type_comment'), config.get('jira', 'find_user_projects'))
if user:
logger.debug('Making (' + user.name + ') the assignee of (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_DEBUG, 'Making (' + user.name + ') the assignee of (' + jira_issue.key + ')')
jira_issue.update(fields={'assignee':{'name': user.name}})
else:
try:
logger.debug('Making (' + comment_creator + ') the assignee of (' + jira_issue.key + ')')
jira_issue.update(fields={'assignee':{'name': comment_creator}})
except:
logger.warn('Unable to find equivalent RT owner in JIRA: ' + comment_creator)
syslog.syslog(syslog.LOG_WARNING, 'Unable to find equivalent RT owner in JIRA: ' + comment_creator)
except:
continue
if 'Given to' in c['Description']:
ticket_owner = re.sub('Given to (\w+) by.*', '\\1', c['Description'])
user = find_user(ticket_owner, config.getint('jira', 'find_user_algo_type_comment'), config.get('jira', 'find_user_projects'))
if user:
logger.debug('Making (' + user.name + ') the assignee of (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_DEBUG, 'Making (' + user.name + ') the assignee of (' + jira_issue.key + ')')
jira_issue.update(fields={'assignee':{'name': user.name}})
else:
logger.warn('Unable to find equivalent RT owner in JIRA: ' + ticket_owner)
syslog.syslog(syslog.LOG_WARNING, 'Unable to find equivalent RT owner in JIRA: ' + ticket_owner)
# Resolve the ticket if it was resolved in RT.
if 'resolved' in c['Description']:
resolve(jira_issue, config.get('jira', 'resolve_resolution_name'), config.get('jira', 'resolve_comment'))
# Once the JIRA ticket is commented, should a new label be assigned to the ticket?
new_comment_label = config.get('jira', 'new_comment_label')
if new_comment_label != "None" and ('Correspondence' in c['Description'] or 'Ticket created' in c['Description']):
logger.debug('Adding label (' + new_comment_label + ') to (' + jira_issue.key + ')')
syslog.syslog(syslog.LOG_DEBUG, 'Adding label (' + new_comment_label + ') to (' + jira_issue.key + ')')
jira_issue.fields.labels.append(new_comment_label)
jira_issue.update(fields={"labels": jira_issue.fields.labels})
# Once the JIRA ticket is commented, should the security level be modified?
if config.getboolean('jira', 'modify_security_level'):
original_security_level = config.get('jira', 'original_security_level')
original_security_level_mentioned = False
if original_security_level != "None" and new_comment and original_security_level in new_comment.body:
original_security_level_mentioned = True
if original_security_level_mentioned:
logger.debug('Original security level for JIRA ticket (' + jira_issue.key + ') mentioned in comment')
syslog.syslog(syslog.LOG_DEBUG, 'Original security level for JIRA ticket (' + jira_issue.key + ') mentioned in comment')
# If checks passed, then modify the security level.
if original_security_level_mentioned and original_security_level != "None":
logger.info('Setting security level of JIRA ticket (' + jira_issue.key + ') to (' + original_security_level + ')')
syslog.syslog(syslog.LOG_INFO, 'Setting security level of JIRA ticket (' + jira_issue.key + ') to (' + original_security_level + ')')
jira_issue.update(fields={"security":{'name': original_security_level}})
except RTResourceError as e:
logger.error('RT processing error occurred.')
syslog.syslog(syslog.LOG_ERR, 'RT processing error occurred.')
logger.error(e.response.status_int)
syslog.syslog(syslog.LOG_ERR, e.response.status_int)
logger.error(e.response.status)
syslog.syslog(syslog.LOG_ERR, e.response.status)
logger.error(e.response.parsed)
syslog.syslog(syslog.LOG_ERR, e.response.parsed)
sys.exit(1)
except JIRAError as e:
logger.error('JIRA processing error occurred.')
syslog.syslog(syslog.LOG_ERR, 'JIRA processing error occurred.')
logger.error(e)
syslog.syslog(syslog.LOG_ERR, e)
sys.exit(1)
except:
logger.error('Unknown processing error occurred.')
syslog.syslog(syslog.LOG_ERR, 'Unknown processing error occurred.')
sys.exit(1)
# Update the RT feed timestamp
try:
config.set('rt', 'last_fetched_timestamp', rt_format_ticket_time(last_updated_activity))
with open(config_file, 'wb') as config_output:
config.write(config_output)
logger.info('Done - Feed Last Updated: ' + config.get('rt', 'last_fetched_timestamp') + ' UTC')
syslog.syslog(syslog.LOG_NOTICE, 'Done - Feed Last Updated: ' + config.get('rt', 'last_fetched_timestamp') + ' UTC')
except:
pass