2 # -*- coding: utf-8 -*-
4 # stats.py - part of the FDroid server tools
5 # Copyright (C) 2010-12, 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/>.
28 from optparse import OptionParser
35 def carbon_send(key, value):
37 s.connect((carbon_host, carbon_port))
38 msg = '%s %d %d\n' % (key, value, int(time.time()))
44 # Read configuration...
45 global update_stats, stats_to_carbon
47 stats_to_carbon = False
48 execfile('config.py', globals())
51 print "Stats are disabled - check your configuration"
54 # Parse command line...
55 parser = OptionParser()
56 parser.add_option("-v", "--verbose", action="store_true", default=False,
57 help="Spew out even more information than normal")
58 parser.add_option("-d", "--download", action="store_true", default=False,
59 help="Download logs we don't have")
60 (options, args) = parser.parse_args()
62 # Get all metadata-defined apps...
63 metaapps = common.read_metadata(options.verbose)
66 logsdir = os.path.join(statsdir, 'logs')
67 logsarchivedir = os.path.join(logsdir, 'archive')
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=webserver_keyfile)
87 ftp.get_channel().settimeout(60)
93 if f.startswith('access-') and f.endswith('.log'):
95 destpath = os.path.join(logsdir, f)
96 archivepath = os.path.join(logsarchivedir, f + '.gz')
97 if os.path.exists(archivepath):
98 if os.path.exists(destpath):
99 # Just in case we have it archived but failed to remove
103 destsize = ftp.stat(f).st_size
104 if (not os.path.exists(destpath) or
105 os.path.getsize(destpath) != destsize):
106 print "...retrieving " + f
108 except Exception as e:
109 traceback.print_exc()
119 logexpr = '(?P<ip>[.:0-9a-fA-F]+) - - \[(?P<time>.*?)\] "GET (?P<uri>.*?) HTTP/1.\d" (?P<statuscode>\d+) \d+ "(?P<referral>.*?)" "(?P<useragent>.*?)"'
120 logsearch = re.compile(logexpr).search
123 knownapks = common.KnownApks()
124 for logfile in glob.glob(os.path.join(logsdir,'access-*.log')):
125 logdate = logfile[len(logsdir) + 1 + len('access-'):-4]
126 matches = (logsearch(line) for line in file(logfile))
127 for match in matches:
128 if match and match.group('statuscode') == '200':
129 uri = match.group('uri')
130 if uri.endswith('.apk'):
131 _, apkname = os.path.split(uri)
132 app = knownapks.getapp(apkname)
140 if not apkname in unknownapks:
141 unknownapks.append(apkname)
143 # Calculate and write stats for total downloads...
146 for app, count in apps.iteritems():
147 lst.append(app + " " + str(count))
149 carbon_send('fdroid.download.' + app.replace('.', '_'), count)
150 alldownloads += count
151 lst.append("ALL " + str(alldownloads))
152 f = open('stats/total_downloads_app.txt', 'w')
153 f.write('# Total downloads by application, since October 2011\n')
154 for line in sorted(lst):
158 # Calculate and write stats for repo types...
161 if len(app['Repo Type']) == 0:
164 if app['Repo Type'] == 'srclib':
165 rtype = common.getsrclibvcs(app['Repo'])
167 rtype = app['Repo Type']
168 if rtype in repotypes:
169 repotypes[rtype] += 1;
172 f = open('stats/repotypes.txt', 'w')
173 for rtype, count in repotypes.iteritems():
174 f.write(rtype + ' ' + str(count) + '\n')
177 # Calculate and write stats for update check modes...
180 checkmode = app['Update Check Mode'].split('/')[0]
181 if checkmode in ucms:
182 ucms[checkmode] += 1;
185 f = open('stats/update_check_modes.txt', 'w')
186 for checkmode, count in ucms.iteritems():
187 f.write(checkmode + ' ' + str(count) + '\n')
190 # Calculate and write stats for licenses...
193 license = app['License']
194 if license in licenses:
195 licenses[license] += 1;
197 licenses[license] = 1
198 f = open('stats/licenses.txt', 'w')
199 for license, count in licenses.iteritems():
200 f.write(license + ' ' + str(count) + '\n')
203 # Write list of latest apps added to the repo...
204 latest = knownapks.getlatest(10)
205 f = open('stats/latestapps.txt', 'w')
210 if len(unknownapks) > 0:
211 print '\nUnknown apks:'
212 for apk in unknownapks:
217 if __name__ == "__main__":