summaryrefslogtreecommitdiffstats
path: root/ansible/start-prov-boot.py
blob: ed183f13359d66dd9d745966a3ed3d5df92bcd04 (plain)
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
#!/usr/bin/python -tt
#written by skvidal@fedoraproject.org
# (c) 2012, Red Hat, Inc
# GPLv2+

import sys
import socket
from socket import gaierror
import ansible
import ansible.runner
import ansible.playbook
import time
from ansible import callbacks
from pprint import pprint
import optparse

def get_ans_results(results, hostname):
    if hostname in results['dark']:
        return results['dark'][hostname]
    if hostname in results['contacted']:
        return results['contacted'][hostname]
    
    return {}

def confirm():
    ans = raw_input()
    if ans.lower() == 'yes':
        return True
    return False
    
def check_for_ans_error(results, hostname, err_codes=[], success_codes=[0], 
                             return_on_error=['stdout', 'stderr']):
    # returns True or False + dict
    # dict includes 'msg'
    # may include 'rc', 'stderr', 'stdout' and any other
    # requested result codes
    err_results = {}
    
    if 'dark' in results and hostname in results['dark']:
        err_results['msg'] = "Error: Could not contact/connect to %s." % hostname
        return (True, err_results)
    
    error = False

    if err_codes or success_codes:
        if hostname in results['contacted']:
            if 'rc' in results['contacted'][hostname]:
                rc = int(results['contacted'][hostname]['rc'])
                err_results['rc'] = rc
                # check for err codes first
                if rc in err_codes:
                    error = True
                    err_results['msg'] = 'rc %s matched err_codes' % rc
                elif rc not in success_codes:
                    error = True
                    err_results['msg'] = 'rc %s not in success_codes' % rc
            elif 'failed' in results['contacted'][hostname] and results['contacted'][hostname]['failed']:
                error = True
                err_results['msg'] = 'results included failed as true'
                 
        if error:
            for item in return_on_error:
                if item in results['contacted'][hostname]:
                    err_results[item] = results['contacted'][hostname][item]
                    
    return error, err_results

def vm_is_defined(conn, vm, vmhost):
    # get list of vms
    conn.module_name = 'virt'
    conn.module_args = 'command=list_vms'
    results = get_ans_results(conn.run(), vmhost)
    # if vm is in in there
    if vm in results.get('list_vms', []):
        return True
    return False
    

def vm_is_alive(conn, vm, vmhost):
    if not vm_is_defined(conn, vm, vmhost):
        return False
    conn.module_name = 'virt'
    conn.module_args = 'command=status guest=%s' % vm
    results = get_ans_results(conn.run(), vmhost)
    if results.get('status', None)  == 'running':
        return True

    return False

def wait_for_host(hn, timeout=300):
    # watch for that host ssh to come up
    conn = ansible.runner.Runner(host_list=[hn], pattern=hn)
    is_up = False
    start = time.time()
    while not is_up:
        if time.time() - start >= timeout:
            raise Exception, "Hit Timeout waiting for %s to boot" % hn
        conn.module_name='ping'
        res = get_ans_results(conn.run(), hn)
        if res.get('ping'):
            is_up=True
        else:
            time.sleep(2)
        



def parse_args(args):
    parser = optparse.OptionParser('\nnewbuilder [options] buildvm buildvmhost]')
    parser.add_option('-s', default='50G', dest='lvm_size',
                    help='size of lv for vm: %default')
    parser.add_option('-m', default='4096', dest='memsize',
                    help='size of memory for vm: %default')
    parser.add_option('-n', default='4', dest='numcpus',
                    help='num of vcpus for vm: %default')
    parser.add_option('-k', default='http://myhost.org/ks/my_ks.cfg', dest='ks',
                    help='url to kickstart to use for install: %default')
    parser.add_option('-r', default='http://myhost.org/repo/6-x86_64/', dest='repo',
                    help='url of repo to use for install: %default')
    parser.add_option('--nm', default='255.255.255.0', dest='netmask',
                    help='netmask to use for kickstart: %default')
    parser.add_option('--gw', default='10.1.1.1', dest='gw',
                    help='gw to use for kickstart: %default')
    parser.add_option('--dns', default='10.1.1.2', dest='dns',
                    help='dns server to use for kickstart: %default')
    parser.add_option('--vg', default='/dev/vg_host01', dest='vg',
                    help='path to volumegroup to use on vmhost for vm disk: %default')
    parser.add_option('--postinst-play', default='playbooks/postinstall.yml', dest='postinst_play',
                    help='relative path to postinstall playbook to execute on vm: %default')
    parser.add_option('--reboot-play', default='playbooks/reboot.yml', dest='reboot_play',
                    help='relative path to reboot playbook to execute on vm: %default')
    parser.add_option('-y', '--yes', default=False, dest='yes', action="store_true",
                    help='Do not confirm any of the destructive actions - just do them')

    opts, args = parser.parse_args(args)

    if len(args) != 2:
        print 'usage:\n   newbuilder [options] buildvm buildvmhost\n\n'
        sys.exit(1)


    return opts, args



