Statistics
| Branch: | Revision:

root / TroubleTicket_db2db.py @ 11:0b389c93be20

History | View | Annotate | Download (6.5 kB)

1
#!/usr/bin/env python
2
#-------------------------------------------------------------------------------
3
# Name:        TroubleTicketParser.py
4
# Purpose:     To parse Trouble Tickets mail messages stored in database
5
#
6
# Author:      Panos Louridas, from an initial version by Spyros Kopsidas
7
# Copyright:   (c) EGEE Project 2009
8
# Licence:     Apache Software License
9

    
10
#-------------------------------------------------------------------------------
11

    
12
import sys
13
import getopt
14

    
15
from datetime import datetime
16

    
17
import TTConfig
18
import MySQLdb
19

    
20
from TroubleTicketParser import *
21

    
22
def get_unparsed_emails(cursor, table):
23
    query = """SELECT Message_ID, Subject, Header, Body
24
        FROM %s 
25
        WHERE IS_STANDARDISED IS NULL"""
26
#        "ORDER BY Date_Stored""" 
27
    cursor.execute(query % (table))
28

    
29
    while (1):
30
        row = cursor.fetchone()
31
        if row is None:
32
            return
33
        email = {
34
            'ID': row[0],
35
            'subject' : row[1],
36
            'header'  : row[2],
37
            'body'    : row[3]
38
            }
39
        yield email
40

    
41
def get_datetime_str(raw_datetime):
42
    try:
43
        dt = datetime.strptime(raw_datetime, "%d-%m-%Y")
44
    except ValueError:
45
        try:
46
            dt = datetime.strptime(raw_datetime, "%Y-%m-%d")
47
        except ValueError:
48
            return None
49
    return dt.isoformat()
50

    
51
def insert_values(values, db, destination_table, cursor, ttid):
52

    
53
    # Find messages previously normalised with the same NREN / ID combination
54
    # as this will be an update. The previous ones will have their
55
    # MESSAGE_RNUMBER attribute increased by 1.
56
    original_id = int(values.get("ORIGINAL_ID", ""))
57
    partner_id = values.get("NREN", "")
58
    query = """SELECT ENOC_ID, MESSAGE_RNUMBER
59
        FROM %s 
60
        WHERE ORIGINAL_ID = %d AND PARTNER_ID = '%s'"""
61
    query = query % (destination_table, original_id, partner_id)
62
    cursor.execute(query)
63
    while (1):
64
        row = cursor.fetchone()
65
        if row == None:
66
            break
67
        enoc_id = row[0]
68
        message_rnumber = row[1]
69
        update_stmt = 'UPDATE ' + destination_table + ' ' + \
70
            'SET MESSAGE_RNUMBER = MESSAGE_RNUMBER + 1 ' + \
71
            'WHERE ENOC_ID  = ' + str(enoc_id)
72
        cursor.execute(update_stmt)
73
        
74
    statement_pattern = "INSERT INTO " + destination_table + """
75
        (ORIGINAL_ID,
76
        TT_OPEN_DATETIME, 
77
        OPEN_ENGINEER,
78
        CLOSE_ENGINEER, 
79
        TT_LASTUPDATE_DATETIME,
80
        TT_TYPE,
81
        NETWORK_NODE,
82
        NETWORK_LINK_CIRCUIT,
83
        TT_TITLE, 
84
        TT_SHORT_DESCRIPTION,
85
        TT_PRIORITY,
86
        TT_STATUS,
87
        TT_CLOSE_DATETIME,
88
        TT_LONG_DESCRIPTION,
89
        ADDITIONAL_DATA, 
90
        HISTORY,
91
        MESSAGE_RNUMBER) 
92
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, 
93
        %s, %s, %s, %s, %s, %s, %s, %s)"""
94
          
95
    raw_datetime = values.get("TT_OPEN_DATETIME", "")
96
    tt_open_datetime = get_datetime_str(raw_datetime)
97
    if tt_open_datetime is None:
98
        return
99
    raw_datetime = values.get("TT_CLOSE_DATETIME", "")
100
    tt_close_datetime = get_datetime_str(raw_datetime)
101
    raw_datetime = values.get("TT_LASTUPDATE_DATETIME", "")
102
    tt_lastupdate_datetime = get_datetime_str(raw_datetime)
103

    
104
    statement_params = (
105
        original_id,
106
        # partner_id,
107
        tt_open_datetime,
108
        values.get("OPEN_ENGINEER", ""),
109
        values.get("CLOSE_ENGINEER", ""),
110
        tt_lastupdate_datetime,
111
        values.get("TT_TYPE", ""),
112
        values.get("NETWORK_NODE", ""),
113
        values.get("NETWORK_LINK_CIRCUIT", ""),
114
        values.get("TT_TITLE", ""),
115
        values.get("TT_SHORT_DESCRIPTION", ""),
116
        values.get("TT_PRIORITY", ""),
117
        values.get("TT_STATUS", ""),
118
        tt_close_datetime,
119
        values.get("TT_LONG_DESCRIPTION", ""),
120
        values.get("ADDITIONAL_DATA", ""),
121
        values.get("TT_HISTORY", ""),
122
        1)
123

    
124
    # Insert the new normalised ticket.
125
    cursor.execute(statement_pattern, statement_params)
126

    
127
def get_query_mark_as_parsed(row_id, db, source_table):
128
    return str("UPDATE `%s`.`%s`  SET `IS_STANDARDISED` = '1' WHERE `%s`.`ID` =%d LIMIT 1 ;" % (str(db), str(source_table), str(source_table), row_id))
129

    
130
def overwrite_print(output_str, overwrite):
131
    sys.stdout.write("%s%s\r" % (output_str, " " * overwrite))
132
    return len(output_str)
133

    
134
def usage():
135
    print "python TroubleTicket_db2db.py -passwd1=password1 -passwd2=password2"
136

    
137
def main(argv):
138
    try:
139
        opts, args = getopt.getopt(argv, "", ["passwd1=", "passwd2="])
140
    except getopt.GetoptError:
141
        usage()
142
        sys.exit(2)
143
    for o, a in opts:
144
        if o == "--passwd1":
145
            TTConfig.TTdb['passwd'] = a
146
        elif o == "--passwd2":
147
            TTConfig.TTdb_v2['passwd'] = a
148
        else:
149
            assert False, "unhandled option: " + o
150

    
151
    try:
152
        db1_conn = MySQLdb.connect(**TTConfig.TTdb)
153
        db1_cursor = db1_conn.cursor()
154
    except:
155
        print "Error connecting to database " + str(TTConfig.TTdb['db'])
156
        print TTConfig.TTdb
157
        exit()
158

    
159
    try:
160
        db2_conn = MySQLdb.connect(**TTConfig.TTdb_v2)
161
        db2_cursor = db2_conn.cursor()
162
    except:
163
        print "Error connecting to database " + str(TTConfig.TTdb_v2['db'])
164
        exit()
165

    
166
    print "Successfully connected to databases."
167
    print "Trying to read unparsed tickets from " + str(TTConfig.TTdb['db']) \
168
        + "..."
169

    
170
    emails_table = TTConfig.configuration['table_raw_emails']
171

    
172
    ttp = TroubleTicketParser()
173

    
174
    mails_read = 0
175
    rows_inserted = 0
176
    overwrite = 0
177
    for raw_mail in get_unparsed_emails(db1_cursor, emails_table):
178
        mails_read = mails_read + 1
179
        num_found_keys = 0
180
        ttp.parse(raw_mail)
181
        parse_results = ttp.resultset
182
        num_found_keys = len(parse_results.keys())
183
        if not 'ORIGINAL_ID' in parse_results:
184
            continue
185
        if not parse_results['ORIGINAL_ID'].isdigit():
186
            continue
187
        if num_found_keys >= TTConfig.configuration['min_keys_parsed']:
188
            insert_values(parse_results,
189
                          TTConfig.TTdb_v2['db'],
190
                          TTConfig.configuration['stdTickets_table'],
191
                          db2_cursor,
192
                          raw_mail['ID'])
193
            rows_inserted = rows_inserted + 1
194
        overwrite = overwrite_print("Mails read: %d; normalised"
195
                                    % (mails_read, rows_inserted),
196
                                    overwrite)
197

    
198

    
199
    db1_conn.close()            
200
    db2_conn.commit()
201
    db2_conn.close()
202

    
203
if __name__ == "__main__":
204
    main(sys.argv[1:])
205