chiark / gitweb /
server update: mkdir 'archive' if it does not exist
[fdroidserver.git] / fdroidserver / server.py
1 #!/usr/bin/env python2
2 # -*- coding: utf-8 -*-
3 #
4 # server.py - part of the FDroid server tools
5 # Copyright (C) 2010-13, Ciaran Gultnieks, ciaran@ciarang.com
6 #
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.
11 #
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.
16 #
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/>.
19
20 import sys
21 import hashlib
22 import os
23 import subprocess
24 from optparse import OptionParser
25 import logging
26 import common
27
28 config = None
29 options = None
30
31
32 def update_awsbucket(repo_section):
33     '''
34     Upload the contents of the directory `repo_section` (including
35     subdirectories) to the AWS S3 "bucket". The contents of that subdir of the
36     bucket will first be deleted.
37
38     Requires AWS credentials set in config.py: awsaccesskeyid, awssecretkey
39     '''
40
41     import libcloud.security
42     libcloud.security.VERIFY_SSL_CERT = True
43     from libcloud.storage.types import Provider, ContainerDoesNotExistError
44     from libcloud.storage.providers import get_driver
45
46     if not config.get('awsaccesskeyid') or not config.get('awssecretkey'):
47         logging.error('To use awsbucket, you must set awssecretkey and awsaccesskeyid in config.py!')
48         sys.exit(1)
49     awsbucket = config['awsbucket']
50
51     cls = get_driver(Provider.S3)
52     driver = cls(config['awsaccesskeyid'], config['awssecretkey'])
53     try:
54         container = driver.get_container(container_name=awsbucket)
55     except ContainerDoesNotExistError:
56         container = driver.create_container(container_name=awsbucket)
57         logging.info('Created new container "' + container.name + '"')
58
59     upload_dir = 'fdroid/' + repo_section
60     objs = dict()
61     for obj in container.list_objects():
62         if obj.name.startswith(upload_dir + '/'):
63             objs[obj.name] = obj
64
65     for root, _, files in os.walk(os.path.join(os.getcwd(), repo_section)):
66         for name in files:
67             upload = False
68             file_to_upload = os.path.join(root, name)
69             object_name = 'fdroid/' + os.path.relpath(file_to_upload, os.getcwd())
70             if object_name not in objs:
71                 upload = True
72             else:
73                 obj = objs.pop(object_name)
74                 if obj.size != os.path.getsize(file_to_upload):
75                     upload = True
76                 else:
77                     # if the sizes match, then compare by MD5
78                     md5 = hashlib.md5()
79                     with open(file_to_upload, 'rb') as f:
80                         while True:
81                             data = f.read(8192)
82                             if not data:
83                                 break
84                             md5.update(data)
85                     if obj.hash != md5.hexdigest():
86                         s3url = 's3://' + awsbucket + '/' + obj.name
87                         logging.info(' deleting ' + s3url)
88                         if not driver.delete_object(obj):
89                             logging.warn('Could not delete ' + s3url)
90                         upload = True
91
92             if upload:
93                 logging.debug(' uploading "' + file_to_upload + '"...')
94                 extra = {'acl': 'public-read'}
95                 if file_to_upload.endswith('.sig'):
96                     extra['content_type'] = 'application/pgp-signature'
97                 elif file_to_upload.endswith('.asc'):
98                     extra['content_type'] = 'application/pgp-signature'
99                 logging.info(' uploading ' + os.path.relpath(file_to_upload)
100                              + ' to s3://' + awsbucket + '/' + object_name)
101                 obj = driver.upload_object(file_path=file_to_upload,
102                                            container=container,
103                                            object_name=object_name,
104                                            verify_hash=False,
105                                            extra=extra)
106     # delete the remnants in the bucket, they do not exist locally
107     while objs:
108         object_name, obj = objs.popitem()
109         s3url = 's3://' + awsbucket + '/' + object_name
110         if object_name.startswith(upload_dir):
111             logging.warn(' deleting ' + s3url)
112             driver.delete_object(obj)
113         else:
114             logging.info(' skipping ' + s3url)
115
116
117 def update_serverwebroot(repo_section):
118     rsyncargs = ['rsync', '--archive', '--delete']
119     if options.verbose:
120         rsyncargs += ['--verbose']
121     if options.quiet:
122         rsyncargs += ['--quiet']
123     if options.identity_file is not None:
124         rsyncargs += ['-e', 'ssh -i ' + options.identity_file]
125     if 'identity_file' in config:
126         rsyncargs += ['-e', 'ssh -i ' + config['identity_file']]
127     indexxml = os.path.join(repo_section, 'index.xml')
128     indexjar = os.path.join(repo_section, 'index.jar')
129     # serverwebroot is guaranteed to have a trailing slash in common.py
130     if subprocess.call(rsyncargs +
131                        ['--exclude', indexxml, '--exclude', indexjar,
132                         repo_section, config['serverwebroot']]) != 0:
133         sys.exit(1)
134     # use stricter checking on the indexes since they provide the signature
135     rsyncargs += ['--checksum']
136     sectionpath = config['serverwebroot'] + repo_section
137     if subprocess.call(rsyncargs + [indexxml, sectionpath]) != 0:
138         sys.exit(1)
139     if subprocess.call(rsyncargs + [indexjar, sectionpath]) != 0:
140         sys.exit(1)
141
142
143 def _local_sync(fromdir, todir):
144     rsyncargs = ['rsync', '--archive', '--one-file-system', '--delete']
145     # use stricter rsync checking on all files since people using offline mode
146     # are already prioritizing security above ease and speed
147     rsyncargs += ['--checksum']
148     if options.verbose:
149         rsyncargs += ['--verbose']
150     if options.quiet:
151         rsyncargs += ['--quiet']
152     logging.debug(' '.join(rsyncargs + [fromdir, todir]))
153     if subprocess.call(rsyncargs + [fromdir, todir]) != 0:
154         sys.exit(1)
155
156
157 def sync_from_localcopy(repo_section, local_copy_dir):
158     logging.info('Syncing from local_copy_dir to this repo.')
159     # trailing slashes have a meaning in rsync which is not needed here, so
160     # remove them all
161     _local_sync(os.path.join(local_copy_dir, repo_section).rstrip('/'),
162                 repo_section.rstrip('/'))
163
164
165 def update_localcopy(repo_section, local_copy_dir):
166     # local_copy_dir is guaranteed to have a trailing slash in main() below
167     _local_sync(repo_section, local_copy_dir)
168
169
170 def main():
171     global config, options
172
173     # Parse command line...
174     parser = OptionParser()
175     parser.add_option("-i", "--identity-file", default=None,
176                       help="Specify an identity file to provide to SSH for rsyncing")
177     parser.add_option("--local-copy-dir", default=None,
178                       help="Specify a local folder to sync the repo to")
179     parser.add_option("--sync-from-local-copy-dir", action="store_true", default=False,
180                       help="Before uploading to servers, sync from local copy dir")
181     parser.add_option("-v", "--verbose", action="store_true", default=False,
182                       help="Spew out even more information than normal")
183     parser.add_option("-q", "--quiet", action="store_true", default=False,
184                       help="Restrict output to warnings and errors")
185     (options, args) = parser.parse_args()
186
187     config = common.read_config(options)
188
189     if len(args) != 1:
190         logging.critical("Specify a single command")
191         sys.exit(1)
192
193     if args[0] != 'init' and args[0] != 'update':
194         logging.critical("The only commands currently supported are 'init' and 'update'")
195         sys.exit(1)
196
197     if config.get('nonstandardwebroot') is True:
198         standardwebroot = False
199     else:
200         standardwebroot = True
201
202     if config.get('serverwebroot'):
203         serverwebroot = config['serverwebroot']
204         host, fdroiddir = serverwebroot.rstrip('/').split(':')
205         repobase = os.path.basename(fdroiddir)
206         if standardwebroot and repobase != 'fdroid':
207             logging.error('serverwebroot does not end with "fdroid", '
208                           + 'perhaps you meant one of these:\n\t'
209                           + serverwebroot.rstrip('/') + '/fdroid\n\t'
210                           + serverwebroot.rstrip('/').rstrip(repobase) + 'fdroid')
211             sys.exit(1)
212
213     if options.local_copy_dir is not None:
214         local_copy_dir = options.local_copy_dir
215     elif config.get('local_copy_dir'):
216         local_copy_dir = config['local_copy_dir']
217     else:
218         local_copy_dir = None
219     if local_copy_dir is not None:
220         fdroiddir = local_copy_dir.rstrip('/')
221         if os.path.exists(fdroiddir) and not os.path.isdir(fdroiddir):
222             logging.error('local_copy_dir must be directory, not a file!')
223             sys.exit(1)
224         if not os.path.exists(os.path.dirname(fdroiddir)):
225             logging.error('The root dir for local_copy_dir "'
226                           + os.path.dirname(fdroiddir)
227                           + '" does not exist!')
228             sys.exit(1)
229         if not os.path.isabs(fdroiddir):
230             logging.error('local_copy_dir must be an absolute path!')
231             sys.exit(1)
232         repobase = os.path.basename(fdroiddir)
233         if standardwebroot and repobase != 'fdroid':
234             logging.error('local_copy_dir does not end with "fdroid", '
235                           + 'perhaps you meant: ' + fdroiddir + '/fdroid')
236             sys.exit(1)
237         if local_copy_dir[-1] != '/':
238             local_copy_dir += '/'
239         local_copy_dir = local_copy_dir.replace('//', '/')
240         if not os.path.exists(fdroiddir):
241             os.mkdir(fdroiddir)
242
243     if not config.get('awsbucket') \
244             and not config.get('serverwebroot') \
245             and local_copy_dir is None:
246         logging.warn('No serverwebroot, local_copy_dir, or awsbucket set!'
247                      + 'Edit your config.py to set at least one.')
248         sys.exit(1)
249
250     repo_sections = ['repo']
251     if config['archive_older'] != 0:
252         repo_sections.append('archive')
253         if not os.path.exists('archive'):
254             os.mkdir('archive')
255
256     if args[0] == 'init':
257         if config.get('serverwebroot'):
258             sshargs = ['ssh']
259             if options.quiet:
260                 sshargs += ['-q']
261             for repo_section in repo_sections:
262                 cmd = sshargs + [host, 'mkdir -p', fdroiddir + '/' + repo_section]
263                 if options.verbose:
264                     # ssh -v produces different output than rsync -v, so this
265                     # simulates rsync -v
266                     logging.info(' '.join(cmd))
267                 if subprocess.call(cmd) != 0:
268                     sys.exit(1)
269     elif args[0] == 'update':
270         for repo_section in repo_sections:
271             if local_copy_dir is not None:
272                 if config['sync_from_local_copy_dir'] and os.path.exists(repo_section):
273                     sync_from_localcopy(repo_section, local_copy_dir)
274                 else:
275                     update_localcopy(repo_section, local_copy_dir)
276             if config.get('serverwebroot'):
277                 update_serverwebroot(repo_section)
278             if config.get('awsbucket'):
279                 update_awsbucket(repo_section)
280
281     sys.exit(0)
282
283 if __name__ == "__main__":
284     main()