2 # -*- coding: utf-8 -*-
4 # stats.py - part of the FDroid server tools
5 # Copyright (C) 2010-13, Ciaran Gultnieks, ciaran@ciarang.com
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
27 from argparse import ArgumentParser
34 from collections import Counter
37 def carbon_send(key, value):
39 s.connect((config['carbon_host'], config['carbon_port']))
40 msg = '%s %d %d\n' % (key, value, int(time.time()))
48 def most_common_stable(counts):
51 pairs.append((s, counts[s]))
52 return sorted(pairs, key=lambda t: (-t[1], t[0]))
57 global options, config
59 # Parse command line...
60 parser = ArgumentParser()
61 common.setup_global_opts(parser)
62 parser.add_argument("-d", "--download", action="store_true", default=False,
63 help="Download logs we don't have")
64 parser.add_argument("--recalc", action="store_true", default=False,
65 help="Recalculate aggregate stats - use when changes "
66 "have been made that would invalidate old cached data.")
67 parser.add_argument("--nologs", action="store_true", default=False,
68 help="Don't do anything logs-related")
69 options = parser.parse_args()
71 config = common.read_config(options)
73 if not config['update_stats']:
74 logging.info("Stats are disabled - set \"update_stats = True\" in your config.py")
77 # Get all metadata-defined apps...
78 allmetaapps = [app for app in metadata.read_metadata().itervalues()]
79 metaapps = [app for app in allmetaapps if not app.Disabled]
82 logsdir = os.path.join(statsdir, 'logs')
83 datadir = os.path.join(statsdir, 'data')
84 if not os.path.exists(statsdir):
86 if not os.path.exists(logsdir):
88 if not os.path.exists(datadir):
92 # Get any access logs we don't have...
96 logging.info('Retrieving logs')
97 ssh = paramiko.SSHClient()
98 ssh.load_system_host_keys()
99 ssh.connect(config['stats_server'], username=config['stats_user'],
100 timeout=10, key_filename=config['webserver_keyfile'])
101 ftp = ssh.open_sftp()
102 ftp.get_channel().settimeout(60)
103 logging.info("...connected")
106 files = ftp.listdir()
108 if f.startswith('access-') and f.endswith('.log.gz'):
110 destpath = os.path.join(logsdir, f)
111 destsize = ftp.stat(f).st_size
112 if (not os.path.exists(destpath) or
113 os.path.getsize(destpath) != destsize):
114 logging.debug("...retrieving " + f)
117 traceback.print_exc()
126 knownapks = common.KnownApks()
129 if not options.nologs:
131 logging.info('Processing logs...')
132 appscount = Counter()
133 appsvercount = Counter()
134 logexpr = '(?P<ip>[.:0-9a-fA-F]+) - - \[(?P<time>.*?)\] ' + \
135 '"GET (?P<uri>.*?) HTTP/1.\d" (?P<statuscode>\d+) ' + \
136 '\d+ "(?P<referral>.*?)" "(?P<useragent>.*?)"'
137 logsearch = re.compile(logexpr).search
138 for logfile in glob.glob(os.path.join(logsdir, 'access-*.log.gz')):
139 logging.debug('...' + logfile)
141 # Get the date for this log - e.g. 2012-02-28
142 thisdate = os.path.basename(logfile)[7:-7]
144 agg_path = os.path.join(datadir, thisdate + '.json')
145 if not options.recalc and os.path.exists(agg_path):
146 # Use previously calculated aggregate data
147 with open(agg_path, 'r') as f:
151 # Calculate from logs...
155 'appsver': Counter(),
159 p = subprocess.Popen(["zcat", logfile], stdout=subprocess.PIPE)
160 matches = (logsearch(line) for line in p.stdout)
161 for match in matches:
164 if match.group('statuscode') != '200':
166 if match.group('ip') in config['stats_ignore']:
168 uri = match.group('uri')
169 if not uri.endswith('.apk'):
171 _, apkname = os.path.split(uri)
172 app = knownapks.getapp(apkname)
175 today['apps'][appid] += 1
176 # Strip the '.apk' from apkname
177 appver = apkname[:-4]
178 today['appsver'][appver] += 1
180 if apkname not in today['unknown']:
181 today['unknown'].append(apkname)
183 # Save calculated aggregate data for today to cache
184 with open(agg_path, 'w') as f:
187 # Add today's stats (whether cached or recalculated) to the total
188 for appid in today['apps']:
189 appscount[appid] += today['apps'][appid]
190 for appid in today['appsver']:
191 appsvercount[appid] += today['appsver'][appid]
192 for uk in today['unknown']:
193 if uk not in unknownapks:
194 unknownapks.append(uk)
196 # Calculate and write stats for total downloads...
199 for appid in appscount:
200 count = appscount[appid]
201 lst.append(appid + " " + str(count))
202 if config['stats_to_carbon']:
203 carbon_send('fdroid.download.' + appid.replace('.', '_'),
205 alldownloads += count
206 lst.append("ALL " + str(alldownloads))
207 with open(os.path.join(statsdir, 'total_downloads_app.txt'), 'w') as f:
208 f.write('# Total downloads by application, since October 2011\n')
209 for line in sorted(lst):
213 for appver in appsvercount:
214 count = appsvercount[appver]
215 lst.append(appver + " " + str(count))
217 with open(os.path.join(statsdir, 'total_downloads_app_version.txt'), 'w') as f:
218 f.write('# Total downloads by application and version, '
219 'since October 2011\n')
220 for line in sorted(lst):
223 # Calculate and write stats for repo types...
224 logging.info("Processing repo types...")
225 repotypes = Counter()
227 rtype = app.RepoType or 'none'
228 if rtype == 'srclib':
229 rtype = common.getsrclibvcs(app.Repo)
230 repotypes[rtype] += 1
231 with open(os.path.join(statsdir, 'repotypes.txt'), 'w') as f:
232 for rtype, count in most_common_stable(repotypes):
233 f.write(rtype + ' ' + str(count) + '\n')
235 # Calculate and write stats for update check modes...
236 logging.info("Processing update check modes...")
239 checkmode = app.UpdateCheckMode
240 if checkmode.startswith('RepoManifest/'):
241 checkmode = checkmode[:12]
242 if checkmode.startswith('Tags '):
243 checkmode = checkmode[:4]
245 with open(os.path.join(statsdir, 'update_check_modes.txt'), 'w') as f:
246 for checkmode, count in most_common_stable(ucms):
247 f.write(checkmode + ' ' + str(count) + '\n')
249 logging.info("Processing categories...")
252 for category in app.Categories:
254 with open(os.path.join(statsdir, 'categories.txt'), 'w') as f:
255 for category, count in most_common_stable(ctgs):
256 f.write(category + ' ' + str(count) + '\n')
258 logging.info("Processing antifeatures...")
261 if app.AntiFeatures is None:
263 for antifeature in app.AntiFeatures:
264 afs[antifeature] += 1
265 with open(os.path.join(statsdir, 'antifeatures.txt'), 'w') as f:
266 for antifeature, count in most_common_stable(afs):
267 f.write(antifeature + ' ' + str(count) + '\n')
269 # Calculate and write stats for licenses...
270 logging.info("Processing licenses...")
273 license = app.License
274 licenses[license] += 1
275 with open(os.path.join(statsdir, 'licenses.txt'), 'w') as f:
276 for license, count in most_common_stable(licenses):
277 f.write(license + ' ' + str(count) + '\n')
279 # Write list of disabled apps...
280 logging.info("Processing disabled apps...")
281 disabled = [app.id for app in allmetaapps if app.Disabled]
282 with open(os.path.join(statsdir, 'disabled_apps.txt'), 'w') as f:
283 for appid in sorted(disabled):
284 f.write(appid + '\n')
286 # Write list of latest apps added to the repo...
287 logging.info("Processing latest apps...")
288 latest = knownapks.getlatest(10)
289 with open(os.path.join(statsdir, 'latestapps.txt'), 'w') as f:
291 f.write(appid + '\n')
294 logging.info('\nUnknown apks:')
295 for apk in unknownapks:
298 logging.info("Finished.")
300 if __name__ == "__main__":