public String getSnmpReadCommunity(String current) {
   String readCommunity = ParameterMap.getKeyedString(getParameters(), "read-community", null);
   if (readCommunity == null) {
     // incase someone is using an ancient config file
     readCommunity = ParameterMap.getKeyedString(m_parameters, "readCommunity", current);
   }
   return readCommunity;
 }
Beispiel #2
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);
  }
  /** {@inheritDoc} */
  @Override
  public boolean checkStatus(Connection con, Map<String, Object> qualifiers) {
    Statement st = null;
    String query = ParameterMap.getKeyedString(qualifiers, "query", null);

    if (query == null) return false;

    try {
      st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
      ResultSet rs = st.executeQuery(query);
      rs.first();

      if (rs.getRow() == 1) return true;

    } catch (SQLException exp) {
      return false;

    } catch (Throwable exp) {
      return false;
    } finally {
      closeStmt(st);
    }

    return false;
  }
Beispiel #4
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);
    }
  }
 public String getCollectionName() {
   // icky hard coded old names; we need to handle some old cases where configs might be not yet
   // updated, but they should
   // still work
   if (getParameters().containsKey("collection")) {
     return ParameterMap.getKeyedString(getParameters(), "collection", "default");
   } else if (getParameters().containsKey("http-collection")) {
     return ParameterMap.getKeyedString(getParameters(), "http-collection", "default");
   } else if (getParameters().containsKey("nsclient-collection")) {
     return ParameterMap.getKeyedString(getParameters(), "nsclient-collection", "default");
   } else if (m_parameters.containsKey("wmi-collection")) {
     return ParameterMap.getKeyedString(getParameters(), "wmi-collection", "default");
   } else {
     return "default";
   }
   // Previous code:  we can return to this in time (maybe 1.6, or even 2.0) when all old
   // configs should be long gone
   // return ParameterMap.getKeyedString(getParameters(), "collection", "default");
 }
 public InetAddress getSnmpProxyFor(InetAddress current) {
   String address = ParameterMap.getKeyedString(getParameters(), "proxy-host", null);
   InetAddress addr = null;
   if (address != null) {
     addr = InetAddressUtils.addr(address);
     if (addr == null) {
       LOG.error("determineProxyHost: Problem converting proxy host string to InetAddress");
     }
   }
   return addr == null ? current : addr;
 }
 public int getSnmpVersion(int current) {
   String version = ParameterMap.getKeyedString(getParameters(), "version", null);
   if (version != null) {
     if (version.equals("v1")) {
       return SnmpAgentConfig.VERSION1;
     } else if (version.equals("v2c")) {
       return SnmpAgentConfig.VERSION2C;
     } else if (version.equals("v3")) {
       return SnmpAgentConfig.VERSION3;
     }
   }
   return current;
 }
Beispiel #8
0
 /* (non-Javadoc)
  * @see org.opennms.netmgt.collectd.ServiceCollector#collect(org.opennms.netmgt.collectd.CollectionAgent, org.opennms.netmgt.model.events.EventProxy, java.util.Map)
  */
 @Override
 public CollectionSet collect(
     CollectionAgent agent, EventProxy eproxy, Map<String, Object> parameters)
     throws CollectionException {
   try {
     String collectionName = ParameterMap.getKeyedString(parameters, "collection", null);
     if (collectionName == null) {
       collectionName = ParameterMap.getKeyedString(parameters, "tca-collection", null);
     }
     if (collectionName == null) {
       throw new CollectionException("Parameter collection is required for the TCA Collector!");
     }
     TcaCollectionSet collectionSet =
         new TcaCollectionSet(agent, getRrdRepository(collectionName));
     collectionSet.setCollectionTimestamp(new Date());
     collectionSet.collect();
     return collectionSet;
   } catch (Throwable t) {
     throw new CollectionException(
         "Unexpected error during node TCA collection for: " + agent.getHostAddress() + ": " + t,
         t);
   }
 }
 public String getSnmpAuthPassPhrase(String current) {
   return ParameterMap.getKeyedString(getParameters(), "auth-passphrase", current);
 }
 public String getSnmpSecurityName(String current) {
   return ParameterMap.getKeyedString(getParameters(), "security-name", current);
 }
 public String getStorFlagOverride() {
   return ParameterMap.getKeyedString(getParameters(), "storFlagOverride", "false");
 }
 public String getStoreByNodeID() {
   return ParameterMap.getKeyedString(getParameters(), "storeByNodeID", "normal");
 }
 public String getSnmpPrivProtocol(String current) {
   return ParameterMap.getKeyedString(getParameters(), "privacy-protocol", current);
 }
 public String getIfAliasComment() {
   return ParameterMap.getKeyedString(getParameters(), "ifAliasComment", null);
 }
