/**
     * Process the received events. For each event, use the EventExpander to look up matching
     * eventconf entry and load info from that match, expand event parms, add event to database and
     * send event to appropriate listeners.
     */
    @Override
    public void run() {
      Events events = m_eventLog.getEvents();
      if (events == null || events.getEventCount() <= 0) {
        // no events to process
        return;
      }

      for (final Event event : events.getEventCollection()) {
        final ThreadCategory log = log();
        if (log.isDebugEnabled()) {
          // Log the uei, source, and other important aspects
          final String uuid = event.getUuid();
          log.debug("Event {");
          log.debug("  uuid  = " + (uuid != null && uuid.length() > 0 ? uuid : "<not-set>"));
          log.debug("  uei   = " + event.getUei());
          log.debug("  src   = " + event.getSource());
          log.debug("  iface = " + event.getInterface());
          log.debug("  time  = " + event.getTime());
          if (event.getParmCollection().size() > 0) {
            log.debug("  parms {");
            for (final Parm parm : event.getParmCollection()) {
              if ((parm.getParmName() != null) && (parm.getValue().getContent() != null)) {
                log.debug(
                    "    ("
                        + parm.getParmName().trim()
                        + ", "
                        + parm.getValue().getContent().trim()
                        + ")");
              }
            }
            log.debug("  }");
          }
          log.debug("}");
        }

        for (final EventProcessor eventProcessor : m_eventProcessors) {
          try {
            eventProcessor.process(m_eventLog.getHeader(), event);
          } catch (SQLException e) {
            log.warn(
                "Unable to process event using processor "
                    + eventProcessor
                    + "; not processing with any later processors.  Exception: "
                    + e,
                e);
            break;
          } catch (Throwable t) {
            log.warn(
                "Unknown exception processing event with processor "
                    + eventProcessor
                    + "; not processing with any later processors.  Exception: "
                    + t,
                t);
            break;
          }
        }
      }
    }
  /** {@inheritDoc} */
  @Override
  public DeliveryOptions getDeliveryOptions(String reportId, String userId) {
    DeliveryOptions options = new DeliveryOptions();

    options.setFormat(ReportFormat.HTML);
    options.setPersist(true);
    options.setSendMail(false);

    UserManager userFactory = UserFactory.getInstance();

    try {
      String emailAddress = userFactory.getEmail(userId);
      if (emailAddress != null) {
        options.setMailTo(emailAddress);
      }
    } catch (MarshalException e) {
      log.error("marshal exception trying to set destination email address", e);
    } catch (ValidationException e) {
      log.error("validation exception trying to set destination email address", e);
    } catch (IOException e) {
      log.error("IO exception trying to set destination email address", e);
    } catch (NullPointerException e) { // See NMS-5111 for more details.
      log.warn("the user " + userId + " does not have any email configured.");
    }

    options.setInstanceId(reportId + " " + userId);

    return options;
  }
  /**
   * {@inheritDoc}
   *
   * <p>This method is invoked by the EventIpcManager when a new event is available for processing.
   * Each message is examined for its Universal Event Identifier and the appropriate action is
   * taking based on each UEI.
   */
  public void onEvent(Event event) {
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    String eventUei = event.getUei();
    if (eventUei == null) {
      log.warn("Received an unexpected event with a null UEI");
      return;
    }

    if (log.isDebugEnabled()) {
      log.debug("Received event: " + eventUei);
    }

    if (eventUei.equals(EventConstants.NODE_GAINED_INTERFACE_EVENT_UEI)
        || eventUei.equals(EventConstants.INTERFACE_REPARENTED_EVENT_UEI)) {
      String action =
          eventUei.equals(EventConstants.INTERFACE_REPARENTED_EVENT_UEI) ? "reparent" : "add";
      if (Long.toString(event.getNodeid()) == null) {
        log.warn("Not " + action + "ing interface to known node list: " + "nodeId is null");
      } else if (event.getInterface() == null) {
        log.warn("Not " + action + "ing interface to known node list: " + "interface is null");
      } else {
        m_trapdIpMgr.setNodeId(event.getInterface(), event.getNodeid());
        if (log.isDebugEnabled()) {
          log.debug(
              "Successfully " + action + "ed " + event.getInterface() + " to known node list");
        }
      }
    } else if (eventUei.equals(EventConstants.INTERFACE_DELETED_EVENT_UEI)) {
      if (event.getInterface() != null) {
        m_trapdIpMgr.removeNodeId(event.getInterface());
        if (log.isDebugEnabled()) {
          log.debug("Removed " + event.getInterface() + " from known node list");
        }
      }
    } else {
      log.warn("Received an unexpected event with UEI of \"" + eventUei + "\"");
    }
  }
  /** The execution context. */
  @Override
  public void run() {
    // get the context
    m_context = Thread.currentThread();

    // Get a log instance
    ThreadCategory.setPrefix(m_logPrefix);
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    if (m_stop) {
      log.debug("Stop flag set before thread started, exiting");
      return;
    } else log.debug("Thread context started");

    // allocate a buffer
    final int length = 0xffff;
    final byte[] buffer = new byte[length];

    // set an SO timeout to make sure we don't block forever
    // if a socket is closed.
    try {
      log.debug("Setting socket timeout to " + SOCKET_TIMEOUT + "ms");
      m_dgSock.setSoTimeout(SOCKET_TIMEOUT);
    } catch (SocketException e) {
      log.warn("An I/O error occured while trying to set the socket timeout", e);
    }

    // Increase the receive buffer for the socket
    try {
      log.debug("Setting receive buffer size to " + length);
      m_dgSock.setReceiveBufferSize(length);
    } catch (SocketException e) {
      log.info("Failed to set the receive buffer to " + length, e);
    }
    // set to avoid numerous tracing message
    boolean ioInterrupted = false;
    // now start processing incoming requests
    while (!m_stop) {
      if (m_context.isInterrupted()) {
        log.debug("Thread context interrupted");
        break;
      }

      try {
        if (!ioInterrupted) {
          log.debug("Waiting on a datagram to arrive");
        }

        DatagramPacket pkt = new DatagramPacket(buffer, length);
        m_dgSock.receive(pkt);

        // SyslogConnection *Must* copy packet data and InetAddress as DatagramPacket is a mutable
        // type
        WaterfallExecutor.waterfall(
            m_executors,
            new SyslogConnection(
                pkt,
                m_matchPattern,
                m_hostGroup,
                m_messageGroup,
                m_UeiList,
                m_HideMessages,
                m_discardUei));
        ioInterrupted = false; // reset the flag
      } catch (SocketTimeoutException e) {
        ioInterrupted = true;
        continue;
      } catch (InterruptedIOException e) {
        ioInterrupted = true;
        continue;
      } catch (ExecutionException e) {
        log.error("Task execution failed in " + this.getClass().getSimpleName(), e);
        break;
      } catch (InterruptedException e) {
        log.error("Task interrupted in " + this.getClass().getSimpleName(), e);
        break;
      } catch (IOException e) {
        log.error("An I/O exception occured on the datagram receipt port, exiting", e);
        break;
      }
    } // end while status OK

    log.debug("Thread context exiting");
  }
  /**
   * getNotifForEvent
   *
   * @param event a {@link org.opennms.netmgt.xml.event.Event} object.
   * @return an array of {@link org.opennms.netmgt.config.notifications.Notification} objects.
   * @throws java.io.IOException if any.
   * @throws org.exolab.castor.xml.MarshalException if any.
   * @throws org.exolab.castor.xml.ValidationException if any.
   */
  public Notification[] getNotifForEvent(final Event event)
      throws IOException, MarshalException, ValidationException {
    update();
    List<Notification> notifList = new ArrayList<Notification>();
    boolean matchAll = getConfigManager().getNotificationMatch();
    ThreadCategory log = this.log();

    // This if statement will check to see if notification should be suppressed for this event.

    if (event == null) {
      log.warn("unable to get notification for null event!");
      return null;
    } else if (event.getLogmsg() != null && !(event.getLogmsg().getNotify())) {
      if (log.isDebugEnabled())
        log.debug("Event " + event.getUei() + " is configured to suppress notifications.");
      return null;
    }

    for (Notification curNotif : m_notifications.getNotificationCollection()) {
      if (log.isDebugEnabled())
        log.debug("Checking " + event.getUei() + " against " + curNotif.getUei());

      if (event.getUei().equals(curNotif.getUei()) || "MATCH-ANY-UEI".equals(curNotif.getUei())) {
        // Match!
      } else if (curNotif.getUei().charAt(0) == '~') {
        if (event.getUei().matches(curNotif.getUei().substring(1))) {
          // Match!
        } else {
          if (log.isDebugEnabled())
            log.debug(
                "Notification regex "
                    + curNotif.getUei()
                    + " failed to match event UEI: "
                    + event.getUei());
          continue;
        }
      } else {
        if (log.isDebugEnabled())
          log.debug("Event UEI " + event.getUei() + " did not match " + curNotif.getUei());
        continue;
      }

      /** Check if event severity matches pattern in notification */
      if (log.isDebugEnabled())
        log.debug(
            "Checking event severity: "
                + event.getSeverity()
                + " against notification severity: "
                + curNotif.getEventSeverity());
      // parameter is optional, return true if not set
      if (curNotif.getEventSeverity() == null) {
        // Skip matching on severity
      } else if (event
          .getSeverity()
          .toLowerCase()
          .matches(curNotif.getEventSeverity().toLowerCase())) {
        // Severities match
      } else {
        if (log.isDebugEnabled())
          log.debug(
              "Event severity: "
                  + event.getSeverity()
                  + " did not match notification severity: "
                  + curNotif.getEventSeverity());
        continue;
      }

      // The notice has to be "on"
      // The notice has to match a severity if configured - currHasSeverity should be true if there
      // is no severity rule
      // The notice has to match the UEI of the event or MATCH-ANY-UEI
      // If all those things are true:
      // Then the service has to match if configured, the interface if configured, and the node if
      // configured.

      if (curNotif.getStatus().equals("on")) {
        if (nodeInterfaceServiceValid(curNotif, event)) {
          boolean parmsmatched = getConfigManager().matchNotificationParameters(event, curNotif);

          if (!parmsmatched) {
            if (log.isDebugEnabled())
              log.debug(
                  "Event "
                      + event.getUei()
                      + " did not match parameters for notice "
                      + curNotif.getName());
            continue;
          }
          // Add this notification to the return value
          notifList.add(curNotif);

          if (log.isDebugEnabled())
            log.debug("Event " + event.getUei() + " matched notice " + curNotif.getName());

          if (!matchAll) break;
        } else {
          if (log.isDebugEnabled())
            log.debug("Node/interface/service combination in the event was invalid");
        }
      } else {
        if (log.isDebugEnabled()) log.debug("Current notification is turned off.");
      }
    }

    if (!notifList.isEmpty()) {
      return notifList.toArray(new Notification[0]);
    } else {
      return null;
    }
  }
  /**
   * Private utility method used by the getMibObjectList() method. This method takes a group name
   * and a list of MibObject objects as arguments and adds all of the MibObjects associated with the
   * group to the object list. If the passed group consists of any additional sub-groups, then this
   * method will be called recursively for each sub-group until the entire
   * log.debug("processGroupName: adding MIB objects from group: " + groupName); group is processed.
   *
   * @param cName Collection name
   * @param groupName Name of the group to process
   * @param ifType Interface type
   * @param mibObjectList List of MibObject objects being built.
   */
  private void processGroupName(
      final String cName,
      final String groupName,
      final int ifType,
      final List<MibObject> mibObjectList) {
    ThreadCategory log = log();

    // Using the collector name retrieve the group map
    final Map<String, Group> groupMap = getCollectionGroupMap(getContainer()).get(cName);

    // Next use the groupName to access the Group object
    final Group group = groupMap.get(groupName);

    // Verify that we have a valid Group object...generate
    // warning message if not...
    if (group == null) {
      log.warn(
          "DataCollectionConfigFactory.processGroupName: unable to retrieve group information for group name '"
              + groupName
              + "': check DataCollection.xml file.");
      return;
    }

    if (log.isDebugEnabled()) {
      log.debug(
          "processGroupName:  processing group: "
              + groupName
              + " groupIfType: "
              + group.getIfType()
              + " ifType: "
              + ifType);
    }

    // Process any sub-groups contained within this group
    for (final String includeGroup : group.getIncludeGroupCollection()) {
      processGroupName(cName, includeGroup, ifType, mibObjectList);
    }

    // Add this group's objects to the object list provided
    // that the group's ifType string does not exclude the
    // provided ifType parm.
    //
    // ifType parm of -1 indicates that only node-level
    // objects are to be added
    //
    // Any other ifType parm value must be compared with
    // the group's ifType value to verify that they match
    // (if group's ifType is "all" then the objects will
    // automatically be added.
    final String ifTypeStr = String.valueOf(ifType);
    String groupIfType = group.getIfType();

    boolean addGroupObjects = false;
    if (ifType == NODE_ATTRIBUTES) {
      if (groupIfType.equals("ignore")) {
        addGroupObjects = true;
      }
    } else {
      if (groupIfType.equals("all")) {
        addGroupObjects = true;
      } else if ("ignore".equals(groupIfType)) {
        // Do nothing
      } else if (ifType == ALL_IF_ATTRIBUTES) {
        addGroupObjects = true;
      } else {
        // First determine if the group's ifType value contains
        // a single type value or a list of values. In the case
        // of a list the ifType values will be delimited by commas.
        boolean isList = false;
        if (groupIfType.indexOf(',') != -1) isList = true;

        // Next compare the provided ifType parameter with the
        // group's ifType value to determine if the group's OIDs
        // should be added to the MIB object list.
        //
        // If the group ifType value is a single value then only
        // a simple comparison is needed to see if there is an
        // exact match.
        //
        // In the case of the group ifType value being a list
        // of ifType values it is more complicated...each comma
        // delimited substring which starts with the provided
        // ifType parm must be extracted and compared until an
        // EXACT match is found..
        if (!isList) {
          if (ifTypeStr.equals(groupIfType)) addGroupObjects = true;
        } else {
          int tmpIndex = groupIfType.indexOf(ifTypeStr);
          while (tmpIndex != -1) {
            groupIfType = groupIfType.substring(tmpIndex);

            // get substring starting at tmpIndex to
            // either the end of the groupIfType string
            // or to the first comma after tmpIndex
            final int nextComma = groupIfType.indexOf(',');

            String parsedType = null;
            if (nextComma == -1) // No comma, this is last type
            // value
            {
              parsedType = groupIfType;
            } else // Found comma
            {
              parsedType = groupIfType.substring(0, nextComma);
            }
            if (ifTypeStr.equals(parsedType)) {
              addGroupObjects = true;
              break;
            }

            // No more commas indicates no more ifType values to
            // compare...we're done
            if (nextComma == -1) break;

            // Get next substring and reset tmpIndex to
            // once again point to the first occurrence of
            // the ifType string parm.
            groupIfType = groupIfType.substring(nextComma + 1);
            tmpIndex = groupIfType.indexOf(ifTypeStr);
          }
        }
      }
    }

    if (addGroupObjects) {
      if (log.isDebugEnabled()) {
        log.debug(
            "processGroupName: OIDs from group '"
                + group.getName()
                + ":"
                + group.getIfType()
                + "' are included for ifType: "
                + ifType);
      }
      processObjectList(groupName, groupIfType, group.getMibObjCollection(), mibObjectList);
    } else {
      if (log.isDebugEnabled())
        log.debug(
            "processGroupName: OIDs from group '"
                + group.getName()
                + ":"
                + group.getIfType()
                + "' are excluded for ifType: "
                + ifType);
    }
  }
