demo: simplify demoreload.sh
[racktables-contribs] / local_portgenerator.php
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 /*
15 This 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
16 uses 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
17 maintainable through the same interface. It will also allow you to use the attribute 'number of ports' when generating ports which can be
18 convenient for example with patch panels.
19
20 The 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
23 If there already is a definition for a specific hardware type the ports that will be generated is shown. With one click those ports are
24 generated. You can also chose to update the definition (or create one if the object type or hardware type does not already have one.
25
26 A definition consists of one or more semicolon seperated port definitions. Each definition has 4 or optionally 5 parts which are seperated by a |
27 The 5 parts are:
28 Start number : at which number should the range start. If there is only 1 port this can be set at anything
29 Count : the number of ports of this type (this is where you can use %n for the value of the attribute number of ports)
30 Port name : the name of the port. If the count is greater than 1 you should include %u which is replaced by the the number.
31 Port type id : the port type id of this group of ports
32 Label : 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
35 An example for a server:
36 1|2|pwr%u|16;0|2|eth%u|24|%u
37
38 This will generate the following ports:
39 pwr1 of type 16
40 pwr2 of type 16
41 eth0 of type 24 with label 0
42 eth1 of type 24 with label 1
43
44 An example for a patch panel:
45 1|%n|eth%u|24|%u;1|%n|eth%ulink|50198
46
47 This will generate the following ports:
48 eth1 of type 24 with label 1
49 eth2 of type 24 with label 2
50 ....
51 ethx of type 24 with label x (where x is the number of ports defined in the attribute)
52 eth1link of type 50198 (the type we use for utpLink cable)
53 ....
54 ethxlink of type 50198 (where x is the number of ports defined in the attribute)
55
56 Example for a Port Innerinterface + Outerinterface:
57 1|2|G%u|4-1077|gigabitEthernet0/%u
58
59 This will generate the following ports:
60 G1 of inner Type 4 and outer type 1077 (SFP-1000 with empty SFP-1000 inside)
61 G2 of inner Type 4 and outer type 1077 (SFP-1000 with empty SFP-1000 inside)
62
63 */
64
65 //
66 // This php file depends on 2 variables and 2 constants that have to be set before this file is included:
67 //
68 // $tablePortGenerator is the name of the table used
69 // $noPortGenerator contains dictionary keys that will not have a portgenerator
70 // _portGeneratorHWType the attribute key for the hardware type attribute, in the default installation this is 2
71 // _portGeneratorNumberOfPorts the attribute key for the number of ports attribute, in default installation this is 6
72 //
73
74 //
75 // It also depends on a new table which contains all the autoport configurations
76 //
77 // SQL statement to create this:
78 /*
79 CREATE TABLE IF NOT EXISTS `AutoPort` (
80 `dict_key` int(11) NOT NULL,
81 `autoportconfig` text NOT NULL,
82 UNIQUE KEY `dict_key` (`dict_key`)
83 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
84 */
85 //
86
87 //
88 // Set up the RackTables variables that create the tab
89 // The tab only shows up if there are no ports yet defined
90 //
91 // The functions referred to in the handlers and trigger are all in this php file
92 //-----------------------------------
93 //Version 1.2
94 //Revised by Jorge Sanchez
95 //04-2011
96 //------------------------------------
97 //Changes:
98 //------------------------------------
99 //****The php file has been changed to work with 0.18.7 and the 0.19.x****
100 //
101 //****Note: you need to place process.php into the wwwroot directory from 0.18.7 for local_portgenerator to work.****
102 //
103 //****Also, make sure to include port_generator in the local.php file****
104 //
105 //First: $result variable no longers equals function useSelectBlade but uses function usePreparedSelectBlade because of the changes since
106 //0.17.x files for rendering objects. Also with that, the FUNCTION included with useSelectBlade has been removed
107 //
108 //Second: The orientation of the table has been altered to have each dictionary entry be rendered
109 //in a cell instead of fifteen in one cell. This makes the table look more neat and easier to read
110 //
111 //Third: Information of how to use the port generator has been added such as an EXAMPLE, an EXPLANATION of the EXAMPLE, and a note to allow port generator to render
112 //to port after the link has been pressed.
113 //
114 //Fourth: the autoport dialog box has been moved from below the table to the top of the table for easier accessibility
115 //
116 //Fifth: for some reason, the label would not update when the link was pressed so no labels would be present even if you added them to the Port Generator. To fix this,
117 //at line 443, inside of the commitaddPort variable, needed to add $aPort['label'] to allow it to function correctly
118 //----------------------------------
119 //Working On
120 //----------------------------------
121 //One: the padding with whitespace for each needs to be incorperated so that each cell is the same size. This is due to the browser more than anything else.
122 //
123 //Version 1.3
124 //Revised by Jorge Sanchez
125 //04-2011
126 //------------------------------------
127 //Changes:
128 //------------------------------------
129 //***No longer needs the process.php file to work. ***
130 //
131 //Version 1.4
132 //Revised by Marian Stetina, Viktor Daniel
133 //02-2012
134 //------------------------------------
135 //Changes:
136 //------------------------------------
137 //*** Added support for PortInnterInterface ***
138 //
139 //
140 //Version 1.5
141 //Revised by Marian Stetina
142 //09-2014
143 //------------------------------------
144 //Changes:
145 //------------------------------------
146 //*** Compatibility with RT v.0.20.8, because DB-Model was changed (RactTables Changelog: update: move port outer interfaces from the dictionary)
147 //*** Port listing with InnerInterface ID (Example: 10-1588 QSFP+ => empty QSFP+)
148 //*** some HTML Tags bugfixed
149 //
150
151 $tab['object']['portgenerator'] = 'Port generator';
152 $trigger['object']['portgenerator'] = 'localtrigger_PortGenerator';
153 $tabhandler['object']['portgenerator'] = 'localfunc_PortGenerator';
154 $ophandler['object']['portgenerator']['updateportgenerator'] = 'updateconfig_PortGenerator';
155 $ophandler['object']['ports']['addports'] = 'localexecute_PortGenerator';
156
157 //
158 // Check whether the variables are set or otherwise set the default values.
159 //
160 global $noPortGenerator;
161 if (!isset($noPortGenerator)) {
162 $noPortGenerator = array();
163 }
164 global $tablePortGenerator;
165 if (!isset($tablePortGenerator)) {
166 $tablePortGenerator = "AutoPort";
167 }
168 if (!defined("_portGeneratorHWType")) {
169 define("_portGeneratorHWType",2);
170 }
171 if (!defined("_portGeneratorNumberOfPorts")) {
172 define("_portGeneratorNumberOfPorts",6);
173 }
174 //
175 // Check whether the table exists. If not, create it
176 //
177 function checkForTable ()
178 {
179 global $tablePortGenerator;
180 $result = usePreparedSelectBlade ("SHOW TABLES LIKE '{$tablePortGenerator}'");
181 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
182 if (!($row = $result->fetch (PDO::FETCH_NUM))) {
183 $q = "CREATE TABLE IF NOT EXISTS `{$tablePortGenerator}` (
184 `dict_key` int(10) unsigned NOT NULL auto_increment,
185 `autoportconfig` text NOT NULL,
186 UNIQUE KEY `dict_key` (`dict_key`)
187 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
188 $result = usePreparedSelectBlade ($q);
189 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
190 }
191 }
192
193 //
194 // function to check whether a tab Port generator should be shown
195 // If there are already ports configured or the object type id is in $noPortGenerator
196 // (which is an array of object type ids) then do not show the tab
197 //
198 function localtrigger_PortGenerator()
199 {
200 global $noPortGenerator;
201 assertUIntArg ('object_id', __FUNCTION__);
202 $object = spotEntity ('object', $_REQUEST['object_id']);
203 $record = getObjectPortsAndLinks ($object['id']);
204 if (count($record)==0 && !in_array($object['objtype_id'],$noPortGenerator))
205 //return 1;
206 return 'std';
207 else
208 {
209 return '';
210 }
211 }
212
213 //
214 // This function checks whether there is a configuration available for the selected object type id
215 // (and if necessary for the hardware type id which is found as attribute id _portGeneratorHWType
216 function localverify_PortGenerator($object) {
217 global $tablePortGenerator, $errorText, $lookFor, $portList, $genText, $valueConfiguration, $searchIt;
218 checkForTable();
219 $foundError = true;
220 $record = getObjectPortsAndLinks ($object['id']);
221 //
222 // Make sure that there are no ports configured
223 //
224 if (count($record)==0) {
225 //
226 // Check whether the object type for the selected object has an attribute hardware type
227 // If it does, use the hardware type for configuration. Otherwise use the generic object type
228 //
229 $lookFor = "Hardware type";
230 $q = "SELECT * FROM AttributeMap WHERE attr_id="._portGeneratorHWType." AND objtype_id={$object['objtype_id']} ";
231 $result = usePreparedSelectBlade ($q);
232 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
233 if ($row = $result->fetch (PDO::FETCH_NUM)) {
234 //
235 // There is a hardware type available for this object type. Check whether it is set
236 // If it is, search for the specific port configuration for that hardware type
237 // If it is not set, use the generic port configuration for the object type
238 //
239 $q = "SELECT uint_value, dict_value FROM AttributeValue, Dictionary ";
240 $q .= "WHERE attr_id="._portGeneratorHWType." AND object_id={$object['id']} AND dict_key=uint_value ";
241 $result = usePreparedSelectBlade ($q);
242 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
243 if ($row = $result->fetch (PDO::FETCH_NUM)) {
244 $searchIt = $row[0];
245 $searchText = "OK (based on hardware type)";
246 $searchType = 3;
247 $genText = "{$object['objtype_name']}: {$row[1]}";
248 $genText = str_replace(array("%GPASS%")," ",$genText);
249 } else {
250 $searchIt = $object['objtype_id'];
251 $searchText = "Based on object type, hardware type not set";
252 $searchType = 2;
253 $genText = "<b>GENERIC</b> {$object['objtype_name']}";
254 }
255 } else {
256 $searchIt = $object['objtype_id'];
257 $searchText = "OK (based on object type)";
258 $searchType = 1;
259 $genText = "{$object['objtype_name']}";
260 }
261 $lookFor = "Autoport configuration";
262 $q = "SELECT autoportconfig FROM {$tablePortGenerator} WHERE dict_key={$searchIt} ";
263 $result = usePreparedSelectBlade ($q);
264 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
265 //
266 // Check if there is an autoport configuration for the requested key
267 //
268 if ($valueConfiguration = $result->fetch (PDO::FETCH_NUM)) {
269 $lookFor = "Configuration";
270 $q = "SELECT uint_value FROM AttributeValue ";
271 $q .= "WHERE attr_id="._portGeneratorNumberOfPorts." AND object_id={$_REQUEST['object_id']} ";
272 //
273 // Check for the value of the number of ports. If it is not found set it to 0
274 //
275 $result = usePreparedSelectBlade ($q);
276 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
277 if ($valueNumberOfPorts = $result->fetch (PDO::FETCH_NUM)) {
278 } else {
279 $valueNumberOfPorts[0] = 0;;
280 }
281 //
282 // $portList will contain the list of ports to be generated
283 //
284 $portList = array();
285 //
286 // $portOrders array will be filled with individual port generation schemes
287 // <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>]
288 // The configuration contains a semicolon seperated list of the schemes
289 //
290 // An example of this would be:
291 // 1|2|pwr%u|16;1|%n|eth%u|24|%u
292 //
293 $portOrders = explode(";",$valueConfiguration[0]);
294 if (count($portOrders)>0) {
295 $orderCnt = 0;
296 foreach ($portOrders as $aPortOrder) {
297 //
298 // Split up each scheme and check for errors
299 // If there are not errors, populate the $portList
300 //
301 $orderCnt++;
302 $thisOrder = explode("|",$aPortOrder);
303 if (count($thisOrder)==4 || count($thisOrder)==5) {
304 if ($thisOrder[1]!="%n" || $valueNumberOfPorts[0]!=0) {
305 if ($thisOrder[1]=="%n") {
306 $thisOrder[1] = $valueNumberOfPorts[0];
307 }
308 if ($thisOrder[1]==1 || strpos($thisOrder[2],"%u")!==false) {
309 if (preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $thisOrder[3], $matches))
310 $oif_id = $matches[2];
311 else
312 $oif_id = $thisOrder[3];
313 $q = "SELECT oif_name FROM PortOuterInterface WHERE id='$oif_id'";
314 $result = usePreparedSelectBlade ($q);
315 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
316 if ($row3 = $result->fetch (PDO::FETCH_NUM)) {
317 for ($i=1;$i<=$thisOrder[1];$i++) {
318 $ii = $thisOrder[0]+$i-1;
319 $name = str_replace("%u",$ii,$thisOrder[2]);
320 if (count($thisOrder)==5) {
321 $label = str_replace("%u",$ii,$thisOrder[4]);
322 } else {
323 $label = "";
324 }
325 $portList[] = array("name"=>$name,"port_id"=>$thisOrder[3],"port_name"=>$row3[0],"label"=>$label);
326 }
327 } else {
328 $errorText = "Port type {$thisOrder[3]} is not found or not a port type.";
329 }
330 } else {
331 $errorText = "Config part {$orderCnt} wants more than 1 port without using %u parameter.";
332 }
333 } else {
334 $errorText = "Config part {$orderCnt} refers to <i>HW Number of Ports</i> but that is not defined or 0.";
335 }
336 } else {
337 $errorText = "Config part {$orderCnt} does not have 4 parts seperated by a |";
338 }
339 }
340 if (!isset($errorText)) {
341 $foundError = false;
342 }
343 } else {
344 $errorText = "Autoport configuration for this dictionary key ({$searchIt}) is empty.";
345 }
346 } else {
347 $errorText = "Autoport configuration for this dictionary key ({$searchIt}) not found.";
348 }
349 } else {
350 $errorText = "Port generator only works if no ports have been configured yet.";
351 }
352 return !$foundError;
353 }
354
355 function localfunc_PortGenerator()
356 {
357 global $errorText, $lookFor, $portList, $genText, $valueConfiguration, $searchIt;
358 assertUIntArg ('object_id', __FUNCTION__);
359 $object = spotEntity ('object', $_REQUEST['object_id']);
360 startPortlet("Port generator");
361 print "<center><br>";
362 if (!localverify_PortGenerator($object)) {
363 //
364 // Autoport configuration did not work. Show this and show the error
365 //
366 print "{$lookFor} :&nbsp; &nbsp; &nbsp;Error\n";
367 if (isset($errorText)) {
368 print $errorText;
369 }
370 } else {
371 //
372 // Show the list of ports that will be generated and provide a link to actually do so
373 //
374 print "<a href='".makeHrefProcess(array('op'=>'addports','page'=>'object','object_id'=>$object['id'],'tab'=>'ports')).
375 "'>Generate the ports for <b>{$object['name']}</b> as listed below NOW</a><br>\n";
376 print $genText."<p>";
377 print "<table cellspacing=0 cellpadding='5' align='center' class='widetable'>";
378 print "<tr><th>Port name&nbsp;&nbsp;</th><th>Port label&nbsp;&nbsp;</th><th>Port type</th></tr>\n";
379 foreach ($portList as $aPort) {
380 print "<tr><td>{$aPort['name']}</td><td>{$aPort['label']}</td><td>{$aPort['port_name']}</td></tr>\n";
381 }
382 print "</table>";
383 }
384 print "<br></center>";
385 finishPortlet();
386 //
387 // Check whether the user is allowed to do an update of the port configurator
388 //
389 // if you do not want this, make sure you add a
390 // deny {$op_updateportgenerator}
391 // for the apprioriate groups (or any allow first and deny for the rest
392 //
393 if (permitted('object','portgenerator',null,array(array ('tag' => '$op_updateportgenerator')))) {
394 startPortlet("Update autoport configuration");
395 //
396 // Description of the config rules
397 //
398 print "<center>";
399 print $genText."<p>\n";
400 print "<b>USAGE</b><br><br>";
401 print "&lt;list1&gt;;&lt;list2&gt;;.... where &lt;listx&gt; is<br>";
402 print "&lt;start port #&gt;|&lt;port count, use %n for number of ports&gt;|";
403 print "&lt;port name, use %u for number&gt;|[&lt;port innerinterface id&gt;-]&lt;port type id&gt;[|&lt;port label, use %u for number&gt;]<br><br>";
404 print "<b>EXAMPLE (for Force10 S4810)</b><br><br>0|48|%u|9-1084|TenGigabitEthernet0/%u;48|4|%u|10-1588|FortyGigE0/48;52|4|%u|10-1588|FortyGigE0/52;56|4|%u|10-1588|FortyGigE0/56;60|4|%u|10-1588|FortyGigE0/60;1|1|RS-232|29|Serial port;1|1|Ethernet|24|ManagementEthernet0/%u;1|2|AC%u|16<br><br>";
405 print "<b>EXPLANATION (for AC-in ports)</b><br><br> <b>1</b> = starting number,
406 <b>2</b> = number of generated ports,
407 <b>AC%u</b> = will begin with <b>starting number</b> and create up to the <b>number of generated ports</b>,
408 <b>16</b> = the value displayed on the chart below <b>in bold</b> (Notice: Default innerinterface ID is 1 /hardwired/, so the realy value is <b>1-16</b>)<br><br>"; //explains example
409 print "<b>PLEASE NOTE</b><br><br> If you do not add the port that is selected <b>(dictionary value)</b> to the default list in the <b>Ports</b> Tab,
410 you will get a <b>foriegn key violation</b> error.
411 You must go to the <b>Configuration</b> area on the main page, go to <b>Enable port types</b>
412 and hit the <b>Edit</b> tab to place the selected port in either <b>GBIC</b>, <b>hardwired</b>, or any other configuration
413 on the page so that the error is not recieved.<br><br><br>"; //Very important to have a sucessful implementation of port generator
414 //
415 // The form that can update the configuration
416 // On top of the table of ports avialabe instead of beneath it
417 //
418 printOpFormIntro ('updateportgenerator', array ('yId' => $searchIt));
419 print "<b>Autoport Configuration:</b><br><br><input type='text' style='width:100%; font-size: 16px' name='yConfig' value='";
420 if ($valueConfiguration) {
421 print $valueConfiguration[0];
422 }
423 print "'><br><br>\n";
424 print "<input type='submit' name='autoportconfig' value='";
425 if ($valueConfiguration) {
426 print "Update";
427 } else {
428 print "Create";
429 }
430 print "'>\n";
431 print "</form>\n";
432 print "</center><br>";
433
434 print "<table border='2' rules=all>\n<tr class=row_odd>";
435 $isfirst = true;
436 $i = 0;
437 //
438 // List all available port types with their dictionary key
439 //
440 $q = "SELECT IF(iif_id,CONCAT(i.id,'-',o.id),o.id) as ID , IF(iif_id,CONCAT(i.iif_name,' => ',o.oif_name),o.oif_name) as name FROM PortOuterInterface o left join PortInterfaceCompat c on o.id = c.oif_id left join PortInnerInterface i on c.iif_id = i.id order by i.id,o.id";
441 $result = usePreparedSelectBlade ($q);//Changed for new configeration in versions after 0.17.x
442 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
443 while ($row4 = $result->fetch (PDO::FETCH_NUM)) {
444 if (!$isfirst && $i%10==0) {
445 print "</td></tr>\n<tr class=".( ($i%4==0) ? "row_odd" : "row_even" ).">";
446 } else {
447 $isfirst = false;
448 }
449 print "<td><b>{$row4[0]}</b><br>";//seperated values to make them easier to read
450 print "{$row4[1]}\n</td>";
451 $i++;
452 }
453 print "</td>\n";
454 print "</tr></table>\n";
455
456 finishPortlet();
457 }
458 }
459
460 //
461 // The actual port generator
462 //
463 //$msgcode['localexecute_PortGenerator']['OK'] = 0;
464 //$msgcode['localexecute_PortGenerator']['ERR'] = 100;
465
466 function localexecute_PortGenerator()
467 {
468 global $errorText, $portList;
469 $linkok = localtrigger_PortGenerator();
470 if ($linkok) {
471 assertUIntArg ('object_id', __FUNCTION__);
472 $object = spotEntity ('object', $_REQUEST['object_id']);
473 if (localverify_PortGenerator($object)) {
474 $cnt = 0;
475 foreach ($portList as $aPort) {
476 commitAddPort($_REQUEST['object_id'],$aPort['name'],$aPort['port_id'],$aPort['label'],"");
477 $cnt++;
478 }
479 }
480 } else {
481 $errorText = "Port generator not allowed";
482 }
483 if ($linkok) {
484 //return buildRedirectURL (__FUNCTION__, 'OK', array ("Successfully added {$cnt} ports"));
485 return setMessage ('success', $message="Successfully added {$cnt} ports");
486 } else {
487 //return buildRedirectURL (__FUNCTION__, 'ERR', array ("Error adding the ports ({$errorText})"));
488 return setMessage ('error', $message="Error adding the ports ({$errorText})");
489 }
490 }
491
492 //
493 // Update the configuration scheme
494 //
495 //$msgcode['updateconfig_PortGenerator']['OK'] = 0;
496 //$msgcode['updateconfig_PortGenerator']['ERR'] = 100;
497
498
499 function updateconfig_PortGenerator()
500 {
501 global $tablePortGenerator;
502 checkForTable();
503 $q = "SELECT autoportconfig FROM {$tablePortGenerator} WHERE dict_key={$_REQUEST['yId']} ";
504 $result = usePreparedSelectBlade ($q);
505 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
506 if ($row = $result->fetch (PDO::FETCH_NUM)) {
507 $q = "UPDATE {$tablePortGenerator} SET autoportconfig='{$_REQUEST['yConfig']}' WHERE dict_key={$_REQUEST['yId']} ";
508 } else {
509 $q = "INSERT INTO {$tablePortGenerator} (dict_key,autoportconfig) VALUES ({$_REQUEST['yId']},'{$_REQUEST['yConfig']}') ";
510 }
511 $result = usePreparedSelectBlade ($q);
512 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
513 if (true) {
514 return setMessage('success',$message="Successfully updated auto port configuration");
515 } else {
516 print "false";
517 return setMessage ('error', $message="Error in update to auto port configuration");
518 }
519 }