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/>.
26 from optparse import OptionParser
30 import common, metadata
31 from common import FDroidPopen
33 def carbon_send(key, value):
35 s.connect((config['carbon_host'], config['carbon_port']))
36 msg = '%s %d %d\n' % (key, value, int(time.time()))
45 global options, config
47 # Parse command line...
48 parser = OptionParser()
49 parser.add_option("-v", "--verbose", action="store_true", default=False,
50 help="Spew out even more information than normal")
51 parser.add_option("-d", "--download", action="store_true", default=False,
52 help="Download logs we don't have")
53 parser.add_option("--nologs", action="store_true", default=False,
54 help="Don't do anything logs-related")
55 (options, args) = parser.parse_args()
57 config = common.read_config(options)
59 if not config['update_stats']:
60 print "Stats are disabled - check your configuration"
63 # Get all metadata-defined apps...
64 metaapps = metadata.read_metadata(options.verbose)
67 logsdir = os.path.join(statsdir, 'logs')
68 datadir = os.path.join(statsdir, 'data')
69 if not os.path.exists(statsdir):
71 if not os.path.exists(logsdir):
73 if not os.path.exists(datadir):
77 # Get any access logs we don't have...
81 print 'Retrieving logs'
82 ssh = paramiko.SSHClient()
83 ssh.load_system_host_keys()
84 ssh.connect('f-droid.org', username='fdroid', timeout=10,
85 key_filename=config['webserver_keyfile'])
87 ftp.get_channel().settimeout(60)
93 if f.startswith('access-') and f.endswith('.log.gz'):
95 destpath = os.path.join(logsdir, f)
96 destsize = ftp.stat(f).st_size
97 if (not os.path.exists(destpath) or
98 os.path.getsize(destpath) != destsize):
99 print "...retrieving " + f
102 traceback.print_exc()
111 knownapks = common.KnownApks()
114 if not options.nologs:
117 print 'Processing logs...'
120 logexpr = '(?P<ip>[.:0-9a-fA-F]+) - - \[(?P<time>.*?)\] "GET (?P<uri>.*?) HTTP/1.\d" (?P<statuscode>\d+) \d+ "(?P<referral>.*?)" "(?P<useragent>.*?)"'
121 logsearch = re.compile(logexpr).search
122 for logfile in glob.glob(os.path.join(logsdir,'access-*.log.gz')):
124 print '...' + logfile
125 p = FDroidPopen(["zcat", logfile])
126 matches = (logsearch(line) for line in p.stdout)
127 for match in matches:
128 if match and match.group('statuscode') == '200':
129 uri = match.group('uri')
130 if not uri.endswith('.apk'):
132 _, apkname = os.path.split(uri)
133 app = knownapks.getapp(apkname)
140 # Strip the '.apk' from apkname
141 appVer = apkname[:-4]
142 if appVer in appsVer:
147 if not apkname in unknownapks:
148 unknownapks.append(apkname)
150 # Calculate and write stats for total downloads...
153 for app, count in apps.iteritems():
154 lst.append(app + " " + str(count))
155 if config['stats_to_carbon']:
156 carbon_send('fdroid.download.' + app.replace('.', '_'), count)
157 alldownloads += count
158 lst.append("ALL " + str(alldownloads))
159 f = open('stats/total_downloads_app.txt', 'w')
160 f.write('# Total downloads by application, since October 2011\n')
161 for line in sorted(lst):
165 f = open('stats/total_downloads_app_version.txt', 'w')
166 f.write('# Total downloads by application and version, since October 2011\n')
168 for appver, count in appsVer.iteritems():
169 lst.append(appver + " " + str(count))
170 for line in sorted(lst):
174 # Calculate and write stats for repo types...
176 print "Processing repo types..."
179 if len(app['Repo Type']) == 0:
182 if app['Repo Type'] == 'srclib':
183 rtype = common.getsrclibvcs(app['Repo'])
185 rtype = app['Repo Type']
186 if rtype in repotypes:
187 repotypes[rtype] += 1;
190 f = open('stats/repotypes.txt', 'w')
191 for rtype, count in repotypes.iteritems():
192 f.write(rtype + ' ' + str(count) + '\n')
195 # Calculate and write stats for update check modes...
197 print "Processing update check modes..."
200 checkmode = app['Update Check Mode'].split('/')[0]
201 if checkmode in ucms:
202 ucms[checkmode] += 1;
205 f = open('stats/update_check_modes.txt', 'w')
206 for checkmode, count in ucms.iteritems():
207 f.write(checkmode + ' ' + str(count) + '\n')
211 print "Processing categories..."
214 if app['Categories'] is None:
216 categories = [c.strip() for c in app['Categories'].split(',')]
217 for category in categories:
222 f = open('stats/categories.txt', 'w')
223 for category, count in ctgs.iteritems():
224 f.write(category + ' ' + str(count) + '\n')
228 print "Processing antifeatures..."
231 if app['AntiFeatures'] is None:
233 antifeatures = [a.strip() for a in app['AntiFeatures'].split(',')]
234 for antifeature in antifeatures:
235 if antifeature in afs:
236 afs[antifeature] += 1;
239 f = open('stats/antifeatures.txt', 'w')
240 for antifeature, count in afs.iteritems():
241 f.write(antifeature + ' ' + str(count) + '\n')
244 # Calculate and write stats for licenses...
246 print "Processing licenses..."
249 license = app['License']
250 if license in licenses:
251 licenses[license] += 1;
253 licenses[license] = 1
254 f = open('stats/licenses.txt', 'w')
255 for license, count in licenses.iteritems():
256 f.write(license + ' ' + str(count) + '\n')
259 # Write list of latest apps added to the repo...
261 print "Processing latest apps..."
262 latest = knownapks.getlatest(10)
263 f = open('stats/latestapps.txt', 'w')
269 print '\nUnknown apks:'
270 for apk in unknownapks:
275 if __name__ == "__main__":