Beispiel #7
0
  /**
   * Test to see if the passed host-port pair is the endpoint for an SMTP server. If there is an
   * SMTP server at that destination then a value of true is returned from the method. Otherwise a
   * false value is returned to the caller.
   *
   * @param host The remote host to connect to.
   * @param port The remote port on the host.
   * @return True if server supports SMTP on the specified port, false otherwise
   */
  private boolean isServer(InetAddress host, int port, int retries, int timeout) {
    // get a log to send errors
    //
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    boolean isAServer = false;
    for (int attempts = 0; attempts <= retries && !isAServer; attempts++) {
      Socket socket = null;
      try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(host, port), timeout);
        socket.setSoTimeout(timeout);
        log.debug("SmtpPlugin: connected to host: " + host + " on port: " + port);

        // Allocate a line reader
        //
        BufferedReader lineRdr = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        // Read responses from the server. The initial line should just
        // be a banner, but go ahead and check for multiline response.
        //
        String result = null;
        do {
          result = lineRdr.readLine();

        } while (result != null && result.length() > 0 && MULTILINE_RESULT.match(result));

        if (result == null || result.length() == 0) {
          log.info("Received truncated response from SMTP server " + InetAddressUtils.str(host));
          continue;
        }

        // Tokenize the last line result
        //
        StringTokenizer t = new StringTokenizer(result);
        int rc = Integer.parseInt(t.nextToken());
        if (rc == 220) {
          //
          // Send the HELO command
          //
          String cmd = "HELO " + LOCALHOST_NAME + "\r\n";
          socket.getOutputStream().write(cmd.getBytes());

          // Response from HELO command may be a multi-line response
          // (but
          // most likely will be single-line)..
          // We are expecting to get a response with an integer return
          // code in the first token. We can't ge sure that the first
          // response will give us what we want. Consider the
          // following
          // reponse for example:
          //
          // 250-First line
          // 250-Second line
          // 250 Requested mail action okay, completed
          //
          // In this case the final line of the response contains the
          // return
          // code we are looking for.
          do {
            result = lineRdr.readLine();

          } while (result != null && result.length() > 0 && MULTILINE_RESULT.match(result));

          if (result == null || result.length() == 0) {
            log.info("Received truncated response from SMTP server " + InetAddressUtils.str(host));
            continue;
          }

          t = new StringTokenizer(result);
          rc = Integer.parseInt(t.nextToken());
          if (rc == 250) {
            //
            // Send the QUIT command
            //
            cmd = "QUIT\r\n";
            socket.getOutputStream().write(cmd.getBytes());

            // Response from QUIT command may be a multi-line
            // response.
            // We are expecting to get a response with an integer
            // return
            // code in the first token. We can't ge sure that the
            // first
            // response will give us what we want. Consider the
            // following
            // reponse for example:
            //
            // 221-First line
            // 221-Second line
            // 221 <domain> Service closing transmission channel.
            //
            // In this case the final line of the response contains
            // the return
            // code we are looking for.
            do {
              result = lineRdr.readLine();

            } while (result != null && result.length() > 0 && MULTILINE_RESULT.match(result));

            if (result == null || result.length() == 0) {
              log.info(
                  "Received truncated response from SMTP server " + InetAddressUtils.str(host));
              continue;
            }

            t = new StringTokenizer(result);
            rc = Integer.parseInt(t.nextToken());

            if (rc == 221) isAServer = true;
          }
        }
      } catch (NumberFormatException e) {
        log.info(
            "SmtpPlugin: received invalid result code from server " + InetAddressUtils.str(host),
            e);
        isAServer = false;
      } catch (ConnectException cE) {
        // Connection refused!! Continue to retry.
        //
        log.debug("SmtpPlugin: connection refused to " + InetAddressUtils.str(host) + ":" + port);
        isAServer = false;
      } catch (NoRouteToHostException e) {
        // No route to host!! No need to perform retries.
        e.fillInStackTrace();
        log.info(
            "SmtpPlugin: Unable to test host "
                + InetAddressUtils.str(host)
                + ", no route available",
            e);
        isAServer = false;
        throw new UndeclaredThrowableException(e);
      } catch (InterruptedIOException e) {
        log.debug(
            "SmtpPlugin: did not connect to host within timeout: "
                + timeout
                + " attempt: "
                + attempts);
        isAServer = false;
      } catch (IOException e) {
        log.info("SmtpPlugin: Error communicating with host " + InetAddressUtils.str(host), e);
        isAServer = false;
      } catch (Throwable t) {
        log.warn(
            "SmtpPlugin: Undeclared throwable exception caught contacting host "
                + InetAddressUtils.str(host),
            t);
        isAServer = false;
      } finally {
        try {
          if (socket != null) socket.close();
        } catch (IOException e) {
        }
      }
    }

    //
    // return the success/failure of this
    // attempt to contact an SMTP server.
    //
    return isAServer;
  }
