-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathopenvz
276 lines (240 loc) · 9.48 KB
/
openvz
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2013, Ilya Rusalowski <[email protected]>
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software. If not, see <http://www.gnu.org/licenses/>.
#
DOCUMENTATION = '''
---
module: openvz
short_description: Manages openvz virtual machines
description:
- Manage openvz vms.
Most options accept the same values as corresponding vzctl options.
Not all commands and parameters implemented now, see sources.
options:
command:
description:
- command to run on vz host machine
required: true
default: null
choises: ['create', 'destroy', 'mount', 'umount', 'stop', 'restart',
'status', 'start', 'create', 'set', 'exec', 'exec2']
create_magic:
description:
- If command is C(create), some default parameters will be applied and C(vzctl set) will be called after C(vzctl create).
If C(name) and/or C(ipadd) is not set, ipadd = getaddrinfo(hostname), name = hostname.
If C(ctid) is not set, it will be set to max ctid from C(vzlist -a) output.
See C(CREATE_DEFAULTS) for other default options.
exec_cmd:
description:
- If command is C(exec) or C(exec2), C(exec_cmd) will be executed in container as C(vzctl <ctid> exec <exec_cmd>).
examples:
- code: openvz command=create hostname=vm1.example.com
description: Create new vm with C(ctid) = C(max(vzlist -a ...)), C(ip) = C(host -t a hostname) (will fail if dns is not properly configured), C(name) = C(hostname). See C(CREATE_DEFAULTS) for default values of C(ostemplate), C(nameservers), ...
- code: openvz command=create ctid=42 hostname=vm1.example.com create_magic=no
description: Just call C(vzctl create 42 --hostname=vm1.example.com). C(ctid) must be specified in case of C(create_magic=no).
'''
import socket
VZCTL_SIMPLE_COMMANDS = [
'destroy', 'mount', 'umount', 'stop', 'restart', 'status', 'start',
]
VZCTL_COMMANDS = [
'create', 'set', 'exec', 'exec2',
]
VZCTL_COMMANDS.extend(VZCTL_SIMPLE_COMMANDS)
CREATE_DEFAULTS = {
'ostemplate': 'ubuntu-12.04-x86_64',
'ram': '512M',
'swap': '0M',
'nameserver': '77.88.8.8 8.8.8.8',
'searchdomain': 'yandex.ru yandex.net',
'onboot': 'yes',
'diskspace': '10G:10G',
}
DEFAULTS = {
'ifname': 'eth0',
}
module = None
# Helpers
def get_free_ctid_or_die():
if module.params['ctid']:
return module.params['ctid']
rc, vzlist, vzlist_err = module.run_command('vzlist -Hajo ctid')
if rc != 0:
module.fail_json(
msg='CTID not specified, unable to determine it automatically',
vzlist_err=vzlist_err
)
vzlist = sorted(map(lambda k: k[u'ctid'], module.from_json(vzlist)))
if not vzlist: vzlist = [0]
return vzlist[-1] + 1
def get_ipadd_or_die():
ip = module.params['ipadd']
if ip:
return ip
if hostname:
try:
res = socket.getaddrinfo(hostname, None, socket.AF_INET)
return res[0][4][0]
except:
pass
module.fail_json(
msg='IP address not specified or cannot be derived from hostname'
)
def simple_run_or_die(cmd, msg=None):
if not msg: msg = 'Command exited with a non-zero status'
rc, stdout, stderr = module.run_command(cmd)
if rc != 0:
module.fail_json(msg=msg, stdout=stdout, stderr=stderr, cmd=cmd)
return stdout
def vz_simple_run_and_exit(cmd=None, check_rc=True):
params = module.params
if not params['ctid']:
module.fail_json(msg='CTID not specified')
cmd_base = "vzctl \'%s\' \'%s\'" % (params['command'], params['ctid'])
if cmd:
cmd = cmd_base + ' ' + cmd
rc, stdout, stderr = module.run_command(cmd, check_rc=check_rc)
module.exit_json(changed=True, ctid=params['ctid'], cmd=cmd,
stdout=stdout,
stderr=stderr,
)
def netif_str_to_dict(netif_str):
netif_dict = {}
for s in netif_str.split(';'):
d = dict([x.split("=", 1) for x in s.split(",")])
ifname = d['ifname']
netif_dict[ifname] = d
return netif_dict
def netif_dict_to_str(netif_dict):
netif_list = []
for ifname, d in netif_dict.items():
netif_list.append(','.join([k + '=' + v for k, v in d.items()]))
return ';'.join(netif_list)
def read_netif_or_die():
ctid = module.params['ctid']
stdout = simple_run_or_die('grep NETIF /etc/vz/conf/%d.conf' % ctid, \
'Cannot get NETIF from %d config' % ctid)
# todo helper for run_command or die
# todo rewrite vz_create = create + set + netif_change
try:
ret = netif_str_to_dict(stdout.split('=', 1)[1].strip('"\n\r'))
except Exception as e:
module.fail_json(msg='Cannot parse NETIF str', exception=str(e))
return ret
def write_netif_or_die():
ctid = module.params['ctid']
cur_netif = read_netif_or_die()
d = module.params['netif_change']
for k, v in d.items():
cur_netif[d['ifname']][k] = v
netif_str = netif_dict_to_str(cur_netif)
conf = '/etc/vz/conf/%d.conf' % ctid
simple_run_or_die('''sed -i '/^NETIF=.*/d' %s''' % conf, \
'Cannot remove NETIF from %d config' % ctid)
try:
with open(conf, 'a') as f:
f.write('''NETIF="%s"''' % netif_str)
except Exception as e:
module.fail_json(msg='Cannot write NETIF to %s' % conf, \
exception=str(e))
def autofill_vzcreate_params():
params = module.params
params['ctid'] = get_free_ctid_or_die()
if not params['netif_change']:
params['ipadd'] = get_ipadd_or_die()
elif not 'ifname' in params['netif_change']:
params['netif_change']['ifname'] = DEFAULTS['ifname']
if not params['name']:
params['name'] = params['hostname']
for p, v in CREATE_DEFAULTS.items():
if not params[p]:
params[p] = v
# vzctl commands
def vz_create():
params = module.params
if params['create_magic']:
autofill_vzcreate_params()
if not params['ctid']:
module.fail_json(msg='CTID not specified')
if params['netif_change'] and not ('ifname' in params['netif_change'] and params['netif_change']['ifname']):
module.fail_json(msg='ifname not specified in netif_change')
# generate and run commands
cmd = "vzctl create \'%s\'" % (params['ctid'])
for p in ['ostemplate', 'hostname', 'name', 'ipadd', 'diskspace']:
if params[p]:
cmd += " --%s \'%s\'" % (p, params[p])
module.run_command(cmd, check_rc=True)
if not params['create_magic']:
module.exit_json(changed=True, ctid=params['ctid'], cmd=cmd)
# violate standart 'vzctl create' behaviour and 'vzctl set' some params
fin_cmd = [cmd]
cmd = 'vzctl set %s' % (params['ctid'])
for p in ['ram', 'swap', 'nameserver', 'searchdomain', 'onboot']:
if params[p]:
cmd += " --%s \'%s\'" % (p, params[p])
cmd += ' --save'
fin_cmd.append(cmd)
module.run_command(cmd, check_rc=True)
if params['netif_change']:
# let vzctl set some defaults - mac, host_ifname, ...
cmd = 'vzctl set %s --netif_add %s --save' % (params['ctid'], params['netif_change']['ifname'])
fin_cmd.append(cmd)
module.run_command(cmd, check_rc=True)
# and apply differences
write_netif_or_die()
module.exit_json(changed=True, ctid=params['ctid'], cmd=fin_cmd)
def vz_set():
pass
def vz_exec():
if not module.params['exec_cmd']:
module.fail_json(msg='exec_cmd not specified')
vz_simple_run_and_exit(module.params['exec_cmd'])
def vz_exec2():
if not module.params['exec_cmd']:
module.fail_json(msg='exec_cmd not specified')
vz_simple_run_and_exit(module.params['exec_cmd'], False)
def main():
global module
arg_spec = dict(
command = dict(required=True, choises=VZCTL_COMMANDS),
ctid = dict(type='int'),
ostemplate = dict(type='str'),
name = dict(type='str'),
hostname = dict(type='str'),
# use ipadd to create vnet like device or netif_change for veth
ipadd = dict(type='str'),
# use it like netif_change="[ifname=<...>],[mac=<...>],
# [host_ifname=<...>],[host_mac=<...>],[bridge=<...>]"
# ifname defaults to eth0
# if there is no NETIF devices yet, <ifname> will be created
# all params except bridge will be autogenerated
netif_change = dict(type='dict'),
exec_cmd = dict(type='str'),
ram = dict(type='str'),
swap = dict(type='str'),
nameserver = dict(type='str'),
searchdomain = dict(type='str'),
onboot = dict(choises=['yes', 'no']),
diskspace = dict(type='str'),
create_magic = dict(default='yes', type='bool'),
)
module = AnsibleModule(argument_spec = arg_spec)
if module.params['command'] in VZCTL_SIMPLE_COMMANDS:
simple_run_and_exit()
globals()['vz_' + module.params['command']]()
# include magic from lib/ansible/module_common.py
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
main()