~bladernr/maas-cert-server/foo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
#!/usr/bin/env python3

import argparse
import sys
import os
import logging
import shutil
from subprocess import Popen, PIPE, TimeoutExpired, STDOUT

def check_dirs(path,dirs):
    ''' Make sure our requested directories exist in the library.
    if not, then we create them and return a list of full paths.'''
    logging.debug('Checking the library to make sure all necessary '
                  'directories exist...')
    for dir in dirs:
        fullpath = os.path.join(path,"mirror",dir)
        if not os.path.isdir(fullpath):
            logging.warning("%s does not exist. Creating it..." % fullpath)
            try:
                os.mkdir(fullpath)
            except OSError as e:
                logging.error('Unable to create %s... aborting.' % fullpath)
                logging.error(e)
                return 1
    logging.debug('OK!')

def sync_isos(url_list,target_dir):
    ''' sync the ISOs using zsync '''
    logging.info('Preparing to sync isos...')
    # make sure zsync is installed
    if not shutil.which('zsync',mode=os.X_OK):
        logging.error('zsync is not installed. Please install it before '
                      'using this script.')
        return 1
    # sadly, zsync needs to be in the target dir :(
    current_dir = os.getcwd()
    logging.debug('CWD: %s' % current_dir)
    logging.debug('Moving to: %s' % target_dir)
    os.chdir(target_dir)
    logging.debug('CWD: %s' % os.getcwd())
    for url in url_list:
        logging.debug('Beginning sync of %s' % url)
        cmd = ['zsync', url]
        out = 'uninitiated'
        err = 'uninitiated'
        try:
            zsync_process = Popen(cmd, stdout=PIPE, stderr=PIPE,
                                  universal_newlines=True)
            #while zsync_process.poll() is None:
            #    l = zsync_process.stdout.readline()
            #    print(l)
            err = zsync_process.communicate(timeout=1200)[1]
        except TimeoutExpired:
            logging.error('Zsync seems to have stalled')
            logging.error('Unable to sync %s' % url)
        except:
            logging.error('Unable to sync %s' % url)
            logging.error('STDERR:')
            logging.error(err)
        logging.info('Completed sync of %s' % url)
    logging.debug('Moving back to %s' % current_dir)
    os.chdir(current_dir)
    logging.debug('CWD: %s' % os.getcwd())

def sync_archive(archive,config_file):
    ''' sync the package archives.  Requires presence of apt-mirror and
    appropriate config files'''
    logging.info('Preparing to sync %s package archive' % archive)
    # make sure apt-mirror is installed
    if not shutil.which('apt-mirror',mode=os.X_OK):
        logging.error('apt-mirror is not installed.  Please install it before '
                      'using this script.')
        return 1
    # Now we Sync
    cmd = ['apt-mirror', config_file]
    logging.debug('Using config file: %s' % config_file)
    try:
        sync_process = Popen(cmd, stdout=PIPE, stderr=PIPE,
                             universal_newlines=True)
        out,err = sync_process.communicate()
    except:
        logging.error('An error occurred while syncing %s' % archive)
        logging.error('STDERR:')
        logging.error(err)
    logging.debug(out)
    logging.info('Completed sync')

def sync_maas_ephemerals(directory):
    #have to use wget, can't find a better way to sync this one
    logging.info("Starting ephemerals sync")
    logging.debug("Synching to %s" % directory)
    cmd=['sstream-mirror', '-vvv',
         '--keyring', '/usr/share/keyrings/ubuntu-cloudimage-keyring.gpg',
         'https://maas.ubuntu.com/images/ephemeral/releases',
         directory]
    try:
        sync_process = Popen(cmd, stdout=PIPE, stderr=STDOUT,
                             universal_newlines=True) 
        while sync_process.poll() is None:
            l = sync_process.stdout.readline()
            logging.debug(l)
        #out,err = sync_process.communicate()
    except Exception as e:
        logging.error('An error occurred while trying to sync cloud images')
        logging.error(e)

