blob: 514bc2352dde92f05b09c5e7b52ca032893dc61e [file] [log] [blame]
Jian Li0bbbb1c2018-06-22 22:01:17 +09001/*
2 * Copyright 2018-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Jian Li7fe7eaf2018-12-31 17:00:33 +090016package org.onosproject.openstacktelemetry.codec.bytebuffer;
Jian Li0bbbb1c2018-06-22 22:01:17 +090017
18import org.onosproject.openstacktelemetry.api.FlowInfo;
Jian Li69600e02018-12-24 13:21:18 +090019import org.onosproject.openstacktelemetry.api.TelemetryCodec;
Jian Li0bbbb1c2018-06-22 22:01:17 +090020
21import java.nio.ByteBuffer;
22import java.util.Set;
23
24/**
25 * Tina Message ByteBuffer Codec.
26 */
Jian Li69600e02018-12-24 13:21:18 +090027public class TinaMessageByteBufferCodec implements TelemetryCodec {
Jian Lia4947682018-07-07 14:53:32 +090028
Jian Li0bbbb1c2018-06-22 22:01:17 +090029 private static final int HEADER_SIZE = 8;
30 private static final int ENTRY_SIZE = 88;
31 private static final int MILLISECONDS = 1000;
32 private static final short KAFKA_MESSAGE_TYPE = 1;
33
34 /**
35 * Encodes a collection flow infos into byte buffer.
36 *
37 * @param flowInfos a collection of flow info
38 * @return encoded byte buffer
39 */
Jian Li69600e02018-12-24 13:21:18 +090040 @Override
Jian Li0bbbb1c2018-06-22 22:01:17 +090041 public ByteBuffer encode(Set<FlowInfo> flowInfos) {
42 ByteBuffer byteBuffer =
43 ByteBuffer.allocate(HEADER_SIZE + flowInfos.size() * ENTRY_SIZE);
44
45 byteBuffer.put(buildMessageHeader(flowInfos));
46 byteBuffer.put(buildMessageBody(flowInfos));
47
48 return byteBuffer;
49 }
50
51 private byte[] buildMessageHeader(Set<FlowInfo> flowInfos) {
52 ByteBuffer byteBuffer = ByteBuffer.allocate(HEADER_SIZE);
53
54 byteBuffer.putShort((short) flowInfos.size());
55 byteBuffer.putShort(KAFKA_MESSAGE_TYPE);
56 byteBuffer.putInt((int) (System.currentTimeMillis() / MILLISECONDS));
57
58 return byteBuffer.array();
59 }
60
61 private byte[] buildMessageBody(Set<FlowInfo> flowInfos) {
62 ByteBuffer byteBuffer = ByteBuffer.allocate(flowInfos.size() * ENTRY_SIZE);
63
64 TinaFlowInfoByteBufferCodec codec = new TinaFlowInfoByteBufferCodec();
Jian Lie7b1bd22018-06-27 15:15:28 +090065 flowInfos.forEach(flowInfo -> byteBuffer.put(codec.encode(flowInfo).array()));
Jian Li0bbbb1c2018-06-22 22:01:17 +090066
67 return byteBuffer.array();
68 }
69}