Beispiel #8
0
  /**
   * Test to see if the passed host-port pair is the endpoint for a TCP server. If there is a TCP
   * server at that destination then a value of true is returned from the method. Otherwise a false
   * value is returned to the caller. In order to return true the remote host must generate a banner
   * line which contains the text from the bannerMatch argument.
   *
   * @param host The remote host to connect to.
   * @param port The remote port on the host.
   * @param bannerResult Banner line generated by the remote host must contain this text.
   * @return True if a connection is established with the host and the banner line contains the
   *     bannerMatch text.
   */
  private boolean isServer(
      InetAddress host, int port, int retries, int timeout, RE regex, StringBuffer bannerResult) {
    ThreadCategory log = ThreadCategory.getInstance(getClass());

    boolean isAServer = false;
    for (int attempts = 0; attempts <= retries && !isAServer; attempts++) {
      Socket socket = null;
      try {
        // create a connected socket
        //
        socket = new Socket();
        socket.connect(new InetSocketAddress(host, port), timeout);
        socket.setSoTimeout(timeout);
        log.debug("TcpPlugin: connected to host: " + host + " on port: " + port);

        // If banner matching string is null or wildcard ("*") then we
        // only need to test connectivity and we've got that!
        //
        if (regex == null) {
          isAServer = true;
        } else {
          // get a line reader
          //
          BufferedReader lineRdr =
              new BufferedReader(new InputStreamReader(socket.getInputStream()));

          // Read the server's banner line ouptput and validate it
          // against
          // the bannerMatch parameter to determine if this interface
          // supports the
          // service.
          //
          String response = lineRdr.readLine();
          if (regex.match(response)) {
            if (log.isDebugEnabled()) log.debug("isServer: matching response=" + response);
            isAServer = true;
            if (bannerResult != null) bannerResult.append(response);
          } else {
            // Got a response but it didn't match...no need to
            // attempt retries
            isAServer = false;
            if (log.isDebugEnabled()) log.debug("isServer: NON-matching response=" + response);
            break;
          }
        }
      } catch (ConnectException e) {
        // Connection refused!! Continue to retry.
        //
        log.debug("TcpPlugin: Connection refused to " + InetAddressUtils.str(host) + ":" + port);
        isAServer = false;
      } catch (NoRouteToHostException e) {
        // No Route to host!!!
        //
        e.fillInStackTrace();
        log.info(
            "TcpPlugin: Could not connect to host "
                + InetAddressUtils.str(host)
                + ", no route to host",
            e);
        isAServer = false;
        throw new UndeclaredThrowableException(e);
      } catch (InterruptedIOException e) {
        // This is an expected exception
        //
        log.debug(
            "TcpPlugin: did not connect to host within timeout: "
                + timeout
                + " attempt: "
                + attempts);
        isAServer = false;
      } catch (IOException e) {
        log.info(
            "TcpPlugin: An expected I/O exception occured connecting to host "
                + InetAddressUtils.str(host)
                + " on port "
                + port,
            e);
        isAServer = false;
      } catch (Throwable t) {
        isAServer = false;
        log.warn(
            "TcpPlugin: An undeclared throwable exception was caught connecting to host "
                + InetAddressUtils.str(host)
                + " on port "
                + port,
            t);
      } finally {
        try {
          if (socket != null) socket.close();
        } catch (IOException e) {
        }
      }
    }

    //
    // return the success/failure of this
    // attempt to contact an ftp server.
    //
    return isAServer;
  }