r4429 Adding a new custom script by Göran Törnqvist: "I thought I share my daily
[racktables-contribs] / local_portgenerator.php
CommitLineData
91b12714
DO
1<?php
2//
3// This extension for RackTables is used to generate ports based on object type and hardware type
4//
5// Version 1.1
6//
7// Created by Jeroen Benda
8// 04-2010
9// http://racktablescode.j-tools.net
10//
11// Please do not remove the credentials if you alter this file.
12//
13
14/*
15This port generator is a replacement for the built-in auto port generator. I found the built-in version to be to limited. This port generator
16uses not only the object type but also the hardware type to determine the ports needed. The definition used to generate the ports is also used
17maintainable through the same interface. It will also allow you to use the attribute 'number of ports' when generating ports which can be
18convenient for example with patch panels.
19
20The way it works is easy. A new table is created which holds the definition per dictionary key. When an object has no ports defined yet
21(and the object type is not in the exclude-from-port-generator list ($noPortGenerator)) a tab will pop up for the selected object.
22
23If there already is a definition for a specific hardware type the ports that will be generated is shown. With one click those ports are
24generated. You can also chose to update the definition (or create one if the object type or hardware type does not already have one.
25
26A definition consists of one or more semicolon seperated port definitions. Each definition has 4 or optionally 5 parts which are seperated by a |
27The 5 parts are:
28Start number : at which number should the range start. If there is only 1 port this can be set at anything
29Count : the number of ports of this type (this is where you can use %n for the value of the attribute number of ports)
30Port name : the name of the port. If the count is greater than 1 you should include %u which is replaced by the the number.
31Port type id : the port type id of this group of ports
32Label : optional, the label for the port. Again you can should use %u if you have more than 1 port. If you do not include it, the label
33 will be left blank
34
35An example for a server:
361|2|pwr%u|16;0|2|eth%u|24|%u
37
38This will generate the following ports:
39pwr1 of type 16
40pwr2 of type 16
41eth0 of type 24 with label 0
42eth1 of type 24 with label 1
43
44An example for a patch panel:
451|%n|eth%u|24|%u;1|%n|eth%ulink|50198
46
47This will generate the following ports:
48eth1 of type 24 with label 1
49eth2 of type 24 with label 2
50....
51ethx of type 24 with label x (where x is the number of ports defined in the attribute)
52eth1link of type 50198 (the type we use for utpLink cable)
53....
54ethxlink of type 50198 (where x is the number of ports defined in the attribute)
55
56*/
57
58//
59// This php file depends on 2 variables and 2 constants that have to be set before this file is included:
60//
61// $tablePortGenerator is the name of the table used
62// $noPortGenerator contains dictionary keys that will not have a portgenerator
63// _portGeneratorHWType the attribute key for the hardware type attribute, in the default installation this is 2
64// _portGeneratorNumberOfPorts the attribute key for the number of ports attribute, in default installation this is 6
65//
66
67//
68// It also depends on a new table which contains all the autoport configurations
69//
70// SQL statement to create this:
71/*
72CREATE TABLE IF NOT EXISTS `AutoPort` (
73 `dict_key` int(11) NOT NULL,
74 `autoportconfig` text NOT NULL,
75 UNIQUE KEY `dict_key` (`dict_key`)
76) ENGINE=MyISAM DEFAULT CHARSET=utf8;
77*/
78//
79
80//
81// Set up the RackTables variables that create the tab
82// The tab only shows up if there are no ports yet defined
83//
84// The functions referred to in the handlers and trigger are all in this php file
85//
86$tab['object']['portgenerator'] = 'Port generator';
87$trigger['object']['portgenerator'] = 'localtrigger_PortGenerator';
88$tabhandler['object']['portgenerator'] = 'localfunc_PortGenerator';
89$ophandler['object']['portgenerator']['updateportgenerator'] = 'updateconfig_PortGenerator';
90$ophandler['object']['ports']['addports'] = 'localexecute_PortGenerator';
91
92//
93// Check whether the variables are set or otherwise set the default values.
94//
95global $noPortGenerator;
96if (!isset($noPortGenerator)) {
97 $noPortGenerator = array();
98}
99global $tablePortGenerator;
100if (!isset($tablePortGenerator)) {
101 $tablePortGenerator = "AutoPort";
102}
103if (!defined("_portGeneratorHWType")) {
104 define("_portGeneratorHWType",2);
105}
106if (!defined("_portGeneratorNumberOfPorts")) {
107 define("_portGeneratorNumberOfPorts",6);
108}
109//
110// Check whether the table exists. If not, create it
111//
fd5a3356
DO
112function checkForTable ()
113{
114 global $tablePortGenerator;
115 $result = useSelectBlade ("SHOW TABLES LIKE '{$tablePortGenerator}'", __FUNCTION__);
91b12714 116 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
fd5a3356
DO
117 if (!($row = $result->fetch (PDO::FETCH_NUM))) {
118 $q = "CREATE TABLE IF NOT EXISTS `{$tablePortGenerator}` (
119 `dict_key` int(11) NOT NULL,
120 `autoportconfig` text NOT NULL,
121 UNIQUE KEY `dict_key` (`dict_key`)
122 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
123 $result = useSelectBlade ($q, __FUNCTION__);
124 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
125 }
91b12714
DO
126}
127
128//
129// function to check whether a tab Port generator should be shown
130// If there are already ports configured or the object type id is in $noPortGenerator
131// (which is an array of object type ids) then do not show the tab
132//
133function localtrigger_PortGenerator()
134{
135 global $noPortGenerator;
136 assertUIntArg ('object_id', __FUNCTION__);
137 $object = spotEntity ('object', $_REQUEST['object_id']);
138 $record = getObjectPortsAndLinks ($object['id']);
139 if (count($record)==0 && !in_array($object['objtype_id'],$noPortGenerator))
140 return 1;
141 else
142 {
143 return '';
144 }
145}
146
147//
148// This function checks whether there is a configuration available for the selected object type id
149// (and if necessary for the hardware type id which is found as attribute id _portGeneratorHWType
150function localverify_PortGenerator($object) {
151 global $tablePortGenerator, $errorText, $lookFor, $portList, $genText, $valueConfiguration, $searchIt;
fd5a3356 152 checkForTable();
91b12714
DO
153 $foundError = true;
154 $record = getObjectPortsAndLinks ($object['id']);
155 //
156 // Make sure that there are no ports configured
157 //
158 if (count($record)==0) {
159 //
160 // Check whether the object type for the selected object has an attribute hardware type
161 // If it does, use the hardware type for configuration. Otherwise use the generic object type
162 //
163 $lookFor = "Hardware type";
164 $q = "SELECT * FROM AttributeMap WHERE attr_id="._portGeneratorHWType." AND objtype_id={$object['objtype_id']} ";
165 $result = useSelectBlade ($q, __FUNCTION__);
166 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
167 if ($row = $result->fetch (PDO::FETCH_NUM)) {
168 //
169 // There is a hardware type available for this object type. Check whether it is set
170 // If it is, search for the specific port configuration for that hardware type
171 // If it is not set, use the generic port configuration for the object type
172 //
173 $q = "SELECT uint_value, dict_value FROM AttributeValue, Dictionary ";
174 $q .= "WHERE attr_id="._portGeneratorHWType." AND object_id={$object['id']} AND dict_key=uint_value ";
175 $result = useSelectBlade ($q, __FUNCTION__);
176 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
177 if ($row = $result->fetch (PDO::FETCH_NUM)) {
178 $searchIt = $row[0];
179 $searchText = "OK (based on hardware type)";
180 $searchType = 3;
181 $genText = "{$object['objtype_name']}: {$row[1]}";
182 $genText = str_replace(array("%GPASS%")," ",$genText);
183 } else {
184 $searchIt = $object['objtype_id'];
185 $searchText = "Based on object type, hardware type not set";
186 $searchType = 2;
187 $genText = "<b>GENERIC</b> {$object['objtype_name']}";
188 }
189 } else {
190 $searchIt = $object['objtype_id'];
191 $searchText = "OK (based on object type)";
192 $searchType = 1;
193 $genText = "{$object['objtype_name']}";
194 }
195 $lookFor = "Autoport configuration";
196 $q = "SELECT autoportconfig FROM {$tablePortGenerator} WHERE dict_key={$searchIt} ";
197 $result = useSelectBlade ($q, __FUNCTION__);
198 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
199 //
200 // Check if there is an autoport configuration for the requested key
201 //
202 if ($valueConfiguration = $result->fetch (PDO::FETCH_NUM)) {
203 $lookFor = "Configuration";
204 $q = "SELECT uint_value FROM AttributeValue ";
205 $q .= "WHERE attr_id="._portGeneratorNumberOfPorts." AND object_id={$_REQUEST['object_id']} ";
206 //
207 // Check for the value of the number of ports. If it is not found set it to 0
208 //
209 $result = useSelectBlade ($q, __FUNCTION__);
210 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
211 if ($valueNumberOfPorts = $result->fetch (PDO::FETCH_NUM)) {
212 } else {
213 $valueNumberOfPorts[0] = 0;;
214 }
215 //
216 // $portList will contain the list of ports to be generated
217 //
218 $portList = array();
219 //
220 // $portOrders array will be filled with individual port generation schemes
221 // <start port #>|<port count, use %n for number of ports>|<port name, use %u for number>|<port type id>[|<port label, use %u for number>]
222 // The configuration contains a semicolon seperated list of the schemes
223 //
224 // An example of this would be:
225 // 1|2|pwr%u|16;1|%n|eth%u|24|%u
226 //
227 $portOrders = explode(";",$valueConfiguration[0]);
228 if (count($portOrders)>0) {
229 $orderCnt = 0;
230 foreach ($portOrders as $aPortOrder) {
231 //
232 // Split up each scheme and check for errors
233 // If there are not errors, populate the $portList
234 //
235 $orderCnt++;
236 $thisOrder = explode("|",$aPortOrder);
237 if (count($thisOrder)==4 || count($thisOrder)==5) {
238 if ($thisOrder[1]!="%n" || $valueNumberOfPorts[0]!=0) {
239 if ($thisOrder[1]=="%n") {
240 $thisOrder[1] = $valueNumberOfPorts[0];
241 }
242 if ($thisOrder[1]==1 || strpos($thisOrder[2],"%u")!==false) {
243 $q = "SELECT dict_value FROM Dictionary WHERE dict_key='{$thisOrder[3]}' AND chapter_id=2 ";
244 $result = useSelectBlade ($q, __FUNCTION__);
245 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
246 if ($row3 = $result->fetch (PDO::FETCH_NUM)) {
247 for ($i=1;$i<=$thisOrder[1];$i++) {
248 $ii = $thisOrder[0]+$i-1;
249 $name = str_replace("%u",$ii,$thisOrder[2]);
250 if (count($thisOrder)==5) {
251 $label = str_replace("%u",$ii,$thisOrder[4]);
252 } else {
253 $label = "";
254 }
255 $portList[] = array("name"=>$name,"port_id"=>$thisOrder[3],"port_name"=>$row3[0],"label"=>$label);
256 }
257 } else {
258 $errorText = "Port type {$thisOrder[3]} is not found or not a port type.";
259 }
260 } else {
261 $errorText = "Config part {$orderCnt} wants more than 1 port without using %u parameter.";
262 }
263 } else {
264 $errorText = "Config part {$orderCnt} refers to <i>HW Number of Ports</i> but that is not defined or 0.";
265 }
266 } else {
267 $errorText = "Config part {$orderCnt} does not have 4 parts seperated by a |";
268 }
269 }
270 if (!isset($errorText)) {
271 $foundError = false;
272 }
273 } else {
274 $errorText = "Autoport configuration for this dictionary key ({$searchIt}) is empty.";
275 }
276 } else {
277 $errorText = "Autoport configuration for this dictionary key ({$searchIt}) not found.";
278 }
279 } else {
280 $errorText = "Port generator only works if no ports have been configured yet.";
281 }
282 return !$foundError;
283}
284
285function localfunc_PortGenerator()
286{
287 global $errorText, $lookFor, $portList, $genText, $valueConfiguration, $searchIt;
288 assertUIntArg ('object_id', __FUNCTION__);
289 $object = spotEntity ('object', $_REQUEST['object_id']);
290 startPortlet("Port generator");
291 print "<center><br>";
292 if (!localverify_PortGenerator($object)) {
293 //
294 // Autoport configuration did not work. Show this and show the error
295 //
296 print "{$lookFor} :&nbsp; &nbsp; &nbsp;Error\n";
297 if (isset($errorText)) {
298 print $errorText;
299 }
300 } else {
301 //
302 // Show the list of ports that will be generated and provide a link to actually do so
303 //
304 print "<a href='".makeHrefProcess(array('op'=>'addports','page'=>'object','object_id'=>$object['id'],'tab'=>'ports')).
305 "'>Generate the ports for <b>{$object['name']}</b> as listed below NOW</a><br>\n";
306 print $genText."<p>";
307 print "<table cellspacing=0 cellpadding='5' align='center' class='widetable'>";
308 print "<tr><th>Port name&nbsp;&nbsp;</th><th>Port label&nbsp;&nbsp;</th><th>Port type</th></tr>\n";
309 foreach ($portList as $aPort) {
310 print "<tr><td>{$aPort['name']}</td><td>{$aPort['label']}</td><td>{$aPort['port_name']}</td></tr>\n";
311 }
312 print "</table>";
313 }
314 print "<br></center>";
315 finishPortlet();
316 //
317 // Check whether the user is allowed to do an update of the port configurator
318 //
319 // if you do not want this, make sure you add a
320 // deny {$op_updateportgenerator}
321 // for the apprioriate groups (or any allow first and deny for the rest
322 //
323 if (permitted('object','portgenerator',null,array(array ('tag' => '$op_updateportgenerator')))) {
324 startPortlet("Update autoport configuration");
325 //
326 // Description of the config rules
327 //
328 print "<center>";
329 print $genText."<p>\n";
330 print "&lt;list1&gt;;&lt;list2&gt;;.... where &lt;listx&gt; is<br>";
331 print "&lt;start port #&gt;|&lt;port count, use %n for number of ports&gt;|";
332 print "&lt;port name, use %u for number&gt;|&lt;port type id&gt;[|&lt;port label, use %u for number&gt;]<br><br>";
333 print "<table><tr>\n";
334 $isfirst = true;
335 $i = 0;
336 //
337 // List all available port types with their dictionary key
338 //
339 $q = "SELECT dict_key, dict_value FROM Dictionary WHERE chapter_id=2 ORDER BY dict_value ";
340 $result = useSelectBlade ($q, __FUNCTION__);
341 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
342 while ($row4 = $result->fetch (PDO::FETCH_NUM)) {
343 if (!$isfirst && $i%12==0) {
344 print "</td>";
345 } else {
346 $isfirst = false;
347 }
348 if ($i%12==0) {
349 print "<td align='left'>";
350 }
351 print "<b>{$row4[0]}</b>:{$row4[1]}<br>\n";
352 $i++;
353 }
354 print "</td>\n";
355 print "</tr></table>\n";
356 //
357 // The form that can update the configuration
358 //
359 print "<form action='process.php' method='GET'>\n";
360 print "<input type='hidden' name='page' value='object'>\n";
361 print "<input type='hidden' name='tab' value='portgenerator'>\n";
362 print "<input type='hidden' name='op' value='updateportgenerator'>\n";
363 print "<input type='hidden' name='object_id' value='{$_REQUEST['object_id']}'>\n";
364 print "<input type='hidden' name='yId' value='{$searchIt}'>\n";
365 print "Autoport Configuration : <input type='text' size='60' name='yConfig' value='";
366 if ($valueConfiguration) {
367 print $valueConfiguration[0];
368 }
369 print "'><br><br>\n";
370 print "<input type='submit' name='autoportconfig' value='";
371 if ($valueConfiguration) {
372 print "Update";
373 } else {
374 print "Create";
375 }
376 print "'>\n";
377 print "</form>\n";
378 print "</center>";
379 finishPortlet();
380 }
381}
382
383//
384// The actual port generator
385//
386$msgcode['localexecute_PortGenerator']['OK'] = 0;
387$msgcode['localexecute_PortGenerator']['ERR'] = 100;
388
389function localexecute_PortGenerator()
390{
391 global $errorText, $portList;
392 $linkok = localtrigger_PortGenerator();
393 if ($linkok) {
394 assertUIntArg ('object_id', __FUNCTION__);
395 $object = spotEntity ('object', $_REQUEST['object_id']);
396 if (localverify_PortGenerator($object)) {
397 $cnt = 0;
398 foreach ($portList as $aPort) {
399 commitAddPort($_REQUEST['object_id'],$aPort['name'],$aPort['port_id'],"","");
400 $cnt++;
401 }
402 }
403 } else {
404 $errorText = "Port generator not allowed";
405 }
406 if ($linkok) {
407 return buildRedirectURL (__FUNCTION__, 'OK', array ("Successfully added {$cnt} ports"));
408 } else {
409 return buildRedirectURL (__FUNCTION__, 'ERR', array ("Error adding the ports ({$errorText})"));
410 }
411}
412
413//
414// Update the configuration scheme
415//
416$msgcode['updateconfig_PortGenerator']['OK'] = 0;
417$msgcode['updateconfig_PortGenerator']['ERR'] = 100;
418
419function updateconfig_PortGenerator()
420{
421 global $tablePortGenerator;
fd5a3356 422 checkForTable();
91b12714
DO
423 $q = "SELECT autoportconfig FROM {$tablePortGenerator} WHERE dict_key={$_REQUEST['yId']} ";
424 $result = useSelectBlade ($q, __FUNCTION__);
425 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
426 if ($row = $result->fetch (PDO::FETCH_NUM)) {
427 $q = "UPDATE {$tablePortGenerator} SET autoportconfig='{$_REQUEST['yConfig']}' WHERE dict_key={$_REQUEST['yId']} ";
428 } else {
429 $q = "INSERT INTO {$tablePortGenerator} (dict_key,autoportconfig) VALUES ({$_REQUEST['yId']},'{$_REQUEST['yConfig']}') ";
430 }
431 $result = useSelectBlade ($q, __FUNCTION__);
432 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
433 if (true) {
434 return buildRedirectURL (__FUNCTION__, 'OK', array ("Successfully updated auto port configuration"));
435 } else {
436 return buildRedirectURL (__FUNCTION__, 'ERR', array ("Error update auto port configuration"));
437 }
438}
439
440?>