Debian Codegraph @

ansible_collections/community/general/tests/unit/plugins/inventory/test_opennebula.py

raw
1 # Copyright (c) 2020, FELDSAM s.r.o. - FeldHost™ <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4 #
5 # The API responses used in these tests were recorded from OpenNebula version 5.10.
6
7 from __future__ import annotations
8
9 import json
10 import os
11 from collections import OrderedDict
12
13 import pytest
14 from ansible import constants as C
15 from ansible.inventory.data import InventoryData
16 from ansible.inventory.manager import InventoryManager
17 from ansible.module_utils.common.text.converters import to_native
18 from ansible_collections.community.internal_test_tools.tests.unit.mock.loader import DictDataLoader
19 from ansible_collections.community.internal_test_tools.tests.unit.mock.path import mock_unfrackpath_noop
20
21 from ansible_collections.community.general.plugins.inventory.opennebula import InventoryModule
22
23 original_exists = os.path.exists
24 original_access = os.access
25
26
27 def exists_mock(path, exists=True):
28 def exists(f):
29 if to_native(f) == path:
30 return exists
31 return original_exists(f)
32
33 return exists
34
35
36 def access_mock(path, can_access=True):
37 def access(f, m, *args, **kwargs):
38 if to_native(f) == path:
39 return can_access
40 return original_access(f, m, *args, **kwargs) # pragma: no cover
41
42 return access
43
44
45 class HistoryEntry:
46 def __init__(self):
47 self.SEQ = "384"
48 self.HOSTNAME = "sam-691-sam"
49 self.HID = "10"
50 self.CID = "0"
51 self.DS_ID = "100"
52 self.VM_MAD = "kvm"
53 self.TM_MAD = "3par"
54 self.ACTION = "0"
55
56
57 class HistoryRecords:
58 def __init__(self):
59 self.HISTORY = [HistoryEntry()]
60
61
62 @pytest.fixture
63 def inventory():
64 r = InventoryModule()
65 r.inventory = InventoryData()
66 return r
67
68
69 def test_verify_file(tmp_path, inventory):
70 file = tmp_path / "foobar.opennebula.yml"
71 file.touch()
72 assert inventory.verify_file(str(file)) is True
73
74
75 def test_verify_file_bad_config(inventory):
76 assert inventory.verify_file("foobar.opennebula.yml") is False
77
78
79 def get_vm_pool_json():
80 with open("tests/unit/plugins/inventory/fixtures/opennebula_inventory.json") as json_file:
81 jsondata = json.load(json_file)
82
83 data = type("pyone.bindings.VM_POOLSub", (object,), {"VM": []})()
84
85 for fake_server in jsondata:
86 data.VM.append(type("pyone.bindings.VMType90Sub", (object,), fake_server)())
87
88 return data
89
90
91 def get_vm_pool():
92 data = type("pyone.bindings.VM_POOLSub", (object,), {"VM": []})()
93
94 vm = type(
95 "pyone.bindings.VMType90Sub",
96 (object,),
97 {
98 "DEPLOY_ID": "one-7157",
99 "ETIME": 0,
100 "GID": 132,
101 "GNAME": "CSApparelVDC",
102 "HISTORY_RECORDS": HistoryRecords(),
103 "ID": 7157,
104 "LAST_POLL": 1632762935,
105 "LCM_STATE": 3,
106 "MONITORING": {},
107 "NAME": "sam-691-sam",
108 "RESCHED": 0,
109 "SNAPSHOTS": [],
110 "STATE": 3,
111 "STIME": 1632755245,
112 "TEMPLATE": OrderedDict(
113 {
114 "NIC": OrderedDict(
115 {
116 "AR_ID": "0",
117 "BRIDGE": "onebr80",
118 "BRIDGE_TYPE": "linux",
119 "CLUSTER_ID": "0",
120 "IP": "172.22.4.187",
121 "MAC": "02:00:ac:16:04:bb",
122 "MTU": "8192",
123 "NAME": "NIC0",
124 "NETWORK": "Private Net CSApparel",
125 "NETWORK_ID": "80",
126 "NETWORK_UNAME": "CSApparelVDC-admin",
127 "NIC_ID": "0",
128 "PHYDEV": "team0",
129 "SECURITY_GROUPS": "0",
130 "TARGET": "one-7157-0",
131 "VLAN_ID": "480",
132 "VN_MAD": "802.1Q",
133 }
134 )
135 }
136 ),
137 "USER_TEMPLATE": OrderedDict(
138 {
139 "HYPERVISOR": "kvm",
140 "INPUTS_ORDER": "",
141 "LOGO": "images/logos/centos.png",
142 "MEMORY_UNIT_COST": "MB",
143 "SCHED_REQUIREMENTS": 'CLUSTER_ID="0"',
144 }
145 ),
146 },
147 )()
148 data.VM.append(vm)
149
150 vm = type(
151 "pyone.bindings.VMType90Sub",
152 (object,),
153 {
154 "DEPLOY_ID": "one-327",
155 "ETIME": 0,
156 "GID": 0,
157 "GNAME": "oneadmin",
158 "HISTORY_RECORDS": [],
159 "ID": 327,
160 "LAST_POLL": 1632763543,
161 "LCM_STATE": 3,
162 "MONITORING": {},
163 "NAME": "zabbix-327",
164 "RESCHED": 0,
165 "SNAPSHOTS": [],
166 "STATE": 3,
167 "STIME": 1575410106,
168 "TEMPLATE": OrderedDict(
169 {
170 "NIC": [
171 OrderedDict(
172 {
173 "AR_ID": "0",
174 "BRIDGE": "onerb.103",
175 "BRIDGE_TYPE": "linux",
176 "IP": "185.165.1.1",
177 "IP6_GLOBAL": "2000:a001::b9ff:feae:aa0d",
178 "IP6_LINK": "fe80::b9ff:feae:aa0d",
179 "MAC": "02:00:b9:ae:aa:0d",
180 "NAME": "NIC0",
181 "NETWORK": "Public",
182 "NETWORK_ID": "7",
183 "NIC_ID": "0",
184 "PHYDEV": "team0",
185 "SECURITY_GROUPS": "0",
186 "TARGET": "one-327-0",
187 "VLAN_ID": "100",
188 "VN_MAD": "802.1Q",
189 }
190 ),
191 OrderedDict(
192 {
193 "AR_ID": "0",
194 "BRIDGE": "br0",
195 "BRIDGE_TYPE": "linux",
196 "CLUSTER_ID": "0",
197 "IP": "192.168.1.1",
198 "MAC": "02:00:c0:a8:3b:01",
199 "NAME": "NIC1",
200 "NETWORK": "Management",
201 "NETWORK_ID": "11",
202 "NIC_ID": "1",
203 "SECURITY_GROUPS": "0",
204 "TARGET": "one-327-1",
205 "VN_MAD": "bridge",
206 }
207 ),
208 ]
209 }
210 ),
211 "USER_TEMPLATE": OrderedDict(
212 {
213 "HYPERVISOR": "kvm",
214 "INPUTS_ORDER": "",
215 "LABELS": "Oracle Linux",
216 "LOGO": "images/logos/centos.png",
217 "MEMORY_UNIT_COST": "MB",
218 "SAVED_TEMPLATE_ID": "29",
219 }
220 ),
221 },
222 )()
223 data.VM.append(vm)
224
225 vm = type(
226 "pyone.bindings.VMType90Sub",
227 (object,),
228 {
229 "DEPLOY_ID": "one-107",
230 "ETIME": 0,
231 "GID": 0,
232 "GNAME": "oneadmin",
233 "HISTORY_RECORDS": [],
234 "ID": 107,
235 "LAST_POLL": 1632764186,
236 "LCM_STATE": 3,
237 "MONITORING": {},
238 "NAME": "gitlab-107",
239 "RESCHED": 0,
240 "SNAPSHOTS": [],
241 "STATE": 3,
242 "STIME": 1572485522,
243 "TEMPLATE": OrderedDict(
244 {
245 "NIC": OrderedDict(
246 {
247 "AR_ID": "0",
248 "BRIDGE": "onerb.103",
249 "BRIDGE_TYPE": "linux",
250 "IP": "185.165.1.3",
251 "IP6_GLOBAL": "2000:a001::b9ff:feae:aa03",
252 "IP6_LINK": "fe80::b9ff:feae:aa03",
253 "MAC": "02:00:b9:ae:aa:03",
254 "NAME": "NIC0",
255 "NETWORK": "Public",
256 "NETWORK_ID": "7",
257 "NIC_ID": "0",
258 "PHYDEV": "team0",
259 "SECURITY_GROUPS": "0",
260 "TARGET": "one-107-0",
261 "VLAN_ID": "100",
262 "VN_MAD": "802.1Q",
263 }
264 )
265 }
266 ),
267 "USER_TEMPLATE": OrderedDict(
268 {
269 "HYPERVISOR": "kvm",
270 "INPUTS_ORDER": "",
271 "LABELS": "Gitlab,Centos",
272 "LOGO": "images/logos/centos.png",
273 "MEMORY_UNIT_COST": "MB",
274 "SCHED_REQUIREMENTS": 'ID="0" | ID="1" | ID="2"',
275 "SSH_PORT": "8822",
276 }
277 ),
278 },
279 )()
280 data.VM.append(vm)
281
282 return data
283
284
285 options_base_test = {
286 "api_url": "https://opennebula:2633/RPC2",
287 "api_username": "username",
288 "api_password": "password",
289 "api_authfile": "~/.one/one_auth",
290 "hostname": "v4_first_ip",
291 "group_by_labels": True,
292 "filter_by_label": None,
293 }
294
295
296 # given a dictionary `opts_dict`, return a function that behaves like ansible's inventory get_options
297 def mk_get_options(opts_dict):
298 def inner(opt):
299 return opts_dict.get(opt, False)
300
301 return inner
302
303
304 def test_get_connection_info(inventory, mocker):
305 inventory.get_option = mocker.MagicMock(side_effect=mk_get_options(options_base_test))
306
307 auth = inventory._get_connection_info()
308 assert auth.username and auth.password
309
310
311 def test_populate_constructable_templating(mocker):
312 inventory_filename = "/fake/opennebula.yml"
313
314 mocker.patch.object(InventoryModule, "_get_vm_pool", side_effect=get_vm_pool_json)
315 mocker.patch("ansible_collections.community.general.plugins.inventory.opennebula.HAS_PYONE", True)
316 mocker.patch("ansible.inventory.manager.unfrackpath", mock_unfrackpath_noop)
317 mocker.patch("os.path.exists", exists_mock(inventory_filename))
318 mocker.patch("os.access", access_mock(inventory_filename))
319
320 # the templating engine is needed for the constructable groups/vars
321 # so give that some fake data and instantiate it.
322 C.INVENTORY_ENABLED = ["community.general.opennebula"]
323 inventory_file = {
324 inventory_filename: r"""
325 ---
326 plugin: community.general.opennebula
327 api_url: https://opennebula:2633/RPC2
328 api_username: username
329 api_password: password
330 api_authfile: '~/.one/one_auth'
331 hostname: v4_first_ip
332 group_by_labels: true
333 compose:
334 is_linux: GUEST_OS == 'linux'
335 filter_by_label: bench
336 groups:
337 benchmark_clients: TGROUP.endswith('clients')
338 lin: is_linux == true
339 keyed_groups:
340 - key: TGROUP
341 prefix: tgroup
342 """
343 }
344 im = InventoryManager(loader=DictDataLoader(inventory_file), sources=inventory_filename)
345
346 # note the vm_pool (and json data file) has four hosts,
347 # but the options above asks ansible to filter one out
348 assert len(get_vm_pool_json().VM) == 4
349 assert {vm.NAME for vm in get_vm_pool_json().VM} == {
350 "terraform_demo_00",
351 "terraform_demo_01",
352 "terraform_demo_srv_00",
353 "bs-windows",
354 }
355 assert set(im._inventory.hosts) == {"terraform_demo_00", "terraform_demo_01", "terraform_demo_srv_00"}
356
357 host_demo00 = im._inventory.get_host("terraform_demo_00")
358 host_demo01 = im._inventory.get_host("terraform_demo_01")
359 host_demosrv = im._inventory.get_host("terraform_demo_srv_00")
360
361 assert "benchmark_clients" in im._inventory.groups
362 assert "lin" in im._inventory.groups
363 assert im._inventory.groups["benchmark_clients"].hosts == [host_demo00, host_demo01]
364 assert im._inventory.groups["lin"].hosts == [host_demo00, host_demo01, host_demosrv]
365
366 # test group by label:
367 assert "bench" in im._inventory.groups
368 assert "foo" in im._inventory.groups
369 assert im._inventory.groups["bench"].hosts == [host_demo00, host_demo01, host_demosrv]
370 assert im._inventory.groups["serv"].hosts == [host_demosrv]
371 assert im._inventory.groups["foo"].hosts == [host_demo00, host_demo01]
372
373 # test `compose` transforms GUEST_OS=Linux to is_linux == True
374 assert host_demo00.get_vars()["GUEST_OS"] == "linux"
375 assert host_demo00.get_vars()["is_linux"] is True
376
377 # test `keyed_groups`
378 assert im._inventory.groups["tgroup_bench_clients"].hosts == [host_demo00, host_demo01]
379 assert im._inventory.groups["tgroup_bench_server"].hosts == [host_demosrv]
380
381
382 def test_populate(inventory, mocker):
383 # bypass API fetch call
384 inventory._get_vm_pool = mocker.MagicMock(side_effect=get_vm_pool)
385 inventory.get_option = mocker.MagicMock(side_effect=mk_get_options(options_base_test))
386 inventory._populate()
387
388 # get different hosts
389 host_sam = inventory.inventory.get_host("sam-691-sam")
390 host_zabbix = inventory.inventory.get_host("zabbix-327")
391 host_gitlab = inventory.inventory.get_host("gitlab-107")
392
393 # test if groups exists
394 assert "Gitlab" in inventory.inventory.groups
395 assert "Centos" in inventory.inventory.groups
396 assert "Oracle_Linux" in inventory.inventory.groups
397
398 # check if host_zabbix is in Oracle_Linux group
399 group_oracle_linux = inventory.inventory.groups["Oracle_Linux"]
400 assert group_oracle_linux.hosts == [host_zabbix]
401
402 # check if host_gitlab is in Gitlab and Centos group
403 group_gitlab = inventory.inventory.groups["Gitlab"]
404 group_centos = inventory.inventory.groups["Centos"]
405 assert group_gitlab.hosts == [host_gitlab]
406 assert group_centos.hosts == [host_gitlab]
407
408 # check IPv4 address
409 assert host_sam.get_vars()["v4_first_ip"] == "172.22.4.187"
410
411 # check IPv6 address
412 assert host_zabbix.get_vars()["v6_first_ip"] == "2000:a001::b9ff:feae:aa0d"
413
414 # check ansible_hosts
415 assert host_sam.get_vars()["ansible_host"] == "172.22.4.187"
416 assert host_zabbix.get_vars()["ansible_host"] == "185.165.1.1"
417 assert host_gitlab.get_vars()["ansible_host"] == "185.165.1.3"
418
419 # check for custom ssh port
420 assert host_gitlab.get_vars()["ansible_port"] == "8822"