function getExpirationsText() { $row_format = "%3s|%-30s|%-15s|%-15s|%s\r\n"; $ret = ''; $breakdown = array(); $breakdown[21] = array(array('from' => -365, 'to' => 0, 'title' => 'has expired within last year'), array('from' => 0, 'to' => 30, 'title' => 'expires within 30 days')); $breakdown[22] = $breakdown[21]; $breakdown[24] = $breakdown[21]; $attrmap = getAttrMap(); foreach ($breakdown as $attr_id => $sections) { $ret .= $attrmap[$attr_id]['name'] . "\r\n"; $ret .= "===========================================\r\n"; foreach ($sections as $section) { $count = 1; $result = scanAttrRelativeDays($attr_id, $section['from'], $section['to']); if (!count($result)) { continue; } $ret .= $section['title'] . "\r\n"; $ret .= "-----------------------------------------------------------------------------------\r\n"; $ret .= sprintf($row_format, '#', 'Name', 'Asset Tag', 'OEM S/N 1', 'Date Warranty Expires'); $ret .= "-----------------------------------------------------------------------------------\r\n"; foreach ($result as $row) { $object = spotEntity('object', $row['object_id']); $attributes = getAttrValues($object['id']); $ret .= sprintf($row_format, $count, $object['dname'], $object['asset_no'], array_key_exists(1, $attributes) ? $attributes[1]['a_value'] : '', datetimestrFromTimestamp($row['uint_value'])); $count++; } $ret .= "-----------------------------------------------------------------------------------\r\n"; } $ret .= "\r\n"; } return $ret; }
function NagiosTabHandler() { global $nagios_user, $nagios_password, $nagios_url; # Load object data assertUIntArg('object_id', __FUNCTION__); $object = spotEntity('object', $_REQUEST['object_id']); $nagios_url_cgi = $nagios_url . '/cgi-bin/status.cgi?host=%%NAGIOS%%'; $nagios_url_cgi = str_replace("%%NAGIOS%%", urlencode($object['name']), $nagios_url_cgi); # Curl request $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $nagios_url_cgi); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERPWD, "{$nagios_user}:{$nagios_password}"); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); $output = curl_exec($ch); $info = curl_getinfo($ch); curl_close($ch); # Remove unwanted tags & headline & hyperlinks $output = strip_tags($output, '<p><div><table><tr><td><th><br><a>'); $output = substr($output, strpos($output, '<')); $output = str_replace("HREF='", "onclick='return popup(this.href);' target='_blank' HREF='{$nagios_url}/cgi-bin/", $output); $output = str_replace("href='", "onclick='return popup(this.href);' target='_blank' href='{$nagios_url}/cgi-bin/", $output); $output = str_replace($nagios_url . "/cgi-bin/http://www.nagios.org", "http://www.nagios.org", $output); # Output htmlExtras(); echo '<div class=portlet><h2>Nagios</h2>' . $output . '</div>'; }
function CableIDTabHandler() { echo '<div class=portlet><h2>Cable ID Helper</h2></div>'; $rack = spotEntity('rack', $_REQUEST['rack_id']); $result = usePreparedSelectBlade('SELECT DISTINCT object_id FROM RackSpace WHERE rack_id = ? ', array($rack['id'])); $objects = $result->fetchAll(PDO::FETCH_ASSOC); $cableIDs = array(); foreach ($objects as $object) { $pals = getObjectPortsAndLinks($object['object_id']); foreach ($pals as $portLink) { if ($portLink['cableid']) { $new = true; $dublicate = false; foreach ($cableIDs as $key => $cableID) { if ($portLink['object_id'] == $cableID['object1_id'] && $portLink['name'] == $cableID['object1_port'] || $portLink['object_id'] == $cableID['object2_id'] && $portLink['name'] == $cableID['object2_port']) { $new = false; // Link already in List } // Check for duplicate cable ids if ($new && $portLink['cableid'] == $cableID['cableID']) { $dublicate = true; $cableIDs[$key]['dublicate'] = true; } } if ($new) { $cableID = array(); $cableID['cableID'] = $portLink['cableid']; $cableID['object1_id'] = $portLink['object_id']; $cableID['object1_name'] = $portLink['object_name']; $cableID['object1_port'] = $portLink['name']; $cableID['object2_id'] = $portLink['remote_object_id']; $cableID['object2_name'] = $portLink['remote_object_name']; $cableID['object2_port'] = $portLink['remote_name']; $cableID['dublicate'] = $dublicate; array_push($cableIDs, $cableID); } } } } // Sort by cableIDs usort($cableIDs, function ($elem1, $elem2) { return strnatcasecmp($elem1['cableID'], $elem2['cableID']); }); // Print table echo '<table class="cooltable" align="center" border="0" cellpadding="5" cellspacing="0">' . '<tbody>' . ' <tr>' . ' <th>CableID</th>' . ' <th>Object 1</th>' . ' <th>Object 2</th>' . ' </tr>'; $i = 0; foreach ($cableIDs as $cableID) { if ($i % 2) { $class = 'row_even tdleft'; } else { $class = 'row_odd tdleft'; } if ($cableID['dublicate']) { $class .= ' trerror'; } echo '<tr class="' . $class . '">' . '<td>' . $cableID['cableID'] . '</td>' . '<td><a href="' . makeHref(array('page' => 'object', 'object_id' => $cableID['object1_id'])) . '">' . $cableID['object1_name'] . ': ' . $cableID['object1_port'] . '</a></td>' . '<td><a href="' . makeHref(array('page' => 'object', 'object_id' => $cableID['object2_id'])) . '">' . $cableID['object2_name'] . ': ' . $cableID['object2_port'] . '</a></td>' . '</tr>'; $i++; } echo ' </tbody>' . '</table>'; }
function requireMandatoryAttrGeneric($listsrc, $attr_id, $newval) { $object_id = getBypassValue(); $attrs = getAttrValues($object_id); if (array_key_exists($attr_id, $attrs) && considerGivenConstraint(spotEntity('object', $object_id), $listsrc) && !mb_strlen($newval)) { showError('Mandatory attribute "' . $attrs[$attr_id]['name'] . '" not set'); stopOpPropagation(); } return ''; }
function renderUser($user_id) { $userinfo = spotEntity('user', $user_id); $summary = array(); $summary['Account name'] = $userinfo['user_name']; $summary['Real name'] = $userinfo['user_realname']; $summary['tags'] = ''; renderEntitySummary($userinfo, 'summary', $summary); renderFilesPortlet('user', $user_id); }
public function __construct($lb_id, $vs_id, $rs_id, $db_row = NULL) { $this->lb = spotEntity('object', $lb_id); $this->vs = spotEntity('ipv4vs', $vs_id); $this->rs = spotEntity('ipv4rspool', $rs_id); $this->display_cells = array('lb', 'vs', 'rs'); if (isset($db_row)) { $this->slb = $db_row; } else { $result = usePreparedSelectBlade("SELECT prio, vsconfig, rsconfig FROM IPv4LB WHERE object_id = ? AND vs_id = ? AND rspool_id = ?", array($lb_id, $vs_id, $rs_id)); if ($row = $result->fetch(PDO::FETCH_ASSOC)) { $this->slb = $row; } else { throw new RackTablesError("SLB triplet not found in the DB"); } } }
function ripeTab($id) { $ripe_db = "http://rest.db.ripe.net/search.xml?source=ripe&query-string="; assertUIntArg('id'); $net = spotEntity('ipv4net', $id); loadIPAddrList($net); $startip = ip4_bin2int($net['ip_bin']); $endip = ip4_bin2int(ip_last($net)); // Get Data from RIPE $ripe_inetnum_str = ip4_format(ip4_int2bin($startip)) . ' - ' . ip4_format(ip4_int2bin($endip)); $ripe_query = $ripe_db . ip4_format(ip4_int2bin($startip)); $ripe_result_str = file_get_contents($ripe_query, false, NULL); $ripe_result = simplexml_load_string($ripe_result_str); // Check inetnum object $ripe_inetnum_check = "/whois-resources/objects/object[@type='inetnum']/attributes/attribute[@name='inetnum'][@value='{$ripe_inetnum_str}']"; $ripe_inetnum = $ripe_result->xpath($ripe_inetnum_check); if (empty($ripe_inetnum)) { echo "<div class=trerror><center><h1>{$net['ip']}/{$net['mask']}</h1><h2>{$net['name']}</h2></center></div>\n"; } else { $ripe_netname_check = "/whois-resources/objects/object[@type='inetnum']/attributes/attribute[@name='netname']"; $ripe_netname = $ripe_result->xpath($ripe_netname_check); $netname = trim($ripe_netname[0]['value']); if (strcmp($netname, $net['name']) != 0) { echo "<div class=trwarning><center><h1>{$net['ip']}/{$net['mask']}</h1><h2>{$net['name']}</h2></center></div><div><center>"; } else { echo "<div class=trok><center><h1>{$net['ip']}/{$net['mask']}</h1><h2>{$net['name']}</h2></center></div><div><center>"; } printOpFormIntro('importRipeData', array('ripe_query' => $ripe_query, 'net_id' => $id, 'net_name' => $netname)); echo "<input type=submit value='Import RIPE records in to comments'></center></div>"; echo "</form>"; } // echo '<em>'.$ripe_query.'</em>'; echo "<table border=0 width='100%'><tr><td class=pcleft>"; $filedir = realpath(dirname(__FILE__)); $ripe_xsl = simplexml_load_file($filedir . '/ripe_html.xsl'); startPortlet("RIPE Information Datatbase<br>{$ripe_inetnum_str}"); $proc = new XSLTProcessor(); $proc->importStyleSheet($ripe_xsl); echo '<div class=commentblock>' . trim($proc->transformToXML($ripe_result)) . '</div>'; finishPortlet(); echo "</td></tr></table>\n"; }
function renderEditVService($vsid) { $vsinfo = spotEntity('ipv4vs', $vsid); printOpFormIntro('updIPv4VS'); echo '<table border=0 align=center>'; echo "<tr><th class=tdright>VIP:</th><td class=tdleft><input type=text name=vip value='{$vsinfo['vip']}'></td></tr>\n"; echo "<tr><th class=tdright>Port:</th><td class=tdleft><input type=text name=vport value='{$vsinfo['vport']}'></td></tr>\n"; echo "<tr><th class=tdright>Proto:</th><td class=tdleft>"; global $vs_proto; printSelect($vs_proto, array('name' => 'proto'), $vsinfo['proto']); echo "</td></tr>\n"; echo "<tr><th class=tdright>Name:</th><td class=tdleft><input type=text name=name value='{$vsinfo['name']}'></td></tr>\n"; echo "<tr><th class=tdright>Tags:</th><td class=tdleft>"; printTagsPicker(); echo "</td></tr>\n"; echo "<tr><th class=tdright>VS config:</th><td class=tdleft><textarea name=vsconfig rows=20 cols=80>{$vsinfo['vsconfig']}</textarea></td></tr>\n"; echo "<tr><th class=tdright>RS config:</th><td class=tdleft><textarea name=rsconfig rows=20 cols=80>{$vsinfo['rsconfig']}</textarea></td></tr>\n"; echo "<tr><th class=submit colspan=2>"; printImageHREF('SAVE', 'Save changes', TRUE); echo "</td></tr>\n"; echo "</table></form>\n"; // delete link echo '<p class="centered">'; if ($vsinfo['refcnt'] > 0) { echo getOpLink(NULL, 'Delete virtual service', 'nodestroy', "Could not delete: there are {$vsinfo['refcnt']} LB links"); } else { echo getOpLink(array('op' => 'del', 'id' => $vsinfo['id']), 'Delete virtual service', 'destroy'); } }
function doSNMPmining($object_id, $snmpsetup) { global $objectInfo; $objectInfo = spotEntity('object', $object_id); $objectInfo['attrs'] = getAttrValues($object_id); $endpoints = findAllEndpoints($object_id, $objectInfo['name']); if (count($endpoints) == 0) { showFuncMessage(__FUNCTION__, 'ERR1'); // endpoint not found return; } if (count($endpoints) > 1) { showFuncMessage(__FUNCTION__, 'ERR2'); // can't pick an address return; } switch ($objectInfo['objtype_id']) { case 7: // Router // Router case 8: // Network switch // Network switch case 965: // Wireless // Wireless case 1503: // Network chassis $device = new RTSNMPDevice($endpoints[0], $snmpsetup); return doGenericSNMPmining($device); case 2: $device = new APCPowerSwitch($endpoints[0], $snmpsetup); return doPDUSNMPmining($device); } }
function findAutoTagWarnings($expr) { global $user_defined_atags; $self = __FUNCTION__; static $entityIDs = array('' => array('object', 'Object'), 'ipv4net' => array('ipv4net', 'IPv4 network'), 'ipv6net' => array('ipv6net', 'IPv6 network'), 'rack' => array('rack', 'Rack'), 'row' => array('row', 'Row'), 'location' => array('location', 'Location'), 'ipvs' => array('ipv4vs', 'Virtual service'), 'ipv4rsp' => array('ipv4rspool', 'RS pool'), 'file' => array('file', 'File'), 'vst' => array('vst', '802.1Q template'), 'user' => array('user', 'User')); switch ($expr['type']) { case 'LEX_TRUE': case 'LEX_FALSE': case 'LEX_PREDICATE': case 'LEX_TAG': return array(); case 'LEX_AUTOTAG': switch (1) { case preg_match('/^\\$(.*)?id_(\\d+)$/', $expr['load'], $m) && isset($entityIDs[$m[1]]): list($realm, $description) = $entityIDs[$m[1]]; try { spotEntity($realm, $m[2]); return array(); } catch (EntityNotFoundException $e) { return array(array('header' => refRCLineno($expr['lineno']), 'class' => 'warning', 'text' => "{$description} with ID '{$recid}' does not exist.")); } case preg_match('/^\\$username_/', $expr['load']): $recid = preg_replace('/^\\$username_/', '', $expr['load']); global $require_local_account; if (!$require_local_account) { return array(); } if (NULL !== getUserIDByUsername($recid)) { return array(); } return array(array('header' => refRCLineno($expr['lineno']), 'class' => 'warning', 'text' => "Local user account '{$recid}' does not exist.")); case preg_match('/^\\$page_([\\p{L}0-9]+)$/u', $expr['load'], $m): $recid = $m[1]; global $page; if (isset($page[$recid])) { return array(); } return array(array('header' => refRCLineno($expr['lineno']), 'class' => 'warning', 'text' => "Page number '{$recid}' does not exist.")); case preg_match('/^\\$(tab|op)_[\\p{L}0-9_]+$/u', $expr['load']): case preg_match('/^\\$any_(op|rack|object|ip4net|ip6net|net|ipv4vs|vs|ipv4rsp|rsp|file|location|row)$/', $expr['load']): case preg_match('/^\\$typeid_\\d+$/', $expr['load']): // FIXME: check value validity // FIXME: check value validity case preg_match('/^\\$cn_.+$/', $expr['load']): // FIXME: check name validity and asset existence // FIXME: check name validity and asset existence case preg_match('/^\\$lgcn_.+$/', $expr['load']): // FIXME: check name validity // FIXME: check name validity case preg_match('/^\\$(vlan|fromvlan|tovlan)_\\d+$/', $expr['load']): case preg_match('/^\\$(aggregate|unused|nameless|portless|unmounted|untagged|no_asset_tag|runs_8021Q)$/', $expr['load']): case preg_match('/^\\$(masklen_eq|spare)_\\d{1,3}$/', $expr['load']): case preg_match('/^\\$attr_\\d+(_\\d+)?$/', $expr['load']): case preg_match('/^\\$ip4net(-\\d{1,3}){5}$/', $expr['load']): case preg_match('/^\\$(8021Q_domain|8021Q_tpl)_\\d+$/', $expr['load']): case preg_match('/^\\$type_(tcp|udp|mark)$/', $expr['load']): return array(); default: foreach ($user_defined_atags as $regexp) { if (preg_match($regexp, $expr['load'])) { return array(); } } return array(array('header' => refRCLineno($expr['lineno']), 'class' => 'warning', 'text' => "Martian autotag '{$expr['load']}'")); } case 'SYNT_NOT_EXPR': return $self($expr['load']); case 'SYNT_AND_EXPR': case 'SYNT_EXPR': return array_merge($self($expr['left']), $self($expr['right'])); default: return array(array('header' => "internal error in {$self}", 'class' => 'error', 'text' => "Skipped expression of unknown type '{$expr['type']}'")); } }
} // don't indicate failure unless the pidfile is 15 minutes or more old if ($current_time < $pidfile_mtime + 15 * 60) { exit(0); } print_message_line("Failed to lock {$filename}, already locked by PID " . trim(fgets($fp, 10))); exit(1); } ftruncate($fp, 0); fwrite($fp, getmypid() . "\n"); // don't close $fp yet: we need to keep an flock } // fetch all the needed data from DB (preparing for DB connection loss) $switch_queue = array(); foreach ($switch_list as $object_id) { $cell = spotEntity('object', $object_id); $new_disabled = !considerConfiguredConstraint($cell, 'SYNC_802Q_LISTSRC'); $queue = detectVLANSwitchQueue(getVLANSwitchInfo($object_id)); if ($queue == 'disabled' xor $new_disabled) { usePreparedExecuteBlade('UPDATE VLANSwitch SET out_of_sync="yes", last_error_ts=NOW(), last_errno=? WHERE object_id=?', array($new_disabled ? E_8021Q_SYNC_DISABLED : E_8021Q_NOERROR, $object_id)); } elseif (in_array($queue, $todo[$options['mode']])) { $switch_queue[] = $cell; } } // YOU SHOULD NOT USE DB FUNCTIONS BELOW IN THE PARENT PROCESS // THE PARENT'S DB CONNECTION IS LOST DUE TO RECONNECTING IN THE CHILD $fork_slots = getConfigVar('SYNCDOMAIN_MAX_PROCESSES'); $do_fork = $fork_slots > 1 and extension_loaded('pcntl'); if ($fork_slots > 1 and !$do_fork) { throw new RackTablesError('PHP extension \'pcntl\' not found, can not use childs', RackTablesError::MISCONFIGURED); }
function buildVSMigratePlan($new_vs_id, $vs_id_list) { $ret = array('properties' => array('vsconfig' => '', 'rsconfig' => ''), 'ports' => array(), 'vips' => array(), 'triplets' => array(), 'messages' => array()); $config_stat = array('vsconfig' => array(), 'rsconfig' => array()); $gt = array(); // grouped triplets foreach ($vs_id_list as $vs_id) { $vsinfo = spotEntity('ipv4vs', $vs_id); // create nesessary vips and ports if ($vsinfo['proto'] != 'MARK') { $vip_key = $vsinfo['vip_bin']; $port_key = $vsinfo['proto'] . '-' . $vsinfo['vport']; $ret['vips'][$vip_key] = array('vip' => $vsinfo['vip_bin'], 'vsconfig' => '', 'rsconfig' => ''); $ret['ports'][$port_key] = array('proto' => $vsinfo['proto'], 'vport' => $vsinfo['vport'], 'vsconfig' => '', 'rsconfig' => ''); } else { $vip_key = ''; $mark = implode('', unpack('N', $vsinfo['vip_bin'])); $port_key = $vsinfo['proto'] . '-' . $mark; $ret['ports'][$port_key] = array('proto' => $vsinfo['proto'], 'vport' => $mark, 'vsconfig' => '', 'rsconfig' => ''); } // fill triplets foreach (SLBTriplet::getTriplets($vsinfo) as $triplet) { $tr_key = $triplet->lb['id'] . '-' . $triplet->rs['id']; if (!isset($ret['triplets'][$tr_key])) { $ret['triplets'][$tr_key] = array('object_id' => $triplet->lb['id'], 'rspool_id' => $triplet->rs['id'], 'vs_id' => $new_vs_id, 'vips' => array(), 'ports' => array()); } $configs = array('vsconfig' => tokenizeConfig($triplet->vs['vsconfig'] . "\n" . $triplet->slb['vsconfig']), 'rsconfig' => tokenizeConfig($triplet->vs['rsconfig'] . "\n" . $triplet->slb['rsconfig'])); if ($vsinfo['proto'] != 'MARK') { if (!isset($ret['triplets'][$tr_key]['ports'][$port_key])) { $ret['triplets'][$tr_key]['ports'][$port_key] = array('proto' => $vsinfo['proto'], 'vport' => $vsinfo['vport'], 'vsconfig' => '', 'rsconfig' => ''); } if (!isset($ret['triplets'][$tr_key]['vips'][$vip_key])) { $ret['triplets'][$tr_key]['vips'][$vip_key] = array('vip' => $vsinfo['vip_bin'], 'prio' => NULL, 'vsconfig' => '', 'rsconfig' => ''); } if ('' != $triplet->slb['prio']) { $ret['triplets'][$tr_key]['vips'][$vip_key]['prio'] = $triplet->slb['prio']; } } else { $ret['triplets'][$tr_key]['ports'][$port_key] = array('proto' => $vsinfo['proto'], 'vport' => $mark, 'vsconfig' => '', 'rsconfig' => ''); } $old_tr_key = $tr_key . '-' . $vip_key . '-' . $port_key; $gt['all'][$old_tr_key] = $triplet; $gt['ports'][$port_key][$old_tr_key] = $triplet; $gt['vips'][$vip_key][$old_tr_key] = $triplet; $gt['vip_links'][$tr_key][$vip_key][$old_tr_key] = $triplet; $gt['port_links'][$tr_key][$port_key][$old_tr_key] = $triplet; foreach ($configs as $conf_type => $list) { foreach ($list as $line) { $config_stat[$conf_type][$line][$old_tr_key] = $triplet; } } } } // reduce common config lines and move them from $config_stat into $ret foreach ($config_stat as $conf_type => $stat) { foreach ($stat as $line => $used_in_triplets) { $added_to_triplets = array(); $wrong_triplets = array(); if (!array_sub($gt['all'], $used_in_triplets)) { // line used in all triplets concatConfig($ret['properties'][$conf_type], $line); continue; } foreach ($gt['ports'] as $port_key => $port_triplets) { $diff = array_sub($port_triplets, $used_in_triplets); if (count($diff) < count($port_triplets) / 2) { // line used in most triplets of this port $added_to_triplets += $port_triplets; $wrong_triplets += $diff; concatConfig($ret['ports'][$port_key][$conf_type], $line); } } foreach ($gt['vips'] as $vip_key => $vip_triplets) { if (!array_sub($vip_triplets, $used_in_triplets)) { if (count($vip_triplets) == count(array_sub($vip_triplets, $added_to_triplets))) { // if none of the $vip_triplets are in $added_to_triplets, // line used in all triplets of this vip $added_to_triplets += $vip_triplets; concatConfig($ret['vips'][$vip_key][$conf_type], $line); } } } foreach ($used_in_triplets as $old_tr_key => $triplet) { if (isset($added_to_triplets[$old_tr_key])) { continue; } $tr_key = $triplet->lb['id'] . '-' . $triplet->rs['id']; if ($triplet->vs['proto'] != 'MARK') { $vip_key = $triplet->vs['vip_bin']; $port_key = $triplet->vs['proto'] . '-' . $triplet->vs['vport']; } else { $vip_key = ''; $port_key = $triplet->vs['proto'] . '-' . implode('', unpack('N', $triplet->vs['vip_bin'])); } // if all the triplets for a given port contain line, add it to the ports' config if (!array_sub($gt['port_links'][$tr_key][$port_key], $used_in_triplets)) { if (count($gt['port_links'][$tr_key][$port_key]) == count(array_sub($gt['port_links'][$tr_key][$port_key], $added_to_triplets))) { $added_to_triplets += $gt['port_links'][$tr_key][$port_key]; concatConfig($ret['triplets'][$tr_key]['ports'][$port_key][$conf_type], $line); } } // if all the triplets for a given vip contain line, add it to the vips' config if ($vip_key != '') { if (!array_sub($gt['vip_links'][$tr_key][$vip_key], $used_in_triplets)) { if (count($gt['vip_links'][$tr_key][$vip_key]) == count(array_sub($gt['vip_links'][$tr_key][$vip_key], $added_to_triplets))) { $added_to_triplets += $gt['vip_links'][$tr_key][$vip_key]; concatConfig($ret['triplets'][$tr_key]['vips'][$vip_key][$conf_type], $line); } } } } // check for failed-to-insert lines foreach (array_sub($used_in_triplets, $added_to_triplets) as $old_tr_key => $unused_triplet) { $ret['messages'][$old_tr_key][] = "Failed to add {$conf_type} line '{$line}'"; } foreach ($wrong_triplets as $old_tr_key => $triplet) { $ret['messages'][$old_tr_key][] = "Added {$conf_type} line '{$line}'"; } } } // for $line return $ret; }
function gwDeployDeviceConfig($object_id, $breed, $text) { if ($text == '') { throw new InvalidArgException('text', '', 'deploy text is empty'); } $objectInfo = spotEntity('object', $object_id); $endpoints = findAllEndpoints($object_id, $objectInfo['name']); if (count($endpoints) == 0) { throw new RTGatewayError('no management address set'); } if (count($endpoints) > 1) { throw new RTGatewayError('cannot pick management address'); } $endpoint = str_replace(' ', '\\ ', str_replace(' ', '+', $endpoints[0])); $tmpfilename = tempnam('', 'RackTables-deviceconfig-'); if (FALSE === file_put_contents($tmpfilename, $text)) { unlink($tmpfilename); throw new RTGatewayError('failed to write to temporary file'); } try { queryGateway('deviceconfig', array("deploy {$endpoint} {$breed} {$tmpfilename}")); unlink($tmpfilename); } catch (RTGatewayError $e) { unlink($tmpfilename); throw $e; } }
function snmpgeneric_list($object_id) { global $sg_create_noconnector_ports, $sg_known_sysObjectIDs, $sg_portoifoptions, $sg_ifType_ignore; if (isset($_POST['snmpconfig'])) { $snmpconfig = $_POST; } else { showError("Missing SNMP Config"); return; } // sg_var_dump_html($snmpconfig); echo '<body onload="document.getElementById(\'createbutton\').focus();">'; addJS('function setchecked(classname) { var boxes = document.getElementsByClassName(classname); var value = document.getElementById(classname).checked; for(i=0;i<boxes.length;i++) { if(boxes[i].disabled == false) boxes[i].checked=value; } };', TRUE); $object = spotEntity('object', $object_id); $object['attr'] = getAttrValues($object_id); $snmpdev = new mySNMP($snmpconfig['version'], $snmpconfig['host'], $snmpconfig['community']); if ($snmpconfig['version'] == "v3") { $snmpdev->setSecurity($snmpconfig['sec_level'], $snmpconfig['auth_protocol'], $snmpconfig['auth_passphrase'], $snmpconfig['priv_protocol'], $snmpconfig['priv_passphrase']); } $snmpdev->init(); if ($snmpdev->getErrno()) { showError($snmpdev->getError()); return; } /* SNMP connect successfull */ showSuccess("SNMP " . $snmpconfig['version'] . " connect to {$snmpconfig['host']} successfull"); echo '<form name=CreatePorts method=post action=' . $_SERVER['REQUEST_URI'] . '&module=redirect&op=create>'; echo "<strong>System Informations</strong>"; echo "<table>"; // echo "<tr><th>OID</th><th>Value</th></tr>"; $systemoids = array('sysDescr', 'sysObjectID', 'sysUpTime', 'sysContact', 'sysName', 'sysLocation'); foreach ($systemoids as $shortoid) { $value = $snmpdev->{$shortoid}; if ($shortoid == 'sysUpTime') { /* in hundredths of a second */ $secs = (int) ($value / 100); $days = (int) ($secs / (60 * 60 * 24)); $secs -= $days * 60 * 60 * 24; $hours = (int) ($secs / (60 * 60)); $secs -= $hours * 60 * 60; $mins = (int) ($secs / 60); $secs -= $mins * 60; $value = "{$value} ({$days} {$hours}:{$mins}:{$secs})"; } echo "<tr><td title=\"" . $snmpdev->lastgetoid . "\" align=\"right\">{$shortoid}: </td><td>{$value}</td></tr>"; } unset($shortoid); echo "</table>"; /* sysObjectID Attributes and Ports */ $sysObjectID['object'] =& $object; /* get sysObjectID */ $sysObjectID['raw_value'] = $snmpdev->sysObjectID; //$sysObjectID['raw_value'] = 'NET-SNMP-MIB::netSnmpAgentOIDs.10'; $sysObjectID['value'] = preg_replace('/^.*enterprises\\.([\\.[:digit:]]+)$/', '\\1', $sysObjectID['raw_value']); /* try snmptranslate to numeric */ if (preg_match('/[^\\.0-9]+/', $sysObjectID['value'])) { $numeric_value = $snmpdev->translatetonumeric($sysObjectID['value']); if (!empty($numeric_value)) { showSuccess("sysObjectID: " . $sysObjectID['value'] . " translated to {$numeric_value}"); $sysObjectID['value'] = preg_replace('/^.1.3.6.1.4.1.([\\.[:digit:]]+)$/', '\\1', $numeric_value); } } /* array_merge doesn't work with numeric keys !! */ $sysObjectID['attr'] = array(); $sysObjectID['port'] = array(); $sysobjid = $sysObjectID['value']; $count = 1; while ($count) { if (isset($sg_known_sysObjectIDs[$sysobjid])) { $sysObjectID = $sysObjectID + $sg_known_sysObjectIDs[$sysobjid]; if (isset($sg_known_sysObjectIDs[$sysobjid]['attr'])) { $sysObjectID['attr'] = $sysObjectID['attr'] + $sg_known_sysObjectIDs[$sysobjid]['attr']; } if (isset($sg_known_sysObjectIDs[$sysobjid]['port'])) { $sysObjectID['port'] = $sysObjectID['port'] + $sg_known_sysObjectIDs[$sysobjid]['port']; } if (isset($sg_known_sysObjectIDs[$sysobjid]['text'])) { showSuccess("found sysObjectID ({$sysobjid}) " . $sg_known_sysObjectIDs[$sysobjid]['text']); } } $sysobjid = preg_replace('/\\.[[:digit:]]+$/', '', $sysobjid, 1, $count); /* add default sysobjectid */ if ($count == 0 && $sysobjid != 'default') { $sysobjid = 'default'; $count = 1; } } $sysObjectID['vendor_number'] = $sysobjid; /* device pf */ if (isset($sysObjectID['pf'])) { foreach ($sysObjectID['pf'] as $function) { if (function_exists($function)) { /* call device pf */ $function($snmpdev, $sysObjectID, NULL); } else { showWarning("Missing processor function " . $function . " for device {$sysobjid}"); } } } /* sort attributes maintain numeric keys */ ksort($sysObjectID['attr']); /* DEBUG */ //sg_var_dump_html($sysObjectID['attr'], "Before processing"); /* needs PHP >= 5 foreach call by reference */ /* php 5.1.6 doesn't seem to work */ //foreach($sysObjectID['attr'] as $attr_id => &$attr) foreach ($sysObjectID['attr'] as $attr_id => $value) { $attr =& $sysObjectID['attr'][$attr_id]; if (isset($object['attr'][$attr_id])) { if (array_key_exists('key', $object['attr'][$attr_id])) { $attr['key'] = $object['attr'][$attr_id]['key']; } switch (TRUE) { case isset($attr['pf']): if (function_exists($attr['pf'])) { $attr['pf']($snmpdev, $sysObjectID, $attr_id); } else { showWarning("Missing processor function " . $attr['pf'] . " for attribute {$attr_id}"); } break; case isset($attr['oid']): $attrvalue = $snmpdev->get($attr['oid']); if (isset($attr['regex'])) { $regex = $attr['regex']; if (isset($attr['replacement'])) { $replacement = $attr['replacement']; $attrvalue = preg_replace($regex, $replacement, $attrvalue); } else { if (!preg_match($regex, $attrvalue)) { if (!isset($attr['uncheck'])) { $attr['uncheck'] = "regex doesn't match"; } } else { unset($attr['uncheck']); } } } $attr['value'] = $attrvalue; break; case isset($attr['value']): break; default: showError("Error handling attribute id: {$attr_id}"); } } else { showWarning("Object has no attribute id: {$attr_id}"); unset($sysObjectID['attr'][$attr_id]); } } unset($attr_id); /* sort again in case there where attribs added ,maintain numeric keys */ ksort($sysObjectID['attr']); /* print attributes */ echo '<br>Attributes<br><table>'; echo '<tr><th><input type="checkbox" id="attribute" checked="checked" onclick="setchecked(this.id)"></td>'; echo '<th>Name</th><th>Current Value</th><th>new value</th></tr>'; /* DEBUG */ //sg_var_dump_html($sysObjectID['attr'], "After processing"); foreach ($sysObjectID['attr'] as $attr_id => &$attr) { $attr['id'] = $attr_id; if (isset($object['attr'][$attr_id]) && isset($attr['value'])) { if ($attr['value'] == $object['attr'][$attr_id]['value']) { $attr['uncheck'] = 'Current = new value'; } if (isset($attr['key']) && isset($object['attr'][$attr_id]['key'])) { if ($attr['key'] == $object['attr'][$attr_id]['key']) { $attr['uncheck'] = 'Current = new key'; } } $value = $attr['value']; $val_key = isset($object['attr'][$attr_id]['key']) ? ' (' . $object['attr'][$attr_id]['key'] . ')' : ''; $comment = ''; if (isset($attr['comment'])) { if (!empty($attr['comment'])) { $comment = $attr['comment']; } } if (isset($attr['uncheck'])) { $checked = ''; $comment .= ', ' . $attr['uncheck']; } else { $checked = ' checked="checked"'; } $updateattrcheckbox = '<b style="background-color:#00ff00">' . '<input style="background-color:#00ff00" class="attribute" type="checkbox" name="updateattr[' . $attr_id . ']" value="' . $value . '"' . $checked . '></b>'; $comment = trim($comment, ', '); echo "<tr><td>{$updateattrcheckbox}</td><td title=\"id: {$attr_id}\">" . $object['attr'][$attr_id]['name'] . '</td><td style="background-color:#d8d8d8">' . $object['attr'][$attr_id]['value'] . $val_key . '</td><td>' . $value . '</td>' . '<td style="color:#888888">' . $comment . '</td></tr>'; } } unset($attr_id); echo '</table>'; $object['breed'] = sg_detectDeviceBreedByObject($sysObjectID); if (!empty($object['breed'])) { echo "Found Breed: " . $object['breed'] . "<br>"; } /* ports */ /* get ports */ amplifyCell($object); /* set array key to lowercase port name */ foreach ($object['ports'] as $key => $values) { $object['ports'][strtolower(shortenIfName($values['name'], $object['breed']))] = $values; unset($object['ports'][$key]); } $newporttypeoptions = getNewPortTypeOptions(); // sg_var_dump_html($sysObjectID['port']); if (!empty($sysObjectID['port'])) { echo '<br>Vendor / Device specific ports<br>'; echo '<table><tr><th><input type="checkbox" id="moreport" checked="checked" onclick="setchecked(this.id)"></th><th>ifName</th><th>porttypeid</th></tr>'; foreach ($sysObjectID['port'] as $name => $port) { if (array_key_exists(strtolower($name), $object['ports'])) { $disableport = TRUE; } else { $disableport = FALSE; } $comment = ''; if (isset($port['comment'])) { if (!empty($port['comment'])) { $comment = $port['comment']; } } if (isset($port['uncheck'])) { $checked = ''; $comment .= ', ' . $port['uncheck']; } else { $checked = ' checked="checked"'; } $portcreatecheckbox = '<b style="background-color:' . ($disableport ? '#ff0000' : '#00ff00') . '"><input style="background-color:' . ($disableport ? '#ff0000' : '#00ff00') . '" class="moreport" type="checkbox" name="portcreate[' . $name . ']" value="' . $name . '"' . ($disableport ? ' disabled="disbaled"' : $checked) . '></b>'; $formfield = '<input type="hidden" name="ifName[' . $name . ']" value="' . $name . '">'; echo "<tr>{$formfield}<td>{$portcreatecheckbox}</td><td>{$name}</td>"; if (isset($port['disabled'])) { $disabledselect = array('disabled' => "disabled"); } else { $disabledselect = array(); } foreach ($port as $key => $value) { if ($key == 'uncheck' || $key == 'comment') { continue; } /* TODO iif_name */ if ($key == 'porttypeid') { $displayvalue = getNiftySelect($newporttypeoptions, array('name' => "porttypeid[{$name}]") + $disabledselect, $value); } else { $displayvalue = $value; } $formfield = '<input type="hidden" name="' . $key . '[' . $name . ']" value="' . $value . '">'; echo "{$formfield}<td>{$displayvalue}</td>"; } $comment = trim($comment, ', '); echo "<td style=\"color:#888888\">{$comment}</td></tr>"; } unset($name); unset($port); echo '</table>'; } /* snmp ports */ $ifsnmp = new ifSNMP($snmpdev); // needed for shortenIfName() $ifsnmp->object_breed = $object['breed']; /* ip spaces */ $ipspace = NULL; foreach ($ifsnmp->ipaddress as $ifindex => $ipaddresses) { foreach ($ipaddresses as $ipaddr => $value) { $addrtype = $value['addrtype']; $netaddr = $value['net']; $maskbits = $value['maskbits']; $netid = NULL; $linklocal = FALSE; //echo "<br> - DEBUG: ipspace $ipaddr - $netaddr - $addrtype - $maskbits<br>"; /* check for ip space */ switch ($addrtype) { case 'ipv4': case 'ipv4z': if ($maskbits == 32) { $netid = 'host'; } else { $netid = getIPv4AddressNetworkId(ip_parse($ipaddr)); } break; case 'ipv6': if (ip_checkparse($ipaddr) === false) { /* format ipaddr for ip6_parse */ $ipaddr = preg_replace('/((..):(..))/', '\\2\\3', $ipaddr); $ipaddr = preg_replace('/%.*$/', '', $ipaddr); } if (ip_checkparse($ipaddr) === false) { continue 2; } // 2 because of switch $ip6_bin = ip6_parse($ipaddr); $ip6_addr = ip_format($ip6_bin); $netid = getIPv6AddressNetworkId($ip6_bin); $node = constructIPRange($ip6_bin, $maskbits); $netaddr = $node['ip']; $linklocal = substr($ip6_addr, 0, 5) == "fe80:"; //echo "<br> - DEBUG: ipspace $ipaddr - $addrtype - $maskbits - $netaddr - >$linklocal<<br>"; break; case 'ipv6z': /* link local */ $netid = 'ignore'; break; default: } if (empty($netid) && $netaddr != '::1' && $netaddr != '127.0.0.1' && $netaddr != '127.0.0.0' && $netaddr != '0.0.0.0' && !$linklocal) { $netaddr .= "/{$maskbits}"; $ipspace[$netaddr] = array('addrtype' => $addrtype, 'checked' => $maskbits > 0 ? true : false); } } unset($ipaddr); unset($value); unset($addrtype); } unset($ifindex); unset($ipaddresses); /* print ip spaces table */ if (!empty($ipspace)) { echo '<br><br>Create IP Spaces'; echo '<table><tr><th><input type="checkbox" id="ipspace" onclick="setchecked(this.id)" checked=\\"checked\\"></th>'; echo '<th>Type</th><th>prefix</th><th>name</th><th width=150 title="reserve network and router addresses">reserve network / router addresses</th></tr>'; $i = 1; foreach ($ipspace as $prefix => $ipspace) { $netcreatecheckbox = '<b style="background-color:#00ff00">' . '<input class="ipspace" style="background-color:#00ff00" type="checkbox" name="netcreate[' . $i . ']" value="' . $ipspace['addrtype'] . '"' . ($ipspace['checked'] ? ' checked=\\"checked\\"' : '') . '></b>'; $netprefixfield = '<input type="text" size=50 name="netprefix[' . $i . ']" value="' . $prefix . '">'; $netnamefield = '<input type="text" name="netname[' . $i . ']">'; $netreservecheckbox = '<input type="checkbox" name="netreserve[' . $i . ']" checked="checked">'; echo "<tr><td>{$netcreatecheckbox}</td><td style=\"color:#888888\">{$ipspace['addrtype']}</td><td>{$netprefixfield}</td><td>{$netnamefield}</td><td>{$netreservecheckbox}</td></tr>"; $i++; } unset($prefix); unset($addrtype); unset($i); echo '</table>'; } echo "<br><br>ifNumber: " . $ifsnmp->ifNumber . "<br>indexcount: " . $ifsnmp->indexcount . "<br><table><tbody valign=\"top\">"; $portcompat = getPortInterfaceCompat(); $ipnets = array(); $ifsnmp->printifInfoTableHeader("<th>add ip</th><th>add port</th><th>upd label</th><th title=\"update mac\">upd mac</th><td>upd port type</th><th>porttypeid</th><th>comment</th></tr>"); echo '<tr><td colspan="11"></td> <td><input type="checkbox" id="ipaddr" onclick="setchecked(this.id);" checked="checked">IPv4<br> <input type="checkbox" id="ipv6addr" onclick="setchecked(this.id);" checked="checked">IPv6</td> <td><input type="checkbox" id="ports" onclick="setchecked(this.id)"></td> <td><input type="checkbox" id="label" onclick="setchecked(this.id);" checked="checked"></td> <td><input type="checkbox" id="mac" onclick="setchecked(this.id);" checked="checked"></td> <td><input type="checkbox" id="porttype" onclick="setchecked(this.id);"></td></tr>'; foreach ($ifsnmp as $if) { $createport = TRUE; $disableport = FALSE; $ignoreport = FALSE; $port_info = NULL; $updatelabel = false; $updateporttype = false; $updatemaccheckbox = ''; $hrefs = array(); $comment = ""; if (trim($ifsnmp->ifName($if)) == '') { $comment .= "no ifName"; $createport = FALSE; } else { if (array_key_exists($ifsnmp->ifName($if), $object['ports'])) { $port_info =& $object['ports'][$ifsnmp->ifName($if)]; $comment .= "Name exists"; /* ifalias change */ if ($port_info['label'] != $ifsnmp->ifAlias($if)) { $updatelabel = true; } $createport = FALSE; $disableport = TRUE; } } if ($ifsnmp->ifPhysAddress($if) != '') { $ifPhysAddress = $ifsnmp->ifPhysAddress($if); $l2port = sg_checkL2Address($ifPhysAddress); if (!empty($l2port)) { $l2object_id = key($l2port); $porthref = makeHref(array('page' => 'object', 'tab' => 'ports', 'object_id' => $l2object_id, 'hl_port_id' => $l2port[$l2object_id])); $comment .= ", L2Address exists"; $hrefs['ifPhysAddress'] = $porthref; $createport = FALSE; // $disableport = TRUE; $updatemaccheckbox = ''; } $disablemac = true; if ($disableport) { if ($port_info !== NULL) { if (str_replace(':', '', $port_info['l2address']) != $ifPhysAddress) { $disablemac = false; } else { $disablemac = true; } } } else { /* port create always updates mac */ $updatemaccheckbox = '<b style="background-color:#00ff00">' . '<input style="background-color:' . '#00ff00" type="checkbox"' . ' checked="checked"' . ' disabled=\\"disabled\\"></b>'; } if (!$disablemac) { $updatemaccheckbox = '<b style="background-color:' . ($disablemac ? '#ff0000' : '#00ff00') . '">' . '<input class="mac" style="background-color:' . ($disablemac ? '#ff0000' : '#00ff00') . '" type="checkbox" name="updatemac[' . $if . ']" value="' . $object['ports'][$ifsnmp->ifName($if)]['id'] . '" checked="checked"' . ($disablemac ? ' disabled=\\"disabled\\"' : '') . '></b>'; } } $porttypeid = guessRToif_id($ifsnmp->ifType($if), $ifsnmp->ifDescr($if)); if (in_array($ifsnmp->ifType($if), $sg_ifType_ignore)) { $comment .= ", ignore if type"; $createport = FALSE; $ignoreport = TRUE; } else { if ($port_info) { $ptid = $port_info['iif_id'] . "-" . $port_info['oif_id']; if ($porttypeid != $ptid) { $comment .= ", Update Type {$ptid} -> {$porttypeid}"; $updateporttype = true; } } } /* ignore ports without an Connector */ if (!$sg_create_noconnector_ports && $ifsnmp->ifConnectorPresent($if) == 2) { $comment .= ", no Connector"; $createport = FALSE; } /* Allocate IPs ipv4 and ipv6 */ $ipaddresses = $ifsnmp->ipaddress($if); if (!empty($ipaddresses)) { $ipaddrcell = '<table>'; foreach ($ipaddresses as $ipaddr => $value) { $createipaddr = FALSE; $disableipaddr = FALSE; $ipaddrhref = ''; $linklocal = FALSE; $addrtype = $value['addrtype']; $maskbits = $value['maskbits']; $bcast = $value['bcast']; //echo "<br> - DEBUG: ip $ipaddr - $addrtype - $maskbits - $bcast<br>"; switch ($addrtype) { case 'ipv4z': case 'ipv4': if ($maskbits == 32) { $bcast = "host"; } $inputname = 'ip'; break; case 'ipv6z': $disableipaddr = TRUE; case 'ipv6': $inputname = 'ipv6'; if (ip_checkparse($ipaddr) === false) { /* format ipaddr for ip6_parse */ $ipaddr = preg_replace('/((..):(..))/', '\\2\\3', $ipaddr); $ipaddr = preg_replace('/%.*$/', '', $ipaddr); } if (ip_checkparse($ipaddr) === false) { continue 2; } // 2 because of switch /* ip_parse throws exception on parse errors */ $ip6_bin = ip_parse($ipaddr); $ipaddr = ip_format($ip6_bin); $node = constructIPRange($ip6_bin, $maskbits); $linklocal = $node['ip'] == 'fe80::'; $createipaddr = FALSE; break; } //switch $address = getIPAddress(ip_parse($ipaddr)); /* only if ip not already allocated */ if (empty($address['allocs'])) { if (!$ignoreport) { $createipaddr = TRUE; } } else { $disableipaddr = TRUE; $ipobject_id = $address['allocs'][0]['object_id']; $ipaddrhref = makeHref(array('page' => 'object', 'object_id' => $ipobject_id, 'hl_ipv4_addr' => $ipaddr)); } /* reserved addresses */ if ($address['reserved'] == 'yes') { $comment .= ', ' . $address['ip'] . ' reserved ' . $address['name']; $createipaddr = FALSE; // $disableipaddr = TRUE; } if ($ipaddr == '127.0.0.1' || $ipaddr == '0.0.0.0' || $ipaddr == '::1' || $ipaddr == '::' || $linklocal) { $createipaddr = FALSE; $disableipaddr = TRUE; } if ($ipaddr === $bcast) { $comment .= ", {$ipaddr} broadcast"; $createipaddr = FALSE; $disableipaddr = TRUE; } if (!$disableipaddr) { $ipaddrcheckbox = '<b style="background-color:' . ($disableipaddr ? '#ff0000' : '#00ff00') . '"><input class="' . $inputname . 'addr" style="background-color:' . ($disableipaddr ? '#ff0000' : '#00ff00') . '" type="checkbox" name="' . $inputname . 'addrcreate[' . $ipaddr . ']" value="' . $if . '"' . ($disableipaddr ? ' disabled="disabled"' : '') . ($createipaddr ? ' checked="checked"' : '') . '></b>'; } else { $ipaddrcheckbox = ''; } $ipaddrcell .= "<tr><td>{$ipaddrcheckbox}</td>"; if (!empty($ipaddrhref)) { $ipaddrcell .= "<td><a href={$ipaddrhref}>{$ipaddr}/{$maskbits}</a></td></tr>"; } else { $ipaddrcell .= "<td>{$ipaddr}/{$maskbits}</td></tr>"; } } // foreach unset($ipaddr); unset($value); $ipaddrcell .= '</table>'; // if(!empty($ipaddresses)) } else { $ipaddrcreatecheckbox = ''; $ipaddrcell = ''; } /* checkboxes for add port and add ip */ /* FireFox needs <b style=..>, IE and Opera work with <td style=..> */ if (!$disableport) { $portcreatecheckbox = '<b style="background-color:' . ($disableport ? '#ff0000' : '#00ff00') . '"><input class="ports" style="background-color:' . ($disableport ? '#ff0000' : '#00ff00') . '" type="checkbox" name="portcreate[' . $if . ']" value="' . $if . '"' . ($disableport ? ' disabled="disbaled"' : '') . ($createport ? ' checked="checked"' : '') . '></b>'; } else { $portcreatecheckbox = ''; } /* port type id */ /* add port type to newporttypeoptions if missing */ if (strpos(serialize($newporttypeoptions), $porttypeid) === FALSE) { $portids = explode('-', $porttypeid); $oif_name = $sg_portoifoptions[$portids[1]]; $newporttypeoptions['auto'] = array($porttypeid => "*{$oif_name}"); } $selectoptions = array('name' => "porttypeid[{$if}]"); if ($disableport && !$updateporttype) { $selectoptions['disabled'] = "disabled"; } $updateporttypecheckbox = ""; if ($updateporttype) { $updateporttypecheckbox = '<b style="background-color:#00ff00;">' . '<input class="porttype" style="background-color:#00ff00;" type="checkbox" name="updateporttype[' . $if . ']" value="' . $port_info['id'] . '"></b>'; } $porttypeidselect = getNiftySelect($newporttypeoptions, $selectoptions, $porttypeid); $updatelabelcheckbox = ""; if ($updatelabel) { $updatelabelcheckbox = '<b style="background-color:#00ff00;">' . '<input class="label" style="background-color:#00ff00;" type="checkbox" name="updatelabel[' . $if . ']" value="' . $port_info['id'] . ($updatelabel ? '" checked="checked"' : '') . '></b>'; } $comment = trim($comment, ', '); $ifsnmp->printifInfoTableRow($if, "<td>{$ipaddrcell}</td><td>{$portcreatecheckbox}</td><td>{$updatelabelcheckbox}</td><td>{$updatemaccheckbox}</td><td>{$updateporttypecheckbox}</td><td>{$porttypeidselect}</td><td nowrap=\"nowrap\">{$comment}</td>", $hrefs); } unset($if); /* preserve snmpconfig */ foreach ($_POST as $key => $value) { echo '<input type=hidden name=' . $key . ' value=' . $value . ' />'; } unset($key); unset($value); echo '<tr><td colspan=15 align="right"><p><input id="createbutton" type=submit value="Create Ports and IPs" onclick="return confirm(\'Create selected items?\')"></p></td></tr></tbody></table></form>'; }
case 'dict': $oldvalue = $oldvalues[$attr_id]['key']; break; default: } // skip noops if ($value === $oldvalue) { continue; } // finally update our value error_log("update attribute ID {$attr_id} from {$oldvalue} to {$value}"); commitUpdateAttrValue($object_id, $attr_id, $value); } } // see if we also need to update the object type $object = spotEntity('object', $object_id); if ($sic['object_type_id'] != $object['objtype_id']) { error_log("object type id for object {$object_id} will be changed from " . $object['objtype_id'] . ' to ' . $sic['object_type_id']); // check that the two types are compatible if (!array_key_exists($sic['object_type_id'], getObjectTypeChangeOptions($object_id))) { throw new InvalidRequestArgException('new type_id', $sic['object_type_id'], 'incompatible with requested attribute values'); } usePreparedUpdateBlade('RackObject', array('objtype_id' => $sic['object_type_id']), array('id' => $object_id)); } // Invalidate thumb cache of all racks objects could occupy. foreach (getResidentRacksData($object_id, FALSE) as $rack_id) { usePreparedDeleteBlade('RackThumbnail', array('rack_id' => $rack_id)); } // ok, now we're good $dbxlink->commit(); // redirect to the get_object URL for the edited object
function localtrigger_PortLinker() { global $portLinkerObjectTypes; assertUIntArg('object_id', __FUNCTION__); $object = spotEntity('object', $_REQUEST['object_id']); if (in_array($object['objtype_id'], $portLinkerObjectTypes)) { $linkok = localpretrigger_PortLinker(); } else { $linkok = 0; } if ($linkok == 2) { return 1; } else { return ''; } }
function ConfigTabHandler() { $dateadd = date("Y-m-d H:i:s"); // Add show/hide JS functionality for existing configuration fields echo "<SCRIPT language=\"JavaScript\">\n\t<!--\n\tfunction toggle_visibility(id){\n\tvar e = document.getElementById(id);\n\tif(e.style.display == 'block')\n\t\te.style.display = 'none';\n\telse\n\t\te.style.display = 'block';\n\t}\n\t//-->\n\t</script>\n"; // Print markup content for config tab $display = "<center>\n"; if (isset($_POST['op'])) { if ($_POST['op'] == "addConfig") { commitNewConfig($_POST['object_id'], $_POST['config'], $_POST['comments'], $_POST['dateadd']); } if ($_POST['op'] == "editConfig") { commitUpdateConfig($_POST['conf_id'], $_POST['config'], $_POST['comments'], $_POST['dateadd']); } } if (isset($_GET['op'])) { if ($_GET['op'] == "delConfig") { commitDeleteConfig($_GET['conf_id']); } } // Table header $display .= "<table cellspacing=0 cellpadding='5' align='center' class='widetable'>"; $display .= "<tr><th> </th>"; $display .= "<th class=tdleft></br>Saved Configurations</th>"; //$display .= "<th class=tdleft>Comment</th>"; $display .= "<th> </th></tr>"; assertUIntArg('object_id', __FUNCTION__); $object = spotEntity('object', $_REQUEST['object_id']); // Existing configs $query = "SELECT * FROM ObjectConfigs WHERE object_id = '{$object['id']}'"; $result = NULL; $result = usePreparedSelectBlade($query); while ($row = $result->fetch(PDO::FETCH_ASSOC)) { $conf_id = $row['id']; $object_id = $row['object_id']; $config = $row['config']; $comments = $row['comments']; $date = $row['date']; $display .= "<form method=post id=editConfig name=editConfig autocomplete=off action=\"\">"; $display .= "<input type=hidden name=\"conf_id\" value=\"" . $conf_id . "\">"; $display .= "<input type=hidden name=\"date\" value=\"" . $date . "\">"; $display .= "<input type=hidden name=\"op\" value=\"editConfig\">"; $display .= "<input type=hidden name=\"object_id\" value=\"" . $object_id . "\">"; $display .= "<tr><td><a href='?page=object&tab=configs&object_id=" . $object_id . "&op=delConfig&conf_id=" . $conf_id . "'onclick=\"javascript:return confirm('Are you sure you want to delete this Config?')\">"; $display .= "<img src='?module=chrome&uri=pix/tango-list-remove.png' width=16 height=16 border=0 title='Delete this Config'></a></td>"; $display .= "<td><a href=# onclick=toggle_visibility('{$conf_id}');>{$date}           Comments:  {$comments}</a>"; $display .= "</br><div id={$conf_id} style=display:none;><textarea style=background-color:#CCCCCC form=editConfig name=\"config\" cols=125 rows=15>" . $config . "</textarea></div></td><td></td>"; //$display .= "<td class='tdleft' NOWRAP><textarea name=comment value='".$comments."' cols=25 maxlength=254></textarea></td>"; $display .= "<td><input type=image name=submit class=icon src='?module=chrome&uri=pix/tango-document-save-16x16.png' border=0 title='Save' onclick=\"javascript:return confirm('Are you sure you want to overwrite this Config?')\"></td></form></tr>"; } // New config $display .= "<form action=\"\" method=post autocomplete=off id=\"addConfig\" name=\"addConfig\">"; $display .= "<input type=hidden name=\"object_id\" value=\"" . $object['id'] . "\">"; $display .= "<input type=hidden name=\"dateadd\" value=\"" . $dateadd . "\">"; $display .= "<input type=hidden name=\"op\" value=\"addConfig\">"; $display .= "<tr><td><input type=image name=submit class=icon src='?module=chrome&uri=pix/tango-list-add.png' border=0 title='Add a Config'></td>"; $display .= "<td class='tdleft'></br></br><p style=font-weight:bold;> Add New Configurations</p>Comment: <input cols=40 name=comments tabindex=102></br><textarea cols=125 rows=20 name=config tabindex=100 required></textarea></br></td></tr>"; $display .= "</form></br></table></br></center>"; // Output all .display strings to markup echo $display; }
function proxyMuninRequest($server_id, $graph) { $object = spotEntity('object', $server_id); list($host, $domain) = preg_split("/\\./", $object['dname'], 2); $ret = array(); $servers = getMuninServers(); if (!array_key_exists($server_id, $servers)) { throw new InvalidRequestArgException('server_id', $server_id); } $munin_url = $servers[$server_id]['base_url']; $url = "{$munin_url}/{$domain}/{$object['dname']}/{$graph}-day.png"; $session = curl_init(); // Initial options up here so a specific type can override them curl_setopt($session, CURLOPT_FOLLOWLOCATION, FALSE); curl_setopt($session, CURLOPT_TIMEOUT, 10); curl_setopt($session, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($session, CURLOPT_URL, $url); if (isset($_SESSION['MUNINCOOKIE'][$munin_url])) { curl_setopt($session, CURLOPT_COOKIE, $_SESSION['MUNINCOOKIE'][$munin_url]); } // Request the image $ret['contents'] = curl_exec($session); $ret['type'] = curl_getinfo($session, CURLINFO_CONTENT_TYPE); $ret['size'] = curl_getinfo($session, CURLINFO_SIZE_DOWNLOAD); curl_close($session); if ($ret['type'] != NULL) { header("Content-Type: {$ret['type']}"); } if ($ret['size'] > 0) { header("Content-Length: {$ret['size']}"); } echo $ret['contents']; }
function renderVLANMembership($object_id) { try { $data = getSwitchVLANs($object_id); } catch (RTGatewayError $re) { showWarning('Device configuration unavailable:<br>' . $re->getMessage()); return; } list($vlanlist, $portlist, $maclist) = $data; $vlanpermissions = array(); foreach ($portlist as $port) { if (array_key_exists($port['vlanid'], $vlanpermissions)) { continue; } $vlanpermissions[$port['vlanid']] = array(); foreach (array_keys($vlanlist) as $to) { if (permitted(NULL, NULL, 'setPortVLAN', array(array('tag' => '$fromvlan_' . $port['vlanid']), array('tag' => '$vlan_' . $port['vlanid']))) and permitted(NULL, NULL, 'setPortVLAN', array(array('tag' => '$tovlan_' . $to), array('tag' => '$vlan_' . $to)))) { $vlanpermissions[$port['vlanid']][] = $to; } } } if (isset($_REQUEST['hl_port_id'])) { assertUIntArg('hl_port_id'); $hl_port_id = intval($_REQUEST['hl_port_id']); $object = spotEntity('object', $object_id); amplifyCell($object); foreach ($object['ports'] as $port) { if (mb_strlen($port['name']) && $port['id'] == $hl_port_id) { $hl_port_name = $port['name']; break; } } } echo '<table border=0 width="100%"><tr><td colspan=3>'; startPortlet('Current status'); echo "<table class=widetable cellspacing=3 cellpadding=5 align=center width='100%'><tr>"; printOpFormIntro('setPortVLAN'); $portcount = count($portlist); echo "<input type=hidden name=portcount value=" . $portcount . ">\n"; $portno = 0; $ports_per_row = 12; foreach ($portlist as $port) { // Don't let wide forms break our fancy pages. if ($portno % $ports_per_row == 0) { if ($portno > 0) { echo "</tr>\n"; } echo "<tr><th>" . ($portno + 1) . "-" . ($portno + $ports_per_row > $portcount ? $portcount : $portno + $ports_per_row) . "</th>"; } $td_class = 'port_'; if ($port['status'] == 'notconnect') { $td_class .= 'notconnect'; } elseif ($port['status'] == 'disabled') { $td_class .= 'disabled'; } elseif ($port['status'] != 'connected') { $td_class .= 'unknown'; } elseif (!isset($maclist[$port['portname']])) { $td_class .= 'connected_none'; } else { $maccount = 0; foreach ($maclist[$port['portname']] as $vlanid => $addrs) { $maccount += count($addrs); } if ($maccount == 1) { $td_class .= 'connected_single'; } else { $td_class .= 'connected_multi'; } } if (isset($hl_port_name) and strcasecmp($hl_port_name, $port['portname']) == 0) { $td_class .= (strlen($td_class) ? ' ' : '') . 'border_highlight'; } echo "<td class='{$td_class}'>" . $port['portname'] . '<br>'; echo "<input type=hidden name=portname_{$portno} value=" . $port['portname'] . '>'; if ($port['vlanid'] == 'trunk') { echo "<input type=hidden name=vlanid_{$portno} value='trunk'>"; echo "<select disabled multiple='multiple' size=1><option>TRUNK</option></select>"; } elseif ($port['vlanid'] == 'routed') { echo "<input type=hidden name=vlanid_{$portno} value='routed'>"; echo "<select disabled multiple='multiple' size=1><option>ROUTED</option></select>"; } elseif (!array_key_exists($port['vlanid'], $vlanpermissions) or !count($vlanpermissions[$port['vlanid']])) { echo "<input type=hidden name=vlanid_{$portno} value={$port['vlanid']}>"; echo "<select disabled name=vlanid_{$portno}>"; echo "<option value={$port['vlanid']} selected>{$port['vlanid']}</option>"; echo "</select>"; } else { echo "<select name=vlanid_{$portno}>"; // A port may belong to a VLAN, which is absent from the VLAN table, this is normal. // We must be able to render its SELECT properly at least. $in_table = FALSE; foreach ($vlanpermissions[$port['vlanid']] as $v) { echo "<option value={$v}"; if ($v == $port['vlanid']) { echo ' selected'; $in_table = TRUE; } echo ">{$v}</option>\n"; } if (!$in_table) { echo "<option value={$port['vlanid']} selected>{$port['vlanid']}</option>\n"; } echo "</select>"; } $portno++; echo "</td>"; } echo "</tr><tr><td colspan=" . ($ports_per_row + 1) . "><input type=submit value='Save changes'></form></td></tr></table>"; finishPortlet(); echo '</td></tr><tr><td class=pcleft>'; startPortlet('VLAN table'); echo '<table class=cooltable cellspacing=0 cellpadding=5 align=center width="100%">'; echo "<tr><th>ID</th><th>Description</th></tr>"; $order = 'even'; global $nextorder; foreach ($vlanlist as $id => $descr) { echo "<tr class=row_{$order}><td class=tdright>{$id}</td><td class=tdleft>{$descr}</td></tr>"; $order = $nextorder[$order]; } echo '</table>'; finishPortlet(); echo '</td><td class=pcright>'; startPortlet('Color legend'); echo '<table>'; echo "<tr><th>port state</th><th>color code</th></tr>"; echo "<tr><td>not connected</td><td class=port_notconnect>SAMPLE</td></tr>"; echo "<tr><td>disabled</td><td class=port_disabled>SAMPLE</td></tr>"; echo "<tr><td>unknown</td><td class=port_unknown>SAMPLE</td></tr>"; echo "<tr><td>connected with none MAC addresses active</td><td class=port_connected_none>SAMPLE</td></tr>"; echo "<tr><td>connected with 1 MAC addresses active</td><td class=port_connected_single>SAMPLE</td></tr>"; echo "<tr><td>connected with 1+ MAC addresses active</td><td class=port_connected_multi>SAMPLE</td></tr>"; echo '</table>'; finishPortlet(); echo '</td><td class=pcright>'; if (count($maclist)) { startPortlet('MAC address table'); echo '<table border=0 class=cooltable align=center cellspacing=0 cellpadding=5>'; echo "<tr><th>Port</th><th>VLAN ID</th><th>MAC address</th></tr>\n"; $order = 'even'; foreach ($maclist as $portname => $portdata) { foreach ($portdata as $vlanid => $addrgroup) { foreach ($addrgroup as $addr) { echo "<tr class=row_{$order}><td class=tdleft>{$portname}</td><td class=tdleft>{$vlanid}</td>"; echo "<td class=tdleft>{$addr}</td></tr>\n"; $order = $nextorder[$order]; } } } echo '</table>'; finishPortlet(); } // End of main table. echo '</td></tr></table>'; }
function editUserProperties() { $taglist = genericAssertion('taglist', 'array0'); $user_id = getBypassValue(); rebuildTagChainForEntity('user', $user_id, buildTagChainFromIds($taglist), TRUE); $user = spotEntity('user', $user_id); print_r($user); showFuncMessage(__FUNCTION__, 'OK', array($user['user_name'])); }
function renderDataIntegrityReport() { global $nextorder; $violations = FALSE; // check 1: EntityLink rows referencing not-existent relatives // check 1.1: children $realms = array('location' => 'Location', 'object' => 'RackObject', 'rack' => 'Rack', 'row' => 'Row'); $orphans = array(); foreach ($realms as $realm => $table) { $result = usePreparedSelectBlade('SELECT EL.* FROM EntityLink EL ' . "LEFT JOIN {$table} ON EL.child_entity_id = {$table}.id " . "WHERE EL.child_entity_type = ? AND {$table}.id IS NULL", array($realm)); $rows = $result->fetchAll(PDO::FETCH_ASSOC); unset($result); $orphans = array_merge($orphans, $rows); } if (count($orphans)) { $violations = TRUE; startPortlet('EntityLink: Missing Children (' . count($orphans) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>Parent</th><th>Child Type</th><th>Child ID</th></tr>\n"; $order = 'odd'; foreach ($orphans as $orphan) { $realm_name = formatRealmName($orphan['parent_entity_type']); $parent = spotEntity($orphan['parent_entity_type'], $orphan['parent_entity_id']); echo "<tr class=row_{$order}>"; echo "<td>{$realm_name}: {$parent['name']}</td>"; echo "<td>{$orphan['child_entity_type']}</td>"; echo "<td>{$orphan['child_entity_id']}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 1.2: parents $orphans = array(); foreach ($realms as $realm => $table) { $result = usePreparedSelectBlade('SELECT EL.* FROM EntityLink EL ' . "LEFT JOIN {$table} ON EL.parent_entity_id = {$table}.id " . "WHERE EL.parent_entity_type = ? AND {$table}.id IS NULL", array($realm)); $rows = $result->fetchAll(PDO::FETCH_ASSOC); unset($result); $orphans = array_merge($orphans, $rows); } if (count($orphans)) { $violations = TRUE; startPortlet('EntityLink: Missing Parents (' . count($orphans) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>Child</th><th>Parent Type</th><th>Parent ID</th></tr>\n"; $order = 'odd'; foreach ($orphans as $orphan) { $realm_name = formatRealmName($orphan['child_entity_type']); $child = spotEntity($orphan['child_entity_type'], $orphan['child_entity_id']); echo "<tr class=row_{$order}>"; echo "<td>{$realm_name}: {$child['name']}</td>"; echo "<td>{$orphan['parent_entity_type']}</td>"; echo "<td>{$orphan['parent_entity_id']}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 3: multiple tables referencing non-existent dictionary entries // check 3.1: AttributeMap $orphans = array(); $result = usePreparedSelectBlade('SELECT AM.*, A.name AS attr_name, C.name AS chapter_name ' . 'FROM AttributeMap AM ' . 'LEFT JOIN Attribute A ON AM.attr_id = A.id ' . 'LEFT JOIN Chapter C ON AM.chapter_id = C.id ' . 'LEFT JOIN Dictionary D ON AM.objtype_id = D.dict_key ' . 'WHERE D.dict_key IS NULL'); $orphans = $result->fetchAll(PDO::FETCH_ASSOC); unset($result); if (count($orphans)) { $violations = TRUE; startPortlet('AttributeMap: Invalid Mappings (' . count($orphans) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>Attribute</th><th>Chapter</th><th>Object TypeID</th></tr>\n"; $order = 'odd'; foreach ($orphans as $orphan) { echo "<tr class=row_{$order}>"; echo "<td>{$orphan['attr_name']}</td>"; echo "<td>{$orphan['chapter_name']}</td>"; echo "<td>{$orphan['objtype_id']}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 3.2: Object $orphans = array(); $result = usePreparedSelectBlade('SELECT O.* FROM Object O ' . 'LEFT JOIN Dictionary D ON O.objtype_id = D.dict_key ' . 'WHERE D.dict_key IS NULL'); $orphans = $result->fetchAll(PDO::FETCH_ASSOC); unset($result); if (count($orphans)) { $violations = TRUE; startPortlet('Object: Invalid Types (' . count($orphans) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>ID</th><th>Name</th><th>Type ID</th></tr>\n"; $order = 'odd'; foreach ($orphans as $orphan) { echo "<tr class=row_{$order}>"; echo "<td>{$orphan['id']}</td>"; echo "<td>{$orphan['name']}</td>"; echo "<td>{$orphan['objtype_id']}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 3.3: ObjectHistory $orphans = array(); $result = usePreparedSelectBlade('SELECT OH.* FROM ObjectHistory OH ' . 'LEFT JOIN Dictionary D ON OH.objtype_id = D.dict_key ' . 'WHERE D.dict_key IS NULL'); $orphans = $result->fetchAll(PDO::FETCH_ASSOC); unset($result); if (count($orphans)) { $violations = TRUE; startPortlet('ObjectHistory: Invalid Types (' . count($orphans) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>ID</th><th>Name</th><th>Type ID</th></tr>\n"; $order = 'odd'; foreach ($orphans as $orphan) { echo "<tr class=row_{$order}>"; echo "<td>{$orphan['id']}</td>"; echo "<td>{$orphan['name']}</td>"; echo "<td>{$orphan['objtype_id']}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 3.4: ObjectParentCompat $orphans = array(); $result = usePreparedSelectBlade('SELECT OPC.*, PD.dict_value AS parent_name, CD.dict_value AS child_name ' . 'FROM ObjectParentCompat OPC ' . 'LEFT JOIN Dictionary PD ON OPC.parent_objtype_id = PD.dict_key ' . 'LEFT JOIN Dictionary CD ON OPC.child_objtype_id = CD.dict_key ' . 'WHERE PD.dict_key IS NULL OR CD.dict_key IS NULL'); $orphans = $result->fetchAll(PDO::FETCH_ASSOC); unset($result); if (count($orphans)) { $violations = TRUE; startPortlet('Object Container Compatibility rules: Invalid Parent or Child Type (' . count($orphans) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>Parent</th><th>Parent Type ID</th><th>Child</th><th>Child Type ID</th></tr>\n"; $order = 'odd'; foreach ($orphans as $orphan) { echo "<tr class=row_{$order}>"; echo "<td>{$orphan['parent_name']}</td>"; echo "<td>{$orphan['parent_objtype_id']}</td>"; echo "<td>{$orphan['child_name']}</td>"; echo "<td>{$orphan['child_objtype_id']}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 4: relationships that violate ObjectParentCompat Rules $invalids = array(); $result = usePreparedSelectBlade('SELECT CO.id AS child_id, CO.objtype_id AS child_type_id, CD.dict_value AS child_type, CO.name AS child_name, ' . 'PO.id AS parent_id, PO.objtype_id AS parent_type_id, PD.dict_value AS parent_type, PO.name AS parent_name ' . 'FROM Object CO ' . 'LEFT JOIN EntityLink EL ON CO.id = EL.child_entity_id ' . 'LEFT JOIN Object PO ON EL.parent_entity_id = PO.id ' . 'LEFT JOIN ObjectParentCompat OPC ON PO.objtype_id = OPC.parent_objtype_id ' . 'LEFT JOIN Dictionary PD ON PO.objtype_id = PD.dict_key ' . 'LEFT JOIN Dictionary CD ON CO.objtype_id = CD.dict_key ' . "WHERE EL.parent_entity_type = 'object' AND EL.child_entity_type = 'object' " . 'AND OPC.parent_objtype_id IS NULL'); $invalids = $result->fetchAll(PDO::FETCH_ASSOC); unset($result); if (count($invalids)) { $violations = TRUE; startPortlet('Objects: Violate Object Container Compatibility rules (' . count($invalids) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>Contained Obj Name</th><th>Contained Obj Type</th><th>Container Obj Name</th><th>Container Obj Type</th></tr>\n"; $order = 'odd'; foreach ($invalids as $invalid) { echo "<tr class=row_{$order}>"; echo "<td>{$invalid['child_name']}</td>"; echo "<td>{$invalid['child_type']}</td>"; echo "<td>{$invalid['parent_name']}</td>"; echo "<td>{$invalid['parent_type']}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 5: Links that violate PortCompat Rules $invalids = array(); $result = usePreparedSelectBlade('SELECT OA.id AS obja_id, OA.name AS obja_name, L.porta AS porta_id, PA.name AS porta_name, POIA.oif_name AS porta_type, ' . 'OB.id AS objb_id, OB.name AS objb_name, L.portb AS portb_id, PB.name AS portb_name, POIB.oif_name AS portb_type ' . 'FROM Link L ' . 'LEFT JOIN Port PA ON L.porta = PA.id ' . 'LEFT JOIN Object OA ON PA.object_id = OA.id ' . 'LEFT JOIN PortOuterInterface POIA ON PA.type = POIA.id ' . 'LEFT JOIN Port PB ON L.portb = PB.id ' . 'LEFT JOIN Object OB ON PB.object_id = OB.id ' . 'LEFT JOIN PortOuterInterface POIB ON PB.type = POIB.id ' . 'LEFT JOIN PortCompat PC on PA.type = PC.type1 AND PB.type = PC.type2 ' . 'WHERE PC.type1 IS NULL OR PC.type2 IS NULL'); $invalids = $result->fetchAll(PDO::FETCH_ASSOC); unset($result); if (count($invalids)) { $violations = TRUE; startPortlet('Port Links: Violate Port Compatibility Rules (' . count($invalids) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>Object A</th><th>Port A Name</th><th>Port A Type</th><th>Object B</th><th>Port B Name</th><th>Port B Type</th></tr>\n"; $order = 'odd'; foreach ($invalids as $invalid) { echo "<tr class=row_{$order}>"; echo "<td>{$invalid['obja_name']}</td>"; echo "<td>{$invalid['porta_name']}</td>"; echo "<td>{$invalid['porta_type']}</td>"; echo "<td>{$invalid['objb_name']}</td>"; echo "<td>{$invalid['portb_name']}</td>"; echo "<td>{$invalid['portb_type']}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 6: TagStorage rows referencing non-existent parents $realms = array('file' => array('table' => 'File', 'column' => 'id'), 'ipv4net' => array('table' => 'IPv4Network', 'column' => 'id'), 'ipv4rspool' => array('table' => 'IPv4RSPool', 'column' => 'id'), 'ipv4vs' => array('table' => 'IPv4VS', 'column' => 'id'), 'ipv6net' => array('table' => 'IPv6Network', 'column' => 'id'), 'ipvs' => array('table' => 'VS', 'column' => 'id'), 'location' => array('table' => 'Location', 'column' => 'id'), 'object' => array('table' => 'RackObject', 'column' => 'id'), 'rack' => array('table' => 'Rack', 'column' => 'id'), 'user' => array('table' => 'UserAccount', 'column' => 'user_id'), 'vst' => array('table' => 'VLANSwitchTemplate', 'column' => 'id')); $orphans = array(); foreach ($realms as $realm => $details) { $result = usePreparedSelectBlade('SELECT TS.*, TT.tag FROM TagStorage TS ' . 'LEFT JOIN TagTree TT ON TS.tag_id = TT.id ' . "LEFT JOIN {$details['table']} ON TS.entity_id = {$details['table']}.{$details['column']} " . "WHERE TS.entity_realm = ? AND {$details['table']}.{$details['column']} IS NULL", array($realm)); $rows = $result->fetchAll(PDO::FETCH_ASSOC); unset($result); $orphans = array_merge($orphans, $rows); } if (count($orphans)) { $violations = TRUE; startPortlet('TagStorage: Missing Parents (' . count($orphans) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>Tag</th><th>Parent Type</th><th>Parent ID</th></tr>\n"; $order = 'odd'; foreach ($orphans as $orphan) { $realm_name = formatRealmName($orphan['entity_realm']); echo "<tr class=row_{$order}>"; echo "<td>{$orphan['tag']}</td>"; echo "<td>{$realm_name}</td>"; echo "<td>{$orphan['entity_id']}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 7: FileLink rows referencing non-existent parents // re-use the realms list from the TagStorage check, with a few mods unset($realms['file'], $realms['vst']); $realms['row'] = array('table' => 'Row', 'column' => 'id'); $orphans = array(); foreach ($realms as $realm => $details) { $result = usePreparedSelectBlade('SELECT FL.*, F.name FROM FileLink FL ' . 'LEFT JOIN File F ON FL.file_id = F.id ' . "LEFT JOIN {$details['table']} ON FL.entity_id = {$details['table']}.{$details['column']} " . "WHERE FL.entity_type = ? AND {$details['table']}.{$details['column']} IS NULL", array($realm)); $rows = $result->fetchAll(PDO::FETCH_ASSOC); unset($result); $orphans = array_merge($orphans, $rows); } if (count($orphans)) { $violations = TRUE; startPortlet('FileLink: Missing Parents (' . count($orphans) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>File</th><th>Parent Type</th><th>Parent ID</th></tr>\n"; $order = 'odd'; foreach ($orphans as $orphan) { $realm_name = formatRealmName($orphan['entity_type']); echo "<tr class=row_{$order}>"; echo "<td>{$orphan['name']}</td>"; echo "<td>{$realm_name}</td>"; echo "<td>{$orphan['entity_id']}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 8: missing triggers $triggers = array('Link-before-insert' => 'Link', 'Link-before-update' => 'Link'); $result = usePreparedSelectBlade('SELECT TRIGGER_NAME, EVENT_OBJECT_TABLE ' . 'FROM information_schema.TRIGGERS WHERE TRIGGER_SCHEMA = SCHEMA()'); $rows = $result->fetchAll(PDO::FETCH_ASSOC); unset($result); $existing_triggers = $missing_triggers = array(); foreach ($rows as $row) { $existing_triggers[$row['TRIGGER_NAME']] = $row['EVENT_OBJECT_TABLE']; } foreach ($triggers as $trigger => $table) { if (!array_key_exists($trigger, $existing_triggers)) { $missing_triggers[$trigger] = $table; } } if (count($missing_triggers)) { $violations = TRUE; startPortlet('Missing Triggers (' . count($missing_triggers) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>Table</th><th>Trigger</th></tr>\n"; $order = 'odd'; foreach ($missing_triggers as $trigger => $table) { echo "<tr class=row_{$order}>"; echo "<td>{$table}</td>"; echo "<td>{$trigger}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 9: missing foreign keys $fkeys = array('Atom-FK-molecule_id' => 'Atom', 'Atom-FK-rack_id' => 'Atom', 'AttributeMap-FK-chapter_id' => 'AttributeMap', 'AttributeMap-FK-attr_id' => 'AttributeMap', 'AttributeValue-FK-map' => 'AttributeValue', 'AttributeValue-FK-object' => 'AttributeValue', 'CachedPAV-FK-object-port' => 'CachedPAV', 'CachedPAV-FK-vlan_id' => 'CachedPAV', 'CachedPNV-FK-compound' => 'CachedPNV', 'CachedPVM-FK-object_id' => 'CachedPVM', 'CactiGraph-FK-server_id' => 'CactiGraph', 'CactiGraph-FK-server_id' => 'CactiGraph', 'Dictionary-FK-chapter_id' => 'Dictionary', 'FileLink-File_fkey' => 'FileLink', 'IPv4Allocation-FK-object_id' => 'IPv4Allocation', 'IPv4LB-FK-vs_id' => 'IPv4LB', 'IPv4LB-FK-object_id' => 'IPv4LB', 'IPv4LB-FK-rspool_id' => 'IPv4LB', 'IPv4NAT-FK-object_id' => 'IPv4NAT', 'IPv4RS-FK' => 'IPv4RS', 'IPv6Allocation-FK-object_id' => 'IPv6Allocation', 'Link-FK-a' => 'Link', 'Link-FK-b' => 'Link', 'MountOperation-FK-object_id' => 'MountOperation', 'MountOperation-FK-old_molecule_id' => 'MountOperation', 'MountOperation-FK-new_molecule_id' => 'MountOperation', 'MuninGraph-FK-server_id' => 'MuninGraph', 'MuninGraph-FK-server_id' => 'MuninGraph', 'ObjectHistory-FK-object_id' => 'ObjectHistory', 'ObjectLog-FK-object_id' => 'ObjectLog', 'Port-FK-iif-oif' => 'Port', 'Port-FK-object_id' => 'Port', 'PortAllowedVLAN-FK-object-port' => 'PortAllowedVLAN', 'PortAllowedVLAN-FK-vlan_id' => 'PortAllowedVLAN', 'PortCompat-FK-oif_id1' => 'PortCompat', 'PortCompat-FK-oif_id2' => 'PortCompat', 'PortInterfaceCompat-FK-iif_id' => 'PortInterfaceCompat', 'PortInterfaceCompat-FK-oif_id' => 'PortInterfaceCompat', 'PortLog_ibfk_1' => 'PortLog', 'PortNativeVLAN-FK-compound' => 'PortNativeVLAN', 'PortVLANMode-FK-object-port' => 'PortVLANMode', 'RackSpace-FK-rack_id' => 'RackSpace', 'RackSpace-FK-object_id' => 'RackSpace', 'TagStorage-FK-TagTree' => 'TagStorage', 'TagTree-K-parent_id' => 'TagTree', 'UserConfig-FK-varname' => 'UserConfig', 'VLANDescription-FK-domain_id' => 'VLANDescription', 'VLANDescription-FK-vlan_id' => 'VLANDescription', 'VLANIPv4-FK-compound' => 'VLANIPv4', 'VLANIPv4-FK-ipv4net_id' => 'VLANIPv4', 'VLANIPv6-FK-compound' => 'VLANIPv6', 'VLANIPv6-FK-ipv6net_id' => 'VLANIPv6', 'VLANSTRule-FK-vst_id' => 'VLANSTRule', 'VLANSwitch-FK-domain_id' => 'VLANSwitch', 'VLANSwitch-FK-object_id' => 'VLANSwitch', 'VLANSwitch-FK-template_id' => 'VLANSwitch', 'VSEnabledIPs-FK-object_id' => 'VSEnabledIPs', 'VSEnabledIPs-FK-rspool_id' => 'VSEnabledIPs', 'VSEnabledIPs-FK-vs_id-vip' => 'VSEnabledIPs', 'VSEnabledPorts-FK-object_id' => 'VSEnabledPorts', 'VSEnabledPorts-FK-rspool_id' => 'VSEnabledPorts', 'VSEnabledPorts-FK-vs_id-proto-vport' => 'VSEnabledPorts', 'VSIPs-vs_id' => 'VSIPs', 'VS-vs_id' => 'VSPorts'); $result = usePreparedSelectBlade('SELECT CONSTRAINT_NAME, TABLE_NAME ' . 'FROM information_schema.TABLE_CONSTRAINTS ' . "WHERE CONSTRAINT_SCHEMA = SCHEMA() AND CONSTRAINT_TYPE = 'FOREIGN KEY'"); $rows = $result->fetchAll(PDO::FETCH_ASSOC); unset($result); $existing_fkeys = $missing_fkeys = array(); foreach ($rows as $row) { $existing_fkeys[$row['CONSTRAINT_NAME']] = $row['TABLE_NAME']; } foreach ($fkeys as $fkey => $table) { if (!array_key_exists($fkey, $existing_fkeys)) { $missing_fkeys[$fkey] = $table; } } if (count($missing_fkeys)) { $violations = TRUE; startPortlet('Missing Foreign Keys (' . count($missing_fkeys) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>Table</th><th>Key</th></tr>\n"; $order = 'odd'; foreach ($missing_fkeys as $fkey => $table) { echo "<tr class=row_{$order}>"; echo "<td>{$table}</td>"; echo "<td>{$fkey}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 10: circular references // - all affected members of the tree are displayed // - it would be beneficial to only display the offending records // check 10.1: locations $invalids = array(); $locations = listCells('location'); foreach ($locations as $location) { try { $children = getLocationChildrenList($location['id']); } catch (RackTablesError $e) { $invalids[] = $location; } } if (count($invalids)) { $violations = TRUE; startPortlet('Locations: Tree Contains Circular References (' . count($invalids) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>Child ID</th><th>Child Location</th><th>Parent ID</th><th>Parent Location</th></tr>\n"; $order = 'odd'; foreach ($invalids as $invalid) { echo "<tr class=row_{$order}>"; echo "<td>{$invalid['id']}</td>"; echo "<td>{$invalid['name']}</td>"; echo "<td>{$invalid['parent_id']}</td>"; echo "<td>{$invalid['parent_name']}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 10.2: objects $invalids = array(); $objects = listCells('object'); foreach ($objects as $object) { try { $children = getObjectContentsList($object['id']); } catch (RackTablesError $e) { $invalids[] = $object; } } if (count($invalids)) { $violations = TRUE; startPortlet('Objects: Tree Contains Circular References (' . count($invalids) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>Contained ID</th><th>Contained Object</th><th>Container ID</th><th>Container Object</th></tr>\n"; $order = 'odd'; foreach ($invalids as $invalid) { echo "<tr class=row_{$order}>"; echo "<td>{$invalid['id']}</td>"; echo "<td>{$invalid['name']}</td>"; echo "<td>{$invalid['container_id']}</td>"; echo "<td>{$invalid['container_name']}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } // check 10.3: tags $invalids = array(); $tags = getTagList(); foreach ($tags as $tag) { try { $children = getTagChildrenList($tag['id']); } catch (RackTablesError $e) { $invalids[] = $tag; } } if (count($invalids)) { $violations = TRUE; startPortlet('Tags: Tree Contains Circular References (' . count($invalids) . ')'); echo "<table cellpadding=5 cellspacing=0 align=center class=cooltable>\n"; echo "<tr><th>Child ID</th><th>Child Tag</th><th>Parent ID</th><th>Parent Tag</th></tr>\n"; $order = 'odd'; foreach ($invalids as $invalid) { echo "<tr class=row_{$order}>"; echo "<td>{$invalid['id']}</td>"; echo "<td>{$invalid['tag']}</td>"; echo "<td>{$invalid['parent_id']}</td>"; printf('<td>%s</td>', $tags[$invalid['parent_id']]['tag']); echo "</tr>\n"; $order = $nextorder[$order]; } echo "</table>\n"; finishPortLet(); } if (!$violations) { echo '<h2>No integrity violations found</h2>'; } }
function renderExpirations() { global $nextorder; $breakdown = array(); $breakdown[21] = array(array('from' => -365, 'to' => 0, 'class' => 'has_problems_', 'title' => 'has expired within last year'), array('from' => 0, 'to' => 30, 'class' => 'row_', 'title' => 'expires within 30 days'), array('from' => 30, 'to' => 60, 'class' => 'row_', 'title' => 'expires within 60 days'), array('from' => 60, 'to' => 90, 'class' => 'row_', 'title' => 'expires within 90 days')); $breakdown[22] = $breakdown[21]; $breakdown[24] = $breakdown[21]; $attrmap = getAttrMap(); foreach ($breakdown as $attr_id => $sections) { startPortlet($attrmap[$attr_id]['name']); foreach ($sections as $section) { $count = 1; $order = 'odd'; $result = scanAttrRelativeDays($attr_id, $section['from'], $section['to']); echo '<table align=center width=60% border=0 cellpadding=5 cellspacing=0 align=center class=cooltable>'; echo "<caption>{$section['title']}</caption>\n"; if (!count($result)) { echo "<tr><td colspan=4>(none)</td></tr></table><br>\n"; continue; } echo '<tr valign=top><th align=center>Count</th><th align=center>Name</th>'; echo "<th align=center>Asset Tag</th><th align=center>Date Warranty <br> Expires</th></tr>\n"; foreach ($result as $row) { $date_value = date(getConfigVar('DATETIME_FORMAT'), $row['uint_value']); $object = spotEntity('object', $row['object_id']); echo '<tr class=' . $section['class'] . $order . ' valign=top>'; echo "<td>{$count}</td>"; echo '<td>' . mkA($object['dname'], 'object', $object['id']) . '</td>'; echo "<td>{$object['asset_no']}</td>"; echo "<td>{$date_value}</td>"; echo "</tr>\n"; $order = $nextorder[$order]; $count++; } echo "</table><br>\n"; } finishPortlet(); } }
function constructUserCell($username) { if (NULL !== ($userid = getUserIDByUsername($username))) { return spotEntity('user', $userid); } $ret = array('realm' => 'user', 'user_name' => $username, 'user_realname' => '', 'etags' => array(), 'itags' => array()); $ret['atags'] = generateEntityAutoTags($ret); return $ret; }
function renderPopupPortSelector() { if (isset($_REQUEST['do_link'])) { return handlePopupPortLink(); } assertPermission('depot', 'default'); assertUIntArg('port'); $port_id = $_REQUEST['port']; $port_info = getPortInfo($port_id); $in_rack = isCheckSet('in_rack'); // fill port filter structure $filter = array('racks' => array(), 'objects' => '', 'ports' => '', 'asset_no' => ''); if (isset($_REQUEST['filter-obj'])) { $filter['objects'] = trim($_REQUEST['filter-obj']); } if (isset($_REQUEST['filter-port'])) { $filter['ports'] = trim($_REQUEST['filter-port']); } if (isset($_REQUEST['filter-asset_no'])) { $filter['asset_no'] = trim($_REQUEST['filter-asset_no']); } if ($in_rack) { $object = spotEntity('object', $port_info['object_id']); if ($object['rack_id']) { // the object itself is mounted in a rack $filter['racks'] = getProximateRacks($object['rack_id'], getConfigVar('PROXIMITY_RANGE')); } elseif ($object['container_id']) { $container = spotEntity('object', $object['container_id']); if ($container['rack_id']) { $filter['racks'] = getProximateRacks($container['rack_id'], getConfigVar('PROXIMITY_RANGE')); } } } $spare_ports = array(); if (!empty($filter['racks']) || !empty($filter['objects']) || !empty($filter['ports']) || !empty($filter['asset_no'])) { $spare_ports = findSparePorts($port_info, $filter); } // display search form echo 'Link ' . formatPort($port_info) . ' to...'; echo '<form method=GET>'; startPortlet('Port list filter'); echo '<input type=hidden name="module" value="popup">'; echo '<input type=hidden name="helper" value="portlist">'; echo '<input type=hidden name="port" value="' . $port_id . '">'; echo '<table align="center" valign="bottom"><tr>'; echo '<td class="tdleft"><label>Object name:<br><input type=text size=8 name="filter-obj" value="' . htmlspecialchars($filter['objects'], ENT_QUOTES) . '"></label></td>'; echo '<td class="tdleft"><label>Asset tag:<br><input type=text size=8 name="filter-asset_no" value="' . htmlspecialchars($filter['asset_no'], ENT_QUOTES) . '"></label></td>'; echo '<td class="tdleft"><label>Port name:<br><input type=text size=6 name="filter-port" value="' . htmlspecialchars($filter['ports'], ENT_QUOTES) . '"></label></td>'; echo '<td class="tdleft" valign="bottom"><label><input type=checkbox name="in_rack"' . ($in_rack ? ' checked' : '') . '>Nearest racks</label></td>'; echo '<td valign="bottom"><input type=submit value="show ports"></td>'; echo '</tr></table>'; finishPortlet(); // display results startPortlet('Compatible spare ports'); if (empty($spare_ports)) { echo '(nothing found)'; } else { echo getSelect($spare_ports, array('name' => 'remote_port', 'size' => getConfigVar('MAXSELSIZE')), NULL, FALSE); echo "<p>Cable ID: <input type=text id=cable name=cable>"; // suggest patch cables where it makes sense $heaps = getPatchCableHeapOptionsForOIF($port_info['oif_id']); if (count($heaps)) { // Use + instead of array_merge() to avoid renumbering the keys. echo '<p>Patch cable: ' . getSelect(array(0 => 'none') + $heaps, array('name' => 'heap_id')); } echo "<p><input type='submit' value='Link' name='do_link'>"; } finishPortlet(); echo '</form>'; }
// add your regexps here to suppress 'Martian autotag' warnings $user_defined_atags = array(); // This also can be modified in local.php. $pageheaders = array(100 => "<link rel='ICON' type='image/x-icon' href='?module=chrome&uri=pix/favicon.ico' />"); addCSS('css/pi.css'); if (!isset($script_mode) or $script_mode !== TRUE) { // A successful call to authenticate() always generates autotags and somethimes // even given/implicit tags. It also sets remote_username and remote_displayname. authenticate(); // Authentication passed. // Note that we don't perform autorization here, so each 1st level page // has to do it in its way, e.g. by calling authorize() after fixContext(). } elseif (!isset($remote_username)) { // Some functions require remote_username to be set to something to act correctly, // even though they don't use the value itself. $admin_account = spotEntity('user', 1); if (isCLIMode() && FALSE !== ($env_user = getenv('USER'))) { // use USER env var if we are in CLI mode $remote_username = $env_user; } else { $remote_username = $admin_account['user_name']; } unset($env_user); unset($admin_account); } $virtual_obj_types = explode(',', getConfigVar('VIRTUAL_OBJ_LISTSRC')); alterConfigWithUserPreferences(); $op = ''; // load additional plugins ob_start(); foreach (glob("{$racktables_plugins_dir}/*.php") as $filename) {
function importFingData() { $net = spotEntity('ipv4net', getBypassValue()); assertUIntArg('addrcount'); $nbad = $ngood = 0; for ($i = 1; $i <= $_REQUEST['addrcount']; $i++) { $inputname = "import_{$i}"; if (!isCheckSet($inputname)) { continue; } $ip_bin = assertIPv4Arg("addr_{$i}"); assertStringArg("descr_{$i}", TRUE); assertStringArg("rsvd_{$i}"); // Non-existent addresses will not have this argument set in request. $rsvd = 'no'; if ($_REQUEST["rsvd_{$i}"] == 'yes') { $rsvd = 'yes'; } try { if (!ip_in_range($ip_bin, $net)) { throw new InvalidArgException('ip_bin', $ip_bin); } updateAddress($ip_bin, $_REQUEST["descr_{$i}"], $rsvd); $ngood++; } catch (RackTablesError $e) { $nbad++; } } if (!$nbad) { showFuncMessage(__FUNCTION__, 'OK', array($ngood)); } else { showFuncMessage(__FUNCTION__, 'ERR', array($nbad, $ngood)); } }
function makeIPAllocLink($ip_bin, $alloc, $display_ifname = FALSE) { $object_name = !isset($object_name) || !strlen($object_name) ? formatEntityName(spotEntity('object', $alloc['object_id'])) : $alloc['object_name']; $title = $display_ifname ? '' : "{$alloc['name']} @ {$object_name}"; return '<a href="' . makeHref(array('page' => 'object', 'tab' => 'default', 'object_id' => $alloc['object_id'], 'hl_ip' => ip_format($ip_bin))) . '"' . ' title="' . htmlspecialchars($title, ENT_QUOTES) . '"' . ">" . ($display_ifname ? $alloc['name'] . '@' : '') . $object_name . "</a>"; }
function renderIPVSConvert($vs_id) { $old_vs_list = callHook('getVSIDsByGroup', $vs_id); $grouped = array(); $used_tags = array(); foreach ($old_vs_list as $old_vs_id) { $vsinfo = spotEntity('ipv4vs', $old_vs_id); foreach ($vsinfo['etags'] as $taginfo) { $used_tags[$taginfo['id']] = $taginfo; } $port_key = $vsinfo['proto'] . '-' . $vsinfo['vport']; $grouped[$port_key][] = $vsinfo; } startPortlet("Found " . count($old_vs_list) . " matching VS"); printOpFormIntro('convert'); if (count($used_tags)) { echo '<p>Assign these tags to VS group:</p>'; foreach ($used_tags as $taginfo) { echo '<p><label><input type=checkbox checked name="taglist[]" value="' . htmlspecialchars($taginfo['id'], ENT_QUOTES) . '""> ' . serializeTags(array($taginfo)) . '<label>'; } } echo '<p>Import settings of these VS:</p>'; echo '<table align=center><tr>'; foreach ($grouped as $port_key => $list) { echo '<th>' . $port_key . '</th>'; } echo '</tr><tr>'; foreach ($grouped as $port_key => $list) { echo '<td><table>'; foreach ($list as $vsinfo) { echo '<tr><td><input type=checkbox name="vs_list[]" checked value="' . htmlspecialchars($vsinfo['id'], ENT_QUOTES) . '"></td><td>'; renderSLBEntityCell($vsinfo); echo '</td></tr>'; } echo '</table></td>'; } echo '</tr></table>'; printImageHREF('next', "Import settings of the selected services", TRUE); echo '</form>'; finishPortlet(); }
function updateCableIdAJAX() { global $sic; assertUIntArg('id'); assertStringArg('text', TRUE); $port_info = getPortInfo($sic['id']); fixContext(spotEntity('object', $port_info['object_id'])); assertPermission('object', 'ports', 'editPort'); if (!$port_info['linked']) { throw new RackTablesError('Cant update cable ID: port is not linked'); } if ($port_info['reservation_comment'] !== $sic['text']) { commitUpdatePortLink($sic['id'], $sic['text']); } echo 'OK'; }
function initRackTablesObject($rackDatas) { // zabbix host data $params = array('output' => 'extend'); $result = doPost('host.get', $params); $hosts = isset($result['result']) ? $result['result'] : array(); $objectDatas = array(); foreach ($hosts as $host) { $object_type_id = 4; $object_name = isset($host['host']) ? $host['host'] : ""; $object_label = ""; $object_asset_no = ""; $taglist = array(); $has_problems = $host['status'] == 0 ? 'no' : 'yes'; $object_id = commitAddObject($object_name, $object_label, $object_type_id, $object_asset_no, $taglist); usePreparedUpdateBlade('Object', array('has_problems' => $has_problems), array('id' => $object_id)); $objectDatas[$host['hostid']] = $object_id; // set hostgroup $params = array('output' => array('name'), 'hostids' => array($host['hostid'])); $result = doPost('hostgroup.get', $params); $hostgroups = isset($result['result']) ? $result['result'] : array(); $rack_ids = array(); $_REQUEST = array(); foreach ($hostgroups as $hostgroup) { if (isset($rackDatas[$hostgroup['name']])) { $rack = $rackDatas[$hostgroup['name']]; amplifyCell($rack); array_push($rack_ids, $rack['id']); $height = $rack['height']; for ($i = 0; $i < 3; $i++) { for ($j = $height; $j > 0; $j--) { if ($rack[$j][$i]['state'] == 'F') { # state == "T" : mounted $_REQUEST['atom_' . $rack['id'] . "_{$j}" . "_{$i}"] = 'on'; break 2; } } } } } $_REQUEST['object_id'] = $object_id; $_REQUEST['rackmulti'] = $rack_ids; $object = spotEntity('object', $object_id); $changecnt = 0; // Get a list of rack ids which are parents of the object $parentRacks = reduceSubarraysToColumn(getParents($object, 'rack'), 'id'); $workingRacksData = array(); foreach ($_REQUEST['rackmulti'] as $cand_id) { if (!isset($workingRacksData[$cand_id])) { $rackData = spotEntity('rack', $cand_id); amplifyCell($rackData); $workingRacksData[$cand_id] = $rackData; } else { $rackData = $workingRacksData[$cand_id]; } $is_ro = !rackModificationPermitted($rackData, 'updateObjectAllocation', FALSE); // It's zero-U mounted to this rack on the form, but not in the DB. Mount it. if (isset($_REQUEST["zerou_{$cand_id}"]) && !in_array($cand_id, $parentRacks)) { if ($is_ro) { continue; } $changecnt++; commitLinkEntities('rack', $cand_id, 'object', $object_id); } // It's not zero-U mounted to this rack on the form, but it is in the DB. Unmount it. if (!isset($_REQUEST["zerou_{$cand_id}"]) && in_array($cand_id, $parentRacks)) { if ($is_ro) { continue; } $changecnt++; commitUnlinkEntities('rack', $cand_id, 'object', $object_id); } } foreach ($workingRacksData as &$rd) { applyObjectMountMask($rd, $object_id); } $oldMolecule = getMoleculeForObject($object_id); foreach ($workingRacksData as $rack_id => $rackData) { $is_ro = !rackModificationPermitted($rackData, 'updateObjectAllocation', FALSE); if ($is_ro || !processGridForm($rackData, 'F', 'T', $object_id)) { continue; } $changecnt++; // Reload our working copy after form processing. $rackData = spotEntity('rack', $cand_id); amplifyCell($rackData); applyObjectMountMask($rackData, $object_id); $workingRacksData[$rack_id] = $rackData; } if ($changecnt) { // Log a record. $newMolecule = getMoleculeForObject($object_id); global $remote_username, $sic; usePreparedInsertBlade('MountOperation', array('object_id' => $object_id, 'old_molecule_id' => count($oldMolecule) ? createMolecule($oldMolecule) : NULL, 'new_molecule_id' => count($newMolecule) ? createMolecule($newMolecule) : NULL, 'user_name' => $remote_username, 'comment' => empty($sic['comment']) ? NULL : $sic['comment'])); } // set IP $params = array('output' => 'extend', 'hostids' => $host['hostid']); $result = doPost('hostinterface.get', $params); $hostinterfaces = isset($result['result']) ? $result['result'] : array(); foreach ($hostinterfaces as $interface) { if (isset($interface['ip']) && $interface['ip'] != '127.0.0.1') { $allocs = getObjectIPAllocations($object_id); $current_ips = array(); foreach ($allocs as $alloc) { $ip = $alloc["addrinfo"]["ip"]; $current_ips[$ip] = $ip; } $ip = $interface['ip']; if (!in_array($ip, array_values($current_ips))) { // new IP $ip_bin = ip_parse($ip); if (null == getIPAddressNetworkId($ip_bin)) { // if ip is not exists, adding it into RackTables IPv4Prefix. $range = substr($ip, 0, strripos($ip, '.')) . '.0/24'; $vlan_ck = NULL; $net_id = createIPv4Prefix($range, 'admim', isCheckSet('is_connected'), $taglist); $net_cell = spotEntity('ipv4net', $net_id); if (isset($vlan_ck)) { if (considerConfiguredConstraint($net_cell, 'VLANIPV4NET_LISTSRC')) { commitSupplementVLANIPv4($vlan_ck, $net_id); } } } bindIPToObject($ip_bin, $object_id, "", ""); } } } } return $objectDatas; }