public void testProxiedAgent() throws UnknownHostException {
   SnmpAgentConfig agentConfig =
       SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("10.0.0.3"));
   assertEquals("10.0.0.3", InetAddressUtils.str(agentConfig.getProxyFor()));
   assertEquals("127.0.0.1", InetAddressUtils.str(agentConfig.getAddress()));
   agentConfig.toString();
 }
  public String getForeignSource(InetAddress address) {
    getReadLock().lock();
    try {
      LOG.debug(
          "Looking for matching foreign source specific IP or IP range with address: {}...",
          address);

      List<Specific> specificCollection = getConfiguration().getSpecificCollection();
      for (Specific specific : specificCollection) {
        String ipAddr = specific.getContent();

        if (ipAddr.equals(InetAddressUtils.str(address))) {

          String foreignSource = specific.getForeignSource();
          LOG.debug(
              "Matched foreign source {} matching address: {} against specific {}.",
              foreignSource,
              address,
              ipAddr);
          return foreignSource;
        }
      }

      final byte[] laddr = address.getAddress();

      List<IncludeRange> includeRangeCollection = getConfiguration().getIncludeRangeCollection();
      for (IncludeRange range : includeRangeCollection) {

        if (InetAddressUtils.isInetAddressInRange(laddr, range.getBegin(), range.getEnd())) {

          String foreignSource = range.getForeignSource();
          LOG.debug(
              "Found foreign source {} with address {} in the range begin: {} and end: {}.",
              foreignSource,
              address,
              range.getBegin(),
              range.getEnd());
          return foreignSource;
        }
      }

      List<IncludeUrl> includeUrlCollection = getConfiguration().getIncludeUrlCollection();
      for (IncludeUrl includeUrl : includeUrlCollection) {
        String ipAddr = includeUrl.getContent();
        if (ipAddr.equals(InetAddressUtils.str(address))) {

          String foreignSource = includeUrl.getForeignSource();
          LOG.debug(
              "Matched foreign source {} matching address: {} in specified URL.",
              foreignSource,
              address);
          return foreignSource;
        }
      }

      return getConfiguration().getForeignSource();
    } finally {
      getReadLock().unlock();
    }
  }
 private InetAddress getIpForNode(final OnmsNode node) {
   LogUtils.debugf(
       this,
       "getIpForNode: node: %s Foreign Source: %s",
       node.getNodeId(),
       node.getForeignSource());
   final OnmsIpInterface primaryInterface = node.getPrimaryInterface();
   InetAddress ipaddr = InetAddressUtils.getLocalHostAddress();
   if (primaryInterface == null) {
     log().debug("getIpForNode: found null SNMP Primary Interface, getting interfaces");
     final Set<OnmsIpInterface> ipInterfaces = node.getIpInterfaces();
     for (final OnmsIpInterface onmsIpInterface : ipInterfaces) {
       log().debug("getIpForNode: trying Interface with id: " + onmsIpInterface.getId());
       if (InetAddressUtils.str(onmsIpInterface.getIpAddress()) != null)
         ipaddr = onmsIpInterface.getIpAddress();
       else
         log()
             .debug(
                 "getIpForNode: found null ip address on Interface with id: "
                     + onmsIpInterface.getId());
     }
   } else {
     log().debug("getIpForNode: found SNMP Primary Interface");
     if (InetAddressUtils.str(primaryInterface.getIpAddress()) != null)
       ipaddr = primaryInterface.getIpAddress();
     else log().debug("getIpForNode: found null ip address on Primary Interface");
   }
   return ipaddr;
 }
  /** {@inheritDoc} */
  public boolean isInterfaceInDB(Connection dbConn, InetAddress ifAddress) throws SQLException {
    boolean result = false;

    if (log().isDebugEnabled()) {
      log()
          .debug(
              "isInterfaceInDB: attempting to lookup interface "
                  + InetAddressUtils.str(ifAddress)
                  + " in the database.");
    }

    // Set connection as read-only
    //
    // dbConn.setReadOnly(true);

    ResultSet rs = null;
    final DBUtils d = new DBUtils(getClass());

    try {
      PreparedStatement s = dbConn.prepareStatement(RETRIEVE_IPADDR_SQL);
      d.watch(s);
      s.setString(1, InetAddressUtils.str(ifAddress));

      rs = s.executeQuery();
      d.watch(rs);
      result = rs.next();
    } finally {
      d.cleanUp();
    }

    return result;
  }
Exemple #5
0
  /**
   * Creates a new IPAddressRange object that can be used to encapsulate a contiguous range of IP
   * Addresses. Once created the object can be used to get either an Iterator or Enumeration object
   * to cycle through the list of address encapsulated by this object.
   *
   * <p>It is important to note that if the address for start is greater than end, the values will
   * be swapped so that the iteration is always from the lowest address to the highest address.
   *
   * @param start The starting address.
   * @param end The ending address.
   */
  IPAddrRange(InetAddress start, InetAddress end) {
    byte[] from = start.getAddress();
    byte[] to = end.getAddress();

    if (new ByteArrayComparator().compare(from, to) > 0) {
      LOG.warn(
          "The beginning of the address range is greater than the end of the address range ({} - {}), swapping values to create a valid IP address range",
          InetAddressUtils.str(start),
          InetAddressUtils.str(end));
      m_end = from;
      m_begin = to;
    } else {
      m_begin = from;
      m_end = to;
    }
  }
Exemple #6
0
  /**
   * {@inheritDoc}
   *
   * <p>Responsible for performing all necessary initialization for the specified interface in
   * preparation for data collection.
   */
  @Override
  public void initialize(CollectionAgent agent, Map<String, Object> parameters) {
    InetAddress ipAddr = agent.getAddress();
    int nodeID = agent.getNodeId();

    // Retrieve the name of the JMX data collector
    String collectionName = ParameterMap.getKeyedString(parameters, "collection", serviceName);

    final String hostAddress = InetAddressUtils.str(ipAddr);
    LogUtils.debugf(
        this, "initialize: InetAddress=%s, collectionName=%s", hostAddress, collectionName);

    JMXNodeInfo nodeInfo = new JMXNodeInfo(nodeID);
    LogUtils.debugf(this, "nodeInfo: %s %d %s", hostAddress, nodeID, agent);

    /*
     * Retrieve list of MBean objects to be collected from the
     * remote agent which are to be stored in the node-level RRD file.
     * These objects pertain to the node itself not any individual
     * interfaces.
     */
    Map<String, List<Attrib>> attrMap =
        JMXDataCollectionConfigFactory.getInstance()
            .getAttributeMap(collectionName, serviceName, hostAddress);
    nodeInfo.setAttributeMap(attrMap);

    Map<String, JMXDataSource> dsList = buildDataSourceList(collectionName, attrMap);
    nodeInfo.setDsMap(dsList);
    nodeInfo.setMBeans(JMXDataCollectionConfigFactory.getInstance().getMBeanInfo(collectionName));

    // Add the JMXNodeInfo object as an attribute of the interface
    agent.setAttribute(NODE_INFO_KEY, nodeInfo);
    agent.setAttribute("collectionName", collectionName);
  }
Exemple #7
0
  /**
   * Method that updates info in List nodes and also save info into database. This method is called
   * by SnmpCollection after all stuff is done
   *
   * @param snmpcoll
   */
  @Transactional
  public void updateNodeSnmpCollection(final SnmpCollection snmpcoll) {
    LogUtils.debugf(
        this, "Updating SNMP collection for %s", InetAddressUtils.str(snmpcoll.getTarget()));
    LinkableNode node = removeNode(snmpcoll.getTarget());
    if (node == null) {
      LogUtils.errorf(
          this, "No node found for SNMP collection: %s unscheduling!", snmpcoll.getInfo());
      m_scheduler.unschedule(snmpcoll);
      return;
    }

    try {
      node = m_queryMgr.storeSnmpCollection(node, snmpcoll);
    } catch (SQLException e) {
      LogUtils.errorf(
          this,
          e,
          "Failed to save on db snmpcollection/package: %s/%s",
          snmpcoll.getPackageName(),
          snmpcoll.getInfo());
      return;
    }
    if (node != null) {
      synchronized (m_nodes) {
        m_nodes.add(node);
      }
    }
  }
  public DbIfServiceEntry[] getServices(Connection db) throws SQLException {
    PreparedStatement stmt = null;
    ResultSet rset = null;
    final DBUtils d = new DBUtils(getClass());
    List<DbIfServiceEntry> l;

    try {
      stmt = db.prepareStatement(SQL_LOAD_IFSVC_LIST);
      d.watch(stmt);
      stmt.setLong(1, m_nodeId);
      stmt.setString(2, InetAddressUtils.str(m_ipAddr));

      rset = stmt.executeQuery();
      d.watch(rset);
      l = new ArrayList<DbIfServiceEntry>();

      while (rset.next()) {
        int sid = rset.getInt(1);
        DbIfServiceEntry entry = DbIfServiceEntry.get(db, m_nodeId, m_ipAddr, sid);
        if (entry != null) {
          l.add(entry);
        }
      }
    } finally {
      d.cleanUp();
    }

    DbIfServiceEntry[] entries = new DbIfServiceEntry[l.size()];
    return l.toArray(entries);
  }
 /** String representing snmp-config.xml */
 public String getSnmpConfig() throws IOException {
   return ConfigurationTestUtils.getConfigForResourceWithReplacements(
       this,
       "/org/opennms/netmgt/mock/snmp-config.xml",
       new String[] {"\\$\\{myVersion\\}", myVersion()},
       new String[] {"\\$\\{myLocalHost\\}", InetAddressUtils.str(myLocalHost())});
 }
 /**
  * getIpAddrToInterfaceMap
  *
  * @param imported a {@link org.opennms.netmgt.model.OnmsNode} object.
  * @return a {@link java.util.Map} object.
  */
 protected Map<String, OnmsIpInterface> getIpAddrToInterfaceMap(OnmsNode imported) {
   Map<String, OnmsIpInterface> ipAddrToIface = new HashMap<String, OnmsIpInterface>();
   for (final OnmsIpInterface iface : imported.getIpInterfaces()) {
     final String ipAddress = InetAddressUtils.str(iface.getIpAddress());
     ipAddrToIface.put(ipAddress, iface);
   }
   return ipAddrToIface;
 }
  private OnmsResource createResource(final OnmsIpInterface ipInterface) {
    final String intf = InetAddressUtils.str(ipInterface.getIpAddress());
    final String label = intf;
    final String resource = intf;

    final Set<OnmsAttribute> set = new LazySet<OnmsAttribute>(new AttributeLoader(intf));
    final OnmsResource r = new OnmsResource(resource, label, this, set);
    r.setEntity(ipInterface);
    return r;
  }
  /**
   * getInterfaceDbNodeId
   *
   * @param dbConn a {@link java.sql.Connection} object.
   * @param ifAddress a {@link java.net.InetAddress} object.
   * @param ifIndex a int.
   * @return a int.
   * @throws java.sql.SQLException if any.
   */
  public int getInterfaceDbNodeId(Connection dbConn, InetAddress ifAddress, int ifIndex)
      throws SQLException {
    if (log().isDebugEnabled()) {
      log()
          .debug(
              "getInterfaceDbNodeId: attempting to lookup interface "
                  + InetAddressUtils.str(ifAddress)
                  + "/ifindex: "
                  + ifIndex
                  + " in the database.");
    }

    // Set connection as read-only
    // dbConn.setReadOnly(true);

    StringBuffer qs = new StringBuffer(RETRIEVE_IPADDR_NODEID_SQL);
    if (ifIndex != -1) {
      qs.append(" AND ifindex=?");
    }

    int nodeid = -1;

    final DBUtils d = new DBUtils(getClass());
    try {
      PreparedStatement s = dbConn.prepareStatement(qs.toString());
      d.watch(s);
      s.setString(1, InetAddressUtils.str(ifAddress));

      if (ifIndex != -1) {
        s.setInt(2, ifIndex);
      }

      ResultSet rs = s.executeQuery();
      d.watch(rs);
      if (rs.next()) {
        nodeid = rs.getInt(1);
      }
    } finally {
      d.cleanUp();
    }

    return nodeid;
  }
  /**
   * Tests getting the correct SNMP Peer after a configureSNMP event and merge to the running
   * config.
   *
   * @throws UnknownHostException
   */
  public void testSnmpEventInfoClassWithSpecific() throws UnknownHostException {
    final String addr = "192.168.0.5";
    EventBuilder bldr = createConfigureSnmpEventBuilder(addr, null);
    addCommunityStringToEvent(bldr, "abc");
    SnmpEventInfo info = new SnmpEventInfo(bldr.getEvent());

    SnmpPeerFactory.getInstance().define(info);

    SnmpAgentConfig agent =
        SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr(addr));
    assertEquals(InetAddressUtils.str(agent.getAddress()), addr);
    assertEquals("abc", agent.getReadCommunity());
  }
  /**
   * This method is used to determine if the named interface is included in the passed package's URL
   * includes. If the interface is found in any of the URL files, then a value of true is returned,
   * else a false value is returned.
   *
   * <pre>
   *
   *  The file URL is read and each entry in this file checked. Each line
   *   in the URL file can be one of -
   *   &lt;IP&gt;&lt;space&gt;#&lt;comments&gt;
   *   or
   *   &lt;IP&gt;
   *   or
   *   #&lt;comments&gt;
   *
   *   Lines starting with a '#' are ignored and so are characters after
   *   a '&lt;space&gt;#' in a line.
   *
   * </pre>
   *
   * @param addr The interface to test against the package's URL
   * @param url The URL file to read
   * @return True if the interface is included in the URL, false otherwise.
   */
  private boolean isInterfaceInUrl(final InetAddress addr, final String url) {
    try {
      getReadLock().lock();

      // get list of IPs in this URL
      final List<String> iplist = m_urlIPMap.get(url);
      if (iplist != null && iplist.size() > 0) {
        return iplist.contains(InetAddressUtils.str(addr));
      }
    } finally {
      getReadLock().unlock();
    }
    return false;
  }
