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
32 def carbon_send(key, value):
34 s.connect((config['carbon_host'], config['carbon_port']))
35 msg = '%s %d %d\n' % (key, value, int(time.time()))
43 # Read configuration...
44 common.read_config(config)
46 if not config['update_stats']:
47 print "Stats are disabled - check your configuration"
50 # Parse command line...
51 parser = OptionParser()
52 parser.add_option("-v", "--verbose", action="store_true", default=False,
53 help="Spew out even more information than normal")
54 parser.add_option("-d", "--download", action="store_true", default=False,
55 help="Download logs we don't have")
56 (options, args) = parser.parse_args()
58 # Get all metadata-defined apps...
59 metaapps = common.read_metadata(options.verbose)
62 logsdir = os.path.join(statsdir, 'logs')
63 datadir = os.path.join(statsdir, 'data')
64 if not os.path.exists(statsdir):
66 if not os.path.exists(logsdir):
68 if not os.path.exists(datadir):
72 # Get any access logs we don't have...
76 print 'Retrieving logs'
77 ssh = paramiko.SSHClient()
78 ssh.load_system_host_keys()
79 ssh.connect('f-droid.org', username='fdroid', timeout=10,
80 key_filename=config['webserver_keyfile'])
82 ftp.get_channel().settimeout(60)
88 if f.startswith('access-') and f.endswith('.log.gz'):
90 destpath = os.path.join(logsdir, f)
91 destsize = ftp.stat(f).st_size
92 if (not os.path.exists(destpath) or
93 os.path.getsize(destpath) != destsize):
94 print "...retrieving " + f
108 print 'Processing logs...'
109 logexpr = '(?P<ip>[.:0-9a-fA-F]+) - - \[(?P<time>.*?)\] "GET (?P<uri>.*?) HTTP/1.\d" (?P<statuscode>\d+) \d+ "(?P<referral>.*?)" "(?P<useragent>.*?)"'
110 logsearch = re.compile(logexpr).search
113 knownapks = common.KnownApks()
114 for logfile in glob.glob(os.path.join(logsdir,'access-*.log.gz')):
116 print '...' + logfile
117 logdate = logfile[len(logsdir) + 1 + len('access-'):-7]
118 p = subprocess.Popen(["zcat", logfile], stdout = subprocess.PIPE)
119 matches = (logsearch(line) for line in p.stdout)
120 for match in matches:
121 if match and match.group('statuscode') == '200':
122 uri = match.group('uri')
123 if uri.endswith('.apk'):
124 _, apkname = os.path.split(uri)
125 app = knownapks.getapp(apkname)
133 if not apkname in unknownapks:
134 unknownapks.append(apkname)
136 # Calculate and write stats for total downloads...
139 for app, count in apps.iteritems():
140 lst.append(app + " " + str(count))
141 if config['stats_to_carbon']:
142 carbon_send('fdroid.download.' + app.replace('.', '_'), count)
143 alldownloads += count
144 lst.append("ALL " + str(alldownloads))
145 f = open('stats/total_downloads_app.txt', 'w')
146 f.write('# Total downloads by application, since October 2011\n')
147 for line in sorted(lst):
151 # Calculate and write stats for repo types...
154 if len(app['Repo Type']) == 0:
157 if app['Repo Type'] == 'srclib':
158 rtype = common.getsrclibvcs(app['Repo'])
160 rtype = app['Repo Type']
161 if rtype in repotypes:
162 repotypes[rtype] += 1;
165 f = open('stats/repotypes.txt', 'w')
166 for rtype, count in repotypes.iteritems():
167 f.write(rtype + ' ' + str(count) + '\n')
170 # Calculate and write stats for update check modes...
173 checkmode = app['Update Check Mode'].split('/')[0]
174 if checkmode in ucms:
175 ucms[checkmode] += 1;
178 f = open('stats/update_check_modes.txt', 'w')
179 for checkmode, count in ucms.iteritems():
180 f.write(checkmode + ' ' + str(count) + '\n')
185 if app['Categories'] is None:
187 categories = [c.strip() for c in app['Categories'].split(',')]
188 for category in categories:
193 f = open('stats/categories.txt', 'w')
194 for category, count in ctgs.iteritems():
195 f.write(category + ' ' + str(count) + '\n')
200 if app['AntiFeatures'] is None:
202 antifeatures = [a.strip() for a in app['AntiFeatures'].split(',')]
203 for antifeature in antifeatures:
204 if antifeature in afs:
205 afs[antifeature] += 1;
208 f = open('stats/antifeatures.txt', 'w')
209 for antifeature, count in afs.iteritems():
210 f.write(antifeature + ' ' + str(count) + '\n')
214 # Calculate and write stats for licenses...
217 license = app['License']
218 if license in licenses:
219 licenses[license] += 1;
221 licenses[license] = 1
222 f = open('stats/licenses.txt', 'w')
223 for license, count in licenses.iteritems():
224 f.write(license + ' ' + str(count) + '\n')
227 # Write list of latest apps added to the repo...
228 latest = knownapks.getlatest(10)
229 f = open('stats/latestapps.txt', 'w')
234 if len(unknownapks) > 0:
235 print '\nUnknown apks:'
236 for apk in unknownapks:
241 if __name__ == "__main__":