Beispiel #15
0
  /** {@inheritDoc} */
  @Override
  public CollectionSet collect(
      final CollectionAgent agent, final EventProxy eproxy, final Map<String, Object> parameters) {

    String collectionName =
        ParameterMap.getKeyedString(
            parameters,
            "collection",
            ParameterMap.getKeyedString(parameters, "wmi-collection", null));
    // Find attributes to collect - check groups in configuration. For each,
    // check scheduled nodes to see if that group should be collected
    final WmiCollection collection =
        WmiDataCollectionConfigFactory.getInstance().getWmiCollection(collectionName);
    final WmiAgentState agentState = m_scheduledNodes.get(agent.getNodeId());

    // Load the attribute group types.
    loadAttributeGroupList(collection);

    // Load the attribute types.
    loadAttributeTypeList(collection);

    // Create a new collection set.
    final WmiCollectionSet collectionSet = new WmiCollectionSet();
    collectionSet.setCollectionTimestamp(new Date());
    final WmiSingleInstanceCollectionResource nodeResource =
        new WmiSingleInstanceCollectionResource(agent);

    // Iterate through the WMI collection groups.
    for (final Wpm wpm : collection.getWpms().getWpm()) {
      // A wpm consists of a list of attributes, identified by name
      if (agentState.shouldCheckAvailability(wpm.getName(), wpm.getRecheckInterval())) {
        if (!isGroupAvailable(agentState, wpm)) {
          continue;
        }
      }

      if (agentState.groupIsAvailable(wpm.getName())) {
        WmiClient client = null;
        // Collect the data
        try {
          // Tell the agent to connect
          agentState.connect(wpm.getWmiNamespace());

          // And retrieve the client object for working.
          client = (WmiClient) agentState.getWmiClient();

          // Retrieve the WbemObjectSet from the class defined on the group.
          final OnmsWbemObjectSet wOS = client.performInstanceOf(wpm.getWmiClass());

          // If we received a WbemObjectSet result, lets go through it and collect it.
          if (wOS != null) {
            //  Go through each object (class instance) in the object set.
            for (int i = 0; i < wOS.count(); i++) {
              // Create a new collection resource.
              WmiCollectionResource resource = null;

              // Fetch our WBEM Object
              final OnmsWbemObject obj = wOS.get(i);

              // If this is multi-instance, fetch the instance name and store it.
              if (wOS.count() > 1) {
                // Fetch the value of the key value. e.g. Name.
                final OnmsWbemProperty prop = obj.getWmiProperties().getByName(wpm.getKeyvalue());
                final Object propVal = prop.getWmiValue();
                String instance = null;
                if (propVal instanceof String) {
                  instance = (String) propVal;
                } else {
                  instance = propVal.toString();
                }
                resource =
                    new WmiMultiInstanceCollectionResource(agent, instance, wpm.getResourceType());
              } else {
                resource = nodeResource;
              }

              for (final Attrib attrib : wpm.getAttrib()) {
                final OnmsWbemProperty prop =
                    obj.getWmiProperties().getByName(attrib.getWmiObject());
                final WmiCollectionAttributeType attribType =
                    m_attribTypeList.get(attrib.getName());
                resource.setAttributeValue(attribType, prop.getWmiValue().toString());
              }
              collectionSet.getCollectionResources().add(resource);
            }
          }
        } catch (final WmiException e) {
          LOG.info("unable to collect params for wpm '{}'", wpm.getName(), e);
        } finally {
          if (client != null) {
            try {
              client.disconnect();
            } catch (final WmiException e) {
              LOG.warn("An error occurred disconnecting while collecting from WMI.", e);
            }
          }
        }
      }
    }
    collectionSet.setStatus(ServiceCollector.COLLECTION_SUCCEEDED);
    return collectionSet;
  }
