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
31 from collections import Counter
34 from . import metadata
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()))
49 def most_common_stable(counts):
52 pairs.append((s, counts[s]))
53 return sorted(pairs, key=lambda t: (-t[1], t[0]))
58 global options, config
60 # Parse command line...
61 parser = ArgumentParser()
62 common.setup_global_opts(parser)
63 parser.add_argument("-d", "--download", action="store_true", default=False,
64 help="Download logs we don't have")
65 parser.add_argument("--recalc", action="store_true", default=False,
66 help="Recalculate aggregate stats - use when changes "
67 "have been made that would invalidate old cached data.")
68 parser.add_argument("--nologs", action="store_true", default=False,
69 help="Don't do anything logs-related")
70 metadata.add_metadata_arguments(parser)
71 options = parser.parse_args()
72 metadata.warnings_action = options.W
74 config = common.read_config(options)
76 if not config['update_stats']:
77 logging.info("Stats are disabled - set \"update_stats = True\" in your config.py")
80 # Get all metadata-defined apps...
81 allmetaapps = [app for app in metadata.read_metadata().values()]
82 metaapps = [app for app in allmetaapps if not app.Disabled]
85 logsdir = os.path.join(statsdir, 'logs')
86 datadir = os.path.join(statsdir, 'data')
87 if not os.path.exists(statsdir):
89 if not os.path.exists(logsdir):
91 if not os.path.exists(datadir):
95 # Get any access logs we don't have...
99 logging.info('Retrieving logs')
100 ssh = paramiko.SSHClient()
101 ssh.load_system_host_keys()
102 ssh.connect(config['stats_server'], username=config['stats_user'],
103 timeout=10, key_filename=config['webserver_keyfile'])
104 ftp = ssh.open_sftp()
105 ftp.get_channel().settimeout(60)
106 logging.info("...connected")
109 files = ftp.listdir()
111 if f.startswith('access-') and f.endswith('.log.gz'):
113 destpath = os.path.join(logsdir, f)
114 destsize = ftp.stat(f).st_size
115 if (not os.path.exists(destpath) or
116 os.path.getsize(destpath) != destsize):
117 logging.debug("...retrieving " + f)
120 traceback.print_exc()
129 knownapks = common.KnownApks()
132 if not options.nologs:
134 logging.info('Processing logs...')
135 appscount = Counter()
136 appsvercount = Counter()
137 logexpr = '(?P<ip>[.:0-9a-fA-F]+) - - \[(?P<time>.*?)\] ' + \
138 '"GET (?P<uri>.*?) HTTP/1.\d" (?P<statuscode>\d+) ' + \
139 '\d+ "(?P<referral>.*?)" "(?P<useragent>.*?)"'
140 logsearch = re.compile(logexpr).search
141 for logfile in glob.glob(os.path.join(logsdir, 'access-*.log.gz')):
142 logging.debug('...' + logfile)
144 # Get the date for this log - e.g. 2012-02-28
145 thisdate = os.path.basename(logfile)[7:-7]
147 agg_path = os.path.join(datadir, thisdate + '.json')
148 if not options.recalc and os.path.exists(agg_path):
149 # Use previously calculated aggregate data
150 with open(agg_path, 'r') as f:
154 # Calculate from logs...
158 'appsver': Counter(),
162 p = subprocess.Popen(["zcat", logfile], stdout=subprocess.PIPE)
163 matches = (logsearch(line) for line in p.stdout)
164 for match in matches:
167 if match.group('statuscode') != '200':
169 if match.group('ip') in config['stats_ignore']:
171 uri = match.group('uri')
172 if not uri.endswith('.apk'):
174 _, apkname = os.path.split(uri)
175 app = knownapks.getapp(apkname)
178 today['apps'][appid] += 1
179 # Strip the '.apk' from apkname
180 appver = apkname[:-4]
181 today['appsver'][appver] += 1
183 if apkname not in today['unknown']:
184 today['unknown'].append(apkname)
186 # Save calculated aggregate data for today to cache
187 with open(agg_path, 'w') as f:
190 # Add today's stats (whether cached or recalculated) to the total
191 for appid in today['apps']:
192 appscount[appid] += today['apps'][appid]
193 for appid in today['appsver']:
194 appsvercount[appid] += today['appsver'][appid]
195 for uk in today['unknown']:
196 if uk not in unknownapks:
197 unknownapks.append(uk)
199 # Calculate and write stats for total downloads...
202 for appid in appscount:
203 count = appscount[appid]
204 lst.append(appid + " " + str(count))
205 if config['stats_to_carbon']:
206 carbon_send('fdroid.download.' + appid.replace('.', '_'),
208 alldownloads += count
209 lst.append("ALL " + str(alldownloads))
210 with open(os.path.join(statsdir, 'total_downloads_app.txt'), 'w') as f:
211 f.write('# Total downloads by application, since October 2011\n')
212 for line in sorted(lst):
216 for appver in appsvercount:
217 count = appsvercount[appver]
218 lst.append(appver + " " + str(count))
220 with open(os.path.join(statsdir, 'total_downloads_app_version.txt'), 'w') as f:
221 f.write('# Total downloads by application and version, '
222 'since October 2011\n')
223 for line in sorted(lst):
226 # Calculate and write stats for repo types...
227 logging.info("Processing repo types...")
228 repotypes = Counter()
230 rtype = app.RepoType or 'none'
231 if rtype == 'srclib':
232 rtype = common.getsrclibvcs(app.Repo)
233 repotypes[rtype] += 1
234 with open(os.path.join(statsdir, 'repotypes.txt'), 'w') as f:
235 for rtype, count in most_common_stable(repotypes):
236 f.write(rtype + ' ' + str(count) + '\n')
238 # Calculate and write stats for update check modes...
239 logging.info("Processing update check modes...")
242 checkmode = app.UpdateCheckMode
243 if checkmode.startswith('RepoManifest/'):
244 checkmode = checkmode[:12]
245 if checkmode.startswith('Tags '):
246 checkmode = checkmode[:4]
248 with open(os.path.join(statsdir, 'update_check_modes.txt'), 'w') as f:
249 for checkmode, count in most_common_stable(ucms):
250 f.write(checkmode + ' ' + str(count) + '\n')
252 logging.info("Processing categories...")
255 for category in app.Categories:
257 with open(os.path.join(statsdir, 'categories.txt'), 'w') as f:
258 for category, count in most_common_stable(ctgs):
259 f.write(category + ' ' + str(count) + '\n')
261 logging.info("Processing antifeatures...")
264 if app.AntiFeatures is None:
266 for antifeature in app.AntiFeatures:
267 afs[antifeature] += 1
268 with open(os.path.join(statsdir, 'antifeatures.txt'), 'w') as f:
269 for antifeature, count in most_common_stable(afs):
270 f.write(antifeature + ' ' + str(count) + '\n')
272 # Calculate and write stats for licenses...
273 logging.info("Processing licenses...")
276 license = app.License
277 licenses[license] += 1
278 with open(os.path.join(statsdir, 'licenses.txt'), 'w') as f:
279 for license, count in most_common_stable(licenses):
280 f.write(license + ' ' + str(count) + '\n')
282 # Write list of disabled apps...
283 logging.info("Processing disabled apps...")
284 disabled = [app.id for app in allmetaapps if app.Disabled]
285 with open(os.path.join(statsdir, 'disabled_apps.txt'), 'w') as f:
286 for appid in sorted(disabled):
287 f.write(appid + '\n')
289 # Write list of latest apps added to the repo...
290 logging.info("Processing latest apps...")
291 latest = knownapks.getlatest(10)
292 with open(os.path.join(statsdir, 'latestapps.txt'), 'w') as f:
294 f.write(appid + '\n')
297 logging.info('\nUnknown apks:')
298 for apk in unknownapks:
301 logging.info("Finished.")
304 if __name__ == "__main__":