def main():

    opts, args = parse_args(sys.argv[1:])
    # args
    vm = args[0]
    vmhost = args[1]


    try:
        ip = socket.gethostbyname(vm)
    except gaierror,e:
        print 'Could not find ip for %s' % vm
        return 1

    if vm.find('.') == -1:
        print '%s was not a fqdn, cmon!' % vm
        return 1
           
    s_vm = vm.split('.')[0]

    # FIXME check out the vmhost to make sure it is a vmhost
    # error out if it is not
    vmhost_conn = ansible.runner.Runner(host_list=[vmhost], pattern=vmhost)
        
    print 'Checking for %s' % vm

    if vm_is_defined(vmhost_conn, vm, vmhost):
        if vm_is_alive(vmhost_conn, vm, vmhost):
            if not opts.yes:
                print "%s is running. Okay to Destroy? ('yes' to confirm): " % vm,
                if not confirm():
                    print 'Exiting on user input'
                    return 1
                
            # destroy it
            vmhost_conn.module_args = "command=destroy guest=%s" % vm
            err, err_res = check_for_ans_error(vmhost_conn.run(), vmhost)
            if err:
                print 'Error destroying %s on %s' % (vm, vmhost)
                print err_res
                return 1
                
        # undefine it
        if not opts.yes:
            print "%s is defined. Okay to Undefine? ('yes' to confirm): " % vm,
            if not confirm():
                print 'Exiting on user input'
                return 1
        
        vmhost_conn.module_args = "command=undefine guest=%s" % vm
        err, err_res = check_for_ans_error(vmhost_conn.run(), vmhost)
        if err:
            print 'Error undefining %s on %s' % (vm, vmhost)
            print err_res
            return 1

    # check for the lv being allocated already
    lv_check = '/sbin/lvs %s/%s --noheadings' % (opts.vg, s_vm)
    vmhost_conn.module_name='command'
    vmhost_conn.module_args=lv_check
    results = get_ans_results(vmhost_conn.run(), vmhost)
    if 'rc' not in results:
        print 'Could not talk to vmhost about disks'
        return 1

    if results['rc'] == 0:
        print 'Removing old disk: %s/%s' % (opts.vg, s_vm)
        # lvremove its disk
        lvrm='/sbin/lvremove -f %s/%s' % (opts.vg, s_vm)
        vmhost_conn.module_name='command'   
        vmhost_conn.module_args=lvrm
        results = get_ans_results(vmhost_conn.run(), vmhost)
        if results.get('rc', None) != 0:
            print "Could not remove lv for old vm %s" % vm
            print results
            return 1


     
    # lvcreate it 
    print 'Creating %s LV at %s/%s' % (opts.lvm_size, opts.vg, s_vm)
    lvcreate = '/sbin/lvcreate -L %s -n %s %s' % (opts.lvm_size, s_vm, opts.vg)
    vmhost_conn.module_name='command'
    vmhost_conn.module_args=lvcreate
    results = get_ans_results(vmhost_conn.run(), vmhost)
    if results.get('rc', None) != 0:
        print "Could not create lv for new vm %s"
        print results
        return 1
       


    ks_start = time.time()
    # do the virt-install 
    inst_cmd = """/usr/bin/virt-install -n %s -r %s \
     --disk %s/%s --vcpus=%s  -l %s -x "ksdevice=eth0 ks=%s ip=%s netmask=%s gateway=%s dns=%s console=tty0 console=ttyS0" \
     --network=bridge=br0 --network=bridge=br1 --vnc --noautoconsole""" % (vm, opts.memsize, opts.vg, 
                             s_vm, opts.numcpus, opts.repo, opts.ks, ip, opts.netmask, opts.gw, opts.dns)
    print 'running on %s' % vmhost
    print '%r' % inst_cmd
    vmhost_conn.module_name='command'
    vmhost_conn.module_args=inst_cmd
    err, err_res = check_for_ans_error(vmhost_conn.run(), vmhost)
    if err:
        print 'Error starting install of %s on %s' % (vm, vmhost)
        print err_res
        return 1

    # watch vmhost for vm to not be running 
    print 'Waiting for kickstart to complete.',
    time.sleep(1)
    while vm_is_alive(vmhost_conn, vm, vmhost):
        time.sleep(10)
        print '.',

    print 'Kicked!'   

    print 'Finished, kicking the vm: took %d seconds' % (time.time() - ks_start)

    # set vm autostart
    vmhost_conn.module_name='virt'
    vmhost_conn.module_args='command=start guest=%s' % vm
    err, err_res = check_for_ans_error(vmhost_conn.run(), vmhost)
    if err:
        print 'Error setting start of %s on %s' % (vm, vmhost)
        print err_res
        return 1   


    # start vm
    vmhost_conn.module_args='command=autostart guest=%s' % vm
    err, err_res = check_for_ans_error(vmhost_conn.run(), vmhost)
    if err:
        print 'Error setting autostart of %s on %s' % (vm, vmhost)
        print err_res
        print 'continuing'


    print 'Waiting for host to boot'
    try:
        wait_for_host(vm)
    except Exception, e:
        print e
        return 1
        
    print 'Booted'

    pl_start = time.time()
    # once up  run the postinstall playbook on the 
    for thisplay in (opts.postinst_play, opts.reboot_play):
        stats = callbacks.AggregateStats()
        playbook_cb = callbacks.PlaybookCallbacks(verbose=False)
        runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=False)
        play = ansible.playbook.PlayBook(host_list=[vm], stats=stats, playbook=thisplay, 
                 callbacks=playbook_cb, runner_callbacks=runner_cb)
        play.run()

        pprint(play.stats.summarize(vm))

    print 'Playbooks finished time was: %d' % (time.time()-pl_start)
    print 'Waiting for it to come back up'
    try:
        wait_for_host(vm)
    except Exception, e:
        print e
        return 1

    print '%s is now ready for use' % vm
    return 0




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