File: CHostImporter.php

package info (click to toggle)
zabbix 1%3A4.0.4%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 83,104 kB
  • sloc: php: 162,280; ansic: 154,778; sql: 96,479; sh: 5,281; makefile: 1,340; java: 1,068; cpp: 227; perl: 41; xml: 29
file content (278 lines) | stat: -rw-r--r-- 8,784 bytes parent folder | download
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
<?php
/*
** Zabbix
** Copyright (C) 2001-2019 Zabbix SIA
**
** This program 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 2 of the License, or
** (at your option) any later version.
**
** This program 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 program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/


class CHostImporter extends CImporter {

	/**
	 * @var array		a list of host IDs which were created or updated to create an interface cache for those hosts
	 */
	protected $processedHostIds = [];

	/**
	 * Import hosts.
	 *
	 * @param array $hosts
	 *
	 * @throws Exception
	 */
	public function import(array $hosts) {
		$hostsToCreate = [];
		$hostsToUpdate = [];

		foreach ($hosts as $host) {
			// preserve host related templates to massAdd them later
			if ($this->options['templateLinkage']['createMissing'] && !empty($host['templates'])) {
				foreach ($host['templates'] as $template) {
					$templateId = $this->referencer->resolveTemplate($template['name']);
					if (!$templateId) {
						throw new Exception(_s('Template "%1$s" for host "%2$s" does not exist.', $template['name'], $host['host']));
					}
					$templateLinkage[$host['host']][] = ['templateid' => $templateId];
				}
			}
			unset($host['templates']);

			$host = $this->resolveHostReferences($host);

			if (array_key_exists('hostid', $host) && $this->options['hosts']['updateExisting']) {
				$hostsToUpdate[] = $host;
			}
			else if ($this->options['hosts']['createMissing']) {
				if (array_key_exists('hostid', $host)) {
					throw new Exception(_s('Host "%1$s" already exists.', $host['host']));
				}

				$hostsToCreate[] = $host;
			}
		}

		$hostsToUpdate = $this->addInterfaceIds($hostsToUpdate);

		// create/update hosts
		if ($this->options['hosts']['createMissing'] && $hostsToCreate) {
			$newHostIds = API::Host()->create($hostsToCreate);
			foreach ($newHostIds['hostids'] as $hnum => $hostId) {
				$hostHost = $hostsToCreate[$hnum]['host'];
				$this->processedHostIds[$hostHost] = $hostId;

				$this->referencer->addHostRef($hostHost, $hostId);

				if (!empty($templateLinkage[$hostHost])) {
					API::Template()->massAdd([
						'hosts' => ['hostid' => $hostId],
						'templates' => $templateLinkage[$hostHost]
					]);
				}
			}
		}

		if ($this->options['hosts']['updateExisting'] && $hostsToUpdate) {
			API::Host()->update($hostsToUpdate);
			foreach ($hostsToUpdate as $host) {
				$this->processedHostIds[$host['host']] = $host['hostid'];

				if (!empty($templateLinkage[$host['host']])) {
					API::Template()->massAdd([
						'hosts' => $host,
						'templates' => $templateLinkage[$host['host']]
					]);
				}
			}
		}

		// create interfaces cache interface_ref->interfaceid
		$dbInterfaces = API::HostInterface()->get([
			'hostids' => $this->processedHostIds,
			'output' => API_OUTPUT_EXTEND
		]);

		foreach ($hosts as $host) {
			if (isset($this->processedHostIds[$host['host']])) {
				foreach ($host['interfaces'] as $interface) {
					$hostId = $this->processedHostIds[$host['host']];

					if (!isset($this->referencer->interfacesCache[$hostId])) {
						$this->referencer->interfacesCache[$hostId] = [];
					}

					foreach ($dbInterfaces as $dbInterface) {
						if ($hostId == $dbInterface['hostid']
								&& $dbInterface['ip'] == $interface['ip']
								&& $dbInterface['dns'] == $interface['dns']
								&& $dbInterface['useip'] == $interface['useip']
								&& $dbInterface['port'] == $interface['port']
								&& $dbInterface['type'] == $interface['type']
								&& $dbInterface['main'] == $interface['main']
								&& (!isset($interface['bulk']) || $dbInterface['bulk'] == $interface['bulk'])) {
							$refName = $interface['interface_ref'];
							$this->referencer->interfacesCache[$hostId][$refName] = $dbInterface['interfaceid'];
						}
					}
				}
			}
		}
	}

	/**
	 * Get a list of created or updated host IDs.
	 *
	 * @return array
	 */
	public function getProcessedHostIds() {
		return $this->processedHostIds;
	}

	/**
	 * Change all references in host to database ids.
	 *
	 * @throws Exception
	 *
	 * @param array $host
	 *
	 * @return array
	 */
	protected function resolveHostReferences(array $host) {
		foreach ($host['groups'] as $gnum => $group) {
			$groupId = $this->referencer->resolveGroup($group['name']);
			if (!$groupId) {
				throw new Exception(_s('Group "%1$s" for host "%2$s" does not exist.', $group['name'], $host['host']));
			}
			$host['groups'][$gnum] = ['groupid' => $groupId];
		}

		if (isset($host['proxy'])) {
			if (empty($host['proxy'])) {
				$proxyId = 0;
			}
			else {
				$proxyId = $this->referencer->resolveProxy($host['proxy']['name']);
				if (!$proxyId) {
					throw new Exception(_s('Proxy "%1$s" for host "%2$s" does not exist.', $host['proxy']['name'], $host['host']));
				}
			}

			$host['proxy_hostid'] = $proxyId;
		}

		if ($hostId = $this->referencer->resolveHost($host['host'])) {
			$host['hostid'] = $hostId;

			if (array_key_exists('macros', $host)) {
				foreach ($host['macros'] as &$macro) {
					if ($hostMacroId = $this->referencer->resolveMacro($hostId, $macro['macro'])) {
						$macro['hostmacroid'] = $hostMacroId;
					}
				}
				unset($macro);
			}
		}


		return $host;
	}

	/**
	 * For existing hosts we need to set an interfaceid for existing interfaces or they will be added.
	 *
	 * @param array $xmlHosts    hosts from XML for which interfaces will be added
	 *
	 * @return array
	 */
	protected function addInterfaceIds(array $xmlHosts) {
		$dbInterfaces = API::HostInterface()->get([
			'hostids' => zbx_objectValues($xmlHosts, 'hostid'),
			'output' => API_OUTPUT_EXTEND,
			'preservekeys' => true
		]);

		// build lookup maps for:
		// - interfaces per host
		// - default (primary) interface ids per host per interface type
		$dbHostInterfaces = [];
		$dbHostMainInterfaceIds = [];

		foreach ($dbInterfaces as $dbInterface) {
			$dbHostId = $dbInterface['hostid'];

			$dbHostInterfaces[$dbHostId][] = $dbInterface;
			if ($dbInterface['main'] == INTERFACE_PRIMARY) {
				$dbHostMainInterfaceIds[$dbHostId][$dbInterface['type']] = $dbInterface['interfaceid'];
			}
		}

		foreach ($xmlHosts as &$xmlHost) {
			// if interfaces in XML are empty then do not touch existing interfaces
			if (!$xmlHost['interfaces']) {
				unset($xmlHost['interfaces']);
				continue;
			}

			$xmlHostId = $xmlHost['hostid'];

			$currentDbHostMainInterfaceIds = isset($dbHostMainInterfaceIds[$xmlHostId])
				? $dbHostMainInterfaceIds[$xmlHostId]
				: [];

			$reusedInterfaceIds = [];

			foreach ($xmlHost['interfaces'] as &$xmlHostInterface) {
				$xmlHostInterfaceType = $xmlHostInterface['type'];

				// check if an existing interfaceid from current host can be reused
				// in case there is default (primary) interface in current host with same type
				if ($xmlHostInterface['main'] == INTERFACE_PRIMARY
						&& isset($currentDbHostMainInterfaceIds[$xmlHostInterfaceType])) {
					$dbHostInterfaceId = $currentDbHostMainInterfaceIds[$xmlHostInterfaceType];

					$xmlHostInterface['interfaceid'] = $dbHostInterfaceId;
					$reusedInterfaceIds[$dbHostInterfaceId] = true;
				}
			}
			unset($xmlHostInterface);

			// loop through all interfaces of current host and take interfaceids from ones that
			// match completely, ignoring hosts from XML with set interfaceids and ignoring hosts
			// from DB with reused interfaceids
			foreach ($xmlHost['interfaces'] as &$xmlHostInterface) {
				foreach ($dbHostInterfaces[$xmlHostId] as $dbHostInterface) {
					$dbHostInterfaceId = $dbHostInterface['interfaceid'];

					if (!isset($xmlHostInterface['interfaceid']) && !isset($reusedInterfaceIds[$dbHostInterfaceId])
							&& $dbHostInterface['ip'] == $xmlHostInterface['ip']
							&& $dbHostInterface['dns'] == $xmlHostInterface['dns']
							&& $dbHostInterface['useip'] == $xmlHostInterface['useip']
							&& $dbHostInterface['port'] == $xmlHostInterface['port']
							&& $dbHostInterface['type'] == $xmlHostInterface['type']
							&& (!isset($xmlHostInterface['bulk'])
								|| $dbHostInterface['bulk'] == $xmlHostInterface['bulk'])) {
						$xmlHostInterface['interfaceid'] = $dbHostInterfaceId;
						$reusedInterfaceIds[$dbHostInterfaceId] = true;
						break;
					}
				}
			}
			unset($xmlHostInterface);
		}
		unset($xmlHost);

		return $xmlHosts;
	}
}