def main():
    parser = argparse.ArgumentParser()
    main_group = parser.add_argument_group(
                       'Main Arguments',
                       'These affect all update items.')
    main_group.add_argument('--all',
                            action='store_true',
                            default=False,
                            help='Choose this option to update EVERYTHING')
    individual_group = parser.add_argument_group(
                       'Individual Updates',
                       'If you don\'t want to update everything...')
    misc_group = parser.add_argument_group('Miscellaneous Options')
    individual_group.add_argument('--dev-isos',
                        action='store_true',
                        default=False,
                        help='Update the Development ISOs')
    individual_group.add_argument('--release-isos',
                        action='store_true',
                        default=False,
                        help='Update the Active Ubuntu ISOs')
    individual_group.add_argument('--old-release-isos',
                        action='store_true',
                        default=False,
                        help='Update the older Ubuntu ISOs')
    individual_group.add_argument('--cloud-archive',
                        action='store_true',
                        default=False,
                        help=('Update the package mirror for'
                              'ubuntu-cloud.archive.canonical.com'))
    individual_group.add_argument('--ubuntu-archive',
                        action='store_true',
                        default=False,
                        help=('Update the package mirror for'
                              'archive.ubuntu.com'))
    individual_group.add_argument('--ubuntu-ports',
                        action='store_true',
                        default=False,
                        help=('Update the mirror for'
                              'ports.ubuntu.com'))
    individual_group.add_argument('--maas-ephemerals',
                        action='store_true',
                        default='False',
                        help=('Update the MAAS ephemeral images via sstream'))
    main_group.add_argument('--path',
                       action='store',
                       default=os.getcwd(),
                       help=('The path to the top level dir where the '
                             'library is stored. This defaults to the current '
                             'working directory. (Currently: %(default)s)'))
    misc_group.add_argument('-v',
                        dest='verbose',
                        action='store_true',
                        default=False,
                        help="Turn on verbose output.")
    args = parser.parse_args()
    
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)

    formatter = logging.Formatter('[%(asctime)s] %(levelname)s: %(message)s',
                                  '%H:%M:%S')
    ch.setFormatter(formatter)
    
    logger.addHandler(ch)

    if args.verbose:
        ch.setLevel(logging.DEBUG)
        logging.debug('Logging set to Maximum Verbosity')
    
    logging.info('Let\'s Rock!')

    # directories we want to populate
    directories = {'dev_isos':'cdimage.ubuntu.com',
                   'release_isos':'releases.ubuntu.com',
                   'old_release_isos': 'old-releases.ubuntu.com'}
    
    # releases we're interested in
    dev_iso_urls = [
        'http://cdimage.ubuntu.com/ubuntu-server/daily/current/trusty-server-i386.iso.zsync',
        'http://cdimage.ubuntu.com/ubuntu-server/daily/current/trusty-server-amd64.iso.zsync',
        'http://cdimage.ubuntu.com/ubuntu-server/precise/daily/current/precise-server-amd64.iso.zsync',
        'http://cdimage.ubuntu.com/ubuntu-server/precise/daily/current/precise-server-i386.iso.zsync']
    release_iso_urls = [
        'http://releases.ubuntu.com/saucy/ubuntu-13.10-server-amd64.iso.zsync',
        'http://releases.ubuntu.com/saucy/ubuntu-13.10-server-i386.iso.zsync',
        'http://releases.ubuntu.com/precise/ubuntu-12.04.4-server-amd64.iso.zsync',
        'http://releases.ubuntu.com/precise/ubuntu-12.04.4-server-i386.iso.zsync']
    old_release_urls = [
        'http://old-releases.ubuntu.com/releases/precise/ubuntu-12.04-server-amd64.iso.zsync',
        'http://old-releases.ubuntu.com/releases/precise/ubuntu-12.04-server-i386.iso.zsync',
        'http://old-releases.ubuntu.com/releases/precise/ubuntu-12.04.1-server-amd64.iso.zsync',
        'http://old-releases.ubuntu.com/releases/precise/ubuntu-12.04.1-server-i386.iso.zsync',
        'http://old-releases.ubuntu.com/releases/precise/ubuntu-12.04.2-server-amd64.iso.zsync',
        'http://old-releases.ubuntu.com/releases/precise/ubuntu-12.04.2-server-i386.iso.zsync',
        'http://old-releases.ubuntu.com/releases/precise/ubuntu-12.04.3-server-amd64.iso.zsync',
        'http://old-releases.ubuntu.com/releases/precise/ubuntu-12.04.3-server-i386.iso.zsync']
    if args.all:
        args.dev_isos = True
        args.release_isos = True
        args.old_release_isos = True
        args.maas_ephemerals = True
        args.cloud_archive = True
        args.ubuntu_archive = True
        args.ubuntu_ports = True

    if args.dev_isos:
        check_dirs(args.path,[dir for dir in directories.values()])
        logging.info('Syncing Development ISOs')
        sync_isos(dev_iso_urls,os.path.join(args.path,'mirror',directories['dev_isos']))
    if args.release_isos:
        logging.info('Syncing Release ISOs')
        sync_isos(release_iso_urls,os.path.join(args.path,'mirror',directories['release_isos']))
    if args.old_release_isos:
        logging.info('Syncing Old Release ISOs')
        sync_isos(old_release_urls,os.path.join(args.path,'mirror',directories['old_release_isos']))
    if args.maas_ephemerals:
        logging.debug('Syncing cloud images')
        directory = os.path.join(args.path,'mirror/maas.ubuntu.com/images/releases')
        sync_maas_ephemerals(directory)
    if args.cloud_archive:
        logging.debug('Syncing the Cloud Archive Packages')
        sync_archive('cloud',os.path.join(args.path,'etc/apt/','cloud-archive-mirror.list'))
    if args.ubuntu_archive:
        logging.debug('Syncing the Ubuntu Package Archive')
        sync_archive('ubuntu',os.path.join(args.path,'etc/apt/','ubuntu-mirror.list'))
    if args.ubuntu_ports:
        logging.debug('Syncing the Ubuntu Ports Archive')
        sync_archive('ubuntu-ports',os.path.join(args.path,'etc/apt/','ports-mirror.list'))

    return 0
    
if __name__ == "__main__":
    sys.exit(main())