alshabib

initial import

Change-Id: Ief25aef0066ea96bd2c329ccef974c072b3a5a73
Showing 170 changed files with 3939 additions and 0 deletions
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ Copyright (c) 2014 Hewlett-Packard Development Company, L.P.
~
~ This program and the accompanying materials are made available under the
~ terms of the Eclipse Public License v1.0 which accompanies this distribution,
~ and is available at http://www.eclipse.org/legal/epl-v10.html
-->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0"
name="net.onrc.onos-1.0.0">
<repository>mvn:net.onrc.onos/onos-features/1.0.0-SNAPSHOT/xml/features</repository>
<feature name="thirdparty" version="1.0.0"
description="ONOS 3rd party dependencies">
<bundle>mvn:com.google.code.findbugs/annotations/2.0.2</bundle>
<bundle>mvn:io.netty/netty/3.9.2.Final</bundle>
<bundle>mvn:com.google.guava/guava/17.0</bundle>
<bundle>mvn:com.google.guava/guava/15.0</bundle>
</feature>
<feature name="base" version="1.0.0"
description="ONOS Base">
<feature>scr</feature>
<feature>thirdparty</feature>
<bundle>mvn:net.onrc.onos.sb/onos-sb/0.0.1</bundle>
<bundle>mvn:org.projectfloodlight/openflowj/0.3.6-SNAPSHOT</bundle>
</feature>
</features>
package net.onrc.onos.api;
/**
* Base abstraction of a piece of information about network elements.
*/
public interface Description {
}
package net.onrc.onos.api;
import java.net.URI;
/**
* Immutable representaion of a device identity.
*/
public class DeviceId {
private final URI uri;
public DeviceId(URI uri) {
this.uri = uri;
}
/**
* Returns the backing URI.
*
* @return backing device URI
*/
public URI uri() {
return uri;
}
}
package net.onrc.onos.api;
/**
* Representation of a port number.
*/
public interface PortNumber {
}
package net.onrc.onos.api;
/**
* Abstraction of a provider of information about network environment.
*/
public interface Provider {
ProviderId id();
}
package net.onrc.onos.api;
/**
* Broker used for registering/unregistering information providers with the core.
*
* @param <T> type of the information provider
* @param <S> type of the provider service
*/
public interface ProviderBroker<T extends Provider, S extends ProviderService> {
/**
* Registers the supplied provider with the core.
*
* @param provider provider to be registered
* @return provider service for injecting information into core
*/
S register(T provider);
/**
* Unregisters the supplied provider. As a result the previously issued
* provider service will be invalidated.
*
* @param provider provider to be unregistered
*/
void unregister(T provider);
}
package net.onrc.onos.api;
/**
* Notion of provider identity.
*/
public class ProviderId {
private final String id;
public ProviderId(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ProviderId that = (ProviderId) o;
if (!id.equals(that.id)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public String toString() {
return "ProviderId{" +
"id='" + id + '\'' +
'}';
}
}
package net.onrc.onos.api;
/**
* Abstraction of a service through which providers can inject information
* about the network environment into the core.
*/
public interface ProviderService {
}
package net.onrc.onos.api.device;
import net.onrc.onos.api.Description;
import java.net.URI;
/**
* Carrier of immutable information about a device.
*/
public interface DeviceDescription extends Description {
/**
* Protocol/provider specific URI that can be used to encode the identity
* information required to communicate with the device externally, e.g.
* datapath ID.
*
* @return provider specific URI for the device
*/
URI deviceURI();
}
\ No newline at end of file
package net.onrc.onos.api.device;
import net.onrc.onos.api.Provider;
/**
* Abstraction of a device information provider.
*/
public interface DeviceProvider extends Provider {
}
package net.onrc.onos.api.device;
import net.onrc.onos.api.ProviderBroker;
/**
* Abstraction of a device provider brokerage.
*/
public interface DeviceProviderBroker
extends ProviderBroker<DeviceProvider, DeviceProviderService> {
}
package net.onrc.onos.api.device;
import net.onrc.onos.api.ProviderService;
import java.util.List;
/**
* Service through which device providers can inject device information into
* the core.
*/
public interface DeviceProviderService extends ProviderService {
// TODO: define suspend and remove actions on the mezzanine administrative API
/**
* Signals the core that a device has connected or has been detected somehow.
*
* @param deviceDescription information about network device
*/
void deviceConnected(DeviceDescription deviceDescription);
/**
* Signals the core that a device has disconnected or is no longer reachable.
*
* @param deviceDescription device to be removed
*/
void deviceDisconnected(DeviceDescription deviceDescription);
/**
* Sends information about all ports of a device. It is up to the core to
* determine what has changed.
*
* @param ports list of device ports
*/
void updatePorts(List<PortDescription> ports);
/**
* Used to notify the core about port status change of a single port.
*
* @param port description of the port that changed
*/
void portStatusChanged(PortDescription port);
}
package net.onrc.onos.api.device;
/**
* Information about a port.
*/
public interface PortDescription {
// TODO: possibly relocate this to a common ground so that this can also used by host tracking if required
}
package net.onrc.onos.api.host;
/**
* Information describing host and its location.
*/
public interface HostDescription {
// IP, MAC, VLAN-ID, HostLocation -> (ConnectionPoint + timestamp)
}
package net.onrc.onos.api.host;
import net.onrc.onos.api.Provider;
/**
* Provider of information about hosts and their location on the network.
*/
public interface HostProvider extends Provider {
}
package net.onrc.onos.api.host;
import net.onrc.onos.api.ProviderBroker;
/**
* Abstraction of a host provider brokerage.
*/
public interface HostProviderBroker
extends ProviderBroker<HostProvider, HostProviderService> {
}
package net.onrc.onos.api.host;
import net.onrc.onos.api.ProviderService;
/**
* Means of conveying host information to the core.
*/
public interface HostProviderService extends ProviderService {
void hostDetected(HostDescription hostDescription);
}
package net.onrc.onos.api.link;
/**
* Describes an infrastructure link.
*/
public interface LinkDescription {
// TODO: src, dst connection points, which are pairs of (DeviceId, PortNumber)
// On the north:
// Link = (ConnectPoint src, ConnectPoint dst);
// ConnectPoint = (DeviceId, PortNumber);
// On the south
// LinkDescription ~ Link
}
package net.onrc.onos.api.link;
import net.onrc.onos.api.Provider;
/**
* Abstraction of an entity providing information about infrastructure links
* to the core.
*/
public interface LinkProvider extends Provider {
}
package net.onrc.onos.api.link;
import net.onrc.onos.api.ProviderBroker;
/**
* Abstraction of an infrastructure link provider brokerage.
*/
public interface LinkProviderBroker
extends ProviderBroker<LinkProvider, LinkProviderService> {
}
package net.onrc.onos.api.link;
import net.onrc.onos.api.ProviderService;
/**
* Means for injecting link information into the core.
*/
public interface LinkProviderService extends ProviderService {
/**
* Signals that an infrastructure link has been connected.
*
* @param linkDescription link information
*/
void linkConnected(LinkDescription linkDescription);
/**
* Signals that an infrastructure link has been disconnected.
*
* @param linkDescription link information
*/
void linkDisconnected(LinkDescription linkDescription);
}
# See: http://rolf-engelhard.de/2011/04/using-the-same-suppression-filter-for-checkstyle-in-eclipse-and-maven/
config_loc=conf/checkstyle
This diff is collapsed. Click to expand it.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suppressions PUBLIC "-//Puppy Crawl//DTD Suppressions 1.1//EN" "http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<!--
Note: Exclusion definition exists in multiple places.
- In file ${findbugs.excludeFilterFile} defined at top of pom.xml
- In file conf/checkstyle/onos_suppressions.xml (this file)
- maven-pmd-plugin configuration in pom.xml
(under build and reporting)
-->
<suppress files=".*" checks="FinalParametersCheck"/>
<suppress files=".*" checks="MagicNumbersCheck"/>
<suppress files=".*" checks="DesignForExtensionCheck"/>
<suppress files=".*" checks="TodoCommentCheck"/>
<suppress files=".*" checks="AvoidInlineConditionalsCheck"/>
<suppress files=".*" checks="OperatorWrapCheck"/>
</suppressions>
<FindBugsFilter>
<!--
Note: Exclusion definition exists in multiple places.
- In file ${findbugs.excludeFilterFile} defined at top of pom.xml (this file)
- In file conf/checkstyle/onos_suppressions.xml
- maven-pmd-plugin configuration in pom.xml
(under build and reporting)
-->
<Match>
<Class name="~net\.onrc\.onos\.core\.datastore\.serializers\..*" />
</Match>
<Match>
<Class name="~.*edu\.stanford\..*"/>
</Match>
<Match>
<Class name="~.org\.projectfloodlight\..*"/>
</Match>
</FindBugsFilter>
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
package net.onrc.onos.of.ctl;
import org.projectfloodlight.openflow.protocol.OFVersion;
import net.onrc.onos.of.ctl.registry.IControllerRegistry;
/**
* Interface to passed to controller class in order to allow
* it to spawn the appropriate type of switch and furthermore
* specify a registry object (ie. ZooKeeper).
*
*/
public interface IOFSwitchManager {
/**
* Given a description string for a switch spawn the
* concrete representation of that switch.
*
* @param mfr manufacturer description
* @param hwDesc hardware description
* @param swDesc software description
* @param ofv openflow version
* @return A switch of type IOFSwitch.
*/
public IOFSwitch getSwitchImpl(String mfr, String hwDesc, String swDesc, OFVersion ofv);
/**
* Returns the mastership registry used during controller-switch role election.
* @return the registry
*/
public IControllerRegistry getRegistry();
}
package net.onrc.onos.of.ctl;
import org.projectfloodlight.openflow.protocol.OFControllerRole;
/**
* The role of the controller as it pertains to a particular switch.
* Note that this definition of the role enum is different from the
* OF1.3 definition. It is maintained here to be backward compatible to
* earlier versions of the controller code. This enum is translated
* to the OF1.3 enum, before role messages are sent to the switch.
* See sendRoleRequestMessage method in OFSwitchImpl
*/
public enum Role {
EQUAL(OFControllerRole.ROLE_EQUAL),
MASTER(OFControllerRole.ROLE_MASTER),
SLAVE(OFControllerRole.ROLE_SLAVE);
private Role(OFControllerRole nxRole) {
nxRole.ordinal();
}
/*
private static Map<Integer,Role> nxRoleToEnum
= new HashMap<Integer,Role>();
static {
for(Role r: Role.values())
nxRoleToEnum.put(r.toNxRole(), r);
}
public int toNxRole() {
return nxRole;
}
// Return the enum representing the given nxRole or null if no
// such role exists
public static Role fromNxRole(int nxRole) {
return nxRoleToEnum.get(nxRole);
}*/
}
/**
* Copyright 2012, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Annotation used to set the category for log messages for a class.
*
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface LogMessageCategory {
/**
* The category for the log messages for this class.
*
* @return
*/
String value() default "Core";
}
/**
* Copyright 2012, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Annotation used to document log messages. This can be used to generate
* documentation on syslog output.
*
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface LogMessageDoc {
public static final String NO_ACTION = "No action is required.";
public static final String UNKNOWN_ERROR = "An unknown error occured";
public static final String GENERIC_ACTION =
"Examine the returned error or exception and take " +
"appropriate action.";
public static final String CHECK_SWITCH =
"Check the health of the indicated switch. " +
"Test and troubleshoot IP connectivity.";
public static final String CHECK_CONTROLLER =
"Verify controller system health, CPU usage, and memory. " +
"Rebooting the controller node may help if the controller " +
"node is in a distressed state.";
public static final String REPORT_CONTROLLER_BUG =
"This is likely a defect in the controller. Please report this " +
"issue. Restarting the controller or switch may help to " +
"alleviate.";
public static final String REPORT_SWITCH_BUG =
"This is likely a defect in the switch. Please report this " +
"issue. Restarting the controller or switch may help to " +
"alleviate.";
/**
* The log level for the log message.
*
* @return the log level as a tring
*/
String level() default "INFO";
/**
* The message that will be printed.
*
* @return the message
*/
String message() default UNKNOWN_ERROR;
/**
* An explanation of the meaning of the log message.
*
* @return the explanation
*/
String explanation() default UNKNOWN_ERROR;
/**
* The recommendated action associated with the log message.
*
* @return the recommendation
*/
String recommendation() default NO_ACTION;
}
/**
* Copyright 2012, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
/**
* Annotation used to document log messages. This can be used to generate
* documentation on syslog output. This version allows multiple log messages
* to be documentated on an interface.
*
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
public @interface LogMessageDocs {
/**
* A list of {@link LogMessageDoc} elements.
*
* @return the list of log message doc
*/
LogMessageDoc[] value();
}
package net.onrc.onos.of.ctl.debugcounter;
public interface IDebugCounter {
/**
* Increments the counter by 1 thread-locally, and immediately flushes to
* the global counter storage. This method should be used for counters that
* are updated outside the OF message processing pipeline.
*/
void updateCounterWithFlush();
/**
* Increments the counter by 1 thread-locally. Flushing to the global
* counter storage is delayed (happens with flushCounters() in IDebugCounterService),
* resulting in higher performance. This method should be used for counters
* updated in the OF message processing pipeline.
*/
void updateCounterNoFlush();
/**
* Increments the counter thread-locally by the 'incr' specified, and immediately
* flushes to the global counter storage. This method should be used for counters
* that are updated outside the OF message processing pipeline.
*/
void updateCounterWithFlush(int incr);
/**
* Increments the counter thread-locally by the 'incr' specified. Flushing to the global
* counter storage is delayed (happens with flushCounters() in IDebugCounterService),
* resulting in higher performance. This method should be used for counters
* updated in the OF message processing pipeline.
*/
void updateCounterNoFlush(int incr);
/**
* Retrieve the value of the counter from the global counter store.
*/
long getCounterValue();
}
package net.onrc.onos.of.ctl.debugcounter;
import java.util.Collections;
import java.util.List;
import net.onrc.onos.of.ctl.debugcounter.DebugCounter.DebugCounterInfo;
public class NullDebugCounter implements IDebugCounterService {
@Override
public void flushCounters() {
}
@Override
public void resetAllCounters() {
}
@Override
public void resetAllModuleCounters(String moduleName) {
}
@Override
public void resetCounterHierarchy(String moduleName, String counterHierarchy) {
}
@Override
public void enableCtrOnDemand(String moduleName, String counterHierarchy) {
}
@Override
public void disableCtrOnDemand(String moduleName, String counterHierarchy) {
}
@Override
public List<DebugCounterInfo> getCounterHierarchy(String moduleName,
String counterHierarchy) {
return Collections.emptyList();
}
@Override
public List<DebugCounterInfo> getAllCounterValues() {
return Collections.emptyList();
}
@Override
public List<DebugCounterInfo> getModuleCounterValues(String moduleName) {
return Collections.emptyList();
}
@Override
public boolean containsModuleCounterHierarchy(String moduleName,
String counterHierarchy) {
return false;
}
@Override
public boolean containsModuleName(String moduleName) {
return false;
}
@Override
public
IDebugCounter
registerCounter(String moduleName, String counterHierarchy,
String counterDescription,
CounterType counterType, String... metaData)
throws MaxCountersRegistered {
return new NullCounterImpl();
}
@Override
public List<String> getModuleList() {
return Collections.emptyList();
}
@Override
public List<String> getModuleCounterList(String moduleName) {
return Collections.emptyList();
}
public static class NullCounterImpl implements IDebugCounter {
@Override
public void updateCounterWithFlush() {
}
@Override
public void updateCounterNoFlush() {
}
@Override
public void updateCounterWithFlush(int incr) {
}
@Override
public void updateCounterNoFlush(int incr) {
}
@Override
public long getCounterValue() {
return -1;
}
}
}
/**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.internal;
/**
* Exception is thrown when the handshake fails to complete.
* before a specified time
*
*/
public class HandshakeTimeoutException extends Exception {
private static final long serialVersionUID = 6859880268940337312L;
}
/**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.internal;
import java.util.concurrent.TimeUnit;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.Timer;
import org.jboss.netty.util.TimerTask;
/**
* Trigger a timeout if a switch fails to complete handshake soon enough.
*/
public class HandshakeTimeoutHandler
extends SimpleChannelUpstreamHandler {
static final HandshakeTimeoutException EXCEPTION =
new HandshakeTimeoutException();
final OFChannelHandler channelHandler;
final Timer timer;
final long timeoutNanos;
volatile Timeout timeout;
public HandshakeTimeoutHandler(OFChannelHandler channelHandler,
Timer timer,
long timeoutSeconds) {
super();
this.channelHandler = channelHandler;
this.timer = timer;
this.timeoutNanos = TimeUnit.SECONDS.toNanos(timeoutSeconds);
}
@Override
public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
if (timeoutNanos > 0) {
timeout = timer.newTimeout(new HandshakeTimeoutTask(ctx),
timeoutNanos, TimeUnit.NANOSECONDS);
}
ctx.sendUpstream(e);
}
@Override
public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e)
throws Exception {
if (timeout != null) {
timeout.cancel();
timeout = null;
}
}
private final class HandshakeTimeoutTask implements TimerTask {
private final ChannelHandlerContext ctx;
HandshakeTimeoutTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@Override
public void run(Timeout t) throws Exception {
if (t.isCancelled()) {
return;
}
if (!ctx.getChannel().isOpen()) {
return;
}
if (!channelHandler.isHandshakeComplete()) {
Channels.fireExceptionCaught(ctx, EXCEPTION);
}
}
}
}
/**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.internal;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;
import org.projectfloodlight.openflow.protocol.OFFactories;
import org.projectfloodlight.openflow.protocol.OFMessage;
import org.projectfloodlight.openflow.protocol.OFMessageReader;
/**
* Decode an openflow message from a Channel, for use in a netty pipeline.
*/
public class OFMessageDecoder extends FrameDecoder {
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
ChannelBuffer buffer) throws Exception {
if (!channel.isConnected()) {
// In testing, I see decode being called AFTER decode last.
// This check avoids that from reading corrupted frames
return null;
}
// Note that a single call to decode results in reading a single
// OFMessage from the channel buffer, which is passed on to, and processed
// by, the controller (in OFChannelHandler).
// This is different from earlier behavior (with the original openflowj),
// where we parsed all the messages in the buffer, before passing on
// a list of the parsed messages to the controller.
// The performance *may or may not* not be as good as before.
OFMessageReader<OFMessage> reader = OFFactories.getGenericReader();
OFMessage message = reader.readFrom(buffer);
return message;
}
}
/**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.internal;
import java.util.List;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import org.projectfloodlight.openflow.protocol.OFMessage;
/**
* Encode an openflow message for output into a ChannelBuffer, for use in a
* netty pipeline.
*/
public class OFMessageEncoder extends OneToOneEncoder {
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel,
Object msg) throws Exception {
if (!(msg instanceof List)) {
return msg;
}
@SuppressWarnings("unchecked")
List<OFMessage> msglist = (List<OFMessage>) msg;
/* XXX S can't get length of OFMessage in loxigen's openflowj??
int size = 0;
for (OFMessage ofm : msglist) {
size += ofm.getLengthU();
}*/
ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
for (OFMessage ofm : msglist) {
ofm.writeTo(buf);
}
return buf;
}
}
/**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.internal;
import java.util.concurrent.ThreadPoolExecutor;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.handler.execution.ExecutionHandler;
import org.jboss.netty.handler.timeout.IdleStateHandler;
import org.jboss.netty.handler.timeout.ReadTimeoutHandler;
import org.jboss.netty.util.ExternalResourceReleasable;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timer;
/**
* Creates a ChannelPipeline for a server-side openflow channel.
*/
public class OpenflowPipelineFactory
implements ChannelPipelineFactory, ExternalResourceReleasable {
protected Controller controller;
protected ThreadPoolExecutor pipelineExecutor;
protected Timer timer;
protected IdleStateHandler idleHandler;
protected ReadTimeoutHandler readTimeoutHandler;
public OpenflowPipelineFactory(Controller controller,
ThreadPoolExecutor pipelineExecutor) {
super();
this.controller = controller;
this.pipelineExecutor = pipelineExecutor;
this.timer = new HashedWheelTimer();
this.idleHandler = new IdleStateHandler(timer, 20, 25, 0);
this.readTimeoutHandler = new ReadTimeoutHandler(timer, 30);
}
@Override
public ChannelPipeline getPipeline() throws Exception {
OFChannelHandler handler = new OFChannelHandler(controller);
ChannelPipeline pipeline = Channels.pipeline();
pipeline.addLast("ofmessagedecoder", new OFMessageDecoder());
pipeline.addLast("ofmessageencoder", new OFMessageEncoder());
pipeline.addLast("idle", idleHandler);
pipeline.addLast("timeout", readTimeoutHandler);
// XXX S ONOS: was 15 increased it to fix Issue #296
pipeline.addLast("handshaketimeout",
new HandshakeTimeoutHandler(handler, timer, 60));
if (pipelineExecutor != null) {
pipeline.addLast("pipelineExecutor",
new ExecutionHandler(pipelineExecutor));
}
pipeline.addLast("handler", handler);
return pipeline;
}
@Override
public void releaseExternalResources() {
timer.stop();
}
}
package net.onrc.onos.of.ctl.internal;
/**
* Thrown when IOFSwitch.startDriverHandshake() is called more than once.
*
*/
public class SwitchDriverSubHandshakeAlreadyStarted extends
SwitchDriverSubHandshakeException {
private static final long serialVersionUID = -5491845708752443501L;
public SwitchDriverSubHandshakeAlreadyStarted() {
super();
}
}
package net.onrc.onos.of.ctl.internal;
import org.projectfloodlight.openflow.protocol.OFMessage;
/**
* Indicates that a message was passed to a switch driver's subhandshake
* handling code but the driver has already completed the sub-handshake.
*
*/
public class SwitchDriverSubHandshakeCompleted
extends SwitchDriverSubHandshakeException {
private static final long serialVersionUID = -8817822245846375995L;
public SwitchDriverSubHandshakeCompleted(OFMessage m) {
super("Sub-Handshake is already complete but received message "
+ m.getType());
}
}
package net.onrc.onos.of.ctl.internal;
/**
* Base class for exception thrown by switch driver sub-handshake processing.
*
*/
public class SwitchDriverSubHandshakeException extends RuntimeException {
private static final long serialVersionUID = -6257836781419604438L;
protected SwitchDriverSubHandshakeException() {
super();
}
protected SwitchDriverSubHandshakeException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
protected SwitchDriverSubHandshakeException(String arg0) {
super(arg0);
}
protected SwitchDriverSubHandshakeException(Throwable arg0) {
super(arg0);
}
}
package net.onrc.onos.of.ctl.internal;
/**
* Thrown when a switch driver's sub-handshake has not been started but an
* operation requiring the sub-handshake has been attempted.
*
*/
public class SwitchDriverSubHandshakeNotStarted extends
SwitchDriverSubHandshakeException {
private static final long serialVersionUID = -5491845708752443501L;
public SwitchDriverSubHandshakeNotStarted() {
super();
}
}
package net.onrc.onos.of.ctl.internal;
/**
* Thrown when a switch driver's sub-handshake state-machine receives an
* unexpected OFMessage and/or is in an invald state.
*
*/
public class SwitchDriverSubHandshakeStateException extends
SwitchDriverSubHandshakeException {
private static final long serialVersionUID = -8249926069195147051L;
public SwitchDriverSubHandshakeStateException(String msg) {
super(msg);
}
}
/**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.internal;
/**
* This exception indicates an error or unexpected message during
* message handling. E.g., if an OFMessage is received that is illegal or
* unexpected given the current handshake state.
*
* We don't allow wrapping other exception in a switch state exception. We
* only log the SwitchStateExceptions message so the causing exceptions
* stack trace is generally not available.
*
*/
public class SwitchStateException extends Exception {
private static final long serialVersionUID = 9153954512470002631L;
public SwitchStateException() {
super();
}
public SwitchStateException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public SwitchStateException(String arg0) {
super(arg0);
}
public SwitchStateException(Throwable arg0) {
super(arg0);
}
}
package net.onrc.onos.of.ctl.registry;
public class ControllerRegistryEntry implements Comparable<ControllerRegistryEntry> {
//
// TODO: Refactor the implementation and decide whether controllerId
// is needed. If "yes", we might need to consider it inside the
// compareTo(), equals() and hashCode() implementations.
//
private final String controllerId;
private final int sequenceNumber;
public ControllerRegistryEntry(String controllerId, int sequenceNumber) {
this.controllerId = controllerId;
this.sequenceNumber = sequenceNumber;
}
public String getControllerId() {
return controllerId;
}
/**
* Compares this object with the specified object for order.
* NOTE: the test is based on ControllerRegistryEntry sequence numbers,
* and doesn't include the controllerId.
*
* @param o the object to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
*/
@Override
public int compareTo(ControllerRegistryEntry o) {
return this.sequenceNumber - o.sequenceNumber;
}
/**
* Test whether some other object is "equal to" this one.
* NOTE: the test is based on ControllerRegistryEntry sequence numbers,
* and doesn't include the controllerId.
*
* @param obj the reference object with which to compare.
* @return true if this object is the same as the obj argument; false
* otherwise.
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof ControllerRegistryEntry) {
ControllerRegistryEntry other = (ControllerRegistryEntry) obj;
return this.sequenceNumber == other.sequenceNumber;
}
return false;
}
/**
* Get the hash code for the object.
* NOTE: the computation is based on ControllerRegistryEntry sequence
* numbers, and doesn't include the controller ID.
*
* @return a hash code value for this object.
*/
@Override
public int hashCode() {
return Integer.valueOf(this.sequenceNumber).hashCode();
}
}
package net.onrc.onos.of.ctl.registry;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import net.onrc.onos.of.ctl.util.InstanceId;
/**
* A registry service that allows ONOS to register controllers and switches in a
* way that is global to the entire ONOS cluster. The registry is the arbiter
* for allowing controllers to control switches.
* <p/>
* The OVS/OF1.{2,3} fault tolerance model is a switch connects to multiple
* controllers, and the controllers send role requests to tell the switch their
* role in controlling the switch.
* <p/>
* The ONOS fault tolerance model allows only a single controller to have
* control of a switch (MASTER role) at once. Controllers therefore need a
* mechanism that enables them to decide who should control a each switch. The
* registry service provides this mechanism.
*/
public interface IControllerRegistry {
/**
* Callback interface for control change events.
*/
public interface ControlChangeCallback {
/**
* Called whenever the control changes from the point of view of the
* registry. The callee can check whether they have control or not using
* the hasControl parameter.
*
* @param dpid The switch that control has changed for
* @param hasControl Whether the listener now has control or not
*/
void controlChanged(long dpid, boolean hasControl);
}
/**
* Request for control of a switch. This method does not block. When control
* for a switch changes, the controlChanged method on the callback object
* will be called. This happens any time the control changes while the
* request is still active (until releaseControl is called)
*
* @param dpid Switch to request control for
* @param cb Callback that will be used to notify caller of control changes
* @throws RegistryException Errors contacting the registry service
*/
public void requestControl(long dpid, ControlChangeCallback cb)
throws RegistryException;
/**
* Stop trying to take control of a switch. This removes the entry for this
* controller requesting this switch in the registry. If the controller had
* control when this is called, another controller will now gain control of
* the switch. This call doesn't block.
*
* @param dpid Switch to release control of
*/
public void releaseControl(long dpid);
/**
* Check whether the controller has control of the switch This call doesn't
* block.
*
* @param dpid Switch to check control of
* @return true if controller has control of the switch.
*/
public boolean hasControl(long dpid);
/**
* Check whether this instance is the leader for the cluster. This call
* doesn't block.
*
* @return true if the instance is the leader for the cluster, otherwise
* false.
*/
public boolean isClusterLeader();
/**
* Gets the unique ID used to identify this ONOS instance in the cluster.
*
* @return Instance ID.
*/
public InstanceId getOnosInstanceId();
/**
* Register a controller to the ONOS cluster. Must be called before the
* registry can be used to take control of any switches.
*
* @param controllerId A unique string ID identifying this controller in the
* cluster
* @throws RegistryException for errors connecting to registry service,
* controllerId already registered
*/
public void registerController(String controllerId)
throws RegistryException;
/**
* Get all controllers in the cluster.
*
* @return Collection of controller IDs
* @throws RegistryException on error
*/
public Collection<String> getAllControllers() throws RegistryException;
/**
* Get all switches in the cluster, along with which controller is in
* control of them (if any) and any other controllers that have requested
* control.
*
* @return Map of all switches.
*/
public Map<String, List<ControllerRegistryEntry>> getAllSwitches();
/**
* Get the controller that has control of a given switch.
*
* @param dpid Switch to find controller for
* @return controller ID
* @throws RegistryException Errors contacting registry service
*/
public String getControllerForSwitch(long dpid) throws RegistryException;
/**
* Get all switches controlled by a given controller.
*
* @param controllerId ID of the controller
* @return Collection of dpids
*/
public Collection<Long> getSwitchesControlledByController(String controllerId);
/**
* Get a unique Id Block.
*
* @return Id Block.
*/
public IdBlock allocateUniqueIdBlock();
/**
* Get next unique id and retrieve a new range of ids if needed.
*
* @param range range to use for the identifier
* @return Id Block.
*/
public IdBlock allocateUniqueIdBlock(long range);
/**
* Get a globally unique ID.
*
* @return a globally unique ID.
*/
public long getNextUniqueId();
}
package net.onrc.onos.of.ctl.registry;
public class IdBlock {
private final long start;
private final long end;
private final long size;
public IdBlock(long start, long end, long size) {
this.start = start;
this.end = end;
this.size = size;
}
public long getStart() {
return start;
}
public long getEnd() {
return end;
}
public long getSize() {
return size;
}
@Override
public String toString() {
return "IdBlock [start=" + start + ", end=" + end + ", size=" + size
+ "]";
}
}
package net.onrc.onos.of.ctl.registry;
public class RegistryException extends Exception {
private static final long serialVersionUID = -8276300722010217913L;
public RegistryException(String message) {
super(message);
}
public RegistryException(String message, Throwable cause) {
super(message, cause);
}
}
package net.onrc.onos.of.ctl.util;
import org.projectfloodlight.openflow.util.HexString;
/**
* The class representing a network switch DPID.
* This class is immutable.
*/
public final class Dpid {
private static final long UNKNOWN = 0;
private final long value;
/**
* Default constructor.
*/
public Dpid() {
this.value = Dpid.UNKNOWN;
}
/**
* Constructor from a long value.
*
* @param value the value to use.
*/
public Dpid(long value) {
this.value = value;
}
/**
* Constructor from a string.
*
* @param value the value to use.
*/
public Dpid(String value) {
this.value = HexString.toLong(value);
}
/**
* Get the value of the DPID.
*
* @return the value of the DPID.
*/
public long value() {
return value;
}
/**
* Convert the DPID value to a ':' separated hexadecimal string.
*
* @return the DPID value as a ':' separated hexadecimal string.
*/
@Override
public String toString() {
return HexString.toHexString(this.value);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof Dpid)) {
return false;
}
Dpid otherDpid = (Dpid) other;
return value == otherDpid.value;
}
@Override
public int hashCode() {
int hash = 17;
hash += 31 * hash + (int) (value ^ value >>> 32);
return hash;
}
}
package net.onrc.onos.of.ctl.util;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
import org.jboss.netty.channel.Channel;
import org.projectfloodlight.openflow.protocol.OFActionType;
import org.projectfloodlight.openflow.protocol.OFCapabilities;
import org.projectfloodlight.openflow.protocol.OFDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFFeaturesReply;
import org.projectfloodlight.openflow.protocol.OFMessage;
import org.projectfloodlight.openflow.protocol.OFPortDesc;
import org.projectfloodlight.openflow.protocol.OFPortDescStatsReply;
import org.projectfloodlight.openflow.protocol.OFPortStatus;
import org.projectfloodlight.openflow.protocol.OFStatsReply;
import org.projectfloodlight.openflow.protocol.OFStatsRequest;
import org.projectfloodlight.openflow.protocol.OFVersion;
import org.projectfloodlight.openflow.types.DatapathId;
import org.projectfloodlight.openflow.types.U64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.onrc.onos.of.ctl.IOFSwitch;
import net.onrc.onos.of.ctl.Role;
import net.onrc.onos.of.ctl.debugcounter.IDebugCounterService;
import net.onrc.onos.of.ctl.debugcounter.IDebugCounterService.CounterException;
public class DummySwitchForTesting implements IOFSwitch {
protected static final Logger log = LoggerFactory.getLogger(DummySwitchForTesting.class);
private Channel channel;
private boolean connected = false;
private OFVersion ofv = OFVersion.OF_10;
private Collection<OFPortDesc> ports;
private DatapathId datapathId;
private Set<OFCapabilities> capabilities;
private int buffers;
private byte tables;
private String stringId;
private Role role;
@Override
public void disconnectSwitch() {
this.channel.close();
}
@Override
public void write(OFMessage m) throws IOException {
this.channel.write(m);
}
@Override
public void write(List<OFMessage> msglist) throws IOException {
for (OFMessage m : msglist) {
this.channel.write(m);
}
}
@Override
public Date getConnectedSince() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getNextTransactionId() {
return 0;
}
@Override
public boolean isConnected() {
return this.connected;
}
@Override
public void setConnected(boolean connected) {
this.connected = connected;
}
@Override
public void flush() {
// TODO Auto-generated method stub
}
@Override
public void setChannel(Channel channel) {
this.channel = channel;
}
@Override
public long getId() {
if (this.stringId == null) {
throw new RuntimeException("Features reply has not yet been set");
}
return this.datapathId.getLong();
}
@Override
public String getStringId() {
// TODO Auto-generated method stub
return "DummySwitch";
}
@Override
public int getNumBuffers() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Set<OFCapabilities> getCapabilities() {
// TODO Auto-generated method stub
return null;
}
@Override
public byte getNumTables() {
// TODO Auto-generated method stub
return 0;
}
@Override
public OFDescStatsReply getSwitchDescription() {
// TODO Auto-generated method stub
return null;
}
@Override
public void cancelFeaturesReply(int transactionId) {
// TODO Auto-generated method stub
}
@Override
public Set<OFActionType> getActions() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setOFVersion(OFVersion version) {
// TODO Auto-generated method stub
}
@Override
public OFVersion getOFVersion() {
return this.ofv;
}
@Override
public Collection<OFPortDesc> getEnabledPorts() {
// TODO Auto-generated method stub
return null;
}
@Override
public Collection<Integer> getEnabledPortNumbers() {
// TODO Auto-generated method stub
return null;
}
@Override
public OFPortDesc getPort(int portNumber) {
// TODO Auto-generated method stub
return null;
}
@Override
public OFPortDesc getPort(String portName) {
// TODO Auto-generated method stub
return null;
}
@Override
public OrderedCollection<PortChangeEvent> processOFPortStatus(
OFPortStatus ps) {
// TODO Auto-generated method stub
return null;
}
@Override
public Collection<OFPortDesc> getPorts() {
return ports;
}
@Override
public boolean portEnabled(int portName) {
// TODO Auto-generated method stub
return false;
}
@Override
public OrderedCollection<PortChangeEvent> setPorts(
Collection<OFPortDesc> p) {
this.ports = p;
return null;
}
@Override
public Map<Object, Object> getAttributes() {
return null;
}
@Override
public boolean hasAttribute(String name) {
// TODO Auto-generated method stub
return false;
}
@Override
public Object getAttribute(String name) {
return Boolean.FALSE;
}
@Override
public void setAttribute(String name, Object value) {
// TODO Auto-generated method stub
}
@Override
public Object removeAttribute(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public void deliverStatisticsReply(OFMessage reply) {
// TODO Auto-generated method stub
}
@Override
public void cancelStatisticsReply(int transactionId) {
// TODO Auto-generated method stub
}
@Override
public void cancelAllStatisticsReplies() {
// TODO Auto-generated method stub
}
@Override
public Future<List<OFStatsReply>> getStatistics(OFStatsRequest<?> request)
throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public void clearAllFlowMods() {
// TODO Auto-generated method stub
}
@Override
public Role getRole() {
return this.role;
}
@Override
public void setRole(Role role) {
this.role = role;
}
@Override
public U64 getNextGenerationId() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setDebugCounterService(IDebugCounterService debugCounter)
throws CounterException {
// TODO Auto-generated method stub
}
@Override
public void startDriverHandshake() throws IOException {
// TODO Auto-generated method stub
}
@Override
public boolean isDriverHandshakeComplete() {
return true;
}
@Override
public void processDriverHandshakeMessage(OFMessage m) {
}
@Override
public void setTableFull(boolean isFull) {
// TODO Auto-generated method stub
}
@Override
public void setFeaturesReply(OFFeaturesReply featuresReply) {
if (featuresReply == null) {
log.error("Error setting featuresReply for switch: {}", getStringId());
return;
}
this.datapathId = featuresReply.getDatapathId();
this.capabilities = featuresReply.getCapabilities();
this.buffers = (int) featuresReply.getNBuffers();
this.tables = (byte) featuresReply.getNTables();
this.stringId = this.datapathId.toString();
}
@Override
public void setPortDescReply(OFPortDescStatsReply portDescReply) {
// TODO Auto-generated method stub
}
@Override
public void handleMessage(OFMessage m) {
log.info("Got packet {} but I am dumb so I don't know what to do.", m);
}
@Override
public boolean portEnabled(String portName) {
// TODO Auto-generated method stub
return false;
}
@Override
public OrderedCollection<PortChangeEvent> comparePorts(
Collection<OFPortDesc> p) {
// TODO Auto-generated method stub
return null;
}
}
package net.onrc.onos.of.ctl.util;
import java.util.EnumSet;
import java.util.Set;
/**
* A utility class to convert between integer based bitmaps for (OpenFlow)
* flags and Enum and EnumSet based representations.
*
* The enum used to represent individual flags needs to implement the
* BitmapableEnum interface.
*
* Example:
* {@code
* int bitmap = 0x11; // OFPPC_PORT_DOWN | OFPPC_NO_STP
* EnumSet<OFPortConfig> s = toEnumSet(OFPortConfig.class, bitmap);
* // s will contain OFPPC_PORT_DOWN and OFPPC_NO_STP
* }
*
* {@code
* EnumSet<OFPortConfig> s = EnumSet.of(OFPPC_NO_STP, OFPPC_PORT_DOWN);
* int bitmap = toBitmap(s); // returns 0x11
* }
*
*/
public final class EnumBitmaps {
private EnumBitmaps() { }
/**
* Enums used to represent individual flags needs to implement this
* interface.
*/
public interface BitmapableEnum {
/** Return the value in the bitmap that the enum constant represents.
* The returned value must have only a single bit set. E.g.,1 << 3
*/
int getValue();
}
/**
* Convert an integer bitmap to an EnumSet.
*
* See class description for example
* @param type The Enum class to use. Must implement BitmapableEnum
* @param bitmap The integer bitmap
* @return A newly allocated EnumSet representing the bits set in the
* bitmap
* @throws NullPointerException if type is null
* @throws IllegalArgumentException if any enum constant from type has
* more than one bit set.
* @throws IllegalArgumentException if the bitmap has any bits set not
* represented by an enum constant.
*/
public static <E extends Enum<E> & BitmapableEnum>
EnumSet<E> toEnumSet(Class<E> type, int bitmap) {
if (type == null) {
throw new NullPointerException("Given enum type must not be null");
}
EnumSet<E> s = EnumSet.noneOf(type);
// allSetBitmap will eventually have all valid bits for the given
// type set.
int allSetBitmap = 0;
for (E element: type.getEnumConstants()) {
if (Integer.bitCount(element.getValue()) != 1) {
String msg = String.format("The %s (%x) constant of the " +
"enum %s is supposed to represent a bitmap entry but " +
"has more than one bit set.",
element.toString(), element.getValue(), type.getName());
throw new IllegalArgumentException(msg);
}
allSetBitmap |= element.getValue();
if ((bitmap & element.getValue()) != 0) {
s.add(element);
}
}
if (((~allSetBitmap) & bitmap) != 0) {
// check if only valid flags are set in the given bitmap
String msg = String.format("The bitmap %x for enum %s has " +
"bits set that are presented by any enum constant",
bitmap, type.getName());
throw new IllegalArgumentException(msg);
}
return s;
}
/**
* Return the bitmap mask with all possible bits set. E.g., If a bitmap
* has the individual flags 0x1, 0x2, and 0x8 (note the missing 0x4) then
* the mask will be 0xb (1011 binary)
*
* @param type The Enum class to use. Must implement BitmapableEnum
* @throws NullPointerException if type is null
* @throws IllegalArgumentException if any enum constant from type has
* more than one bit set
* @return an integer with all possible bits for the given bitmap enum
* type set.
*/
public static <E extends Enum<E> & BitmapableEnum>
int getMask(Class<E> type) {
if (type == null) {
throw new NullPointerException("Given enum type must not be null");
}
// allSetBitmap will eventually have all valid bits for the given
// type set.
int allSetBitmap = 0;
for (E element: type.getEnumConstants()) {
if (Integer.bitCount(element.getValue()) != 1) {
String msg = String.format("The %s (%x) constant of the " +
"enum %s is supposed to represent a bitmap entry but " +
"has more than one bit set.",
element.toString(), element.getValue(), type.getName());
throw new IllegalArgumentException(msg);
}
allSetBitmap |= element.getValue();
}
return allSetBitmap;
}
/**
* Convert the given EnumSet to the integer bitmap representation.
* @param set The EnumSet to convert. The enum must implement
* BitmapableEnum
* @return the integer bitmap
* @throws IllegalArgumentException if an enum constant from the set (!) has
* more than one bit set
* @throws NullPointerException if the set is null
*/
public static <E extends Enum<E> & BitmapableEnum>
int toBitmap(Set<E> set) {
if (set == null) {
throw new NullPointerException("Given set must not be null");
}
int bitmap = 0;
for (E element: set) {
if (Integer.bitCount(element.getValue()) != 1) {
String msg = String.format("The %s (%x) constant in the set " +
"is supposed to represent a bitmap entry but " +
"has more than one bit set.",
element.toString(), element.getValue());
throw new IllegalArgumentException(msg);
}
bitmap |= element.getValue();
}
return bitmap;
}
}
/**
* Copyright 2012, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* An iterator that will filter values from an iterator and return only
* those values that match the predicate.
*/
public abstract class FilterIterator<T> implements Iterator<T> {
protected Iterator<T> subIterator;
protected T next;
/**
* Construct a filter iterator from the given sub iterator.
*
* @param subIterator the sub iterator over which we'll filter
*/
public FilterIterator(Iterator<T> subIterator) {
super();
this.subIterator = subIterator;
}
/**
* Check whether the given value should be returned by the
* filter.
*
* @param value the value to check
* @return true if the value should be included
*/
protected abstract boolean matches(T value);
// ***********
// Iterator<T>
// ***********
@Override
public boolean hasNext() {
if (next != null) {
return true;
}
while (subIterator.hasNext()) {
next = subIterator.next();
if (matches(next)) {
return true;
}
}
next = null;
return false;
}
@Override
public T next() {
if (hasNext()) {
T cur = next;
next = null;
return cur;
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
package net.onrc.onos.of.ctl.util;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkArgument;
/**
* The class representing an ONOS Instance ID.
*
* This class is immutable.
*/
public final class InstanceId {
private final String id;
/**
* Constructor from a string value.
*
* @param id the value to use.
*/
public InstanceId(String id) {
this.id = checkNotNull(id);
checkArgument(!id.isEmpty(), "Empty ONOS Instance ID");
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof InstanceId)) {
return false;
}
InstanceId that = (InstanceId) obj;
return this.id.equals(that.id);
}
@Override
public String toString() {
return id;
}
}
/**
* Copyright 2012 Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Iterator over all values in an iterator of iterators.
*
* @param <T> the type of elements returned by this iterator
*/
public class IterableIterator<T> implements Iterator<T> {
Iterator<? extends Iterable<T>> subIterator;
Iterator<T> current = null;
public IterableIterator(Iterator<? extends Iterable<T>> subIterator) {
super();
this.subIterator = subIterator;
}
@Override
public boolean hasNext() {
if (current == null) {
if (subIterator.hasNext()) {
current = subIterator.next().iterator();
} else {
return false;
}
}
while (!current.hasNext() && subIterator.hasNext()) {
current = subIterator.next().iterator();
}
return current.hasNext();
}
@Override
public T next() {
if (hasNext()) {
return current.next();
}
throw new NoSuchElementException();
}
@Override
public void remove() {
if (hasNext()) {
current.remove();
}
throw new NoSuchElementException();
}
}
/**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.util;
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUHashMap<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = 1L;
private final int capacity;
public LRUHashMap(int capacity) {
super(capacity + 1, 0.75f, true);
this.capacity = capacity;
}
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}
package net.onrc.onos.of.ctl.util;
import java.util.Collection;
import java.util.LinkedHashSet;
import com.google.common.collect.ForwardingCollection;
/**
* A simple wrapper / forwarder that forwards all calls to a LinkedHashSet.
* This wrappers sole reason for existence is to implement the
* OrderedCollection marker interface.
*
*/
public class LinkedHashSetWrapper<E>
extends ForwardingCollection<E> implements OrderedCollection<E> {
private final Collection<E> delegate;
public LinkedHashSetWrapper() {
super();
this.delegate = new LinkedHashSet<E>();
}
public LinkedHashSetWrapper(Collection<? extends E> c) {
super();
this.delegate = new LinkedHashSet<E>(c);
}
@Override
protected Collection<E> delegate() {
return this.delegate;
}
}
/**
* Copyright 2012 Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
**/
package net.onrc.onos.of.ctl.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Iterator over all values in an iterator of iterators.
*
* @param <T> the type of elements returned by this iterator
*/
public class MultiIterator<T> implements Iterator<T> {
Iterator<Iterator<T>> subIterator;
Iterator<T> current = null;
public MultiIterator(Iterator<Iterator<T>> subIterator) {
super();
this.subIterator = subIterator;
}
@Override
public boolean hasNext() {
if (current == null) {
if (subIterator.hasNext()) {
current = subIterator.next();
} else {
return false;
}
}
while (!current.hasNext() && subIterator.hasNext()) {
current = subIterator.next();
}
return current.hasNext();
}
@Override
public T next() {
if (hasNext()) {
return current.next();
}
throw new NoSuchElementException();
}
@Override
public void remove() {
if (hasNext()) {
current.remove();
}
throw new NoSuchElementException();
}
}
package net.onrc.onos.of.ctl.util;
import java.util.Collection;
/**
* A marker interface indicating that this Collection defines a particular
* iteration order. The details about the iteration order are specified by
* the concrete implementation.
*
* @param <E>
*/
public interface OrderedCollection<E> extends Collection<E> {
}
This diff is collapsed. Click to expand it.
package org.projectfloodlight.openflow.annotations;
/**
* This annotation marks a class that is considered externally immutable. I.e.,
* the externally visible state of the class will not change after its
* construction. Such a class can be freely shared between threads and does not
* require defensive copying (don't call clone).
*
* @author Andreas Wundsam <andreas.wundsam@bigswitch.com>
*/
public @interface Immutable {
}
package org.projectfloodlight.openflow.exceptions;
/**
* Error: someone asked to create an OFMessage with wireformat type and version,
* but that doesn't exist
*
* @author capveg
*/
public class NonExistantMessage extends Exception {
private static final long serialVersionUID = 1L;
byte type;
byte version;
/**
* Error: someone asked to create an OFMessage with wireformat type and
* version, but that doesn't exist
*
* @param type
* the wire format
* @param version
* the OpenFlow wireformat version number, e.g. 1 == v1.1, 2 =
* v1.2, etc.
*/
public NonExistantMessage(final byte type, final byte version) {
this.type = type;
this.version = version;
}
}
package org.projectfloodlight.openflow.exceptions;
public class OFParseError extends Exception {
private static final long serialVersionUID = 1L;
public OFParseError() {
super();
}
public OFParseError(final String message, final Throwable cause) {
super(message, cause);
}
public OFParseError(final String message) {
super(message);
}
public OFParseError(final Throwable cause) {
super(cause);
}
}
package org.projectfloodlight.openflow.exceptions;
public class OFShortRead extends Exception {
private static final long serialVersionUID = 1L;
}
package org.projectfloodlight.openflow.exceptions;
public class OFShortWrite extends Exception {
private static final long serialVersionUID = 1L;
}
package org.projectfloodlight.openflow.exceptions;
public class OFUnsupported extends Exception {
private static final long serialVersionUID = 1L;
}
package org.projectfloodlight.openflow.protocol;
public class OFBsnVportQInQT {
}
package org.projectfloodlight.openflow.protocol;
import org.projectfloodlight.openflow.types.PrimitiveSinkable;
import com.google.common.hash.PrimitiveSink;
public class OFMatchBmap implements PrimitiveSinkable{
@Override
public void putTo(PrimitiveSink sink) {
}
}
package org.projectfloodlight.openflow.protocol;
import org.jboss.netty.buffer.ChannelBuffer;
import org.projectfloodlight.openflow.exceptions.OFParseError;
public interface OFMessageReader<T> {
T readFrom(ChannelBuffer bb) throws OFParseError;
}
package org.projectfloodlight.openflow.protocol;
import org.jboss.netty.buffer.ChannelBuffer;
import org.projectfloodlight.openflow.exceptions.OFParseError;
public interface OFMessageWriter<T> {
public void write(ChannelBuffer bb, T message) throws OFParseError;
}
package org.projectfloodlight.openflow.protocol;
import org.projectfloodlight.openflow.types.PrimitiveSinkable;
/**
* Base interface of all OpenFlow objects (e.g., messages, actions, stats, etc.)
*/
public interface OFObject extends Writeable, PrimitiveSinkable {
OFVersion getVersion();
}
package org.projectfloodlight.openflow.protocol;
import org.jboss.netty.buffer.ChannelBuffer;
public interface OFObjectFactory<T extends OFObject> {
T read(ChannelBuffer buffer);
}
package org.projectfloodlight.openflow.protocol;
import java.util.EnumMap;
import java.util.Iterator;
import java.util.Map;
import org.jboss.netty.buffer.ChannelBuffer;
import org.projectfloodlight.openflow.exceptions.OFParseError;
import org.projectfloodlight.openflow.protocol.match.MatchField;
import org.projectfloodlight.openflow.protocol.match.MatchFields;
import org.projectfloodlight.openflow.protocol.oxm.OFOxm;
import org.projectfloodlight.openflow.types.OFValueType;
import org.projectfloodlight.openflow.types.PrimitiveSinkable;
import org.projectfloodlight.openflow.util.ChannelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableMap;
import com.google.common.hash.PrimitiveSink;
public class OFOxmList implements Iterable<OFOxm<?>>, Writeable, PrimitiveSinkable {
private static final Logger logger = LoggerFactory.getLogger(OFOxmList.class);
private final Map<MatchFields, OFOxm<?>> oxmMap;
public final static OFOxmList EMPTY = new OFOxmList(ImmutableMap.<MatchFields, OFOxm<?>>of());
private OFOxmList(Map<MatchFields, OFOxm<?>> oxmMap) {
this.oxmMap = oxmMap;
}
@SuppressWarnings("unchecked")
public <T extends OFValueType<T>> OFOxm<T> get(MatchField<T> matchField) {
return (OFOxm<T>) oxmMap.get(matchField.id);
}
public static class Builder {
private final Map<MatchFields, OFOxm<?>> oxmMap;
public Builder() {
oxmMap = new EnumMap<MatchFields, OFOxm<?>>(MatchFields.class);
}
public Builder(EnumMap<MatchFields, OFOxm<?>> oxmMap) {
this.oxmMap = oxmMap;
}
public <T extends OFValueType<T>> void set(OFOxm<T> oxm) {
oxmMap.put(oxm.getMatchField().id, oxm);
}
public <T extends OFValueType<T>> void unset(MatchField<T> matchField) {
oxmMap.remove(matchField.id);
}
public OFOxmList build() {
return OFOxmList.ofList(oxmMap.values());
}
}
@Override
public Iterator<OFOxm<?>> iterator() {
return oxmMap.values().iterator();
}
public static OFOxmList ofList(Iterable<OFOxm<?>> oxmList) {
Map<MatchFields, OFOxm<?>> map = new EnumMap<MatchFields, OFOxm<?>>(
MatchFields.class);
for (OFOxm<?> o : oxmList) {
OFOxm<?> canonical = o.getCanonical();
if(logger.isDebugEnabled() && !Objects.equal(o, canonical)) {
logger.debug("OFOxmList: normalized non-canonical OXM {} to {}", o, canonical);
}
if(canonical != null)
map.put(canonical.getMatchField().id, canonical);
}
return new OFOxmList(map);
}
public static OFOxmList of(OFOxm<?>... oxms) {
Map<MatchFields, OFOxm<?>> map = new EnumMap<MatchFields, OFOxm<?>>(
MatchFields.class);
for (OFOxm<?> o : oxms) {
OFOxm<?> canonical = o.getCanonical();
if(logger.isDebugEnabled() && !Objects.equal(o, canonical)) {
logger.debug("OFOxmList: normalized non-canonical OXM {} to {}", o, canonical);
}
if(canonical != null)
map.put(canonical.getMatchField().id, canonical);
}
return new OFOxmList(map);
}
public static OFOxmList readFrom(ChannelBuffer bb, int length,
OFMessageReader<OFOxm<?>> reader) throws OFParseError {
return ofList(ChannelUtils.readList(bb, length, reader));
}
@Override
public void writeTo(ChannelBuffer bb) {
for (OFOxm<?> o : this) {
o.writeTo(bb);
}
}
public OFOxmList.Builder createBuilder() {
return new OFOxmList.Builder(new EnumMap<MatchFields, OFOxm<?>>(oxmMap));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((oxmMap == null) ? 0 : oxmMap.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
OFOxmList other = (OFOxmList) obj;
if (oxmMap == null) {
if (other.oxmMap != null)
return false;
} else if (!oxmMap.equals(other.oxmMap))
return false;
return true;
}
@Override
public String toString() {
return "OFOxmList" + oxmMap;
}
@Override
public void putTo(PrimitiveSink sink) {
for (OFOxm<?> o : this) {
o.putTo(sink);
}
}
}
package org.projectfloodlight.openflow.protocol;
/** Type safety interface. Enables type safe combinations of requests and replies */
public interface OFRequest<REPLY extends OFMessage> extends OFMessage {
}
package org.projectfloodlight.openflow.protocol;
public class OFTableFeature {
// FIXME implement
}
package org.projectfloodlight.openflow.protocol;
public enum OFVersion {
OF_10(1), OF_11(2), OF_12(3), OF_13(4);
public final int wireVersion;
OFVersion(final int wireVersion) {
this.wireVersion = wireVersion;
}
public int getWireVersion() {
return wireVersion;
}
}
package org.projectfloodlight.openflow.protocol;
import org.jboss.netty.buffer.ChannelBuffer;
public interface Writeable {
void writeTo(ChannelBuffer bb);
}
package org.projectfloodlight.openflow.protocol;
public interface XidGenerator {
long nextXid();
}
package org.projectfloodlight.openflow.protocol;
import java.util.concurrent.atomic.AtomicLong;
public class XidGenerators {
private static final XidGenerator GLOBAL_XID_GENERATOR = new StandardXidGenerator();
public static XidGenerator create() {
return new StandardXidGenerator();
}
public static XidGenerator global() {
return GLOBAL_XID_GENERATOR;
}
}
class StandardXidGenerator implements XidGenerator {
private final AtomicLong xidGen = new AtomicLong();
long MAX_XID = 0xFFffFFffL;
@Override
public long nextXid() {
long xid;
do {
xid = xidGen.incrementAndGet();
if(xid > MAX_XID) {
synchronized(this) {
if(xidGen.get() > MAX_XID) {
xidGen.set(0);
}
}
}
} while(xid > MAX_XID);
return xid;
}
}
\ No newline at end of file
package org.projectfloodlight.openflow.protocol.match;
// MUST BE ORDERED BY THE ORDER OF OF SPEC!!!
public enum MatchFields {
IN_PORT,
IN_PHY_PORT,
METADATA,
ETH_DST,
ETH_SRC,
ETH_TYPE,
VLAN_VID,
VLAN_PCP,
IP_DSCP,
IP_ECN,
IP_PROTO,
IPV4_SRC,
IPV4_DST,
TCP_SRC,
TCP_DST,
UDP_SRC,
UDP_DST,
SCTP_SRC,
SCTP_DST,
ICMPV4_TYPE,
ICMPV4_CODE,
ARP_OP,
ARP_SPA,
ARP_TPA,
ARP_SHA,
ARP_THA,
IPV6_SRC,
IPV6_DST,
IPV6_FLABEL,
ICMPV6_TYPE,
ICMPV6_CODE,
IPV6_ND_TARGET,
IPV6_ND_SLL,
IPV6_ND_TLL,
MPLS_LABEL,
MPLS_TC,
TUNNEL_ID,
BSN_IN_PORTS_128,
BSN_LAG_ID,
BSN_VRF,
BSN_GLOBAL_VRF_ALLOWED,
BSN_L3_INTERFACE_CLASS_ID,
BSN_L3_SRC_CLASS_ID,
BSN_L3_DST_CLASS_ID,
BSN_EGR_PORT_GROUP_ID,
BSN_UDF0,
BSN_UDF1,
BSN_UDF2,
BSN_UDF3,
BSN_UDF4,
BSN_UDF5,
BSN_UDF6,
BSN_UDF7,
BSN_TCP_FLAGS,
}
package org.projectfloodlight.openflow.protocol.match;
import java.util.HashSet;
import java.util.Set;
import org.projectfloodlight.openflow.types.OFValueType;
public class Prerequisite<T extends OFValueType<T>> {
private final MatchField<T> field;
private final Set<OFValueType<T>> values;
private boolean any;
@SafeVarargs
public Prerequisite(MatchField<T> field, OFValueType<T>... values) {
this.values = new HashSet<OFValueType<T>>();
this.field = field;
if (values == null || values.length == 0) {
this.any = true;
} else {
this.any = false;
for (OFValueType<T> value : values) {
this.values.add(value);
}
}
}
/**
* Returns true if this prerequisite is satisfied by the given match object.
*
* @param match Match object
* @return true iff prerequisite is satisfied.
*/
public boolean isSatisfied(Match match) {
OFValueType<T> res = match.get(this.field);
if (res == null)
return false;
if (this.any)
return true;
if (this.values.contains(res)) {
return true;
}
return false;
}
}
package org.projectfloodlight.openflow.protocol.ver10;
import java.util.EnumSet;
import java.util.Set;
import org.jboss.netty.buffer.ChannelBuffer;
import org.projectfloodlight.openflow.exceptions.OFParseError;
import org.projectfloodlight.openflow.protocol.OFActionType;
import org.projectfloodlight.openflow.protocol.match.Match;
import com.google.common.hash.PrimitiveSink;
/**
* Collection of helper functions for reading and writing into ChannelBuffers
*
* @author capveg
*/
public class ChannelUtilsVer10 {
public static Match readOFMatch(final ChannelBuffer bb) throws OFParseError {
return OFMatchV1Ver10.READER.readFrom(bb);
}
public static Set<OFActionType> readSupportedActions(ChannelBuffer bb) {
int actions = bb.readInt();
EnumSet<OFActionType> supportedActions = EnumSet.noneOf(OFActionType.class);
if ((actions & (1 << OFActionTypeSerializerVer10.OUTPUT_VAL)) != 0)
supportedActions.add(OFActionType.OUTPUT);
if ((actions & (1 << OFActionTypeSerializerVer10.SET_VLAN_VID_VAL)) != 0)
supportedActions.add(OFActionType.SET_VLAN_VID);
if ((actions & (1 << OFActionTypeSerializerVer10.SET_VLAN_PCP_VAL)) != 0)
supportedActions.add(OFActionType.SET_VLAN_PCP);
if ((actions & (1 << OFActionTypeSerializerVer10.STRIP_VLAN_VAL)) != 0)
supportedActions.add(OFActionType.STRIP_VLAN);
if ((actions & (1 << OFActionTypeSerializerVer10.SET_DL_SRC_VAL)) != 0)
supportedActions.add(OFActionType.SET_DL_SRC);
if ((actions & (1 << OFActionTypeSerializerVer10.SET_DL_DST_VAL)) != 0)
supportedActions.add(OFActionType.SET_DL_DST);
if ((actions & (1 << OFActionTypeSerializerVer10.SET_NW_SRC_VAL)) != 0)
supportedActions.add(OFActionType.SET_NW_SRC);
if ((actions & (1 << OFActionTypeSerializerVer10.SET_NW_DST_VAL)) != 0)
supportedActions.add(OFActionType.SET_NW_DST);
if ((actions & (1 << OFActionTypeSerializerVer10.SET_NW_TOS_VAL)) != 0)
supportedActions.add(OFActionType.SET_NW_TOS);
if ((actions & (1 << OFActionTypeSerializerVer10.SET_TP_SRC_VAL)) != 0)
supportedActions.add(OFActionType.SET_TP_SRC);
if ((actions & (1 << OFActionTypeSerializerVer10.SET_TP_DST_VAL)) != 0)
supportedActions.add(OFActionType.SET_TP_DST);
if ((actions & (1 << OFActionTypeSerializerVer10.ENQUEUE_VAL)) != 0)
supportedActions.add(OFActionType.ENQUEUE);
return supportedActions;
}
public static int supportedActionsToWire(Set<OFActionType> supportedActions) {
int supportedActionsVal = 0;
if (supportedActions.contains(OFActionType.OUTPUT))
supportedActionsVal |= (1 << OFActionTypeSerializerVer10.OUTPUT_VAL);
if (supportedActions.contains(OFActionType.SET_VLAN_VID))
supportedActionsVal |= (1 << OFActionTypeSerializerVer10.SET_VLAN_VID_VAL);
if (supportedActions.contains(OFActionType.SET_VLAN_PCP))
supportedActionsVal |= (1 << OFActionTypeSerializerVer10.SET_VLAN_PCP_VAL);
if (supportedActions.contains(OFActionType.STRIP_VLAN))
supportedActionsVal |= (1 << OFActionTypeSerializerVer10.STRIP_VLAN_VAL);
if (supportedActions.contains(OFActionType.SET_DL_SRC))
supportedActionsVal |= (1 << OFActionTypeSerializerVer10.SET_DL_SRC_VAL);
if (supportedActions.contains(OFActionType.SET_DL_DST))
supportedActionsVal |= (1 << OFActionTypeSerializerVer10.SET_DL_DST_VAL);
if (supportedActions.contains(OFActionType.SET_NW_SRC))
supportedActionsVal |= (1 << OFActionTypeSerializerVer10.SET_NW_SRC_VAL);
if (supportedActions.contains(OFActionType.SET_NW_DST))
supportedActionsVal |= (1 << OFActionTypeSerializerVer10.SET_NW_DST_VAL);
if (supportedActions.contains(OFActionType.SET_NW_TOS))
supportedActionsVal |= (1 << OFActionTypeSerializerVer10.SET_NW_TOS_VAL);
if (supportedActions.contains(OFActionType.SET_TP_SRC))
supportedActionsVal |= (1 << OFActionTypeSerializerVer10.SET_TP_SRC_VAL);
if (supportedActions.contains(OFActionType.SET_TP_DST))
supportedActionsVal |= (1 << OFActionTypeSerializerVer10.SET_TP_DST_VAL);
if (supportedActions.contains(OFActionType.ENQUEUE))
supportedActionsVal |= (1 << OFActionTypeSerializerVer10.ENQUEUE_VAL);
return supportedActionsVal;
}
public static void putSupportedActionsTo(Set<OFActionType> supportedActions, PrimitiveSink sink) {
sink.putInt(supportedActionsToWire(supportedActions));
}
public static void writeSupportedActions(ChannelBuffer bb, Set<OFActionType> supportedActions) {
bb.writeInt(supportedActionsToWire(supportedActions));
}
}
package org.projectfloodlight.openflow.protocol.ver11;
import org.jboss.netty.buffer.ChannelBuffer;
import org.projectfloodlight.openflow.exceptions.OFParseError;
import org.projectfloodlight.openflow.protocol.OFMatchBmap;
import org.projectfloodlight.openflow.protocol.match.Match;
/**
* Collection of helper functions for reading and writing into ChannelBuffers
*
* @author capveg
*/
public class ChannelUtilsVer11 {
public static Match readOFMatch(final ChannelBuffer bb) throws OFParseError {
return OFMatchV2Ver11.READER.readFrom(bb);
}
public static OFMatchBmap readOFMatchBmap(ChannelBuffer bb) {
throw new UnsupportedOperationException("not implemented");
}
public static void writeOFMatchBmap(ChannelBuffer bb, OFMatchBmap match) {
throw new UnsupportedOperationException("not implemented");
}
}
package org.projectfloodlight.openflow.protocol.ver12;
import org.jboss.netty.buffer.ChannelBuffer;
import org.projectfloodlight.openflow.exceptions.OFParseError;
import org.projectfloodlight.openflow.protocol.OFMatchBmap;
import org.projectfloodlight.openflow.protocol.match.Match;
import org.projectfloodlight.openflow.protocol.ver12.OFMatchV3Ver12;
import org.projectfloodlight.openflow.protocol.OFBsnVportQInQ;
/**
* Collection of helper functions for reading and writing into ChannelBuffers
*
* @author capveg
*/
public class ChannelUtilsVer12 {
public static Match readOFMatch(final ChannelBuffer bb) throws OFParseError {
return OFMatchV3Ver12.READER.readFrom(bb);
}
// TODO these need to be figured out / removed
public static OFBsnVportQInQ readOFBsnVportQInQ(ChannelBuffer bb) {
throw new UnsupportedOperationException("not implemented");
}
public static void writeOFBsnVportQInQ(ChannelBuffer bb,
OFBsnVportQInQ vport) {
throw new UnsupportedOperationException("not implemented");
}
public static OFMatchBmap readOFMatchBmap(ChannelBuffer bb) {
throw new UnsupportedOperationException("not implemented");
}
public static void writeOFMatchBmap(ChannelBuffer bb, OFMatchBmap match) {
throw new UnsupportedOperationException("not implemented");
}
}
package org.projectfloodlight.openflow.protocol.ver13;
import org.jboss.netty.buffer.ChannelBuffer;
import org.projectfloodlight.openflow.exceptions.OFParseError;
import org.projectfloodlight.openflow.protocol.OFMatchBmap;
import org.projectfloodlight.openflow.protocol.match.Match;
/**
* Collection of helper functions for reading and writing into ChannelBuffers
*
* @author capveg
*/
public class ChannelUtilsVer13 {
public static Match readOFMatch(final ChannelBuffer bb) throws OFParseError {
return OFMatchV3Ver13.READER.readFrom(bb);
}
public static OFMatchBmap readOFMatchBmap(ChannelBuffer bb) {
throw new UnsupportedOperationException("not implemented");
}
public static void writeOFMatchBmap(ChannelBuffer bb, OFMatchBmap match) {
throw new UnsupportedOperationException("not implemented");
}
}
package org.projectfloodlight.openflow.types;
import org.jboss.netty.buffer.ChannelBuffer;
import com.google.common.hash.PrimitiveSink;
import com.google.common.primitives.UnsignedInts;
public class ArpOpcode implements OFValueType<ArpOpcode> {
final static int LENGTH = 2;
private static final int VAL_REQUEST = 1;
private static final int VAL_REPLY = 2;
private static final int VAL_REQUEST_REVERSE = 3;
private static final int VAL_REPLY_REVERSE = 4;
private static final int VAL_DRARP_REQUEST = 5;
private static final int VAL_DRARP_REPLY = 6;
private static final int VAL_DRARP_ERROR = 7;
private static final int VAL_INARP_REQUEST = 8;
private static final int VAL_INARP_REPLY = 9;
private static final int VAL_ARP_NAK = 10;
private static final int VAL_MARS_REQUEST = 11;
private static final int VAL_MARS_MULTI = 12;
private static final int VAL_MARS_MSERV = 13;
private static final int VAL_MARS_JOIN = 14;
private static final int VAL_MARS_LEAVE = 15;
private static final int VAL_MARS_NAK = 16;
private static final int VAL_MARS_UNSERV = 17;
private static final int VAL_MARS_SJOIN = 18;
private static final int VAL_MARS_SLEAVE = 19;
private static final int VAL_MARS_GROUPLIST_REQUEST = 20;
private static final int VAL_MARS_GROUPLIST_REPLY = 21;
private static final int VAL_MARS_REDIRECT_MAP = 22;
private static final int VAL_MAPOS_UNARP = 23;
private static final int VAL_OP_EXP1 = 24;
private static final int VAL_OP_EXP2 = 25;
public static final ArpOpcode REQUEST = new ArpOpcode(VAL_REQUEST);
public static final ArpOpcode REPLY = new ArpOpcode(VAL_REPLY);
public static final ArpOpcode REQUEST_REVERSE = new ArpOpcode(VAL_REQUEST_REVERSE);
public static final ArpOpcode REPLY_REVERSE = new ArpOpcode(VAL_REPLY_REVERSE);
public static final ArpOpcode DRARP_REQUEST = new ArpOpcode(VAL_DRARP_REQUEST);
public static final ArpOpcode DRARP_REPLY = new ArpOpcode(VAL_DRARP_REPLY);
public static final ArpOpcode DRARP_ERROR = new ArpOpcode(VAL_DRARP_ERROR);
public static final ArpOpcode INARP_REQUEST = new ArpOpcode(VAL_INARP_REQUEST);
public static final ArpOpcode INARP_REPLY = new ArpOpcode(VAL_INARP_REPLY);
public static final ArpOpcode ARP_NAK = new ArpOpcode(VAL_ARP_NAK);
public static final ArpOpcode MARS_REQUEST = new ArpOpcode(VAL_MARS_REQUEST);
public static final ArpOpcode MARS_MULTI = new ArpOpcode(VAL_MARS_MULTI);
public static final ArpOpcode MARS_MSERV = new ArpOpcode(VAL_MARS_MSERV);
public static final ArpOpcode MARS_JOIN = new ArpOpcode(VAL_MARS_JOIN);
public static final ArpOpcode MARS_LEAVE = new ArpOpcode(VAL_MARS_LEAVE);
public static final ArpOpcode MARS_NAK = new ArpOpcode(VAL_MARS_NAK);
public static final ArpOpcode MARS_UNSERV = new ArpOpcode(VAL_MARS_UNSERV);
public static final ArpOpcode MARS_SJOIN = new ArpOpcode(VAL_MARS_SJOIN);
public static final ArpOpcode MARS_SLEAVE = new ArpOpcode(VAL_MARS_SLEAVE);
public static final ArpOpcode MARS_GROUPLIST_REQUEST = new ArpOpcode(VAL_MARS_GROUPLIST_REQUEST);
public static final ArpOpcode MARS_GROUPLIST_REPLY = new ArpOpcode(VAL_MARS_GROUPLIST_REPLY);
public static final ArpOpcode MARS_REDIRECT_MAP = new ArpOpcode(VAL_MARS_REDIRECT_MAP);
public static final ArpOpcode MAPOS_UNARP = new ArpOpcode(VAL_MAPOS_UNARP);
public static final ArpOpcode OP_EXP1 = new ArpOpcode(VAL_OP_EXP1);
public static final ArpOpcode OP_EXP2 = new ArpOpcode(VAL_OP_EXP2);
private static final int MIN_OPCODE = 0;
private static final int MAX_OPCODE = 0xFFFF;
private static final int NONE_VAL = 0;
public static final ArpOpcode NONE = new ArpOpcode(NONE_VAL);
public static final ArpOpcode NO_MASK = new ArpOpcode(0xFFFFFFFF);
public static final ArpOpcode FULL_MASK = new ArpOpcode(0x00000000);
private final int opcode;
private ArpOpcode(int opcode) {
this.opcode = opcode;
}
@Override
public int getLength() {
return LENGTH;
}
public int getOpcode() {
return this.opcode;
}
public static ArpOpcode of(int opcode) {
if (opcode < MIN_OPCODE || opcode > MAX_OPCODE)
throw new IllegalArgumentException("Invalid ARP opcode: " + opcode);
switch (opcode) {
case NONE_VAL:
return NONE;
case VAL_REQUEST:
return REQUEST;
case VAL_REPLY:
return REPLY;
case VAL_REQUEST_REVERSE:
return REQUEST_REVERSE;
case VAL_REPLY_REVERSE:
return REPLY_REVERSE;
case VAL_DRARP_REQUEST:
return DRARP_REQUEST;
case VAL_DRARP_REPLY:
return DRARP_REPLY;
case VAL_DRARP_ERROR:
return DRARP_ERROR;
case VAL_INARP_REQUEST:
return INARP_REQUEST;
case VAL_INARP_REPLY:
return INARP_REPLY;
case VAL_ARP_NAK:
return ARP_NAK;
case VAL_MARS_REQUEST:
return MARS_REQUEST;
case VAL_MARS_MULTI:
return MARS_MULTI;
case VAL_MARS_MSERV:
return MARS_MSERV;
case VAL_MARS_JOIN:
return MARS_JOIN;
case VAL_MARS_LEAVE:
return MARS_LEAVE;
case VAL_MARS_NAK:
return MARS_NAK;
case VAL_MARS_UNSERV:
return MARS_UNSERV;
case VAL_MARS_SJOIN:
return MARS_SJOIN;
case VAL_MARS_SLEAVE:
return MARS_SLEAVE;
case VAL_MARS_GROUPLIST_REQUEST:
return MARS_GROUPLIST_REQUEST;
case VAL_MARS_GROUPLIST_REPLY:
return MARS_GROUPLIST_REPLY;
case VAL_MARS_REDIRECT_MAP:
return MARS_REDIRECT_MAP;
case VAL_MAPOS_UNARP:
return MAPOS_UNARP;
case VAL_OP_EXP1:
return OP_EXP1;
case VAL_OP_EXP2:
return OP_EXP2;
default:
return new ArpOpcode(opcode);
}
}
public void write2Bytes(ChannelBuffer c) {
c.writeShort(this.opcode);
}
public static ArpOpcode read2Bytes(ChannelBuffer c) {
return ArpOpcode.of(c.readUnsignedShort());
}
@Override
public ArpOpcode applyMask(ArpOpcode mask) {
return ArpOpcode.of(this.opcode & mask.opcode);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + opcode;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ArpOpcode other = (ArpOpcode) obj;
if (opcode != other.opcode)
return false;
return true;
}
@Override
public int compareTo(ArpOpcode o) {
return UnsignedInts.compare(opcode, o.opcode);
}
@Override
public void putTo(PrimitiveSink sink) {
sink.putShort((short) this.opcode);
}
@Override
public String toString() {
return String.valueOf(this.opcode);
}
}
package org.projectfloodlight.openflow.types;
import javax.annotation.concurrent.Immutable;
import org.jboss.netty.buffer.ChannelBuffer;
import com.google.common.hash.PrimitiveSink;
import com.google.common.primitives.UnsignedInts;
@Immutable
public class ClassId implements OFValueType<ClassId> {
static final int LENGTH = 4;
private final static int NONE_VAL = 0;
public final static ClassId NONE = new ClassId(NONE_VAL);
private final static int NO_MASK_VAL = 0xFFFFFFFF;
public final static ClassId NO_MASK = new ClassId(NO_MASK_VAL);
public final static ClassId FULL_MASK = NONE;
private final int rawValue;
private ClassId(final int rawValue) {
this.rawValue = rawValue;
}
public static ClassId of(final int raw) {
if(raw == NONE_VAL)
return NONE;
else if(raw == NO_MASK_VAL)
return NO_MASK;
return new ClassId(raw);
}
public int getInt() {
return rawValue;
}
@Override
public int getLength() {
return LENGTH;
}
@Override
public String toString() {
return Integer.toString(rawValue);
}
@Override
public ClassId applyMask(ClassId mask) {
return ClassId.of(rawValue & mask.rawValue); }
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + rawValue;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ClassId other = (ClassId) obj;
if (rawValue != other.rawValue)
return false;
return true;
}
public void write4Bytes(ChannelBuffer c) {
c.writeInt(rawValue);
}
public static ClassId read4Bytes(ChannelBuffer c) {
return ClassId.of(c.readInt());
}
@Override
public int compareTo(ClassId o) {
return UnsignedInts.compare(rawValue, rawValue);
}
@Override
public void putTo(PrimitiveSink sink) {
sink.putInt(rawValue);
}
}
package org.projectfloodlight.openflow.types;
import org.projectfloodlight.openflow.annotations.Immutable;
import org.projectfloodlight.openflow.util.HexString;
import com.google.common.hash.PrimitiveSink;
import com.google.common.primitives.Longs;
import com.google.common.primitives.UnsignedLongs;
/**
* Abstraction of a datapath ID that can be set and/or accessed as either a
* long value or a colon-separated string. Immutable
*
* @author Rob Vaterlaus <rob.vaterlaus@bigswitch.com>
*/
@Immutable
public class DatapathId implements PrimitiveSinkable, Comparable<DatapathId> {
public static final DatapathId NONE = new DatapathId(0);
private final long rawValue;
private DatapathId(long rawValue) {
this.rawValue = rawValue;
}
public static DatapathId of(long rawValue) {
return new DatapathId(rawValue);
}
public static DatapathId of(String s) {
return new DatapathId(HexString.toLong(s));
}
public static DatapathId of(byte[] bytes) {
return new DatapathId(Longs.fromByteArray(bytes));
}
public long getLong() {
return rawValue;
}
public U64 getUnsignedLong() {
return U64.of(rawValue);
}
public byte[] getBytes() {
return Longs.toByteArray(rawValue);
}
@Override
public String toString() {
return HexString.toHexString(rawValue);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (rawValue ^ (rawValue >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
DatapathId other = (DatapathId) obj;
if (rawValue != other.rawValue)
return false;
return true;
}
@Override
public void putTo(PrimitiveSink sink) {
sink.putLong(rawValue);
}
@Override
public int compareTo(DatapathId o) {
return UnsignedLongs.compare(rawValue, o.rawValue);
}
}
package org.projectfloodlight.openflow.types;
import org.jboss.netty.buffer.ChannelBuffer;
import org.projectfloodlight.openflow.exceptions.OFParseError;
import com.google.common.hash.PrimitiveSink;
import com.google.common.primitives.UnsignedInts;
public class GenTableId implements OFValueType<GenTableId>, Comparable<GenTableId> {
final static int LENGTH = 2;
private static final int VALIDATION_MASK = 0xFFFF;
private static final int ALL_VAL = 0xFFFF;
private static final int NONE_VAL = 0x0000;
public static final GenTableId NONE = new GenTableId(NONE_VAL);
public static final GenTableId ALL = new GenTableId(ALL_VAL);
public static final GenTableId ZERO = NONE;
private final int id;
private GenTableId(int id) {
this.id = id;
}
public static GenTableId of(int id) {
switch(id) {
case NONE_VAL:
return NONE;
case ALL_VAL:
return ALL;
default:
if ((id & VALIDATION_MASK) != id)
throw new IllegalArgumentException("Illegal Table id value: " + id);
return new GenTableId(id);
}
}
@Override
public String toString() {
return "0x" + Integer.toHexString(id);
}
public int getValue() {
return id;
}
@Override
public int getLength() {
return LENGTH;
}
public void write2Bytes(ChannelBuffer c) {
c.writeShort(this.id);
}
public static GenTableId read2Bytes(ChannelBuffer c) throws OFParseError {
return GenTableId.of(c.readUnsignedShort());
}
@Override
public GenTableId applyMask(GenTableId mask) {
return GenTableId.of(this.id & mask.id);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof GenTableId))
return false;
GenTableId other = (GenTableId)obj;
if (other.id != this.id)
return false;
return true;
}
@Override
public int hashCode() {
int prime = 13873;
return this.id * prime;
}
@Override
public int compareTo(GenTableId other) {
return UnsignedInts.compare(this.id, other.id);
}
@Override
public void putTo(PrimitiveSink sink) {
sink.putShort((byte) id);
}
}
package org.projectfloodlight.openflow.types;
import javax.annotation.concurrent.Immutable;
/** a hash value that supports bit-wise combinations, mainly to calculate hash values for
* reconciliation operations.
*
* @author Andreas Wundsam <andreas.wundsam@bigswitch.com>
*
* @param <H> - this type, for return type safety.
*/
@Immutable
public interface HashValue<H extends HashValue<H>> {
/** return the "numBits" highest-order bits of the hash.
* @param numBits number of higest-order bits to return [0-32].
* @return a numberic value of the 0-32 highest-order bits.
*/
int prefixBits(int numBits);
/** @return the bitwise inverse of this value */
H inverse();
/** or this value with another value value of the same type */
H or(H other);
/** and this value with another value value of the same type */
H and(H other);
/** xor this value with another value value of the same type */
H xor(H other);
/** calculate a combined hash value of this hash value (the <b>Key</b>) and the hash value
* specified as a parameter (the <b>Value</b>).
* <p>
* The value is constructed as follows:
* <ul>
* <li>the first keyBits bits are taken only from the Key
* <li>the other bits are taken from key xor value.
* </ul>
* The overall result looks like this:
* <pre>
* MSB LSB
* +---------+--------------+
* | key | key ^ value |
* +---------+--------------+
* |-keyBits-|
* </pre>
*
* @param value - hash value to be compared with this value (the key)
* @param keyBits number of prefix bits that are just taken from key
* @return the combined value.
*/
H combineWithValue(H value, int keyBits);
}
\ No newline at end of file
package org.projectfloodlight.openflow.types;
import com.google.common.base.Preconditions;
public class HashValueUtils {
private HashValueUtils() { }
public static long combineWithValue(long key, long value, int keyBits) {
Preconditions.checkArgument(keyBits >= 0 && keyBits <= 64, "keyBits must be [0,64]");
int valueBits = 64 - keyBits;
long valueMask = valueBits == 64 ? 0xFFFFFFFFFFFFFFFFL : (1L << valueBits) - 1;
return key ^ (value & valueMask);
}
public static int prefixBits(long raw1, int numBits) {
Preconditions.checkArgument(numBits >= 0 && numBits <= 32,
"numBits must be in range [0, 32]");
if(numBits == 0)
return 0;
final int shiftDown = 64 - numBits;
return (int) (raw1 >>> shiftDown);
}
}
package org.projectfloodlight.openflow.types;
import org.jboss.netty.buffer.ChannelBuffer;
import com.google.common.hash.PrimitiveSink;
import com.google.common.primitives.Shorts;
/**
*
* @author Yotam Harchol (yotam.harchol@bigswitch.com)
*
*/
public class ICMPv4Code implements OFValueType<ICMPv4Code> {
final static int LENGTH = 1;
final static short MAX_CODE = 0xFF;
private final short code;
private static final short NONE_VAL = 0;
public static final ICMPv4Code NONE = new ICMPv4Code(NONE_VAL);
public static final ICMPv4Code NO_MASK = new ICMPv4Code((short)0xFFFF);
public static final ICMPv4Code FULL_MASK = new ICMPv4Code((short)0x0000);
private ICMPv4Code(short code) {
this.code = code;
}
public static ICMPv4Code of(short code) {
if(code == NONE_VAL)
return NONE;
if (code > MAX_CODE || code < 0)
throw new IllegalArgumentException("Illegal ICMPv4 code: " + code);
return new ICMPv4Code(code);
}
@Override
public int getLength() {
return LENGTH;
}
public short getCode() {
return code;
}
public void writeByte(ChannelBuffer c) {
c.writeByte(this.code);
}
public static ICMPv4Code readByte(ChannelBuffer c) {
return ICMPv4Code.of(c.readUnsignedByte());
}
@Override
public ICMPv4Code applyMask(ICMPv4Code mask) {
return ICMPv4Code.of((short)(this.code & mask.code));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + code;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ICMPv4Code other = (ICMPv4Code) obj;
if (code != other.code)
return false;
return true;
}
@Override
public int compareTo(ICMPv4Code o) {
return Shorts.compare(code, o.code);
}
@Override
public void putTo(PrimitiveSink sink) {
sink.putShort(code);
}
@Override
public String toString() {
return String.valueOf(this.code);
}
}
package org.projectfloodlight.openflow.types;
import org.jboss.netty.buffer.ChannelBuffer;
import com.google.common.hash.PrimitiveSink;
import com.google.common.primitives.Shorts;
public class ICMPv4Type implements OFValueType<ICMPv4Type> {
final static int LENGTH = 1;
private static final short VAL_ECHO_REPLY = 0;
private static final short VAL_DESTINATION_UNREACHABLE = 3;
private static final short VAL_SOURCE_QUENCH = 4;
private static final short VAL_REDIRECT = 5;
private static final short VAL_ALTERNATE_HOST_ADDRESS = 6;
private static final short VAL_ECHO = 8;
private static final short VAL_ROUTER_ADVERTISEMENT = 9;
private static final short VAL_ROUTER_SOLICITATION = 10;
private static final short VAL_TIME_EXCEEDED = 11;
private static final short VAL_PARAMETER_PROBLEM = 12;
private static final short VAL_TIMESTAMP = 13;
private static final short VAL_TIMESTAMP_REPLY = 14;
private static final short VAL_INFORMATION_REQUEST = 15;
private static final short VAL_INFORMATION_REPLY = 16;
private static final short VAL_ADDRESS_MASK_REQUEST = 17;
private static final short VAL_ADDRESS_MASK_REPLY = 18;
private static final short VAL_TRACEROUTE = 30;
private static final short VAL_DATAGRAM_CONVERSION_ERROR = 31;
private static final short VAL_MOBILE_HOST_REDIRECT = 32;
private static final short VAL_IPV6_WHERE_ARE_YOU = 33;
private static final short VAL_IPV6_I_AM_HERE = 34;
private static final short VAL_MOBILE_REGISTRATION_REQUEST = 35;
private static final short VAL_MOBILE_REGISTRATION_REPLY = 36;
private static final short VAL_DOMAIN_NAME_REQUEST = 37;
private static final short VAL_DOMAIN_NAME_REPLY = 38;
private static final short VAL_SKIP = 39;
private static final short VAL_PHOTURIS = 40;
private static final short VAL_EXPERIMENTAL_MOBILITY = 41;
public static final ICMPv4Type ECHO_REPLY = new ICMPv4Type(VAL_ECHO_REPLY);
public static final ICMPv4Type DESTINATION_UNREACHABLE = new ICMPv4Type(VAL_DESTINATION_UNREACHABLE);
public static final ICMPv4Type SOURCE_QUENCH = new ICMPv4Type(VAL_SOURCE_QUENCH);
public static final ICMPv4Type REDIRECT = new ICMPv4Type(VAL_REDIRECT);
public static final ICMPv4Type ALTERNATE_HOST_ADDRESS = new ICMPv4Type(VAL_ALTERNATE_HOST_ADDRESS);
public static final ICMPv4Type ECHO = new ICMPv4Type(VAL_ECHO);
public static final ICMPv4Type ROUTER_ADVERTISEMENT = new ICMPv4Type(VAL_ROUTER_ADVERTISEMENT);
public static final ICMPv4Type ROUTER_SOLICITATION = new ICMPv4Type(VAL_ROUTER_SOLICITATION);
public static final ICMPv4Type TIME_EXCEEDED = new ICMPv4Type(VAL_TIME_EXCEEDED);
public static final ICMPv4Type PARAMETER_PROBLEM = new ICMPv4Type(VAL_PARAMETER_PROBLEM);
public static final ICMPv4Type TIMESTAMP = new ICMPv4Type(VAL_TIMESTAMP);
public static final ICMPv4Type TIMESTAMP_REPLY = new ICMPv4Type(VAL_TIMESTAMP_REPLY);
public static final ICMPv4Type INFORMATION_REQUEST = new ICMPv4Type(VAL_INFORMATION_REQUEST);
public static final ICMPv4Type INFORMATION_REPLY = new ICMPv4Type(VAL_INFORMATION_REPLY);
public static final ICMPv4Type ADDRESS_MASK_REQUEST = new ICMPv4Type(VAL_ADDRESS_MASK_REQUEST);
public static final ICMPv4Type ADDRESS_MASK_REPLY = new ICMPv4Type(VAL_ADDRESS_MASK_REPLY);
public static final ICMPv4Type TRACEROUTE = new ICMPv4Type(VAL_TRACEROUTE);
public static final ICMPv4Type DATAGRAM_CONVERSION_ERROR = new ICMPv4Type(VAL_DATAGRAM_CONVERSION_ERROR);
public static final ICMPv4Type MOBILE_HOST_REDIRECT = new ICMPv4Type(VAL_MOBILE_HOST_REDIRECT);
public static final ICMPv4Type IPV6_WHERE_ARE_YOU = new ICMPv4Type(VAL_IPV6_WHERE_ARE_YOU);
public static final ICMPv4Type IPV6_I_AM_HERE = new ICMPv4Type(VAL_IPV6_I_AM_HERE);
public static final ICMPv4Type MOBILE_REGISTRATION_REQUEST = new ICMPv4Type(VAL_MOBILE_REGISTRATION_REQUEST);
public static final ICMPv4Type MOBILE_REGISTRATION_REPLY = new ICMPv4Type(VAL_MOBILE_REGISTRATION_REPLY);
public static final ICMPv4Type DOMAIN_NAME_REQUEST = new ICMPv4Type(VAL_DOMAIN_NAME_REQUEST);
public static final ICMPv4Type DOMAIN_NAME_REPLY = new ICMPv4Type(VAL_DOMAIN_NAME_REPLY);
public static final ICMPv4Type SKIP = new ICMPv4Type(VAL_SKIP);
public static final ICMPv4Type PHOTURIS = new ICMPv4Type(VAL_PHOTURIS);
public static final ICMPv4Type EXPERIMENTAL_MOBILITY = new ICMPv4Type(VAL_EXPERIMENTAL_MOBILITY);
// HACK alert - we're disapproriating ECHO_REPLY (value 0) as 'none' as well
public static final ICMPv4Type NONE = ECHO_REPLY;
public static final ICMPv4Type NO_MASK = new ICMPv4Type((short)0xFFFF);
public static final ICMPv4Type FULL_MASK = new ICMPv4Type((short)0x0000);
private final short type;
private static final int MIN_TYPE = 0;
private static final int MAX_TYPE = 0xFF;
private ICMPv4Type(short type) {
this.type = type;
}
public static ICMPv4Type of(short type) {
if (type < MIN_TYPE || type > MAX_TYPE)
throw new IllegalArgumentException("Invalid ICMPv4 type: " + type);
switch (type) {
case VAL_ECHO_REPLY:
return ECHO_REPLY;
case VAL_DESTINATION_UNREACHABLE:
return DESTINATION_UNREACHABLE;
case VAL_SOURCE_QUENCH:
return SOURCE_QUENCH;
case VAL_REDIRECT:
return REDIRECT;
case VAL_ALTERNATE_HOST_ADDRESS:
return ALTERNATE_HOST_ADDRESS;
case VAL_ECHO:
return ECHO;
case VAL_ROUTER_ADVERTISEMENT:
return ROUTER_ADVERTISEMENT;
case VAL_ROUTER_SOLICITATION:
return ROUTER_SOLICITATION;
case VAL_TIME_EXCEEDED:
return TIME_EXCEEDED;
case VAL_PARAMETER_PROBLEM:
return PARAMETER_PROBLEM;
case VAL_TIMESTAMP:
return TIMESTAMP;
case VAL_TIMESTAMP_REPLY:
return TIMESTAMP_REPLY;
case VAL_INFORMATION_REQUEST:
return INFORMATION_REQUEST;
case VAL_INFORMATION_REPLY:
return INFORMATION_REPLY;
case VAL_ADDRESS_MASK_REQUEST:
return ADDRESS_MASK_REQUEST;
case VAL_ADDRESS_MASK_REPLY:
return ADDRESS_MASK_REPLY;
case VAL_TRACEROUTE:
return TRACEROUTE;
case VAL_DATAGRAM_CONVERSION_ERROR:
return DATAGRAM_CONVERSION_ERROR;
case VAL_MOBILE_HOST_REDIRECT:
return MOBILE_HOST_REDIRECT;
case VAL_IPV6_WHERE_ARE_YOU:
return IPV6_WHERE_ARE_YOU;
case VAL_IPV6_I_AM_HERE:
return IPV6_I_AM_HERE;
case VAL_MOBILE_REGISTRATION_REQUEST:
return MOBILE_REGISTRATION_REQUEST;
case VAL_MOBILE_REGISTRATION_REPLY:
return MOBILE_REGISTRATION_REPLY;
case VAL_DOMAIN_NAME_REQUEST:
return DOMAIN_NAME_REQUEST;
case VAL_DOMAIN_NAME_REPLY:
return DOMAIN_NAME_REPLY;
case VAL_SKIP:
return SKIP;
case VAL_PHOTURIS:
return PHOTURIS;
case VAL_EXPERIMENTAL_MOBILITY:
return EXPERIMENTAL_MOBILITY;
default:
return new ICMPv4Type(type);
}
}
@Override
public int getLength() {
return LENGTH;
}
public short getType() {
return type;
}
public void writeByte(ChannelBuffer c) {
c.writeByte(this.type);
}
public static ICMPv4Type readByte(ChannelBuffer c) {
return ICMPv4Type.of(c.readUnsignedByte());
}
@Override
public ICMPv4Type applyMask(ICMPv4Type mask) {
return ICMPv4Type.of((short)(this.type & mask.type));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + type;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ICMPv4Type other = (ICMPv4Type) obj;
if (type != other.type)
return false;
return true;
}
@Override
public int compareTo(ICMPv4Type o) {
return Shorts.compare(type, o.type);
}
@Override
public void putTo(PrimitiveSink sink) {
sink.putShort(type);
}
@Override
public String toString() {
return String.valueOf(this.type);
}
}
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.