r3631 Adding a copy of initial verion of patch panel routing extension
[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//
112$result = useSelectBlade ("SHOW TABLES LIKE '{$tablePortGenerator}'", __FUNCTION__);
113if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
114if (!($row = $result->fetch (PDO::FETCH_NUM))) {
115 $q = "CREATE TABLE IF NOT EXISTS `{$tablePortGenerator}` (
116 `dict_key` int(11) NOT NULL,
117 `autoportconfig` text NOT NULL,
118 UNIQUE KEY `dict_key` (`dict_key`)
119 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;";
120 $result = useSelectBlade ($q, __FUNCTION__);
121 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
122}
123
124//
125// function to check whether a tab Port generator should be shown
126// If there are already ports configured or the object type id is in $noPortGenerator
127// (which is an array of object type ids) then do not show the tab
128//
129function localtrigger_PortGenerator()
130{
131 global $noPortGenerator;
132 assertUIntArg ('object_id', __FUNCTION__);
133 $object = spotEntity ('object', $_REQUEST['object_id']);
134 $record = getObjectPortsAndLinks ($object['id']);
135 if (count($record)==0 && !in_array($object['objtype_id'],$noPortGenerator))
136 return 1;
137 else
138 {
139 return '';
140 }
141}
142
143//
144// This function checks whether there is a configuration available for the selected object type id
145// (and if necessary for the hardware type id which is found as attribute id _portGeneratorHWType
146function localverify_PortGenerator($object) {
147 global $tablePortGenerator, $errorText, $lookFor, $portList, $genText, $valueConfiguration, $searchIt;
148 $foundError = true;
149 $record = getObjectPortsAndLinks ($object['id']);
150 //
151 // Make sure that there are no ports configured
152 //
153 if (count($record)==0) {
154 //
155 // Check whether the object type for the selected object has an attribute hardware type
156 // If it does, use the hardware type for configuration. Otherwise use the generic object type
157 //
158 $lookFor = "Hardware type";
159 $q = "SELECT * FROM AttributeMap WHERE attr_id="._portGeneratorHWType." AND objtype_id={$object['objtype_id']} ";
160 $result = useSelectBlade ($q, __FUNCTION__);
161 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
162 if ($row = $result->fetch (PDO::FETCH_NUM)) {
163 //
164 // There is a hardware type available for this object type. Check whether it is set
165 // If it is, search for the specific port configuration for that hardware type
166 // If it is not set, use the generic port configuration for the object type
167 //
168 $q = "SELECT uint_value, dict_value FROM AttributeValue, Dictionary ";
169 $q .= "WHERE attr_id="._portGeneratorHWType." AND object_id={$object['id']} AND dict_key=uint_value ";
170 $result = useSelectBlade ($q, __FUNCTION__);
171 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
172 if ($row = $result->fetch (PDO::FETCH_NUM)) {
173 $searchIt = $row[0];
174 $searchText = "OK (based on hardware type)";
175 $searchType = 3;
176 $genText = "{$object['objtype_name']}: {$row[1]}";
177 $genText = str_replace(array("%GPASS%")," ",$genText);
178 } else {
179 $searchIt = $object['objtype_id'];
180 $searchText = "Based on object type, hardware type not set";
181 $searchType = 2;
182 $genText = "<b>GENERIC</b> {$object['objtype_name']}";
183 }
184 } else {
185 $searchIt = $object['objtype_id'];
186 $searchText = "OK (based on object type)";
187 $searchType = 1;
188 $genText = "{$object['objtype_name']}";
189 }
190 $lookFor = "Autoport configuration";
191 $q = "SELECT autoportconfig FROM {$tablePortGenerator} WHERE dict_key={$searchIt} ";
192 $result = useSelectBlade ($q, __FUNCTION__);
193 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
194 //
195 // Check if there is an autoport configuration for the requested key
196 //
197 if ($valueConfiguration = $result->fetch (PDO::FETCH_NUM)) {
198 $lookFor = "Configuration";
199 $q = "SELECT uint_value FROM AttributeValue ";
200 $q .= "WHERE attr_id="._portGeneratorNumberOfPorts." AND object_id={$_REQUEST['object_id']} ";
201 //
202 // Check for the value of the number of ports. If it is not found set it to 0
203 //
204 $result = useSelectBlade ($q, __FUNCTION__);
205 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
206 if ($valueNumberOfPorts = $result->fetch (PDO::FETCH_NUM)) {
207 } else {
208 $valueNumberOfPorts[0] = 0;;
209 }
210 //
211 // $portList will contain the list of ports to be generated
212 //
213 $portList = array();
214 //
215 // $portOrders array will be filled with individual port generation schemes
216 // <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>]
217 // The configuration contains a semicolon seperated list of the schemes
218 //
219 // An example of this would be:
220 // 1|2|pwr%u|16;1|%n|eth%u|24|%u
221 //
222 $portOrders = explode(";",$valueConfiguration[0]);
223 if (count($portOrders)>0) {
224 $orderCnt = 0;
225 foreach ($portOrders as $aPortOrder) {
226 //
227 // Split up each scheme and check for errors
228 // If there are not errors, populate the $portList
229 //
230 $orderCnt++;
231 $thisOrder = explode("|",$aPortOrder);
232 if (count($thisOrder)==4 || count($thisOrder)==5) {
233 if ($thisOrder[1]!="%n" || $valueNumberOfPorts[0]!=0) {
234 if ($thisOrder[1]=="%n") {
235 $thisOrder[1] = $valueNumberOfPorts[0];
236 }
237 if ($thisOrder[1]==1 || strpos($thisOrder[2],"%u")!==false) {
238 $q = "SELECT dict_value FROM Dictionary WHERE dict_key='{$thisOrder[3]}' AND chapter_id=2 ";
239 $result = useSelectBlade ($q, __FUNCTION__);
240 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
241 if ($row3 = $result->fetch (PDO::FETCH_NUM)) {
242 for ($i=1;$i<=$thisOrder[1];$i++) {
243 $ii = $thisOrder[0]+$i-1;
244 $name = str_replace("%u",$ii,$thisOrder[2]);
245 if (count($thisOrder)==5) {
246 $label = str_replace("%u",$ii,$thisOrder[4]);
247 } else {
248 $label = "";
249 }
250 $portList[] = array("name"=>$name,"port_id"=>$thisOrder[3],"port_name"=>$row3[0],"label"=>$label);
251 }
252 } else {
253 $errorText = "Port type {$thisOrder[3]} is not found or not a port type.";
254 }
255 } else {
256 $errorText = "Config part {$orderCnt} wants more than 1 port without using %u parameter.";
257 }
258 } else {
259 $errorText = "Config part {$orderCnt} refers to <i>HW Number of Ports</i> but that is not defined or 0.";
260 }
261 } else {
262 $errorText = "Config part {$orderCnt} does not have 4 parts seperated by a |";
263 }
264 }
265 if (!isset($errorText)) {
266 $foundError = false;
267 }
268 } else {
269 $errorText = "Autoport configuration for this dictionary key ({$searchIt}) is empty.";
270 }
271 } else {
272 $errorText = "Autoport configuration for this dictionary key ({$searchIt}) not found.";
273 }
274 } else {
275 $errorText = "Port generator only works if no ports have been configured yet.";
276 }
277 return !$foundError;
278}
279
280function localfunc_PortGenerator()
281{
282 global $errorText, $lookFor, $portList, $genText, $valueConfiguration, $searchIt;
283 assertUIntArg ('object_id', __FUNCTION__);
284 $object = spotEntity ('object', $_REQUEST['object_id']);
285 startPortlet("Port generator");
286 print "<center><br>";
287 if (!localverify_PortGenerator($object)) {
288 //
289 // Autoport configuration did not work. Show this and show the error
290 //
291 print "{$lookFor} :&nbsp; &nbsp; &nbsp;Error\n";
292 if (isset($errorText)) {
293 print $errorText;
294 }
295 } else {
296 //
297 // Show the list of ports that will be generated and provide a link to actually do so
298 //
299 print "<a href='".makeHrefProcess(array('op'=>'addports','page'=>'object','object_id'=>$object['id'],'tab'=>'ports')).
300 "'>Generate the ports for <b>{$object['name']}</b> as listed below NOW</a><br>\n";
301 print $genText."<p>";
302 print "<table cellspacing=0 cellpadding='5' align='center' class='widetable'>";
303 print "<tr><th>Port name&nbsp;&nbsp;</th><th>Port label&nbsp;&nbsp;</th><th>Port type</th></tr>\n";
304 foreach ($portList as $aPort) {
305 print "<tr><td>{$aPort['name']}</td><td>{$aPort['label']}</td><td>{$aPort['port_name']}</td></tr>\n";
306 }
307 print "</table>";
308 }
309 print "<br></center>";
310 finishPortlet();
311 //
312 // Check whether the user is allowed to do an update of the port configurator
313 //
314 // if you do not want this, make sure you add a
315 // deny {$op_updateportgenerator}
316 // for the apprioriate groups (or any allow first and deny for the rest
317 //
318 if (permitted('object','portgenerator',null,array(array ('tag' => '$op_updateportgenerator')))) {
319 startPortlet("Update autoport configuration");
320 //
321 // Description of the config rules
322 //
323 print "<center>";
324 print $genText."<p>\n";
325 print "&lt;list1&gt;;&lt;list2&gt;;.... where &lt;listx&gt; is<br>";
326 print "&lt;start port #&gt;|&lt;port count, use %n for number of ports&gt;|";
327 print "&lt;port name, use %u for number&gt;|&lt;port type id&gt;[|&lt;port label, use %u for number&gt;]<br><br>";
328 print "<table><tr>\n";
329 $isfirst = true;
330 $i = 0;
331 //
332 // List all available port types with their dictionary key
333 //
334 $q = "SELECT dict_key, dict_value FROM Dictionary WHERE chapter_id=2 ORDER BY dict_value ";
335 $result = useSelectBlade ($q, __FUNCTION__);
336 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
337 while ($row4 = $result->fetch (PDO::FETCH_NUM)) {
338 if (!$isfirst && $i%12==0) {
339 print "</td>";
340 } else {
341 $isfirst = false;
342 }
343 if ($i%12==0) {
344 print "<td align='left'>";
345 }
346 print "<b>{$row4[0]}</b>:{$row4[1]}<br>\n";
347 $i++;
348 }
349 print "</td>\n";
350 print "</tr></table>\n";
351 //
352 // The form that can update the configuration
353 //
354 print "<form action='process.php' method='GET'>\n";
355 print "<input type='hidden' name='page' value='object'>\n";
356 print "<input type='hidden' name='tab' value='portgenerator'>\n";
357 print "<input type='hidden' name='op' value='updateportgenerator'>\n";
358 print "<input type='hidden' name='object_id' value='{$_REQUEST['object_id']}'>\n";
359 print "<input type='hidden' name='yId' value='{$searchIt}'>\n";
360 print "Autoport Configuration : <input type='text' size='60' name='yConfig' value='";
361 if ($valueConfiguration) {
362 print $valueConfiguration[0];
363 }
364 print "'><br><br>\n";
365 print "<input type='submit' name='autoportconfig' value='";
366 if ($valueConfiguration) {
367 print "Update";
368 } else {
369 print "Create";
370 }
371 print "'>\n";
372 print "</form>\n";
373 print "</center>";
374 finishPortlet();
375 }
376}
377
378//
379// The actual port generator
380//
381$msgcode['localexecute_PortGenerator']['OK'] = 0;
382$msgcode['localexecute_PortGenerator']['ERR'] = 100;
383
384function localexecute_PortGenerator()
385{
386 global $errorText, $portList;
387 $linkok = localtrigger_PortGenerator();
388 if ($linkok) {
389 assertUIntArg ('object_id', __FUNCTION__);
390 $object = spotEntity ('object', $_REQUEST['object_id']);
391 if (localverify_PortGenerator($object)) {
392 $cnt = 0;
393 foreach ($portList as $aPort) {
394 commitAddPort($_REQUEST['object_id'],$aPort['name'],$aPort['port_id'],"","");
395 $cnt++;
396 }
397 }
398 } else {
399 $errorText = "Port generator not allowed";
400 }
401 if ($linkok) {
402 return buildRedirectURL (__FUNCTION__, 'OK', array ("Successfully added {$cnt} ports"));
403 } else {
404 return buildRedirectURL (__FUNCTION__, 'ERR', array ("Error adding the ports ({$errorText})"));
405 }
406}
407
408//
409// Update the configuration scheme
410//
411$msgcode['updateconfig_PortGenerator']['OK'] = 0;
412$msgcode['updateconfig_PortGenerator']['ERR'] = 100;
413
414function updateconfig_PortGenerator()
415{
416 global $tablePortGenerator;
417 $q = "SELECT autoportconfig FROM {$tablePortGenerator} WHERE dict_key={$_REQUEST['yId']} ";
418 $result = useSelectBlade ($q, __FUNCTION__);
419 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
420 if ($row = $result->fetch (PDO::FETCH_NUM)) {
421 $q = "UPDATE {$tablePortGenerator} SET autoportconfig='{$_REQUEST['yConfig']}' WHERE dict_key={$_REQUEST['yId']} ";
422 } else {
423 $q = "INSERT INTO {$tablePortGenerator} (dict_key,autoportconfig) VALUES ({$_REQUEST['yId']},'{$_REQUEST['yConfig']}') ";
424 }
425 $result = useSelectBlade ($q, __FUNCTION__);
426 if ($result==NULL) { print_r($dbxlink->errorInfo()); die(); }
427 if (true) {
428 return buildRedirectURL (__FUNCTION__, 'OK', array ("Successfully updated auto port configuration"));
429 } else {
430 return buildRedirectURL (__FUNCTION__, 'ERR', array ("Error update auto port configuration"));
431 }
432}
433
434?>