3 # stats.py - part of the FDroid server tools
4 # Copyright (C) 2010-13, Ciaran Gultnieks, ciaran@ciarang.com
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU Affero General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU Affero General Public License for more details.
16 # You should have received a copy of the GNU Affero General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
26 from argparse import ArgumentParser
33 from collections import Counter
36 def carbon_send(key, value):
38 s.connect((config['carbon_host'], config['carbon_port']))
39 msg = '%s %d %d\n' % (key, value, int(time.time()))
47 def most_common_stable(counts):
50 pairs.append((s, counts[s]))
51 return sorted(pairs, key=lambda t: (-t[1], t[0]))
56 global options, config
58 # Parse command line...
59 parser = ArgumentParser()
60 common.setup_global_opts(parser)
61 parser.add_argument("-d", "--download", action="store_true", default=False,
62 help="Download logs we don't have")
63 parser.add_argument("--recalc", action="store_true", default=False,
64 help="Recalculate aggregate stats - use when changes "
65 "have been made that would invalidate old cached data.")
66 parser.add_argument("--nologs", action="store_true", default=False,
67 help="Don't do anything logs-related")
68 options = parser.parse_args()
70 config = common.read_config(options)
72 if not config['update_stats']:
73 logging.info("Stats are disabled - set \"update_stats = True\" in your config.py")
76 # Get all metadata-defined apps...
77 allmetaapps = [app for app in metadata.read_metadata().itervalues()]
78 metaapps = [app for app in allmetaapps if not app.Disabled]
81 logsdir = os.path.join(statsdir, 'logs')
82 datadir = os.path.join(statsdir, 'data')
83 if not os.path.exists(statsdir):
85 if not os.path.exists(logsdir):
87 if not os.path.exists(datadir):
91 # Get any access logs we don't have...
95 logging.info('Retrieving logs')
96 ssh = paramiko.SSHClient()
97 ssh.load_system_host_keys()
98 ssh.connect(config['stats_server'], username=config['stats_user'],
99 timeout=10, key_filename=config['webserver_keyfile'])
100 ftp = ssh.open_sftp()
101 ftp.get_channel().settimeout(60)
102 logging.info("...connected")
105 files = ftp.listdir()
107 if f.startswith('access-') and f.endswith('.log.gz'):
109 destpath = os.path.join(logsdir, f)
110 destsize = ftp.stat(f).st_size
111 if (not os.path.exists(destpath) or
112 os.path.getsize(destpath) != destsize):
113 logging.debug("...retrieving " + f)
116 traceback.print_exc()
125 knownapks = common.KnownApks()
128 if not options.nologs:
130 logging.info('Processing logs...')
131 appscount = Counter()
132 appsvercount = Counter()
133 logexpr = '(?P<ip>[.:0-9a-fA-F]+) - - \[(?P<time>.*?)\] ' + \
134 '"GET (?P<uri>.*?) HTTP/1.\d" (?P<statuscode>\d+) ' + \
135 '\d+ "(?P<referral>.*?)" "(?P<useragent>.*?)"'
136 logsearch = re.compile(logexpr).search
137 for logfile in glob.glob(os.path.join(logsdir, 'access-*.log.gz')):
138 logging.debug('...' + logfile)
140 # Get the date for this log - e.g. 2012-02-28
141 thisdate = os.path.basename(logfile)[7:-7]
143 agg_path = os.path.join(datadir, thisdate + '.json')
144 if not options.recalc and os.path.exists(agg_path):
145 # Use previously calculated aggregate data
146 with open(agg_path, 'r') as f:
150 # Calculate from logs...
154 'appsver': Counter(),
158 p = subprocess.Popen(["zcat", logfile], stdout=subprocess.PIPE)
159 matches = (logsearch(line) for line in p.stdout)
160 for match in matches:
163 if match.group('statuscode') != '200':
165 if match.group('ip') in config['stats_ignore']:
167 uri = match.group('uri')
168 if not uri.endswith('.apk'):
170 _, apkname = os.path.split(uri)
171 app = knownapks.getapp(apkname)
174 today['apps'][appid] += 1
175 # Strip the '.apk' from apkname
176 appver = apkname[:-4]
177 today['appsver'][appver] += 1
179 if apkname not in today['unknown']:
180 today['unknown'].append(apkname)
182 # Save calculated aggregate data for today to cache
183 with open(agg_path, 'w') as f:
186 # Add today's stats (whether cached or recalculated) to the total
187 for appid in today['apps']:
188 appscount[appid] += today['apps'][appid]
189 for appid in today['appsver']:
190 appsvercount[appid] += today['appsver'][appid]
191 for uk in today['unknown']:
192 if uk not in unknownapks:
193 unknownapks.append(uk)
195 # Calculate and write stats for total downloads...
198 for appid in appscount:
199 count = appscount[appid]
200 lst.append(appid + " " + str(count))
201 if config['stats_to_carbon']:
202 carbon_send('fdroid.download.' + appid.replace('.', '_'),
204 alldownloads += count
205 lst.append("ALL " + str(alldownloads))
206 with open(os.path.join(statsdir, 'total_downloads_app.txt'), 'w') as f:
207 f.write('# Total downloads by application, since October 2011\n')
208 for line in sorted(lst):
212 for appver in appsvercount:
213 count = appsvercount[appver]
214 lst.append(appver + " " + str(count))
216 with open(os.path.join(statsdir, 'total_downloads_app_version.txt'), 'w') as f:
217 f.write('# Total downloads by application and version, '
218 'since October 2011\n')
219 for line in sorted(lst):
222 # Calculate and write stats for repo types...
223 logging.info("Processing repo types...")
224 repotypes = Counter()
226 rtype = app.RepoType or 'none'
227 if rtype == 'srclib':
228 rtype = common.getsrclibvcs(app.Repo)
229 repotypes[rtype] += 1
230 with open(os.path.join(statsdir, 'repotypes.txt'), 'w') as f:
231 for rtype, count in most_common_stable(repotypes):
232 f.write(rtype + ' ' + str(count) + '\n')
234 # Calculate and write stats for update check modes...
235 logging.info("Processing update check modes...")
238 checkmode = app.UpdateCheckMode
239 if checkmode.startswith('RepoManifest/'):
240 checkmode = checkmode[:12]
241 if checkmode.startswith('Tags '):
242 checkmode = checkmode[:4]
244 with open(os.path.join(statsdir, 'update_check_modes.txt'), 'w') as f:
245 for checkmode, count in most_common_stable(ucms):
246 f.write(checkmode + ' ' + str(count) + '\n')
248 logging.info("Processing categories...")
251 for category in app.Categories:
253 with open(os.path.join(statsdir, 'categories.txt'), 'w') as f:
254 for category, count in most_common_stable(ctgs):
255 f.write(category + ' ' + str(count) + '\n')
257 logging.info("Processing antifeatures...")
260 if app.AntiFeatures is None:
262 for antifeature in app.AntiFeatures:
263 afs[antifeature] += 1
264 with open(os.path.join(statsdir, 'antifeatures.txt'), 'w') as f:
265 for antifeature, count in most_common_stable(afs):
266 f.write(antifeature + ' ' + str(count) + '\n')
268 # Calculate and write stats for licenses...
269 logging.info("Processing licenses...")
272 license = app.License
273 licenses[license] += 1
274 with open(os.path.join(statsdir, 'licenses.txt'), 'w') as f:
275 for license, count in most_common_stable(licenses):
276 f.write(license + ' ' + str(count) + '\n')
278 # Write list of disabled apps...
279 logging.info("Processing disabled apps...")
280 disabled = [app.id for app in allmetaapps if app.Disabled]
281 with open(os.path.join(statsdir, 'disabled_apps.txt'), 'w') as f:
282 for appid in sorted(disabled):
283 f.write(appid + '\n')
285 # Write list of latest apps added to the repo...
286 logging.info("Processing latest apps...")
287 latest = knownapks.getlatest(10)
288 with open(os.path.join(statsdir, 'latestapps.txt'), 'w') as f:
290 f.write(appid + '\n')
293 logging.info('\nUnknown apks:')
294 for apk in unknownapks:
297 logging.info("Finished.")
299 if __name__ == "__main__":