Beispiel #16
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;
  }
 String getGroupName() {
   Map<?, ?> parameters = getParameters();
   String groupName = ParameterMap.getKeyedString(parameters, "thresholding-group", "default");
   return groupName;
 }
  @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;
  }
Beispiel #19
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;
  }
  /**
   * {@inheritDoc}
   *
   * <p>Responsible for performing all necessary initialization for the specified interface in
   * preparation for thresholding.
   */
  public void initialize(ThresholdNetworkInterface iface, Map<?, ?> parameters) {
    // Get interface address from NetworkInterface
    //
    if (iface.getType() != NetworkInterface.TYPE_INET)
      throw new RuntimeException("Unsupported interface type, only TYPE_INET currently supported");
    InetAddress ipAddr = (InetAddress) iface.getAddress();
    String groupName = ParameterMap.getKeyedString(parameters, "thresholding-group", "default");

    // Get the threshold group's RRD repository path
    //
    String repository = null;
    try {
      repository = ThresholdingConfigFactory.getInstance().getRrdRepository(groupName);
    } catch (IllegalArgumentException e) {
      throw new RuntimeException("Thresholding group '" + groupName + "' does not exist.");
    }

    // Add RRD repository as an attribute of the interface for retrieval
    // by the check() method.
    //
    iface.setAttribute(RRD_REPOSITORY_KEY, repository);

    // Get database connection in order to retrieve the nodeid and
    // ifIndex from the database for this interface.
    //
    java.sql.Connection dbConn = null;
    final DBUtils d = new DBUtils(getClass());
    try {
      dbConn = DataSourceFactory.getInstance().getConnection();
      d.watch(dbConn);
    } catch (SQLException sqlE) {
      if (log().isEnabledFor(ThreadCategory.Level.ERROR))
        log().error("initialize: Failed getting connection to the database.", sqlE);
      throw new UndeclaredThrowableException(sqlE);
    }

    // Use IP address to lookup the node id
    //
    // NOTE: All database calls wrapped in try/finally block so we make
    // certain that the connection will be closed when we are
    // finished.
    //
    int nodeId = -1;

    final String hostAddress = InetAddressUtils.str(ipAddr);
    try {
      // Prepare & execute the SQL statement to get the 'nodeid',
      // 'ifIndex' and 'isSnmpPrimary' fields from the ipInterface table.
      //
      PreparedStatement stmt = null;
      try {
        stmt = dbConn.prepareStatement(SQL_GET_NODEID);
        d.watch(stmt);
        stmt.setString(1, hostAddress); // interface address
        ResultSet rs = stmt.executeQuery();
        d.watch(rs);
        if (rs.next()) {
          nodeId = rs.getInt(1);
          if (rs.wasNull()) nodeId = -1;
        }
      } catch (SQLException sqle) {
        if (log().isDebugEnabled()) log().debug("initialize: SQL exception!!", sqle);
        throw new RuntimeException(
            "SQL exception while attempting to retrieve node id for interface " + hostAddress);
      }

      if (log().isDebugEnabled())
        log()
            .debug(
                "initialize: db retrieval info: nodeid = " + nodeId + ", address = " + hostAddress);

      if (nodeId == -1)
        throw new RuntimeException("Unable to retrieve node id for interface " + hostAddress);
    } finally {
      d.cleanUp();
    }

    // Add nodeId as an attribute of the interface for retrieval
    // by the check() method.
    //
    iface.setAttribute(NODE_ID_KEY, new Integer(nodeId));

    // Retrieve the collection of Threshold objects associated with
    // the defined thresholding group and build maps of
    // ThresholdEntity objects keyed by datasource name. The
    // datasource type of the threshold determines which
    // map the threshold entity is added to.
    //
    // Each ThresholdEntity can wrap one high Threshold and one low
    // Threshold castor-generated object for a single datasource.
    // If more than one high or more than one low threshold is defined
    // for a single datasource a warning messages is generated. Only
    // the first threshold in such a scenario will be used for thresholding.
    //

    // Create empty map for storing threshold entities
    Map<String, ThresholdEntity> thresholdMap = new HashMap<String, ThresholdEntity>();

    try {
      for (Basethresholddef thresh :
          ThresholdingConfigFactory.getInstance().getThresholds(groupName)) {
        // See if map entry already exists for this datasource
        // If not, create a new one.
        boolean newEntity = false;
        ThresholdEntity thresholdEntity = null;

        // All latency thresholds are per interface so confirm that
        // the datasource type is set to "if"
        //
        if (!thresh.getDsType().equals("if") && !thresh.getDsType().equals("expr")) {
          log()
              .warn(
                  "initialize: invalid datasource type, latency thresholder only supports interface level datasources.");
          continue; // continue with the next threshold...
        }
        try {
          BaseThresholdDefConfigWrapper wrapper =
              BaseThresholdDefConfigWrapper.getConfigWrapper(thresh);
          // First attempt to lookup the entry in the map
          thresholdEntity = thresholdMap.get(wrapper.getDatasourceExpression());

          // Found entry?
          if (thresholdEntity == null) {
            // Nope, create a new one
            newEntity = true;
            thresholdEntity = new ThresholdEntity();
          }

          try {
            thresholdEntity.addThreshold(wrapper);
          } catch (IllegalStateException e) {
            log()
                .warn(
                    "Encountered duplicate "
                        + thresh.getType()
                        + " for datasource "
                        + wrapper.getDatasourceExpression()
                        + ": "
                        + e,
                    e);
          }

          // Add new entity to the map
          if (newEntity) {
            thresholdMap.put(wrapper.getDatasourceExpression(), thresholdEntity);
          }
        } catch (ThresholdExpressionException e) {
          log().warn("Could not parse threshold expression: " + e.getMessage(), e);
        }
      }
    } catch (IllegalArgumentException e) {
      throw new RuntimeException("Thresholding group '" + groupName + "' does not exist.");
    }

    // Add threshold maps as attributes for retrieval by the check() method.
    //
    iface.setAttribute(THRESHOLD_MAP_KEY, thresholdMap);

    // Debug
    //
    if (log().isDebugEnabled()) {
      log()
          .debug(
              "initialize: dumping interface thresholds defined for "
                  + hostAddress
                  + "/"
                  + groupName
                  + ":");
      Iterator<ThresholdEntity> iter = thresholdMap.values().iterator();
      while (iter.hasNext()) log().debug(iter.next().toString());
    }

    if (log().isDebugEnabled())
      log().debug("initialize: initialization completed for " + hostAddress);
    return;
  }
 public String getSnmpAuthProtocol(String current) {
   return ParameterMap.getKeyedString(getParameters(), "auth-protocol", current);
 }
 public String getSnmpPrivPassPhrase(String current) {
   return ParameterMap.getKeyedString(getParameters(), "privacy-passphrase", current);
 }
Beispiel #23
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;
  }
 public String getDomain() {
   return ParameterMap.getKeyedString(getParameters(), "domain", "default");
 }
Beispiel #25
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;
  }
 public String getStoreByIfAlias() {
   return ParameterMap.getKeyedString(getParameters(), "storeByIfAlias", "false");
 }
 public String getSnmpWriteCommunity(String current) {
   return ParameterMap.getKeyedString(getParameters(), "write-community", current);
 }
  /**
   * {@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;
  }
Beispiel #29
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;
  }