Search in sources :

Example 1 with TransportMapping

use of org.snmp4j.TransportMapping in project opennms by OpenNMS.

the class Snmp4JUtils method convertPduToBytes.

/**
 * @param address
 * @param port
 * @param community
 * @param pdu
 *
 * @return Byte array representing the {@link PDU} in either SNMPv1 or SNMPv2
 * format, depending on the type of the {@link PDU} object.
 */
public static byte[] convertPduToBytes(InetAddress address, int port, String community, PDU pdu) throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicReference<byte[]> bytes = new AtomicReference<>();
    // IP address is optional when using the DummyTransport because
    // all requests are sent to the {@link DummyTransportResponder}
    final DummyTransport<IpAddress> transport = new DummyTransport<IpAddress>(null);
    final AbstractTransportMapping<IpAddress> responder = transport.getResponder(null);
    // Add a DummyTransportResponder listener that will receive the raw bytes of the PDU
    responder.addTransportListener(new TransportListener() {

        @Override
        public void processMessage(TransportMapping transport, Address address, ByteBuffer byteBuffer, TransportStateReference state) {
            byteBuffer.rewind();
            final byte[] byteArray = new byte[byteBuffer.remaining()];
            byteBuffer.get(byteArray);
            bytes.set(byteArray);
            byteBuffer.rewind();
            latch.countDown();
        }
    });
    // Create our own MessageDispatcher since we don't need to do all
    // of the crypto operations necessary to initialize SNMPv3 which is slow
    MessageDispatcher dispatcher = new MessageDispatcherImpl();
    dispatcher.addMessageProcessingModel(new MPv1());
    dispatcher.addMessageProcessingModel(new MPv2c());
    final Snmp snmp = new Snmp(dispatcher, responder);
    Snmp4JStrategy.trackSession(snmp);
    try {
        snmp.listen();
        CommunityTarget target = new CommunityTarget();
        target.setCommunity(new OctetString(community));
        if (pdu instanceof PDUv1) {
            target.setVersion(SnmpConstants.version1);
        } else {
            target.setVersion(SnmpConstants.version2c);
        }
        target.setAddress(Snmp4JAgentConfig.convertAddress(address, port));
        snmp.send(pdu, target, transport);
        latch.await();
        return bytes.get();
    } finally {
        try {
            snmp.close();
        } catch (final IOException e) {
            LOG.error("failed to close SNMP session", e);
        } finally {
            Snmp4JStrategy.reapSession(snmp);
        }
    }
}
Also used : OctetString(org.snmp4j.smi.OctetString) Address(org.snmp4j.smi.Address) IpAddress(org.snmp4j.smi.IpAddress) InetAddress(java.net.InetAddress) TransportMapping(org.snmp4j.TransportMapping) AbstractTransportMapping(org.snmp4j.transport.AbstractTransportMapping) MPv2c(org.snmp4j.mp.MPv2c) AtomicReference(java.util.concurrent.atomic.AtomicReference) MessageDispatcherImpl(org.snmp4j.MessageDispatcherImpl) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) TransportListener(org.snmp4j.transport.TransportListener) MessageDispatcher(org.snmp4j.MessageDispatcher) TransportStateReference(org.snmp4j.TransportStateReference) Snmp(org.snmp4j.Snmp) IpAddress(org.snmp4j.smi.IpAddress) MPv1(org.snmp4j.mp.MPv1) DummyTransport(org.snmp4j.transport.DummyTransport) PDUv1(org.snmp4j.PDUv1) CommunityTarget(org.snmp4j.CommunityTarget)

Example 2 with TransportMapping

use of org.snmp4j.TransportMapping in project Payara by payara.

the class SnmpNotifierService method bootstrap.

@Override
public void bootstrap() {
    register(NotifierType.SNMP, SnmpNotifier.class, SnmpNotifierConfiguration.class, this);
    execOptions = (SnmpNotifierConfigurationExecutionOptions) getNotifierConfigurationExecutionOptions();
    if (execOptions != null && execOptions.isEnabled()) {
        try {
            TransportMapping transport = new DefaultUdpTransportMapping();
            snmp = new Snmp(transport);
            CommunityTarget cTarget = new CommunityTarget();
            cTarget.setCommunity(new OctetString(execOptions.getCommunity()));
            int snmpVersion = decideOnSnmpVersion(execOptions.getVersion());
            cTarget.setVersion(snmpVersion);
            cTarget.setAddress(new UdpAddress(execOptions.getHost() + ADDRESS_SEPARATOR + execOptions.getPort()));
            initializeExecutor();
            scheduledFuture = scheduleExecutor(new SnmpNotificationRunnable(queue, execOptions, snmp, cTarget, snmpVersion));
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Error occurred while creating UDP transport", e);
        } catch (InvalidSnmpVersion invalidSnmpVersion) {
            logger.log(Level.SEVERE, "Error occurred while configuring SNMP version: " + invalidSnmpVersion.getMessage());
        }
    }
}
Also used : InvalidSnmpVersion(fish.payara.notification.snmp.exception.InvalidSnmpVersion) TransportMapping(org.snmp4j.TransportMapping) DefaultUdpTransportMapping(org.snmp4j.transport.DefaultUdpTransportMapping) Snmp(org.snmp4j.Snmp) DefaultUdpTransportMapping(org.snmp4j.transport.DefaultUdpTransportMapping) IOException(java.io.IOException) CommunityTarget(org.snmp4j.CommunityTarget)

