forked from shinken-solutions/shinken
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlink_xen_host_vm.py
More file actions
158 lines (140 loc) · 5.34 KB
/
Copy pathlink_xen_host_vm.py
File metadata and controls
158 lines (140 loc) · 5.34 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# /usr/local/shinken/libexec/link_xen_host_vm.py
# This file is proposed for Shinken to link vm and xenserver.
# Devers Renaud rdevers@chavers.org
#
# Shinken is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Shinken 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Shinken. If not, see <http://www.gnu.org/licenses/>.
import sys
import XenAPI
from string import split
import shutil
import optparse
# Try to load json (2.5 and higer) or simplejson if failed (python2.4)
try:
import json
except ImportError:
# For old Python version, load
# simple json (it can be hard json?! It's 2 functions guy!)
try:
import simplejson as json
except ImportError:
sys.exit("Error: you need the json or simplejson module for this script")
VERSION = '0.1'
# Split and clean the rules from a string to a list
def _split_rules(rules):
return [r.strip() for r in rules.split('|')]
# Apply all rules on the objects names
def _apply_rules(name, rules):
if 'nofqdn' in rules:
name = name.split(' ', 1)[0]
name = name.split('.', 1)[0]
if 'lower' in rules:
name = name.lower()
return name
def create_all_links(res,rules):
r = []
for host in res:
for vm in res[host]:
# First we apply rules on the names
host_name = _apply_rules(host,rules)
vm_name = _apply_rules(vm,rules)
v = (('host', host_name), ('host', vm_name))
r.append(v)
return r
def write_output(path,r):
try:
f = open(path + '.tmp', 'wb')
buf = json.dumps(r)
f.write(buf)
f.close()
shutil.move(path + '.tmp', path)
print "File %s wrote" % path
except IOError, exp:
sys.exit("Error writing the file %s: %s" % (path, exp))
def con_poolmaster(xs, user, password):
try:
s = XenAPI.Session("http://%s" % xs)
s.xenapi.login_with_password(user,password)
return s
except XenAPI.Failure, msg:
if msg.details[0] == "HOST_IS_SLAVE":
host = msg.details[1]
s = XenAPI.Session("http://%s" % host)
s.xenapi.login_with_password(user, password)
return s
else:
print "Error: pool con:", xs, sys.exc_info()[0]
pass
except Exception:
print "Error: pool con:", xs, sys.exc_info()[0]
pass
return None
def main(output, user, password, rules, xenserver):
res = {}
for xs in xenserver:
try:
s = con_poolmaster(xs, user, password)
vms = s.xenapi.VM.get_all()
for vm in vms:
record = s.xenapi.VM.get_record(vm)
if not(record["is_a_template"]) and not(record["is_control_domain"]):
vhost = s.xenapi.VM.get_resident_on(vm)
if vhost != "OpaqueRef:NULL":
host = s.xenapi.host.get_hostname(vhost)
vm_name = s.xenapi.VM.get_name_label(vm)
if host in res.keys():
res[host].append(vm_name)
else:
res[host] = [vm_name]
s.xenapi.session.logout()
except Exception:
pass
r = create_all_links(res,rules)
print "Created %d links" % len(r)
write_output(output, r)
print "Finished!"
if __name__ == "__main__":
# Manage the options
parser = optparse.OptionParser(
version="Shinken XenServer/XCP links dumping script version %s" % VERSION)
parser.add_option("-o", "--output",
default='/tmp/xen_mapping_file.json',
help="Path of the generated mapping file.")
parser.add_option("-u", "--user",
help="User name to connect to this Vcenter")
parser.add_option("-p", "--password",
help="The password of this user")
parser.add_option('-r', '--rules', default='',
help="Rules of name transformation. Valid names are: "
"`lower`: to lower names, "
"`nofqdn`: keep only the first name (server.mydomain.com -> server)."
"You can use several rules like `lower|nofqdn`")
parser.add_option('-x','--xenserver',action="append",
help="multiple ip/fqdn of your XenServer/XCP poll master (or member). "
"ex: -x poolmaster1 -x poolmaster2 -x poolmaster3 "
"If pool member was use, the poll master was found")
opts, args = parser.parse_args()
if args:
parser.error("does not take any positional arguments")
if opts.user is None:
parser.error("missing -u or --user option for the pool master username")
if opts.password is None:
error = True
parser.error("missing -p or --password option for the pool master password")
if opts.output is None:
parser.error("missing -o or --output option for the output mapping file")
if opts.xenserver is None:
parser.error("missing -x or --xenserver option for pool master list")
main(**opts.__dict__)