Merge "increase number of open files for collectd"
[yardstick.git] / ansible / roles / download_pmu_tools / files / event_download_local.py
1 #!/usr/bin/env python
2 # Copyright (c) 2014, Intel Corporation
3 # Author: Andi Kleen
4 #
5 # This program is free software; you can redistribute it and/or modify it
6 # under the terms and conditions of the GNU General Public License,
7 # version 2, as published by the Free Software Foundation.
8 #
9 # This program is distributed in the hope it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 # FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12 # more details.
13 #
14 # Automatic event list downloader
15 #
16 # event_download.py         download for current cpu
17 # event_download.py -a      download all
18 # event_download.py cpustr...  Download for specific CPU
19 from __future__ import absolute_import
20 from __future__ import print_function
21 import sys
22
23 import re
24 import os
25 import string
26 from fnmatch import fnmatch
27 from shutil import copyfile
28
29 try:
30     from urllib2 import URLError
31 except ImportError:
32     # python 3
33     from urllib.error import URLError
34
35
36 urlpath = 'https://download.01.org/perfmon'
37 localpath = 'pmu_local_mirror/download.01.org/perfmon'
38 mapfile = 'mapfile.csv'
39 modelpath = localpath + "/" + mapfile
40 NSB_JSON = os.environ.get("PMU_EVENTS_PATH", "/tmp/pmu_event.json")
41
42
43 def get_cpustr():
44     with open('/proc/cpuinfo', 'r') as f:
45         cpu = [None, None, None]
46         for j in f:
47             n = j.split()
48             if n[0] == 'vendor_id':
49                 cpu[0] = n[2]
50             elif n[0] == 'model' and n[1] == ':':
51                 cpu[2] = int(n[2])
52             elif n[0] == 'cpu' and n[1] == 'family':
53                 cpu[1] = int(n[3])
54             if all(cpu):
55                 break
56     return "%s-%d-%X" % (cpu[0], cpu[1], cpu[2])
57
58
59 def sanitize(s, a):
60     o = ""
61     for j in s:
62         if j in a:
63             o += j
64     return o
65
66
67 def getdir():
68     try:
69         d = os.getenv("XDG_CACHE_HOME")
70         xd = d
71         if not d:
72             home = os.getenv("HOME")
73             d = "%s/.cache" % home
74         d += "/pmu-events"
75         if not os.path.isdir(d):
76             # try to handle the sudo case
77             if not xd:
78                 user = os.getenv("SUDO_USER")
79                 if user:
80                     nd = os.path.expanduser("~" + user) + "/.cache/pmu-events"
81                     if os.path.isdir(nd):
82                         return nd
83             os.makedirs(d)
84         return d
85     except OSError:
86         raise Exception('Cannot access ' + d)
87
88
89 NUM_TRIES = 3
90
91
92 def getfile(url, dir, fn):
93     tries = 0
94     print("Downloading", url, "to", fn)
95     while True:
96         try:
97             f = open(url)
98             data = f.read()
99         except IOError:
100             tries += 1
101             if tries >= NUM_TRIES:
102                 raise
103             print("retrying download")
104             continue
105         break
106     with open(os.path.join(dir, fn), "w") as o:
107         o.write(data)
108     f.close()
109
110
111 allowed_chars = string.ascii_letters + '_-.' + string.digits
112
113
114 def download(match, key=None, link=True):
115     found = 0
116     dir = getdir()
117     try:
118         getfile(modelpath, dir, "mapfile.csv")
119         models = open(os.path.join(dir, "mapfile.csv"))
120         for j in models:
121             n = j.rstrip().split(",")
122             if len(n) < 4:
123                 if len(n) > 0:
124                     print("Cannot parse", n)
125                 continue
126             cpu, version, name, type = n
127             if not fnmatch(cpu, match) or (key is not None and type not in key) or type.startswith("EventType"):
128                 continue
129             cpu = sanitize(cpu, allowed_chars)
130             url = localpath + name
131             fn = "%s-%s.json" % (cpu, sanitize(type, allowed_chars))
132             try:
133                 os.remove(os.path.join(dir, fn))
134             except OSError:
135                 pass
136             getfile(url, dir, fn)
137             if link:
138                 lname = re.sub(r'.*/', '', name)
139                 lname = sanitize(lname, allowed_chars)
140                 try:
141                     os.remove(os.path.join(dir, lname))
142                 except OSError:
143                     pass
144                 try:
145                     os.symlink(fn, os.path.join(dir, lname))
146                 except OSError as e:
147                     print("Cannot link %s to %s:" % (name, lname), e, file=sys.stderr)
148             found += 1
149         models.close()
150         getfile(localpath + "/readme.txt", dir, "readme.txt")
151     except URLError as e:
152         print("Cannot access event server:", e, file=sys.stderr)
153         print("If you need a proxy to access the internet please set it with:", file=sys.stderr)
154         print("\texport https_proxy=http://proxyname...", file=sys.stderr)
155         print("If you are not connected to the internet please run this on a connected system:", file=sys.stderr)
156         print("\tevent_download.py '%s'" % match, file=sys.stderr)
157         print("and then copy ~/.cache/pmu-events to the system under test", file=sys.stderr)
158         print("To get events for all possible CPUs use:", file=sys.stderr)
159         print("\tevent_download.py -a", file=sys.stderr)
160     except OSError as e:
161         print("Cannot write events file:", e, file=sys.stderr)
162     return found
163
164
165 def download_current(link=False):
166     """Download JSON event list for current cpu.
167        Returns >0 when a event list is found"""
168     return download(get_cpustr(), link=link)
169
170
171 def eventlist_name(name=None, key="core"):
172     if not name:
173         name = get_cpustr()
174     cache = getdir()
175     return "%s/%s-%s.json" % (cache, name, key)
176
177
178 if __name__ == '__main__':
179     # only import argparse when actually called from command line
180     # this makes ocperf work on older python versions without it.
181     import argparse
182     p = argparse.ArgumentParser(usage='download Intel event files')
183     p.add_argument('--all', '-a', help='Download all available event files', action='store_true')
184     p.add_argument('--verbose', '-v', help='Be verbose', action='store_true')
185     p.add_argument('--mine', help='Print name of current CPU', action='store_true')
186     p.add_argument('--link', help='Create links with the original event file name',
187                    action='store_true', default=True)
188     p.add_argument('cpus', help='CPU identifiers to download', nargs='*')
189     args = p.parse_args()
190
191     cpustr = get_cpustr()
192     if args.verbose or args.mine:
193         print("My CPU", cpustr)
194     if args.mine:
195         sys.exit(0)
196     d = getdir()
197     if args.all:
198         found = download('*', link=args.link)
199     elif len(args.cpus) == 0:
200         found = download_current(link=args.link)
201     else:
202         found = 0
203         for j in args.cpus:
204             found += download(j, link=args.link)
205
206     if found == 0:
207         print("Nothing found", file=sys.stderr)
208
209     el = eventlist_name()
210     if os.path.exists(el):
211         print("my event list", el)
212         copyfile(el, NSB_JSON)
213         print("File copied to ", NSB_JSON)