Example 3 with TransportMapping

use of org.snmp4j.TransportMapping in project Payara by payara.

the class TestSnmpNotifier method execute.

@Override
public void execute(AdminCommandContext context) {
    ActionReport actionReport = context.getActionReport();
    Config config = targetUtil.getConfig(target);
    if (config == null) {
        context.getActionReport().setMessage("No such config named: " + target);
        context.getActionReport().setActionExitCode(ActionReport.ExitCode.FAILURE);
        return;
    }
    SnmpNotifierConfiguration snmpConfig = config.getExtensionByType(SnmpNotifierConfiguration.class);
    if (community == null) {
        community = snmpConfig.getCommunity();
    }
    if (oid == null) {
        oid = snmpConfig.getOid();
    }
    if (version == null) {
        version = snmpConfig.getVersion();
    }
    if (hostName == null) {
        hostName = snmpConfig.getHost();
    }
    if (port == null) {
        port = snmpConfig.hashCode();
    }
    // prepare SNMP message
    SnmpNotificationEvent event = factory.buildNotificationEvent(SUBJECT, MESSAGE);
    SnmpMessageQueue queue = new SnmpMessageQueue();
    queue.addMessage(new SnmpMessage(event, event.getSubject(), event.getMessage()));
    SnmpNotifierConfigurationExecutionOptions options = new SnmpNotifierConfigurationExecutionOptions();
    options.setCommunity(community);
    options.setOid(oid);
    options.setVersion(version);
    options.setHost(hostName);
    options.setPort(port);
    SnmpNotificationRunnable notifierRun = null;
    try {
        TransportMapping transport = new DefaultUdpTransportMapping();
        Snmp snmp = new Snmp(transport);
        CommunityTarget cTarget = new CommunityTarget();
        cTarget.setCommunity(new OctetString(options.getCommunity()));
        int snmpVersion = SnmpNotifierService.decideOnSnmpVersion(options.getVersion());
        cTarget.setVersion(snmpVersion);
        cTarget.setAddress(new UdpAddress(options.getHost() + SnmpNotifierService.ADDRESS_SEPARATOR + options.getPort()));
        notifierRun = new SnmpNotificationRunnable(queue, options, snmp, cTarget, snmpVersion);
    } catch (IOException e) {
        Logger.getLogger(TestSnmpNotifier.class.getCanonicalName()).log(Level.SEVERE, "Error occurred while creating UDP transport", e);
        actionReport.setMessage("Error occurred while creating UDP transport");
        actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
    } catch (InvalidSnmpVersion invalidSnmpVersion) {
        Logger.getLogger(TestSnmpNotifier.class.getCanonicalName()).log(Level.SEVERE, "Error occurred while configuring SNMP version: " + invalidSnmpVersion.getMessage());
        actionReport.setMessage("Error occurred while configuring SNMP version: " + invalidSnmpVersion.getMessage());
        actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
    }
    // set up logger to store result
    Logger logger = Logger.getLogger(SnmpNotificationRunnable.class.getCanonicalName());
    BlockingQueueHandler bqh = new BlockingQueueHandler(10);
    bqh.setLevel(Level.FINE);
    Level oldLevel = logger.getLevel();
    logger.setLevel(Level.FINE);
    logger.addHandler(bqh);
    // send message, this occurs in its own thread
    Thread notifierThread = new Thread(notifierRun, "test-snmp-notifier-thread");
    notifierThread.start();
    try {
        notifierThread.join();
    } catch (InterruptedException ex) {
        Logger.getLogger(TestSnmpNotifier.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        logger.setLevel(oldLevel);
    }
    LogRecord message = bqh.poll();
    bqh.clear();
    if (message == null) {
        // something's gone wrong
        Logger.getLogger(TestSnmpNotifier.class.getName()).log(Level.SEVERE, "Failed to send SNMP message");
        actionReport.setMessage("Failed to send SNMP message");
        actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
    } else {
        actionReport.setMessage(message.getMessage());
        if (message.getLevel() == Level.FINE) {
            actionReport.setActionExitCode(ActionReport.ExitCode.SUCCESS);
        } else {
            actionReport.setActionExitCode(ActionReport.ExitCode.FAILURE);
        }
    }
}
Also used : OctetString(org.snmp4j.smi.OctetString) UdpAddress(org.snmp4j.smi.UdpAddress) Config(com.sun.enterprise.config.serverbeans.Config) TransportMapping(org.snmp4j.TransportMapping) DefaultUdpTransportMapping(org.snmp4j.transport.DefaultUdpTransportMapping) DefaultUdpTransportMapping(org.snmp4j.transport.DefaultUdpTransportMapping) IOException(java.io.IOException) ActionReport(org.glassfish.api.ActionReport) Logger(java.util.logging.Logger) RestEndpoint(org.glassfish.api.admin.RestEndpoint) InvalidSnmpVersion(fish.payara.notification.snmp.exception.InvalidSnmpVersion) BlockingQueueHandler(fish.payara.nucleus.notification.BlockingQueueHandler) LogRecord(java.util.logging.LogRecord) Snmp(org.snmp4j.Snmp) Level(java.util.logging.Level) CommunityTarget(org.snmp4j.CommunityTarget)

Example 4 with TransportMapping

use of org.snmp4j.TransportMapping in project wso2-synapse by wso2.

the class SNMPAgent method initTransportMappings.

@Override
protected void initTransportMappings() throws IOException {
    String host = getProperty(SNMPConstants.SNMP_HOST, SNMPConstants.SNMP_DEFAULT_HOST);
    int port = Integer.parseInt(getProperty(SNMPConstants.SNMP_PORT, String.valueOf(SNMPConstants.SNMP_DEFAULT_PORT)));
    String address = host + "/" + port;
    Address adr = GenericAddress.parse(address);
    TransportMapping tm = TransportMappings.getInstance().createTransportMapping(adr);
    transportMappings = new TransportMapping[] { tm };
    log.info("SNMP transport adapter initialized on udp:" + address);
}
Also used : TransportMapping(org.snmp4j.TransportMapping)

Example 5 with TransportMapping

use of org.snmp4j.TransportMapping in project mysql_perf_analyzer by yahoo.

the class SNMPClient method start.

/**
 * Start the Snmp session. If you forget the listen() method you will not
 * get any answers because the communication is asynchronous
 * and the listen() method listens for answers.
 * @throws IOException
 */
public void start() throws IOException {
    TransportMapping transport = new DefaultUdpTransportMapping();
    snmp = new Snmp(transport);
    if (// add v3 support
    "3".equals(this.version)) {
        USM usm = new USM(SecurityProtocols.getInstance(), new OctetString(MPv3.createLocalEngineID()), 0);
        SecurityModels.getInstance().addSecurityModel(usm);
    }
    // Do not forget this line!
    transport.listen();
}
Also used : OctetString(org.snmp4j.smi.OctetString) TransportMapping(org.snmp4j.TransportMapping) DefaultUdpTransportMapping(org.snmp4j.transport.DefaultUdpTransportMapping) Snmp(org.snmp4j.Snmp) DefaultUdpTransportMapping(org.snmp4j.transport.DefaultUdpTransportMapping) USM(org.snmp4j.security.USM)

Aggregations

TransportMapping (org.snmp4j.TransportMapping)8 Snmp (org.snmp4j.Snmp)7 CommunityTarget (org.snmp4j.CommunityTarget)6 DefaultUdpTransportMapping (org.snmp4j.transport.DefaultUdpTransportMapping)6 IOException (java.io.IOException)5 OctetString (org.snmp4j.smi.OctetString)4 InvalidSnmpVersion (fish.payara.notification.snmp.exception.InvalidSnmpVersion)2 LinkedList (java.util.LinkedList)2 PDUv1 (org.snmp4j.PDUv1)2 ResponseEvent (org.snmp4j.event.ResponseEvent)2 USM (org.snmp4j.security.USM)2 UdpAddress (org.snmp4j.smi.UdpAddress)2 Config (com.sun.enterprise.config.serverbeans.Config)1 BlockingQueueHandler (fish.payara.nucleus.notification.BlockingQueueHandler)1 InetAddress (java.net.InetAddress)1 ByteBuffer (java.nio.ByteBuffer)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 Level (java.util.logging.Level)1 LogRecord (java.util.logging.LogRecord)1