Advertisement
yugene

jtltodb.py

Jul 1st, 2012
282
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.53 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. """
  4. Description : Split JTL file into a comma delimited CVS by : Oliver Erlewein (c)2008 Date : 04.02.2008 Lang : Python 2.7+
  5. Load data from csv to oracle : Eugene Kazakov (c) 2012-06
  6. XML Log format 2.1
  7. The sample attributes have the following meaning:
  8. Attribute  Content
  9. by         Bytes
  10. de         Data encoding
  11. dt         Data type
  12. ec         Error count (0 or 1, unless multiple samples are aggregated)
  13. hn         Hostname where the sample was generated
  14. it         Idle Time = time not spent sampling (milliseconds) (generally 0)
  15. lb         Label
  16. lt         Latency = time to initial response (milliseconds) - not all samplers support this
  17. na         Number of active threads for all thread groups
  18. ng         Number of active threads in this group
  19. rc         Response Code (e.g. 200)
  20. rm         Response Message (e.g. OK)
  21. s          Success flag (true/false)
  22. sc         Sample count (1, unless multiple samples are aggregated)
  23. t          Elapsed time (milliseconds)
  24. tn         Thread Name
  25. ts         timeStamp (milliseconds since midnight Jan 1, 1970 UTC)
  26. """
  27. import getopt
  28. import sys
  29. import re
  30. import time
  31. import os
  32. import datetime
  33. from subprocess import Popen, PIPE
  34.  
  35.  
  36. startTime = time.time()
  37. cnt = 0
  38. cnt2 = 0
  39. failCnt = 0
  40. reCompile = re.compile("\s([^\s]*?)=\"(.*?)\"")
  41. delimiterCharacterOut = ","
  42.  
  43. def usage():
  44.     usageRules = """Usage:
  45.    """+os.path.basename(__file__)+"""
  46.    --jtl=JmeterLog.jtl                          jmeter log file
  47.    --csv=csvFile.csv                            output csv file
  48.    --filterString=^<                            regexp string for filtering
  49.    --connString=user/pass@host:port/scheme      connection string for oracle
  50.    --project==projectName                       name of project
  51.    --environment=server                         environment description
  52.    --duration=1/2/3 h/d/m                       duration of test
  53.    --test_comment='this great test happened
  54.    with us in beautifull summer day etc'        test description
  55.    --start_date=1970-01-01                      date when test started
  56.    --accepted=yes/no                           results of test
  57.    -h                                          print this usage
  58.    """
  59.     print usageRules
  60.  
  61. def writeCSVLine(line):
  62.  
  63.     x = reCompile.findall(line)
  64.     a = dict((row[0], row[1]) for row in x)
  65.     try:
  66.         #shortTS = str(int(int(a['ts'])/1000))
  67.         #x = str(datetime.datetime.fromtimestamp(float(shortTS)))[0:19]
  68.         #print int(a['ts'])/1000
  69.     #print time.strftime("%Y-%m-%d %H:%M:%S.", time.localtime(int(a['ts'])/1000)) + a['ts'][-3:]
  70.         b = time.strftime("%Y-%m-%d %H:%M:%S.", time.localtime(int(a['ts'])/1000)) + a['ts'][-3:] + "," + a['t'] + "," + a['lt'] + "," + a['s'] + ",\""\
  71.         + a['lb'] + "\"," + a['rc'] + "," + a['rm'] + ",\"" + a['tn'] + "\","\
  72.         + a['dt'] + "," + a['by'] + "\n"
  73.     except:
  74.         return -1
  75.     csvFile.write(b)
  76.     return 1
  77.  
  78. if __name__ == "__main__":
  79.  try:
  80.   # Get option from command line
  81.   opts, args = getopt.getopt(sys.argv[1:], 'h', ['jtl=', 'csv=', 'filterString=',
  82.                                                  'connString=', 'project=',
  83.                                                  'environment=', 'duration=',
  84.                                                  'test_comment=',
  85.                                                  'start_date=',
  86.                                                   'accepted='])
  87.  except getopt.GetoptError as err:
  88.   # print help information and exit:
  89.   print str(err) # will print something like "option -a not recognized"
  90.   usage()
  91.   print err
  92.   sys.exit(2)
  93.  
  94. #options processing
  95. for o, v in opts:
  96.     if o == '-h':
  97.         usage()
  98.         sys.exit()
  99.     elif o == '--jtl':
  100.         jtlInfile = v
  101.     elif o == '--csv':
  102.         cvsOutfile = v
  103.     elif o == '--filterString':
  104.         reFilter = v
  105.     elif o == '--connString':
  106.         connString = v
  107.     elif o == '--project':
  108.         project = v
  109.     elif o == '--environment':
  110.         environment = v
  111.     elif o == '--duration':
  112.         duration = v
  113.     elif o == '--test_comment':
  114.         test_comment = v
  115.     elif o == '--start_date':
  116.         start_date = v
  117.     elif o == '--accepted':
  118.         accepted = v
  119.  
  120. try:
  121.     jtlFile = open(jtlInfile, "r")
  122.     csvFile = open(cvsOutfile, "w")
  123. except:
  124.     raise
  125. #parse jtl file to csv format
  126. print "Splitting JTL file"
  127. print "Filtering on regular expression : " + reFilter
  128. cmpFilter = re.compile(reFilter)
  129.  
  130. for line in jtlFile:
  131.     try:
  132.         if cmpFilter.search(line):
  133. #            print line
  134.             returnVal = writeCSVLine(line)
  135.             if returnVal < 0:
  136.                 failCnt += 1
  137.             else:
  138.                 cnt2 += 1
  139.     except:
  140.         print 'Error in line : ', cnt, line
  141.         raise
  142.     cnt += 1
  143.  
  144. endTime = time.time()
  145. print "Time taken : ", str(endTime-startTime)
  146. print "Lines processed : ", cnt
  147. print "Lines that passed the filter : ", cnt2
  148. print "Lines skipped (error?) : ", failCnt
  149.  
  150. jtlFile.close()
  151. csvFile.close()
  152.  
  153.  
  154. #get next test_id from sequence
  155. proc = Popen(['sqlplus', '-S', connString],
  156.               stdin=PIPE, stdout=PIPE, stderr=PIPE)
  157. proc.stdin.write("select test_id_seq.nextval from dual;\n")
  158. stdout, stderr = proc.communicate()
  159. test_id = re.search("\d+", stdout)
  160.  
  161. #rewrite control file with new test_id value
  162. try:
  163.     ctl = open("jtlToCSV.ctl", "w")
  164. except:
  165.  raise
  166.  
  167. ctlString = """\
  168. LOAD DATA
  169.        INFILE  '"""+cvsOutfile+"""'
  170.        APPEND
  171. INTO TABLE results
  172.        FIELDS
  173.        TERMINATED BY ','
  174.        OPTIONALLY ENCLOSED BY '"'
  175.        trailing nullcols
  176. ( test_id constant """ + test_id.group(0) + """,
  177. time_stamp timestamp 'YYYY-MM-DD HH24:mi:ss.FF',
  178. elapsed,
  179. latency,
  180. success,
  181. label,
  182. responsecode,
  183. responsemessage,
  184. threadname,
  185. datatype,
  186. bytes
  187. )
  188. """
  189. ctl.write(ctlString)
  190. ctl.close()
  191.  
  192. #add description about test into "tests" table
  193. proc = Popen(['sqlplus', '-S', connString],
  194.               stdin=PIPE, stdout=PIPE, stderr=PIPE)
  195. proc.stdin.write("insert into tests values ('" + test_id.group(0) + "', '"+project+
  196.                  "', '"+environment+"', '"+duration+"', '"+test_comment+"', '"
  197.                  +start_date+"', '"+accepted+"');\n")
  198. stdout, stderr = proc.communicate()
  199. print "Insert in test table:"+stdout
  200.  
  201. #load data from csv to "results" table with sql loader
  202. proc = Popen(['sqlldr', connString, 'control=jtltocsv.ctl'],
  203.               stdin=PIPE, stdout=PIPE, stderr=PIPE)
  204. stdout, stderr = proc.communicate()
  205. print stdout
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement