Exemplo n.º 1
0
 public int getSnmpMaxRepetitions(int current) {
   int maxRepetitions = ParameterMap.getKeyedInteger(m_parameters, "max-repetitions", -1);
   if (maxRepetitions == -1) {
     // in case someone is using an ancient config file
     maxRepetitions = ParameterMap.getKeyedInteger(m_parameters, "maxRepetitions", current);
   }
   return maxRepetitions;
 }
Exemplo n.º 2
0
  /**
   * {@inheritDoc}
   *
   * <p>Returns true if the protocol defined by this plugin is supported. If the protocol is not
   * supported then a false value is returned to the caller. The qualifier map passed to the method
   * is used by the plugin to return additional information by key-name. These key-value pairs can
   * be added to service events if needed.
   */
  public boolean isProtocolSupported(InetAddress address, Map<String, Object> qualifiers) {
    int retries = DEFAULT_RETRY;
    int timeout = DEFAULT_TIMEOUT;
    int port = -1;

    String banner = null;
    String match = null;

    if (qualifiers != null) {
      retries = ParameterMap.getKeyedInteger(qualifiers, "retry", DEFAULT_RETRY);
      timeout = ParameterMap.getKeyedInteger(qualifiers, "timeout", DEFAULT_TIMEOUT);
      port = ParameterMap.getKeyedInteger(qualifiers, "port", -1);
      banner = ParameterMap.getKeyedString(qualifiers, "banner", null);
      match = ParameterMap.getKeyedString(qualifiers, "match", null);
    }

    // verify the port
    //
    if (port == -1)
      throw new IllegalArgumentException("The port must be specified when doing TCP discovery");

    try {
      StringBuffer bannerResult = null;
      RE regex = null;
      if (match == null && (banner == null || banner.equals("*"))) {
        regex = null;
      } else if (match != null) {
        regex = new RE(match);
        bannerResult = new StringBuffer();
      } else if (banner != null) {
        regex = new RE(banner);
        bannerResult = new StringBuffer();
      }

      boolean result = isServer(address, port, retries, timeout, regex, bannerResult);
      if (result && qualifiers != null) {
        if (bannerResult != null && bannerResult.length() > 0)
          qualifiers.put("banner", bannerResult.toString());
      }

      return result;
    } catch (RESyntaxException e) {
      throw new java.lang.reflect.UndeclaredThrowableException(e);
    }
  }
Exemplo n.º 3
0
  /**
   * {@inheritDoc}
   *
   * <p>Returns true if the protocol defined by this plugin is supported. If the protocol is not
   * supported then a false value is returned to the caller. The qualifier map passed to the method
   * is used by the plugin to return additional information by key-name. These key-value pairs can
   * be added to service events if needed.
   */
  @Override
  public boolean isProtocolSupported(InetAddress address, Map<String, Object> qualifiers) {
    int retries = DEFAULT_RETRY;
    int timeout = DEFAULT_TIMEOUT;
    int port = DEFAULT_PORT;

    if (qualifiers != null) {
      retries = ParameterMap.getKeyedInteger(qualifiers, "retry", DEFAULT_RETRY);
      timeout = ParameterMap.getKeyedInteger(qualifiers, "timeout", DEFAULT_TIMEOUT);
      port = ParameterMap.getKeyedInteger(qualifiers, "port", DEFAULT_PORT);
    }

    boolean result = isServer(address, port, retries, timeout);
    if (result && qualifiers != null && !qualifiers.containsKey("port"))
      qualifiers.put("port", port);

    return result;
  }
Exemplo n.º 4
0
  private SnmpAgentConfig getAgentConfig(InetAddress ipaddr) {
    // Retrieve this interface's SNMP peer object
    SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(ipaddr);
    if (agentConfig == null) {
      throw new IllegalStateException(
          "SnmpAgentConfig object not available for interface " + ipaddr);
    }

    agentConfig.hashCode();

    // Set timeout and retries on SNMP peer object
    agentConfig.setTimeout(
        ParameterMap.getKeyedInteger(m_parameters, "timeout", agentConfig.getTimeout()));
    agentConfig.setRetries(
        ParameterMap.getKeyedInteger(
            m_parameters,
            "retry",
            ParameterMap.getKeyedInteger(m_parameters, "retries", agentConfig.getRetries())));
    agentConfig.setPort(ParameterMap.getKeyedInteger(m_parameters, "port", agentConfig.getPort()));

    return agentConfig;
  }
Exemplo n.º 5
0
 public int getSnmpMaxRequestSize(int current) {
   return ParameterMap.getKeyedInteger(getParameters(), "max-request-size", current);
 }
Exemplo n.º 6
0
 public int getSnmpMaxVarsPerPdu(int current) {
   return ParameterMap.getKeyedInteger(getParameters(), "max-vars-per-pdu", current);
 }
Exemplo n.º 7
0
 public int getSnmpTimeout(int current) {
   return ParameterMap.getKeyedInteger(getParameters(), "timeout", current);
 }
Exemplo n.º 8
0
 public int getSnmpRetries(int current) {
   return ParameterMap.getKeyedInteger(getParameters(), "retry", current);
 }
Exemplo n.º 9
0
 public int getSnmpPort(int current) {
   return ParameterMap.getKeyedInteger(getParameters(), "port", current);
 }
Exemplo n.º 10
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;
  }
Exemplo n.º 11
0
 int getRange() {
   Map<?, ?> parameters = getParameters();
   int range = ParameterMap.getKeyedInteger(parameters, "range", LatencyThresholder.DEFAULT_RANGE);
   return range;
 }
Exemplo n.º 12
0
 int getInterval() {
   Map<?, ?> parameters = getParameters();
   int interval =
       ParameterMap.getKeyedInteger(parameters, "interval", LatencyThresholder.DEFAULT_INTERVAL);
   return interval;
 }
Exemplo n.º 13
0
  /**
   * {@inheritDoc}
   *
   * <p>Poll an {@link InetAddress} for SSH availability.
   *
   * <p>During the poll an attempt is made to connect on the specified port. If the connection
   * request is successful, the banner line generated by the interface is parsed and if the banner
   * text indicates that we are talking to Provided that the interface's response is valid we mark
   * the poll status as available and return.
   */
  public PollStatus poll(InetAddress address, Map<String, Object> parameters) {

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

    int port = ParameterMap.getKeyedInteger(parameters, "port", DEFAULT_PORT);
    String banner = ParameterMap.getKeyedString(parameters, "banner", null);
    String match = ParameterMap.getKeyedString(parameters, "match", null);
    String clientBanner =
        ParameterMap.getKeyedString(parameters, "client-banner", Ssh.DEFAULT_CLIENT_BANNER);
    PollStatus ps = PollStatus.unavailable();

    Ssh ssh = new Ssh(address, port, tracker.getConnectionTimeout());
    ssh.setClientBanner(clientBanner);

    RE regex = null;
    try {
      if (match == null && (banner == null || banner.equals("*"))) {
        regex = null;
      } else if (match != null) {
        regex = new RE(match);
      } else if (banner != null) {
        regex = new RE(banner);
      }
    } catch (final RESyntaxException e) {
      final String matchString = match == null ? banner : match;
      LogUtils.infof(
          this,
          "Invalid regular expression for SSH banner match /%s/: %s",
          matchString,
          e.getMessage());
      LogUtils.debugf(this, e, "Invalid Regular expression for SSH banner match /%s/", matchString);
    }

    for (tracker.reset(); tracker.shouldRetry() && !ps.isAvailable(); tracker.nextAttempt()) {
      try {
        ps = ssh.poll(tracker);
      } catch (final InsufficientParametersException e) {
        LogUtils.errorf(this, e, "An error occurred polling host '%s'", address);
        break;
      }

      if (!ps.isAvailable()) {
        // not able to connect, retry
        continue;
      }

      // If banner matching string is null or wildcard ("*") then we
      // only need to test connectivity and we've got that!

      if (regex == null) {
        return ps;
      } else {
        String response = ssh.getServerBanner();

        if (response == null) {
          return PollStatus.unavailable("server closed connection before banner was received.");
        }

        if (regex.match(response)) {
          LogUtils.debugf(this, "isServer: matching response=%s", response);
          return ps;
        } else {
          // Got a response but it didn't match... no need to attempt
          // retries
          LogUtils.debugf(this, "isServer: NON-matching response=%s", response);
          return PollStatus.unavailable(
              "server responded, but banner did not match '" + banner + "'");
        }
      }
    }
    return ps;
  }
Exemplo n.º 14
0
  /**
   * {@inheritDoc}
   *
   * <p>Returns true if the protocol defined by this plugin is supported. If the protocol is not
   * supported then a false value is returned to the caller. The qualifier map passed to the method
   * is used by the plugin to return additional information by key-name. These key-value pairs can
   * be added to service events if needed.
   */
  @Override
  public boolean isProtocolSupported(InetAddress address, Map<String, Object> qualifiers) {

    try {

      String oid = ParameterMap.getKeyedString(qualifiers, "vbname", DEFAULT_OID);
      SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(address);
      String expectedValue = null;
      String isTable = null;

      if (qualifiers != null) {
        // "port" parm
        //
        if (qualifiers.get("port") != null) {
          int port = ParameterMap.getKeyedInteger(qualifiers, "port", agentConfig.getPort());
          agentConfig.setPort(port);
        }

        // "timeout" parm
        //
        if (qualifiers.get("timeout") != null) {
          int timeout =
              ParameterMap.getKeyedInteger(qualifiers, "timeout", agentConfig.getTimeout());
          agentConfig.setTimeout(timeout);
        }

        // "retry" parm
        //
        if (qualifiers.get("retry") != null) {
          int retry = ParameterMap.getKeyedInteger(qualifiers, "retry", agentConfig.getRetries());
          agentConfig.setRetries(retry);
        }

        // "force version" parm
        //
        if (qualifiers.get("force version") != null) {
          String version = (String) qualifiers.get("force version");
          if (version.equalsIgnoreCase("snmpv1")) agentConfig.setVersion(SnmpAgentConfig.VERSION1);
          else if (version.equalsIgnoreCase("snmpv2") || version.equalsIgnoreCase("snmpv2c"))
            agentConfig.setVersion(SnmpAgentConfig.VERSION2C);

          // TODO: make sure JoeSnmpStrategy correctly handles this.
          else if (version.equalsIgnoreCase("snmpv3"))
            agentConfig.setVersion(SnmpAgentConfig.VERSION3);
        }

        // "vbvalue" parm
        //
        if (qualifiers.get("vbvalue") != null) {
          expectedValue = (String) qualifiers.get("vbvalue");
        }

        if (qualifiers.get("table") != null) {
          isTable = (String) qualifiers.get("table");
        }
      }

      if (isTable != null && isTable.equalsIgnoreCase("true")) {

        SnmpObjId snmpObjId = SnmpObjId.get(oid);

        Map<SnmpInstId, SnmpValue> table =
            SnmpUtils.getOidValues(agentConfig, "SnmpPlugin", snmpObjId);
        for (Map.Entry<SnmpInstId, SnmpValue> e : table.entrySet()) {
          if (e.getValue().toString().equals(expectedValue)) {
            return true;
          }
        }
      } else {
        String retrievedValue = getValue(agentConfig, oid);

        if (retrievedValue != null && expectedValue != null) {
          return (Pattern.compile(expectedValue).matcher(retrievedValue).find());
        } else {
          return (retrievedValue != null);

          // return (expectedValue == null ? true : retrievedValue.equals(expectedValue));
        }
      }

    } catch (Throwable t) {
      throw new UndeclaredThrowableException(t);
    }

    // should never get here.
    return false;
  }
Exemplo n.º 15
0
  /**
   * {@inheritDoc}
   *
   * <p>Perform data collection.
   */
  @Override
  public CollectionSet collect(CollectionAgent agent, EventProxy eproxy, Map<String, Object> map) {
    InetAddress ipaddr = agent.getAddress();
    JMXNodeInfo nodeInfo = agent.getAttribute(NODE_INFO_KEY);
    Map<String, BeanInfo> mbeans = nodeInfo.getMBeans();
    String collDir = serviceName;

    boolean useMbeanForRrds = ParameterMap.getKeyedBoolean(map, "use-mbean-name-for-rrds", false);
    String port = ParameterMap.getKeyedString(map, "port", null);
    String friendlyName = ParameterMap.getKeyedString(map, "friendly-name", port);
    if (useFriendlyName) {
      collDir = friendlyName;
    }

    JMXCollectionSet collectionSet = new JMXCollectionSet(agent, collDir);
    collectionSet.setCollectionTimestamp(new Date());
    JMXCollectionResource collectionResource = collectionSet.getResource();

    ConnectionWrapper connection = null;

    LogUtils.debugf(
        this, "collecting %s on node ID %d", InetAddressUtils.str(ipaddr), nodeInfo.getNodeId());

    try {
      connection = getMBeanServerConnection(map, ipaddr);

      if (connection == null) {
        return collectionSet;
      }

      MBeanServerConnection mbeanServer = connection.getMBeanServer();

      int retry = ParameterMap.getKeyedInteger(map, "retry", 3);
      for (int attempts = 0; attempts <= retry; attempts++) {
        try {
          /*
           * Iterate over the mbeans, for each object name perform a
           * getAttributes, the update the RRD.
           */

          for (Iterator<BeanInfo> iter = mbeans.values().iterator(); iter.hasNext(); ) {
            BeanInfo beanInfo = iter.next();
            String mbeanName = beanInfo.getMbeanName();
            String objectName = beanInfo.getObjectName();
            String excludeList = beanInfo.getExcludes();
            // All JMX collected values are per node
            String obj = useMbeanForRrds ? mbeanName : objectName;
            AttributeGroupType attribGroupType = new AttributeGroupType(fixGroupName(obj), "all");

            List<String> attribNames = beanInfo.getAttributeNames();
            List<String> compAttribNames = beanInfo.getCompositeAttributeNames();

            for (String compAttribName : compAttribNames) {
              if (attribNames.contains(compAttribName)) {
                attribNames.remove(compAttribName);
                String[] ac = compAttribName.split("\\|", -1);
                String attrName = ac[0];
                if (!attribNames.contains(attrName)) {
                  attribNames.add(attrName);
                }
              }
            }
            // log.debug(" JMXCollector: processed the following attributes: " +
            // attribNames.toString());
            // log.debug(" JMXCollector: processed the following Composite Attributes: " +
            // compAttribNames.toString());

            String[] attrNames = attribNames.toArray(new String[attribNames.size()]);

            if (objectName.indexOf("*") == -1) {
              LogUtils.debugf(
                  this,
                  "%s Collector - getAttributes: %s, # attributes: %d, # composite attribute members: %d",
                  serviceName,
                  objectName,
                  attrNames.length,
                  compAttribNames.size());
              try {
                ObjectName oName = new ObjectName(objectName);
                if (mbeanServer.isRegistered(oName)) {
                  AttributeList attrList = mbeanServer.getAttributes(oName, attrNames);
                  Map<String, JMXDataSource> dsMap = nodeInfo.getDsMap();
                  for (Object attribute : attrList) {
                    List<String> compositeMemberKeys = new ArrayList<String>();
                    Boolean isComposite = false;
                    Attribute attrib = (Attribute) attribute;
                    for (String compAttrName : compAttribNames) {
                      String[] attribKeys = compAttrName.split("\\|", -1);
                      if (attrib.getName().equals(attribKeys[0])) {
                        compositeMemberKeys.add(attribKeys[1]);
                        isComposite = true;
                      }
                    }
                    if (isComposite) {
                      try {
                        CompositeData cd = (CompositeData) attrib.getValue();
                        for (String key : compositeMemberKeys) {
                          /*
                          value = cd.get(key);

                          log.debug(" JMXCollector - got CompositeData: " +
                                    objectName + "|" + attrib.getName() + "|" + key + " |-> " + cd.get(key).toString());
                          */
                          JMXDataSource ds =
                              dsMap.get(objectName + "|" + attrib.getName() + "|" + key);
                          JMXCollectionAttributeType attribType =
                              new JMXCollectionAttributeType(ds, null, null, attribGroupType);
                          collectionResource.setAttributeValue(attribType, cd.get(key).toString());
                        }
                      } catch (final ClassCastException cce) {
                        LogUtils.debugf(
                            this,
                            cce,
                            "%s Collection - getAttributes (try CompositeData) - ERROR: Failed to cast attribute value to type CompositeData!",
                            serviceName);
                      }
                    } else {
                      // this is a normal attribute, so fallback to default handler
                      JMXDataSource ds = dsMap.get(objectName + "|" + attrib.getName());
                      JMXCollectionAttributeType attribType =
                          new JMXCollectionAttributeType(ds, null, null, attribGroupType);
                      collectionResource.setAttributeValue(
                          attribType, attrib.getValue().toString());
                    }
                  }
                }
              } catch (final InstanceNotFoundException e) {
                LogUtils.errorf(this, e, "Unable to retrieve attributes from %s", objectName);
              }
            } else {
              /*
               * This section is for ObjectNames that use the
               * '*' wildcard
               */
              Set<ObjectName> mbeanSet = getObjectNames(mbeanServer, objectName);
              for (Iterator<ObjectName> objectNameIter = mbeanSet.iterator();
                  objectNameIter.hasNext(); ) {
                ObjectName oName = objectNameIter.next();
                LogUtils.debugf(
                    this,
                    "%s Collector - getAttributesWC: %s, # attributes: %d, alias: %s",
                    serviceName,
                    oName,
                    attrNames.length,
                    beanInfo.getKeyAlias());

                try {
                  if (excludeList == null) {
                    // the exclude list doesn't apply
                    if (mbeanServer.isRegistered(oName)) {
                      AttributeList attrList = mbeanServer.getAttributes(oName, attrNames);
                      Map<String, JMXDataSource> dsMap = nodeInfo.getDsMap();

                      for (Object attribute : attrList) {
                        Attribute attrib = (Attribute) attribute;
                        JMXDataSource ds = dsMap.get(objectName + "|" + attrib.getName());
                        JMXCollectionAttributeType attribType =
                            new JMXCollectionAttributeType(
                                ds,
                                oName.getKeyProperty(beanInfo.getKeyField()),
                                beanInfo.getKeyAlias(),
                                attribGroupType);

                        collectionResource.setAttributeValue(
                            attribType, attrib.getValue().toString());
                      }
                    }
                  } else {
                    /*
                     * filter out calls if the key field
                     * matches an entry in the exclude
                     * list
                     */
                    String keyName = oName.getKeyProperty(beanInfo.getKeyField());
                    boolean found = false;
                    StringTokenizer st = new StringTokenizer(excludeList, ",");
                    while (st.hasMoreTokens()) {
                      if (keyName.equals(st.nextToken())) {
                        found = true;
                        break;
                      }
                    }
                    if (!found) {
                      if (mbeanServer.isRegistered(oName)) {
                        AttributeList attrList = mbeanServer.getAttributes(oName, attrNames);
                        Map<String, JMXDataSource> dsMap = nodeInfo.getDsMap();

                        for (Object attribute : attrList) {
                          Attribute attrib = (Attribute) attribute;
                          JMXDataSource ds = dsMap.get(objectName + "|" + attrib.getName());
                          JMXCollectionAttributeType attribType =
                              new JMXCollectionAttributeType(
                                  ds,
                                  oName.getKeyProperty(beanInfo.getKeyField()),
                                  beanInfo.getKeyAlias(),
                                  attribGroupType);

                          collectionResource.setAttributeValue(
                              attribType, attrib.getValue().toString());
                        }
                      }
                    }
                  }
                } catch (final InstanceNotFoundException e) {
                  LogUtils.errorf(this, e, "Error retrieving attributes for %s", oName);
                }
              }
            }
          }
          break;
        } catch (final Exception e) {
          LogUtils.debugf(
              this,
              e,
              "%s Collector.collect: IOException while collecting address: %s",
              serviceName,
              agent.getAddress());
        }
      }
    } catch (final Exception e) {
      LogUtils.errorf(this, e, "Error getting MBeanServer");
    } finally {
      if (connection != null) {
        connection.close();
      }
    }

    collectionSet.setStatus(ServiceCollector.COLLECTION_SUCCEEDED);
    return collectionSet;
  }
Exemplo n.º 16
0
  public OnmsAccessPointCollection call() throws IOException {
    OnmsAccessPointCollection apsUp = new OnmsAccessPointCollection();
    InetAddress ipaddr = m_iface.getIpAddress();

    // Retrieve this interface's SNMP peer object
    SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(ipaddr);
    if (agentConfig == null) {
      throw new IllegalStateException(
          "SnmpAgentConfig object not available for interface " + 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.");
    }

    agentConfig.hashCode();

    // Set timeout and retries on SNMP peer object
    agentConfig.setTimeout(
        ParameterMap.getKeyedInteger(m_parameters, "timeout", agentConfig.getTimeout()));
    agentConfig.setRetries(
        ParameterMap.getKeyedInteger(
            m_parameters,
            "retry",
            ParameterMap.getKeyedInteger(m_parameters, "retries", agentConfig.getRetries())));
    agentConfig.setPort(ParameterMap.getKeyedInteger(m_parameters, "port", agentConfig.getPort()));

    if (log().isDebugEnabled()) {
      log().debug("TableStrategy.poll: SnmpAgentConfig address= " + agentConfig);
    }

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

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

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

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

        String physAddr = getPhysAddrFromValue(value);

        log()
            .debug(
                "AP at value '"
                    + value.toHexString()
                    + "' with MAC '"
                    + physAddr
                    + "' is considered to be ONLINE on controller '"
                    + m_iface.getIpAddress()
                    + "'");
        OnmsAccessPoint ap = m_accessPointDao.findByPhysAddr(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 '" + physAddr + "' is in a different package.");
          }
        } else {
          log().info("No matching AP in database for value '" + value.toHexString() + "'.");
        }
      }
    } catch (InterruptedException e) {
      log().error("Interrupted while polling " + hostAddress, e);
    }

    return apsUp;
  }