Logging improvements to improve efficiency - specifically in critical path.
[controller.git] / opendaylight / sal / api / src / main / java / org / opendaylight / controller / sal / packet / Packet.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.sal.packet;
10
11 import java.net.InetAddress;
12 import java.net.UnknownHostException;
13 import java.util.Map;
14 import java.util.Map.Entry;
15
16 import org.apache.commons.lang3.tuple.Pair;
17 import org.opendaylight.controller.sal.utils.HexEncode;
18 import org.opendaylight.controller.sal.utils.NetUtils;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21
22 /**
23  * Abstract class which represents the generic network packet object It provides
24  * the basic methods which are common for all the packets, like serialize and
25  * deserialize
26  * 
27  * 
28  */
29
30 public abstract class Packet {
31     protected static final Logger logger = LoggerFactory
32             .getLogger(Packet.class);
33     // Access level granted to this packet
34     protected boolean writeAccess;
35     // When deserialized from wire, packet could result corrupted
36     protected boolean corrupted;
37     // The packet that encapsulate this packet
38     protected Packet parent;
39     // The packet encapsulated by this packet
40     protected Packet payload;
41     // Bit coordinates of packet header fields
42     protected Map<String, Pair<Integer, Integer>> hdrFieldCoordMap;
43     // Header fields values: Map<FieldName,Value>
44     protected Map<String, byte[]> hdrFieldsMap;
45     // The class of the encapsulated packet object
46     protected Class<? extends Packet> payloadClass;
47
48     public Packet() {
49         writeAccess = false;
50         corrupted = false;
51     }
52
53     public Packet(boolean writeAccess) {
54         this.writeAccess = writeAccess;
55         this.corrupted = false;
56     }
57
58     public Packet getParent() {
59         return parent;
60     }
61
62     public Packet getPayload() {
63         return payload;
64     }
65
66     public void setParent(Packet parent) {
67         this.parent = parent;
68     }
69
70     public void setPayload(Packet payload) {
71         this.payload = payload;
72     }
73
74     public void setHeaderField(String headerField, byte[] readValue) {
75         hdrFieldsMap.put(headerField, readValue);
76     }
77
78     /**
79      * This method deserializes the data bits obtained from the wire into the
80      * respective header and payload which are of type Packet
81      * 
82      * @param byte[] data - data from wire to deserialize
83      * @param int bitOffset bit position where packet header starts in data
84      *        array
85      * @param int size of packet in bits
86      * @return Packet
87      * @throws PacketException
88      */
89
90     public Packet deserialize(byte[] data, int bitOffset, int size)
91             throws PacketException {
92         String hdrField;
93         Integer startOffset = 0, numBits = 0;
94         byte[] hdrFieldBytes;
95
96         for (Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
97                 .entrySet()) {
98             hdrField = pairs.getKey();
99             startOffset = bitOffset + this.getfieldOffset(hdrField);
100             numBits = this.getfieldnumBits(hdrField);
101
102             try {
103                 hdrFieldBytes = BitBufferHelper.getBits(data, startOffset,
104                         numBits);
105             } catch (BufferException e) {
106                 throw new PacketException(e.getMessage());
107             }
108             /*
109              * Store the raw read value, checks the payload type and set the
110              * payloadClass accordingly
111              */
112             if (logger.isTraceEnabled()) {
113               logger.trace("{}: {}: {} (offset {} bitsize {})",
114                       new Object[] { this.getClass().getSimpleName(), hdrField,
115                               HexEncode.bytesToHexString(hdrFieldBytes),
116                               startOffset, numBits });
117             }
118
119             this.setHeaderField(hdrField, hdrFieldBytes);
120         }
121
122         postDeserializeCustomOperation(data, startOffset);
123
124         int payloadStart = startOffset + numBits;
125         // int payloadSize = size - payloadStart;
126         int payloadSize = data.length * NetUtils.NumBitsInAByte - payloadStart;
127
128         if (payloadClass != null) {
129             try {
130                 payload = payloadClass.newInstance();
131             } catch (Exception e) {
132                 throw new RuntimeException(
133                         "Error parsing payload for Ethernet packet", e);
134             }
135             payload.deserialize(data, payloadStart, payloadSize);
136             payload.setParent(this);
137         } else {
138             // For now let's discard unparsable payload
139         }
140         return this;
141     }
142
143     /**
144      * This method serializes the header and payload bytes from the respective
145      * packet class, into a single stream of bytes to be sent on the wire
146      * 
147      * @return byte[] - serialized bytes
148      * @throws PacketException
149      */
150
151     public byte[] serialize() throws PacketException {
152         byte[] payloadBytes = null;
153         int payloadSize = 0;
154         int headerSize = this.getHeaderSize();
155         int payloadByteOffset = headerSize / NetUtils.NumBitsInAByte;
156         int size = 0;
157
158         if (payload != null) {
159             payloadBytes = payload.serialize();
160             payloadSize = payloadBytes.length * NetUtils.NumBitsInAByte;
161         }
162
163         size = headerSize + payloadSize;
164         int length = size / NetUtils.NumBitsInAByte;
165         byte headerBytes[] = new byte[length];
166
167         if (payload != null) {
168             System.arraycopy(payloadBytes, 0, headerBytes, payloadByteOffset,
169                     payloadBytes.length);
170         }
171
172         String field;
173         byte[] fieldBytes;
174         Integer startOffset, numBits;
175
176         for (Map.Entry<String, Pair<Integer, Integer>> pairs : hdrFieldCoordMap
177                 .entrySet()) {
178             field = pairs.getKey();
179             fieldBytes = hdrFieldsMap.get(field);
180             // Let's skip optional fields when not set
181             if (fieldBytes != null) {
182                 startOffset = this.getfieldOffset(field);
183                 numBits = this.getfieldnumBits(field);
184                 try {
185                     BitBufferHelper.setBytes(headerBytes, fieldBytes,
186                             startOffset, numBits);
187                 } catch (BufferException e) {
188                     throw new PacketException(e.getMessage());
189                 }
190             }
191         }
192         postSerializeCustomOperation(headerBytes);
193
194         if (logger.isTraceEnabled()) {
195           logger.trace("{}: {}", this.getClass().getSimpleName(),
196                   HexEncode.bytesToHexString(headerBytes));
197         }
198         return headerBytes;
199     }
200
201     /**
202      * This method gets called at the end of the serialization process It is
203      * intended for the child packets to insert some custom data into the output
204      * byte stream which cannot be done or cannot be done efficiently during the
205      * normal Packet.serialize() path. An example is the checksum computation
206      * for IPv4
207      * 
208      * @param byte[] - serialized bytes
209      * @throws PacketException
210      */
211     protected void postSerializeCustomOperation(byte[] myBytes)
212             throws PacketException {
213         // no op
214     }
215
216     /**
217      * This method re-computes the checksum of the bits received on the wire and
218      * validates it with the checksum in the bits received Since the computation
219      * of checksum varies based on the protocol, this method is overridden
220      * Currently only IPv4 does checksum computation and validation TCP and UDP
221      * need to implement these if required
222      * 
223      * @param byte[] data
224      * @param int endBitOffset
225      * @throws PacketException
226      */
227     protected void postDeserializeCustomOperation(byte[] data, int endBitOffset)
228             throws PacketException {
229         // no op
230     }
231
232     /**
233      * Gets the header length in bits
234      * 
235      * @return int the header length in bits
236      */
237     public int getHeaderSize() {
238         int size = 0;
239         /*
240          * We need to iterate over the fields that were read in the frame
241          * (hdrFieldsMap) not all the possible ones described in
242          * hdrFieldCoordMap. For ex, 802.1Q may or may not be there
243          */
244         for (Map.Entry<String, byte[]> fieldEntry : hdrFieldsMap.entrySet()) {
245             if (fieldEntry.getValue() != null) {
246                 String field = fieldEntry.getKey();
247                 size += getfieldnumBits(field);
248             }
249         }
250         return size;
251     }
252
253     /**
254      * This method fetches the start bit offset for header field specified by
255      * 'fieldname'. The offset is present in the hdrFieldCoordMap of the
256      * respective packet class
257      * 
258      * @param String
259      *            fieldName
260      * @return Integer - startOffset of the requested field
261      */
262     public int getfieldOffset(String fieldName) {
263         return (((Pair<Integer, Integer>) hdrFieldCoordMap.get(fieldName))
264                 .getLeft());
265     }
266
267     /**
268      * This method fetches the number of bits for header field specified by
269      * 'fieldname'. The numBits are present in the hdrFieldCoordMap of the
270      * respective packet class
271      * 
272      * @param String
273      *            fieldName
274      * @return Integer - number of bits of the requested field
275      */
276     public int getfieldnumBits(String fieldName) {
277         return (((Pair<Integer, Integer>) hdrFieldCoordMap.get(fieldName))
278                 .getRight());
279     }
280
281     @Override
282     public String toString() {
283         StringBuffer ret = new StringBuffer();
284         for (Map.Entry<String, byte[]> entry : hdrFieldsMap.entrySet()) {
285             ret.append(entry.getKey() + ": ");
286             if (entry.getValue().length == 6) {
287                 ret.append(HexEncode.bytesToHexString(entry.getValue()) + " ");
288             } else if (entry.getValue().length == 4) {
289                 try {
290                     ret.append(InetAddress.getByAddress(entry.getValue())
291                             .getHostAddress() + " ");
292                 } catch (UnknownHostException e) {
293                     logger.error("", e);
294                 }
295             } else {
296                 ret.append(((Long) BitBufferHelper.getLong(entry.getValue()))
297                         .toString() + " ");
298             }
299         }
300         return ret.toString();
301     }
302
303     /**
304      * Returns true if the packet is corrupted
305      * 
306      * @return boolean
307      */
308     protected boolean isPacketCorrupted() {
309         return corrupted;
310     }
311 }