workaround Enterasys sfp 1000-sx/lx
[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
1b77584d
AD
56Example for a Port Innerinterface + Outerinterface:
571|2|G%u|4-1077|gigabitEthernet0/%u
58
59This will generate the following ports:
60G1 of inner Type 4 and outer type 1077 (SFP-1000 with empty SFP-1000 inside)
61G2 of inner Type 4 and outer type 1077 (SFP-1000 with empty SFP-1000 inside)
62
91b12714
DO
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/*
79CREATE 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
23217dfb
DO
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. ***
91b12714 130//
1b77584d
AD
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
91b12714
DO
140$tab['object']['portgenerator'] = 'Port generator';
141$trigger['object']['portgenerator'] = 'localtrigger_PortGenerator';
142$tabhandler['object']['portgenerator'] = 'localfunc_PortGenerator';
143$ophandler['object']['portgenerator']['updateportgenerator'] = 'updateconfig_PortGenerator';
144$ophandler['object']['ports']['addports'] = 'localexecute_PortGenerator';
145
146//
147// Check whether the variables are set or otherwise set the default values.
148//
149global $noPortGenerator;
150if (!isset($noPortGenerator)) {
151 $noPortGenerator = array();
152}
153global $tablePortGenerator;
154if (!isset($tablePortGenerator)) {
155 $tablePortGenerator = "AutoPort";
156}
157if (!defined("_portGeneratorHWType")) {
158 define("_portGeneratorHWType",2);
159}
160if (!defined("_portGeneratorNumberOfPorts")) {
161 define("_portGeneratorNumberOfPorts",6);
162}
163//
164// Check whether the table exists. If not, create it
165//
fd5a3356
DO
166function checkForTable ()
167{
168 global $tablePortGenerator;
23217dfb 169 $result = usePreparedSelectBlade ("SHOW TABLES LIKE '{$tablePortGenerator}'");
91b12714 170 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
fd5a3356
DO
171 if (!($row = $result->fetch (PDO::FETCH_NUM))) {
172 $q = "CREATE TABLE IF NOT EXISTS `{$tablePortGenerator}` (
23217dfb 173 `dict_key` int(10) unsigned NOT NULL auto_increment,
fd5a3356
DO
174 `autoportconfig` text NOT NULL,
175 UNIQUE KEY `dict_key` (`dict_key`)
176 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
23217dfb 177 $result = usePreparedSelectBlade ($q);
fd5a3356
DO
178 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
179 }
91b12714
DO
180}
181
182//
183// function to check whether a tab Port generator should be shown
184// If there are already ports configured or the object type id is in $noPortGenerator
185// (which is an array of object type ids) then do not show the tab
186//
187function localtrigger_PortGenerator()
188{
189 global $noPortGenerator;
190 assertUIntArg ('object_id', __FUNCTION__);
191 $object = spotEntity ('object', $_REQUEST['object_id']);
192 $record = getObjectPortsAndLinks ($object['id']);
193 if (count($record)==0 && !in_array($object['objtype_id'],$noPortGenerator))
23217dfb
DO
194 //return 1;
195 return 'std';
91b12714
DO
196 else
197 {
198 return '';
199 }
200}
201
202//
203// This function checks whether there is a configuration available for the selected object type id
204// (and if necessary for the hardware type id which is found as attribute id _portGeneratorHWType
205function localverify_PortGenerator($object) {
206 global $tablePortGenerator, $errorText, $lookFor, $portList, $genText, $valueConfiguration, $searchIt;
fd5a3356 207 checkForTable();
91b12714
DO
208 $foundError = true;
209 $record = getObjectPortsAndLinks ($object['id']);
210 //
211 // Make sure that there are no ports configured
212 //
213 if (count($record)==0) {
214 //
215 // Check whether the object type for the selected object has an attribute hardware type
216 // If it does, use the hardware type for configuration. Otherwise use the generic object type
217 //
218 $lookFor = "Hardware type";
219 $q = "SELECT * FROM AttributeMap WHERE attr_id="._portGeneratorHWType." AND objtype_id={$object['objtype_id']} ";
23217dfb 220 $result = usePreparedSelectBlade ($q);
91b12714
DO
221 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
222 if ($row = $result->fetch (PDO::FETCH_NUM)) {
223 //
224 // There is a hardware type available for this object type. Check whether it is set
225 // If it is, search for the specific port configuration for that hardware type
226 // If it is not set, use the generic port configuration for the object type
227 //
228 $q = "SELECT uint_value, dict_value FROM AttributeValue, Dictionary ";
229 $q .= "WHERE attr_id="._portGeneratorHWType." AND object_id={$object['id']} AND dict_key=uint_value ";
23217dfb 230 $result = usePreparedSelectBlade ($q);
91b12714
DO
231 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
232 if ($row = $result->fetch (PDO::FETCH_NUM)) {
233 $searchIt = $row[0];
234 $searchText = "OK (based on hardware type)";
235 $searchType = 3;
236 $genText = "{$object['objtype_name']}: {$row[1]}";
237 $genText = str_replace(array("%GPASS%")," ",$genText);
238 } else {
239 $searchIt = $object['objtype_id'];
240 $searchText = "Based on object type, hardware type not set";
241 $searchType = 2;
242 $genText = "<b>GENERIC</b> {$object['objtype_name']}";
243 }
244 } else {
245 $searchIt = $object['objtype_id'];
246 $searchText = "OK (based on object type)";
247 $searchType = 1;
248 $genText = "{$object['objtype_name']}";
249 }
250 $lookFor = "Autoport configuration";
251 $q = "SELECT autoportconfig FROM {$tablePortGenerator} WHERE dict_key={$searchIt} ";
23217dfb 252 $result = usePreparedSelectBlade ($q);
91b12714
DO
253 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
254 //
255 // Check if there is an autoport configuration for the requested key
256 //
257 if ($valueConfiguration = $result->fetch (PDO::FETCH_NUM)) {
258 $lookFor = "Configuration";
259 $q = "SELECT uint_value FROM AttributeValue ";
260 $q .= "WHERE attr_id="._portGeneratorNumberOfPorts." AND object_id={$_REQUEST['object_id']} ";
261 //
262 // Check for the value of the number of ports. If it is not found set it to 0
263 //
23217dfb 264 $result = usePreparedSelectBlade ($q);
91b12714
DO
265 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
266 if ($valueNumberOfPorts = $result->fetch (PDO::FETCH_NUM)) {
267 } else {
268 $valueNumberOfPorts[0] = 0;;
269 }
270 //
271 // $portList will contain the list of ports to be generated
272 //
273 $portList = array();
274 //
275 // $portOrders array will be filled with individual port generation schemes
276 // <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>]
277 // The configuration contains a semicolon seperated list of the schemes
278 //
279 // An example of this would be:
280 // 1|2|pwr%u|16;1|%n|eth%u|24|%u
281 //
282 $portOrders = explode(";",$valueConfiguration[0]);
283 if (count($portOrders)>0) {
284 $orderCnt = 0;
285 foreach ($portOrders as $aPortOrder) {
286 //
287 // Split up each scheme and check for errors
288 // If there are not errors, populate the $portList
289 //
290 $orderCnt++;
291 $thisOrder = explode("|",$aPortOrder);
292 if (count($thisOrder)==4 || count($thisOrder)==5) {
293 if ($thisOrder[1]!="%n" || $valueNumberOfPorts[0]!=0) {
294 if ($thisOrder[1]=="%n") {
295 $thisOrder[1] = $valueNumberOfPorts[0];
296 }
297 if ($thisOrder[1]==1 || strpos($thisOrder[2],"%u")!==false) {
1b77584d
AD
298 if (preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $thisOrder[3], $matches))
299 $oif_id = $matches[2];
300 else
301 $oif_id = $thisOrder[3];
302 $q = "SELECT dict_value FROM Dictionary WHERE dict_key='$oif_id' AND chapter_id=2 ";
23217dfb 303 $result = usePreparedSelectBlade ($q);
91b12714
DO
304 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
305 if ($row3 = $result->fetch (PDO::FETCH_NUM)) {
306 for ($i=1;$i<=$thisOrder[1];$i++) {
307 $ii = $thisOrder[0]+$i-1;
308 $name = str_replace("%u",$ii,$thisOrder[2]);
309 if (count($thisOrder)==5) {
310 $label = str_replace("%u",$ii,$thisOrder[4]);
311 } else {
312 $label = "";
313 }
314 $portList[] = array("name"=>$name,"port_id"=>$thisOrder[3],"port_name"=>$row3[0],"label"=>$label);
315 }
316 } else {
317 $errorText = "Port type {$thisOrder[3]} is not found or not a port type.";
318 }
319 } else {
320 $errorText = "Config part {$orderCnt} wants more than 1 port without using %u parameter.";
321 }
322 } else {
323 $errorText = "Config part {$orderCnt} refers to <i>HW Number of Ports</i> but that is not defined or 0.";
324 }
325 } else {
326 $errorText = "Config part {$orderCnt} does not have 4 parts seperated by a |";
327 }
328 }
329 if (!isset($errorText)) {
330 $foundError = false;
331 }
332 } else {
333 $errorText = "Autoport configuration for this dictionary key ({$searchIt}) is empty.";
334 }
335 } else {
336 $errorText = "Autoport configuration for this dictionary key ({$searchIt}) not found.";
337 }
338 } else {
339 $errorText = "Port generator only works if no ports have been configured yet.";
340 }
341 return !$foundError;
342}
343
344function localfunc_PortGenerator()
345{
346 global $errorText, $lookFor, $portList, $genText, $valueConfiguration, $searchIt;
347 assertUIntArg ('object_id', __FUNCTION__);
348 $object = spotEntity ('object', $_REQUEST['object_id']);
349 startPortlet("Port generator");
350 print "<center><br>";
351 if (!localverify_PortGenerator($object)) {
352 //
353 // Autoport configuration did not work. Show this and show the error
354 //
355 print "{$lookFor} :&nbsp; &nbsp; &nbsp;Error\n";
356 if (isset($errorText)) {
357 print $errorText;
358 }
359 } else {
360 //
361 // Show the list of ports that will be generated and provide a link to actually do so
362 //
363 print "<a href='".makeHrefProcess(array('op'=>'addports','page'=>'object','object_id'=>$object['id'],'tab'=>'ports')).
364 "'>Generate the ports for <b>{$object['name']}</b> as listed below NOW</a><br>\n";
365 print $genText."<p>";
366 print "<table cellspacing=0 cellpadding='5' align='center' class='widetable'>";
367 print "<tr><th>Port name&nbsp;&nbsp;</th><th>Port label&nbsp;&nbsp;</th><th>Port type</th></tr>\n";
368 foreach ($portList as $aPort) {
369 print "<tr><td>{$aPort['name']}</td><td>{$aPort['label']}</td><td>{$aPort['port_name']}</td></tr>\n";
370 }
371 print "</table>";
372 }
373 print "<br></center>";
374 finishPortlet();
375 //
376 // Check whether the user is allowed to do an update of the port configurator
377 //
378 // if you do not want this, make sure you add a
379 // deny {$op_updateportgenerator}
380 // for the apprioriate groups (or any allow first and deny for the rest
381 //
382 if (permitted('object','portgenerator',null,array(array ('tag' => '$op_updateportgenerator')))) {
383 startPortlet("Update autoport configuration");
384 //
385 // Description of the config rules
386 //
387 print "<center>";
388 print $genText."<p>\n";
389 print "&lt;list1&gt;;&lt;list2&gt;;.... where &lt;listx&gt; is<br>";
390 print "&lt;start port #&gt;|&lt;port count, use %n for number of ports&gt;|";
1b77584d 391 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>";
23217dfb
DO
392 print "<b>EXAMPLE</b><br><br> 1|15|eth%u|24; <br><br>"; //an example of how to use port generator
393 print "<b>EXPLANATION</b><br><br> <b>1</b> = starting number,
394 <b>15</b> = number of generated ports,
395 <b>eth%u</b> = will begin with <b>starting number</b> and create up to the <b>number of generated ports</b>,
396 <b>24</b> = the dictionary value displayed on the chart below <b>in bold</b><br><br>"; //explains example
397 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,
398 you will get a <b>foriegn key violation</b> error.
399 You must go to the <b>Configuration</b> area on the main page, go to <b>Enable port types</b>
400 and hit the <b>Edit</b> tab to place the selected port in either <b>GBIC</b>, <b>hardwired</b>, or any other configuration
401 on the page so that the error is not recieved.<br><br><br>"; //Very important to have a sucessful implementation of port generator
91b12714
DO
402 //
403 // The form that can update the configuration
23217dfb
DO
404 // On top of the table of ports avialabe instead of beneath it
405 //
406 printOpFormIntro ('updateportgenerator', array ('yId' => $searchIt));
91b12714
DO
407 print "Autoport Configuration : <input type='text' size='60' name='yConfig' value='";
408 if ($valueConfiguration) {
409 print $valueConfiguration[0];
410 }
411 print "'><br><br>\n";
412 print "<input type='submit' name='autoportconfig' value='";
413 if ($valueConfiguration) {
414 print "Update";
415 } else {
416 print "Create";
417 }
418 print "'>\n";
419 print "</form>\n";
23217dfb
DO
420 print "</center><br>";
421
422 print "<table border='2' rules=all>\n<tr>";
423 $isfirst = true;
424 $i = 0;
425 //
426 // List all available port types with their dictionary key
427 //
428 $q = "SELECT dict_key, dict_value FROM Dictionary WHERE chapter_id=2 ORDER BY dict_value ";
429 $result = usePreparedSelectBlade ($q);//Changed for new configeration in versions after 0.17.x
430 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
431 while ($row4 = $result->fetch (PDO::FETCH_NUM)) {
432 if (!$isfirst && $i%10==0) { //Change from %12 to %10 to render table evenly
433 print "</td></tr>\n"; //Change to </td></tr> so that each dictionary entry is nestled in its own cell
434 } else {
435 $isfirst = false;
436 }
437 if ($i%10==0) {
438 print "<td align='left'></td>";
439 $i=0;
440 }
441 $length = strlen($row4[1]);
442
443 $padded_row = str_pad($row4[1], 32, " ", STR_PAD_RIGHT);//Does not work yet, will make each cell the same size
444 print "<td><b>{$row4[0]}</b>:";//seperated values to make them easier to read
445 print "{$padded_row}\n</td>";
446 $i++;
447 }
448 print "</td>\n";
449 print "</tr></table>\n";
450
91b12714
DO
451 finishPortlet();
452 }
453}
454
455//
456// The actual port generator
457//
23217dfb
DO
458//$msgcode['localexecute_PortGenerator']['OK'] = 0;
459//$msgcode['localexecute_PortGenerator']['ERR'] = 100;
91b12714
DO
460
461function localexecute_PortGenerator()
462{
463 global $errorText, $portList;
464 $linkok = localtrigger_PortGenerator();
465 if ($linkok) {
466 assertUIntArg ('object_id', __FUNCTION__);
467 $object = spotEntity ('object', $_REQUEST['object_id']);
468 if (localverify_PortGenerator($object)) {
469 $cnt = 0;
470 foreach ($portList as $aPort) {
23217dfb 471 commitAddPort($_REQUEST['object_id'],$aPort['name'],$aPort['port_id'],$aPort['label'],"");
91b12714
DO
472 $cnt++;
473 }
474 }
475 } else {
476 $errorText = "Port generator not allowed";
477 }
478 if ($linkok) {
23217dfb
DO
479 //return buildRedirectURL (__FUNCTION__, 'OK', array ("Successfully added {$cnt} ports"));
480 return setMessage ('success', $message="Successfully added {$cnt} ports");
91b12714 481 } else {
23217dfb
DO
482 //return buildRedirectURL (__FUNCTION__, 'ERR', array ("Error adding the ports ({$errorText})"));
483 return setMessage ('error', $message="Error adding the ports ({$errorText})");
91b12714
DO
484 }
485}
486
487//
488// Update the configuration scheme
489//
23217dfb
DO
490//$msgcode['updateconfig_PortGenerator']['OK'] = 0;
491//$msgcode['updateconfig_PortGenerator']['ERR'] = 100;
492
91b12714
DO
493
494function updateconfig_PortGenerator()
495{
496 global $tablePortGenerator;
fd5a3356 497 checkForTable();
91b12714 498 $q = "SELECT autoportconfig FROM {$tablePortGenerator} WHERE dict_key={$_REQUEST['yId']} ";
23217dfb 499 $result = usePreparedSelectBlade ($q);
91b12714
DO
500 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
501 if ($row = $result->fetch (PDO::FETCH_NUM)) {
502 $q = "UPDATE {$tablePortGenerator} SET autoportconfig='{$_REQUEST['yConfig']}' WHERE dict_key={$_REQUEST['yId']} ";
503 } else {
504 $q = "INSERT INTO {$tablePortGenerator} (dict_key,autoportconfig) VALUES ({$_REQUEST['yId']},'{$_REQUEST['yConfig']}') ";
505 }
23217dfb 506 $result = usePreparedSelectBlade ($q);
91b12714
DO
507 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
508 if (true) {
23217dfb 509 return setMessage('success',$message="Successfully updated auto port configuration");
91b12714 510 } else {
23217dfb
DO
511 print "false";
512 return setMessage ('error', $message="Error in update to auto port configuration");
91b12714
DO
513 }
514}
515
1b77584d 516?>