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