Exemple #15
0
  /** onInit */
  public synchronized void onInit() {
    Assert.state(m_trapdIpMgr != null, "trapdIpMgr must be set");
    Assert.state(m_eventReader != null, "eventReader must be set");
    Assert.state(m_backlogQ != null, "backlogQ must be set");
    Assert.state(m_snmpTrapAddress != null, "snmpTrapAddress must be set");
    Assert.state(m_snmpTrapPort != null, "snmpTrapPort must be set");
    Assert.state(m_processor != null, "processor must be set");

    try {
      m_trapdIpMgr.dataSourceSync();
    } catch (final SQLException e) {
      LogUtils.errorf(this, e, "init: Failed to load known IP address list");
      throw new UndeclaredThrowableException(e);
    }

    try {
      InetAddress address = getInetAddress();
      LogUtils.infof(
          this,
          "Listening on %s:%d",
          address == null ? "[all interfaces]" : InetAddressUtils.str(address),
          getSnmpTrapPort());
      SnmpUtils.registerForTraps(this, this, address, getSnmpTrapPort(), getSnmpV3Users());
      m_registeredForTraps = true;

      LogUtils.debugf(this, "init: Creating the trap session");
    } catch (final IOException e) {
      if (e instanceof java.net.BindException) {
        managerLog()
            .error(
                "init: Failed to listen on SNMP trap port, perhaps something else is already listening?",
                e);
        LogUtils.errorf(
            this,
            e,
            "init: Failed to listen on SNMP trap port, perhaps something else is already listening?");
      } else {
        LogUtils.errorf(this, e, "init: Failed to initialize SNMP trap socket");
      }
      throw new UndeclaredThrowableException(e);
    }

    try {
      m_eventReader.open();
    } catch (final Throwable e) {
      LogUtils.errorf(this, e, "init: Failed to open event reader");
      throw new UndeclaredThrowableException(e);
    }
  }
 private void resolveIpHostname(final OnmsIpInterface ipIf) {
   final String ipAddress = InetAddressUtils.str(ipIf.getIpAddress());
   ipIf.setIpHostName(ipAddress);
   //
   //     DON'T DO THIS SINCE DNS DOESN'T RELIABLY AVOID HANGING
   //
   //    	log().info("Resolving Hostname for "+ipIf.getIpAddress());
   //		try {
   //			InetAddress addr = InetAddressUtils.addr(ipIf.getIpAddress());
   //			ipIf.setIpHostName(addr.getHostName());
   //		} catch (Throwable e) {
   //			if (ipIf.getIpHostName() == null)
   //				ipIf.setIpHostName(ipIf.getIpAddress());
   //		}
 }
  /**
   * Creates a string that displays the internal contents of the record. This is mainly just used
   * for debug output since the format is ad-hoc.
   *
   * @return a {@link java.lang.String} object.
   */
  public String toString() {
    String sep = System.getProperty("line.separator");
    StringBuffer buf = new StringBuffer();

    buf.append("from database      = ").append(m_fromDb).append(sep);
    buf.append("node identifier    = ").append(m_nodeId).append(sep);
    buf.append("IP Address         = ").append(InetAddressUtils.str(m_ipAddr)).append(sep);
    buf.append("interface index    = ").append(m_ifIndex).append(sep);
    buf.append("last poll time     = ").append(m_lastPoll).append(sep);
    buf.append("hostname           = ").append(m_hostname).append(sep);
    buf.append("status             = ").append(m_status).append(sep);
    buf.append("isManaged          = ").append(m_managedState).append(sep);
    buf.append("isSnmpPrimary      = ").append(m_primaryState).append(sep);
    buf.append("field change map   = 0x").append(Integer.toHexString(m_changed)).append(sep);
    return buf.toString();
  }
