build/import: Fix --virtio parameters.
[mclu.git] / mclu_off.py
1 #!/usr/bin/python
2 # mclu (mini cluster)
3 # Copyright (C) 2014 Red Hat Inc.
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18
19 import argparse
20 import os
21 import subprocess
22 import sys
23 import time
24
25 import ansible.inventory
26 import ansible.runner
27
28 import lib
29
30 def cmdline (subparsers):
31     p = subparsers.add_parser (
32         'off',
33         help='power off a node (or nodes)'
34     )
35     p.add_argument (
36         'wildcard',
37         help='node name(s) to be powered off (wildcard may be used)'
38     )
39     p.set_defaults (run=run)
40
41 def run (c, args):
42     inventory = ansible.inventory.Inventory ()
43     inventory.subset (subset_pattern = args.wildcard)
44     nodes = inventory.get_hosts (c['nodes_group'])
45
46     # Check the nodes have no guests.
47     running, _ = lib.get_all_guests (c)
48     for node in nodes:
49         for vm in running.values():
50             if vm['node'] == node.name:
51                 sys.exit ("error: node %s has running guests, migrate them off or stop them first" % node.name)
52
53     # Power them off.
54     runner = ansible.runner.Runner (
55         remote_user = 'root',
56         module_name = 'command',
57         module_args = '/sbin/poweroff',
58         inventory = inventory,
59         pattern = c['nodes_group'],
60     )
61     data = runner.run ()
62
63     # Wait for them to power off.
64     pings = 60
65     runner = ansible.runner.Runner (
66         remote_user = 'root',
67         module_name = 'ping',
68         inventory = inventory,
69         pattern = c['nodes_group'],
70     )
71     while pings > 0:
72         data = runner.run ()
73         if len (data['contacted']) == 0:
74             break
75         pings -= 1
76         time.sleep (1)
77
78     if pings == 0:
79         sys.exit ('warning: some nodes did not power off')