Exemple #18
0
  Service(OnmsMonitoredService monSvc) {
    setId(monSvc.getId());
    setNodeId(monSvc.getNodeId());

    setIpAddress(InetAddressUtils.str(monSvc.getIpAddress()));
    setServiceId(monSvc.getServiceId());
    setServiceName(monSvc.getServiceName());
    if (monSvc.getLastGood() != null) {
      setLastGood(monSvc.getLastGood().toString());
    }
    if (monSvc.getLastFail() != null) {
      setLastFail(monSvc.getLastFail().toString());
    }
    setNotify(monSvc.getNotify());
    if (monSvc.getStatus() != null) {
      setStatus(monSvc.getStatus().charAt(0));
    }
  }
  /**
   * This test should remove the specific 192.168.0.5 from the first definition and replace it with
   * a range 192.168.0.5 - 192.168.0.7.
   *
   * @throws UnknownHostException
   */
  public void testSnmpEventInfoClassWithRangeReplacingSpecific() throws UnknownHostException {
    final String addr1 = "192.168.0.5";
    final String addr2 = "192.168.0.7";

    SnmpAgentConfig agent =
        SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr(addr1));
    assertEquals(SnmpAgentConfig.VERSION2C, agent.getVersion());

    EventBuilder bldr = createConfigureSnmpEventBuilder(addr1, addr2);
    SnmpEventInfo info = new SnmpEventInfo(bldr.getEvent());
    info.setVersion("v2c");

    SnmpPeerFactory.getInstance().define(info);

    agent = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr(addr1));
    assertEquals(InetAddressUtils.str(agent.getAddress()), addr1);
    assertEquals(SnmpAgentConfig.VERSION2C, agent.getVersion());
    assertEquals(m_startingDefCount, SnmpPeerFactory.getSnmpConfig().getDefinitionCount());
  }
  /**
   * Tests getting the correct SNMP Peer after merging a new range that super sets a current range.
   *
   * @throws UnknownHostException
   */
  public void testSnmpEventInfoClassWithRangeSuperSettingDefRanges() throws UnknownHostException {
    final String addr1 = "192.168.99.1";
    final String addr2 = "192.168.108.254";

    SnmpAgentConfig agent =
        SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr(addr1));
    assertEquals(SnmpAgentConfig.VERSION1, agent.getVersion());

    EventBuilder bldr = createConfigureSnmpEventBuilder(addr1, addr2);
    SnmpEventInfo info = new SnmpEventInfo(bldr.getEvent());
    info.setCommunityString("opennmsrules");

    SnmpPeerFactory.getInstance().define(info);

    agent = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr(addr1));
    assertEquals(InetAddressUtils.str(agent.getAddress()), addr1);
    assertEquals(SnmpAgentConfig.VERSION1, agent.getVersion());
    assertEquals(m_startingDefCount, SnmpPeerFactory.getSnmpConfig().getDefinitionCount());
  }
  /** {@inheritDoc} */
  public List<OnmsResource> getResourcesForNode(final int nodeId) {
    final LinkedList<OnmsResource> resources = new LinkedList<OnmsResource>();

    final OnmsNode node = m_nodeDao.get(nodeId);
    if (node == null) {
      throw new ObjectRetrievalFailureException(
          OnmsNode.class, nodeId, "Could not find node for node Id " + nodeId, null);
    }

    for (final OnmsIpInterface i : node.getIpInterfaces()) {
      String ipAddr = InetAddressUtils.str(i.getIpAddress());

      final File iface = getInterfaceDirectory(ipAddr, false);

      if (iface.isDirectory()) {
        resources.add(createResource(i));
      }
    }

    return resources;
  }
  /** {@inheritDoc} */
  @Override
  public List<OnmsResource> getResourcesForNode(int nodeId) {
    LinkedList<OnmsResource> resources = new LinkedList<OnmsResource>();

    Collection<LocationMonitorIpInterface> statuses =
        m_locationMonitorDao.findStatusChangesForNodeForUniqueMonitorAndInterface(nodeId);

    for (LocationMonitorIpInterface status : statuses) {
      String definitionName = status.getLocationMonitor().getDefinitionName();
      int id = status.getLocationMonitor().getId();
      final OnmsIpInterface ipInterface = status.getIpInterface();
      String ipAddr = InetAddressUtils.str(ipInterface.getIpAddress());

      File iface = getInterfaceDirectory(id, ipAddr);

      if (iface.isDirectory()) {
        resources.add(createResource(definitionName, id, ipAddr));
      }
    }

    return OnmsResource.sortIntoResourceList(resources);
  }
  private void updateSnmpDataForInterface(OnmsIpInterface ipIf) {
    if (m_collector == null || !m_collector.hasIpAddrTable() || !m_collector.hasIfTable()) {
      return;
    }

    final InetAddress inetAddr = ipIf.getIpAddress();
    final String ipAddr = InetAddressUtils.str(inetAddr);

    LOG.debug("Creating SNMP info for interface {}", ipAddr);

    int ifIndex = m_collector.getIfIndex(inetAddr);
    if (ifIndex == -1) {
      return;
    }

    // first look to see if an snmpIf was created already
    OnmsSnmpInterface snmpIf = m_node.getSnmpInterfaceWithIfIndex(ifIndex);

    if (snmpIf == null) {
      // if not then create one
      snmpIf = new OnmsSnmpInterface(m_node, ifIndex);
      snmpIf.setIfAlias(m_collector.getIfAlias(ifIndex));
      snmpIf.setIfName(m_collector.getIfName(ifIndex));
      snmpIf.setIfType(getIfType(ifIndex));
      snmpIf.setNetMask(getNetMask(ifIndex));
      snmpIf.setIfAdminStatus(getAdminStatus(ifIndex));
      snmpIf.setIfDescr(m_collector.getIfDescr(ifIndex));
      snmpIf.setIfSpeed(m_collector.getInterfaceSpeed(ifIndex));
      snmpIf.setPhysAddr(m_collector.getPhysAddr(ifIndex));
    }

    snmpIf.setCollectionEnabled(true);

    ipIf.setSnmpInterface(snmpIf);

    // FIXME: Improve OpenNMS to provide these values
    // ifOperStatus

  }
  /**
   * {@inheritDoc}
   *
   * <p>Poll the specified address for service availability.
   *
   * <p>During the poll an attempt is made to call the specified external script or program. If the
   * connection request is successful, the banner line returned as standard output by the script or
   * program is parsed for a partial match with the banner string specified in the poller
   * configuration. Provided that the script's response is valid we set the service status to
   * SERVICE_AVAILABLE and return.
   *
   * <p>The timeout is handled by ExecRunner and is also passed as a parameter to the script or
   * program being called.
   */
  public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    NetworkInterface<InetAddress> iface = svc.getNetInterface();

    //
    // Process parameters
    //
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    //
    // Get interface address from NetworkInterface
    //
    if (iface.getType() != NetworkInterface.TYPE_INET)
      throw new NetworkInterfaceNotSupportedException(
          "Unsupported interface type, only TYPE_INET currently supported");

    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);

    String hoption = ParameterMap.getKeyedString(parameters, "hoption", "--hostname");
    String toption = ParameterMap.getKeyedString(parameters, "toption", "--timeout");
    //
    // convert timeout to seconds for ExecRunner
    //
    String args = ParameterMap.getKeyedString(parameters, "args", null);

    // Script
    //
    String script = ParameterMap.getKeyedString(parameters, "script", null);
    if (script == null) {
      throw new RuntimeException(
          "GpMonitor: required parameter 'script' is not present in supplied properties.");
    }

    // BannerMatch
    //
    String strBannerMatch = (String) parameters.get("banner");

    // Script standard output
    //
    String scriptoutput = "";

    // Script error output
    //
    String scripterror = "";

    // Get the address instance.
    //
    InetAddress ipv4Addr = (InetAddress) iface.getAddress();

    final String hostAddress = InetAddressUtils.str(ipv4Addr);
    if (log.isDebugEnabled())
      log.debug(
          "poll: address = "
              + hostAddress
              + ", script = "
              + script
              + ", arguments = "
              + args
              + ", "
              + tracker);

    // Give it a whirl
    //
    PollStatus serviceStatus = PollStatus.unavailable();

    for (tracker.reset();
        tracker.shouldRetry() && !serviceStatus.isAvailable();
        tracker.nextAttempt()) {
      try {
        tracker.startAttempt();

        int exitStatus = 100;

        // Some scripts, such as Nagios check scripts, look for -H and -t versus --hostname and
        // --timeout. If the optional parameter option-type is set to short, then the former
        // will be used.

        int timeoutInSeconds = (int) tracker.getTimeoutInSeconds();

        ExecRunner er = new ExecRunner();
        er.setMaxRunTimeSecs(timeoutInSeconds);
        if (args == null)
          exitStatus =
              er.exec(
                  script
                      + " "
                      + hoption
                      + " "
                      + hostAddress
                      + " "
                      + toption
                      + " "
                      + timeoutInSeconds);
        else
          exitStatus =
              er.exec(
                  script
                      + " "
                      + hoption
                      + " "
                      + hostAddress
                      + " "
                      + toption
                      + " "
                      + timeoutInSeconds
                      + " "
                      + args);

        double responseTime = tracker.elapsedTimeInMillis();

        if (exitStatus != 0) {
          scriptoutput = er.getOutString();
          serviceStatus =
              logDown(
                  Level.DEBUG,
                  script
                      + " failed with exit code "
                      + exitStatus
                      + ". Standard out: "
                      + scriptoutput);
        }
        if (er.isMaxRunTimeExceeded()) {

          serviceStatus = logDown(Level.DEBUG, script + " failed. Timeout exceeded");

        } else {
          if (exitStatus == 0) {
            scriptoutput = er.getOutString();
            scripterror = er.getErrString();
            if (!scriptoutput.equals("")) log.debug(script + " output  = " + scriptoutput);
            else log.debug(script + " returned no output");
            if (!scripterror.equals("")) log.debug(script + " error = " + scripterror);
            if (strBannerMatch == null || strBannerMatch.equals("*")) {

              serviceStatus = PollStatus.available(responseTime);

            } else {
              if (scriptoutput.indexOf(strBannerMatch) > -1) {
                serviceStatus = PollStatus.available(responseTime);
              } else {
                serviceStatus =
                    PollStatus.unavailable(
                        script
                            + "banner not contained in output banner='"
                            + strBannerMatch
                            + "' output='"
                            + scriptoutput
                            + "'");
              }
            }
          }
        }

      } catch (ArrayIndexOutOfBoundsException e) {

        serviceStatus = logDown(Level.DEBUG, script + " ArrayIndexOutOfBoundsException", e);

      } catch (IOException e) {

        serviceStatus =
            logDown(
                Level.DEBUG, "IOException occurred. Check for proper operation of " + script, e);

      } catch (Throwable e) {

        serviceStatus = logDown(Level.DEBUG, script + "Exception occurred", e);
      }
    }

    //
    // return the status of the service
    //
    log.debug("poll: GP - serviceStatus= " + serviceStatus + "  " + hostAddress);
    return serviceStatus;
  }
  @Override
  public OnmsAccessPointCollection call() throws IOException {
    OnmsAccessPointCollection apsUp = new OnmsAccessPointCollection();
    InetAddress ipaddr = m_iface.getIpAddress();

    // Retrieve this interface's SNMP peer object
    SnmpAgentConfig agentConfig = getAgentConfig(ipaddr);
    final String hostAddress = InetAddressUtils.str(ipaddr);
    LOG.debug("poll: setting SNMP peer attribute for interface {}", hostAddress);

    // Get configuration parameters
    String oid = ParameterMap.getKeyedString(m_parameters, "oid", null);
    if (oid == null) {
      throw new IllegalStateException("oid parameter is not set.");
    }
    String operator = ParameterMap.getKeyedString(m_parameters, "operator", null);
    String operand = ParameterMap.getKeyedString(m_parameters, "operand", null);
    String matchstr = ParameterMap.getKeyedString(m_parameters, "match", "true");

    LOG.debug("InstanceStrategy.poll: SnmpAgentConfig address= {}", agentConfig);

    // Establish SNMP session with interface
    try {
      SnmpObjId snmpObjectId = SnmpObjId.get(oid);

      Map<SnmpInstId, SnmpValue> map =
          SnmpUtils.getOidValues(agentConfig, "AccessPointMonitor::InstanceStrategy", snmpObjectId);

      if (map.size() <= 0) {
        throw new IOException("No entries found in table (possible timeout).");
      }

      for (Map.Entry<SnmpInstId, SnmpValue> entry : map.entrySet()) {
        boolean isUp = false;
        SnmpInstId instance = entry.getKey();
        SnmpValue value = entry.getValue();

        // Check the value against the configured criteria
        if (meetsCriteria(value, operator, operand)) {
          if ("true".equals(matchstr)) {
            isUp = true;
          }
        } else if ("false".equals(matchstr)) {
          isUp = true;
        }

        // If the criteria is met, find the AP and add it to the list
        // of online APs
        if (isUp) {
          String physAddr = getPhysAddrFromInstance(instance);
          LOG.debug(
              "AP at instance '{}' with MAC '{}' is considered to be ONLINE on controller '{}'",
              instance,
              physAddr,
              m_iface.getIpAddress());
          OnmsAccessPoint ap = m_accessPointDao.get(physAddr);
          if (ap != null) {
            if (ap.getPollingPackage().compareToIgnoreCase(getPackage().getName()) == 0) {
              // Save the controller's IP address
              ap.setControllerIpAddress(ipaddr);
              apsUp.add(ap);
            } else {
              LOG.info("AP with MAC '{}' is in a different package.", physAddr);
            }
          } else {
            LOG.info("No matching AP in database for instance '{}'.", instance);
          }
        }
      }
    } catch (NumberFormatException e) {
      LOG.error("Number operator used on a non-number ", e);
    } catch (IllegalArgumentException e) {
      LOG.error("Invalid SNMP Criteria ", e);
    } catch (InterruptedException e) {
      LOG.error("Interrupted while polling {}", hostAddress, e);
    }

    return apsUp;
  }
  /** {@inheritDoc} */
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws IOException {

    ThreadCategory.setPrefix(MapsConstants.LOG4J_CATEGORY);
    log = ThreadCategory.getInstance(this.getClass());
    String action = request.getParameter("action");
    String elems = request.getParameter("elems");
    log.debug("Adding Nodes action:" + action + ", elems=" + elems);

    BufferedWriter bw =
        new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
    try {
      Integer[] nodeids = null;

      boolean actionfound = false;

      if (action.equals(MapsConstants.ADDNODES_ACTION)) {
        log.debug("Adding nodes by id: " + elems);
        actionfound = true;
        String[] snodeids = elems.split(",");
        nodeids = new Integer[snodeids.length];
        for (int i = 0; i < snodeids.length; i++) {
          nodeids[i] = new Integer(snodeids[i]);
        }
      }

      if (action.equals(MapsConstants.ADDNODES_BY_CATEGORY_ACTION)) {
        log.debug("Adding nodes by category: " + elems);
        actionfound = true;
        String categoryName = elems;
        CategoryFactory.init();
        CatFactory cf = CategoryFactory.getInstance();
        cf.getReadLock().lock();
        try {
          final String rule = cf.getEffectiveRule(categoryName);
          final List<InetAddress> nodeIPs = FilterDaoFactory.getInstance().getIPAddressList(rule);
          LogUtils.debugf(this, "ips found: %s", nodeIPs.toString());
          nodeids = new Integer[nodeIPs.size()];
          for (int i = 0; i < nodeIPs.size(); i++) {
            final InetAddress nodeIp = nodeIPs.get(i);
            final List<Integer> ids =
                NetworkElementFactory.getInstance(getServletContext())
                    .getNodeIdsWithIpLike(InetAddressUtils.str(nodeIp));
            LogUtils.debugf(this, "Ids by ipaddress %s: %s", nodeIp, ids.toString());
            nodeids[i] = ids.get(0);
          }
        } finally {
          cf.getReadLock().unlock();
        }
      }

      if (action.equals(MapsConstants.ADDNODES_BY_LABEL_ACTION)) {
        log.debug("Adding nodes by label: " + elems);
        actionfound = true;
        List<OnmsNode> nodes = NetworkElementFactory.getInstance(getServletContext()).getAllNodes();
        nodeids = new Integer[nodes.size()];
        for (int i = 0; i < nodes.size(); i++) {
          nodeids[i] = nodes.get(i).getId();
        }
      }

      if (action.equals(MapsConstants.ADDRANGE_ACTION)) {
        log.debug("Adding nodes by range: " + elems);
        actionfound = true;
        nodeids =
            (Integer[])
                NetworkElementFactory.getInstance(getServletContext())
                    .getNodeIdsWithIpLike(elems)
                    .toArray(new Integer[0]);
      }

      if (action.equals(MapsConstants.ADDNODES_NEIG_ACTION)) {
        log.debug("Adding nodes neighbor of:" + elems);
        actionfound = true;
        nodeids =
            (Integer[])
                NetworkElementFactory.getInstance(getServletContext())
                    .getLinkedNodeIdOnNode(WebSecurityUtils.safeParseInt(elems))
                    .toArray(new Integer[0]);
      }

      if (action.equals(MapsConstants.ADDNODES_WITH_NEIG_ACTION)) {
        log.debug("Adding nodes with neighbor of:" + elems);
        actionfound = true;
        Set<Integer> linkednodeids =
            NetworkElementFactory.getInstance(getServletContext())
                .getLinkedNodeIdOnNode(WebSecurityUtils.safeParseInt(elems));
        linkednodeids.add(new Integer(elems));
        nodeids = linkednodeids.toArray(new Integer[linkednodeids.size()]);
      }

      VMap map = manager.openMap();
      if (log.isDebugEnabled()) log.debug("Got map from manager " + map);

      List<VElement> velems = new ArrayList<VElement>();
      // response for addElement
      if (actionfound) {
        log.debug("Before Checking map contains elems");

        for (int i = 0; i < nodeids.length; i++) {
          int elemId = nodeids[i].intValue();
          if (map.containsElement(elemId, MapsConstants.NODE_TYPE)) {
            log.debug(
                "Action: "
                    + action
                    + " . Map Contains Element: "
                    + elemId
                    + MapsConstants.NODE_TYPE);
            continue;
          }

          velems.add(manager.newElement(map.getId(), elemId, MapsConstants.NODE_TYPE));
        } // end for

        // get links and add elements to map
        map = manager.addElements(map, velems);
        log.debug("After getting/adding links");

        bw.write(ResponseAssembler.getAddElementResponse(null, velems, map.getLinks()));
      }
    } catch (Throwable e) {
      log.error("Error while adding nodes for action: " + action, e);
      bw.write(ResponseAssembler.getMapErrorResponse(action));
    } finally {
      bw.close();
    }

    return null;
  }
 /**
  * getIpAddr
  *
  * @return a {@link String} object.
  */
 public String getIpAddr() {
   return InetAddressUtils.str(m_addr);
 }
Exemple #28
0
 /** {@inheritDoc} */
 public void connect(InetAddress address, int port, int timeout) throws IOException, Exception {
   m_address = InetAddressUtils.str(address);
 }
Exemple #29
0
  /** {@inheritDoc} */
  @Override
  public PollStatus poll(MonitoredService svc, Map<String, Object> map) {
    PollStatus pollStatus = PollStatus.unresponsive();
    DefaultHttpClient httpClient = new DefaultHttpClient();

    try {
      final String hostAddress = InetAddressUtils.str(svc.getAddress());

      URIBuilder ub = new URIBuilder();
      ub.setScheme(ParameterMap.getKeyedString(map, "scheme", DEFAULT_SCHEME));
      ub.setHost(hostAddress);
      ub.setPort(ParameterMap.getKeyedInteger(map, "port", DEFAULT_PORT));
      ub.setPath(ParameterMap.getKeyedString(map, "path", DEFAULT_PATH));
      HttpGet getMethod = new HttpGet(ub.build());
      httpClient
          .getParams()
          .setIntParameter(
              CoreConnectionPNames.CONNECTION_TIMEOUT,
              ParameterMap.getKeyedInteger(map, "timeout", DEFAULT_TIMEOUT));
      httpClient
          .getParams()
          .setIntParameter(
              CoreConnectionPNames.SO_TIMEOUT,
              ParameterMap.getKeyedInteger(map, "timeout", DEFAULT_TIMEOUT));
      httpClient
          .getParams()
          .setParameter(
              CoreProtocolPNames.USER_AGENT,
              ParameterMap.getKeyedString(map, "user-agent", DEFAULT_USER_AGENT));

      // Set the virtual host to the 'virtual-host' parameter or the host address if 'virtual-host'
      // is not present
      getMethod
          .getParams()
          .setParameter(
              ClientPNames.VIRTUAL_HOST,
              new HttpHost(
                  ParameterMap.getKeyedString(map, "virtual-host", hostAddress),
                  ParameterMap.getKeyedInteger(map, "port", DEFAULT_PORT)));

      if (ParameterMap.getKeyedBoolean(map, "http-1.0", false)) {
        httpClient
            .getParams()
            .setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
      }

      for (Object okey : map.keySet()) {
        String key = okey.toString();
        if (key.matches("header_[0-9]+$")) {
          String headerName = ParameterMap.getKeyedString(map, key, null);
          String headerValue = ParameterMap.getKeyedString(map, key + "_value", null);
          getMethod.setHeader(headerName, headerValue);
        }
      }

      if (ParameterMap.getKeyedBoolean(map, "auth-enabled", false)) {
        httpClient
            .getCredentialsProvider()
            .setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials(
                    ParameterMap.getKeyedString(map, "auth-user", DEFAULT_USER),
                    ParameterMap.getKeyedString(map, "auth-password", DEFAULT_PASSWORD)));
        if (ParameterMap.getKeyedBoolean(map, "auth-preemptive", true)) {
          /**
           * Add an HttpRequestInterceptor that will perform preemptive auth
           *
           * @see http://hc.apache.org/httpcomponents-client-4.0.1/tutorial/html/authentication.html
           */
          HttpRequestInterceptor preemptiveAuth =
              new HttpRequestInterceptor() {

                public void process(final HttpRequest request, final HttpContext context)
                    throws IOException {

                  AuthState authState =
                      (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                  CredentialsProvider credsProvider =
                      (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
                  HttpHost targetHost =
                      (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                  // If not auth scheme has been initialized yet
                  if (authState.getAuthScheme() == null) {
                    AuthScope authScope =
                        new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    // Obtain credentials matching the target host
                    Credentials creds = credsProvider.getCredentials(authScope);
                    // If found, generate BasicScheme preemptively
                    if (creds != null) {
                      authState.update(new BasicScheme(), creds);
                    }
                  }
                }
              };
          httpClient.addRequestInterceptor(preemptiveAuth, 0);
        }
      }

      log().debug("httpClient request with the following parameters: " + httpClient);
      log().debug("getMethod parameters: " + getMethod);
      HttpResponse response = httpClient.execute(getMethod);
      int statusCode = response.getStatusLine().getStatusCode();
      String statusText = response.getStatusLine().getReasonPhrase();
      String expectedText = ParameterMap.getKeyedString(map, "response-text", null);

      log().debug("returned results are:");

      if (!inRange(
          ParameterMap.getKeyedString(map, "response-range", DEFAULT_HTTP_STATUS_RANGE),
          statusCode)) {
        pollStatus = PollStatus.unavailable(statusText);
      } else {
        pollStatus = PollStatus.available();
      }

      if (expectedText != null) {
        String responseText = EntityUtils.toString(response.getEntity());
        if (expectedText.charAt(0) == '~') {
          if (!responseText.matches(expectedText.substring(1))) {
            pollStatus = PollStatus.unavailable("Regex Failed");
          } else pollStatus = PollStatus.available();
        } else {
          if (expectedText.equals(responseText)) pollStatus = PollStatus.available();
          else pollStatus = PollStatus.unavailable("Did not find expected Text");
        }
      }

    } catch (IOException e) {
      log().info(e.getMessage());
    } catch (URISyntaxException e) {
      log().info(e.getMessage());
    } finally {
      if (httpClient != null) {
        httpClient.getConnectionManager().shutdown();
      }
    }
    return pollStatus;
  }
  /** {@inheritDoc} */
  @Override
  protected boolean checkProtocol(Socket socket, ConnectionConfig config) throws IOException {
    boolean isAServer = false;

    m_queryString =
        "GET " + config.getKeyedString(PROPERTY_NAME_URL, DEFAULT_URL) + " HTTP/1.0\r\n\r\n";

    LOG.debug("Query: {}", m_queryString);

    try {
      BufferedReader lineRdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));

      socket.getOutputStream().write(m_queryString.getBytes());
      char[] cbuf = new char[1024];
      int chars = 0;
      StringBuffer response = new StringBuffer();
      try {
        while ((chars = lineRdr.read(cbuf, 0, 1024)) != -1) {
          String line = new String(cbuf, 0, chars);
          LOG.debug("Read: {} bytes: [{}] from socket.", line.length(), line);
          response.append(line);
        }
      } catch (java.net.SocketTimeoutException timeoutEx) {
        if (timeoutEx.bytesTransferred > 0) {
          String line = new String(cbuf, 0, timeoutEx.bytesTransferred);
          LOG.debug("Read: {} bytes: [{}] from socket @ timeout!", line.length(), line);
          response.append(line);
        }
      }
      if (response.toString() != null && response.toString().indexOf(m_responseString) > -1) {
        if (m_checkReturnCode) {
          int maxRetCode = config.getKeyedInteger(PROPERTY_NAME_MAX_RET_CODE, 399);
          if ((DEFAULT_URL.equals(config.getKeyedString(PROPERTY_NAME_URL, DEFAULT_URL)))
              || (config.getKeyedBoolean(PROPERTY_NAME_RETURN_CODE, true) == false)) {
            maxRetCode = 600;
          }
          StringTokenizer t = new StringTokenizer(response.toString());
          t.nextToken();
          int rVal = Integer.parseInt(t.nextToken());
          LOG.debug("{} : Request returned code: {}", getPluginName(), rVal);
          if (rVal >= 99 && rVal <= maxRetCode) isAServer = true;
        } else {
          isAServer = true;
        }
        if (isAServer) {
          isAServer = checkResponseBody(config, response.toString());
        }
      }
    } catch (SocketException e) {
      LOG.debug(
          "{}: a protocol error occurred talking to host {}",
          getPluginName(),
          InetAddressUtils.str(config.getInetAddress()),
          e);
      isAServer = false;
    } catch (NumberFormatException e) {
      LOG.debug(
          "{}: failed to parse response code from host {}",
          getPluginName(),
          InetAddressUtils.str(config.getInetAddress()),
          e);
      isAServer = false;
    }
    return isAServer;
  }