ServerTrafficCounter.java 11.4 KB
Newer Older
Gaston Dombiak's avatar
Gaston Dombiak committed
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: $
 * $Date: $
 *
6
 * Copyright (C) 2005-2008 Jive Software. All rights reserved.
Gaston Dombiak's avatar
Gaston Dombiak committed
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * 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.
Gaston Dombiak's avatar
Gaston Dombiak committed
19 20
 */

21
package org.jivesoftware.openfire.net;
Gaston Dombiak's avatar
Gaston Dombiak committed
22 23

import org.jivesoftware.util.LocaleUtils;
24 25
import org.jivesoftware.openfire.stats.Statistic;
import org.jivesoftware.openfire.stats.StatisticsManager;
Gaston Dombiak's avatar
Gaston Dombiak committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.concurrent.atomic.AtomicLong;

/**
 * A ServerTrafficCounter counts the number of bytes read and written by the server. This
 * includes client-server, server-server, external components and connection managers traffic.
 * Note that traffic is monitored only for entities that are directly connected to the server.
 * However, traffic generated by file transfers is not considered unless files were sent using
 * the in-band method.
 *
 * @author Gaston Dombiak
 */
public class ServerTrafficCounter {

    /**
     * Outgoing server traffic counter.
     */
    private static final AtomicLong outgoingCounter = new AtomicLong(0);
    /**
     * Incoming server traffic counter.
     */
    private static final AtomicLong incomingCounter = new AtomicLong(0);

    private static final String trafficStatGroup = "server_bytes";
    private static final String incomingStatKey = "server_bytes_in";
    private static final String outgoingStatKey = "server_bytes_out";

59 60 61 62
    /**
     * Creates and adds statistics to statistic manager.
     */
    public static void initStatistics() {
Gaston Dombiak's avatar
Gaston Dombiak committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
        addReadBytesStat();
        addWrittenBytesStat();
    }

    /**
     * Wraps the specified input stream to count the number of bytes that were read.
     *
     * @param originalStream the input stream to wrap.
     * @return The wrapped input stream over the original stream.
     */
    public static InputStream wrapInputStream(InputStream originalStream) {
        return new InputStreamWrapper(originalStream);
    }

    /**
     * Wraps the specified output stream to count the number of bytes that were written.
     *
     * @param originalStream the output stream to wrap.
     * @return The wrapped output stream over the original stream.
     */
    public static OutputStream wrapOutputStream(OutputStream originalStream) {
        return new OutputStreamWrapper(originalStream);
    }

    /**
     * Wraps the specified readable channel to count the number of bytes that were read.
     *
     * @param originalChannel the readable byte channel to wrap.
     * @return The wrapped readable channel over the original readable channel .
     */
    public static ReadableByteChannel wrapReadableChannel(ReadableByteChannel originalChannel) {
        return new ReadableByteChannelWrapper(originalChannel);
    }

    /**
     * Wraps the specified writable channel to count the number of bytes that were written.
     *
     * @param originalChannel the writable byte channel to wrap.
     * @return The wrapped writable channel over the original writable channel .
     */
    public static WritableByteChannel wrapWritableChannel(WritableByteChannel originalChannel) {
        return new WritableByteChannelWrapper(originalChannel);
    }

107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    /**
     * Increments the counter of read bytes by delta.
     *
     * @param delta the delta of bytes that were read.
     */
    public static void incrementIncomingCounter(long delta) {
        incomingCounter.getAndAdd(delta);
    }

    /**
     * Increments the counter of written bytes by delta.
     *
     * @param delta the delta of bytes that were written.
     */
    public static void incrementOutgoingCounter(long delta) {
        outgoingCounter.getAndAdd(delta);
    }

Gaston Dombiak's avatar
Gaston Dombiak committed
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    private static void addReadBytesStat() {
        // Register a statistic.
        Statistic statistic = new Statistic() {
            public String getName() {
                return LocaleUtils.getLocalizedString("server_bytes.stats.incoming.name");
            }

            public Type getStatType() {
                return Type.rate;
            }

            public String getDescription() {
                return LocaleUtils.getLocalizedString("server_bytes.stats.incoming.description");
            }

            public String getUnits() {
                return LocaleUtils.getLocalizedString("server_bytes.stats.incoming.label");
            }

            public double sample() {
Matt Tucker's avatar
Matt Tucker committed
145
                // Divide result by 1024 so that we return the result in Kb.
146
                return incomingCounter.getAndSet(0)/1024d;
Gaston Dombiak's avatar
Gaston Dombiak committed
147
            }
148 149 150 151

            public boolean isPartialSample() {
                return true;
            }
Gaston Dombiak's avatar
Gaston Dombiak committed
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
        };
        StatisticsManager.getInstance()
                .addMultiStatistic(incomingStatKey, trafficStatGroup, statistic);
    }

    private static void addWrittenBytesStat() {
        // Register a statistic.
        Statistic statistic = new Statistic() {
            public String getName() {
                return LocaleUtils.getLocalizedString("server_bytes.stats.outgoing.name");
            }

            public Type getStatType() {
                return Type.rate;
            }

            public String getDescription() {
                return LocaleUtils.getLocalizedString("server_bytes.stats.outgoing.description");
            }

            public String getUnits() {
                return LocaleUtils.getLocalizedString("server_bytes.stats.outgoing.label");
            }

            public double sample() {
177
                return outgoingCounter.getAndSet(0)/1024d;
Gaston Dombiak's avatar
Gaston Dombiak committed
178
            }
179 180 181 182

            public boolean isPartialSample() {
                return true;
            }
Gaston Dombiak's avatar
Gaston Dombiak committed
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
        };
        StatisticsManager.getInstance()
                .addMultiStatistic(outgoingStatKey, trafficStatGroup, statistic);
    }

    /**
     * Wrapper on an input stream to intercept and count number of read bytes.
     */
    private static class InputStreamWrapper extends InputStream {
        /**
         * Original input stream being wrapped to count incmoing traffic.
         */
        private InputStream originalStream;

        public InputStreamWrapper(InputStream originalStream) {
            this.originalStream = originalStream;
        }

201 202
        @Override
		public int read() throws IOException {
Gaston Dombiak's avatar
Gaston Dombiak committed
203 204
            int readByte = originalStream.read();
            if (readByte > -1) {
205
                incrementIncomingCounter(1);
Gaston Dombiak's avatar
Gaston Dombiak committed
206 207 208 209
            }
            return readByte;
        }

210 211
        @Override
		public int read(byte b[]) throws IOException {
Gaston Dombiak's avatar
Gaston Dombiak committed
212 213
            int bytes = originalStream.read(b);
            if (bytes > -1) {
214
                incrementIncomingCounter(bytes);
Gaston Dombiak's avatar
Gaston Dombiak committed
215 216 217 218
            }
            return bytes;
        }

219 220
        @Override
		public int read(byte b[], int off, int len) throws IOException {
Gaston Dombiak's avatar
Gaston Dombiak committed
221 222
            int bytes = originalStream.read(b, off, len);
            if (bytes > -1) {
223
                incrementIncomingCounter(bytes);
Gaston Dombiak's avatar
Gaston Dombiak committed
224 225 226 227
            }
            return bytes;
        }

228 229
        @Override
		public int available() throws IOException {
Gaston Dombiak's avatar
Gaston Dombiak committed
230 231 232
            return originalStream.available();
        }

233 234
        @Override
		public void close() throws IOException {
Gaston Dombiak's avatar
Gaston Dombiak committed
235 236 237
            originalStream.close();
        }

238 239
        @Override
		public synchronized void mark(int readlimit) {
Gaston Dombiak's avatar
Gaston Dombiak committed
240 241 242
            originalStream.mark(readlimit);
        }

243 244
        @Override
		public boolean markSupported() {
Gaston Dombiak's avatar
Gaston Dombiak committed
245 246 247
            return originalStream.markSupported();
        }

248 249
        @Override
		public synchronized void reset() throws IOException {
Gaston Dombiak's avatar
Gaston Dombiak committed
250 251 252
            originalStream.reset();
        }

253 254
        @Override
		public long skip(long n) throws IOException {
Gaston Dombiak's avatar
Gaston Dombiak committed
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
            return originalStream.skip(n);
        }
    }

    /**
     * Wrapper on an output stream to intercept and count number of written bytes.
     */
    private static class OutputStreamWrapper extends OutputStream {
        /**
         * Original output stream being wrapped to count outgoing traffic.
         */
        private OutputStream originalStream;

        public OutputStreamWrapper(OutputStream originalStream) {
            this.originalStream = originalStream;
        }

272 273
        @Override
		public void write(int b) throws IOException {
Gaston Dombiak's avatar
Gaston Dombiak committed
274 275 276
            // forward request to wrapped stream
            originalStream.write(b);
            // update outgoingCounter
277
            incrementOutgoingCounter(1);
Gaston Dombiak's avatar
Gaston Dombiak committed
278 279
        }

280 281
        @Override
		public void write(byte b[]) throws IOException {
Gaston Dombiak's avatar
Gaston Dombiak committed
282 283 284
            // forward request to wrapped stream
            originalStream.write(b);
            // update outgoingCounter
285
            incrementOutgoingCounter(b.length);
Gaston Dombiak's avatar
Gaston Dombiak committed
286 287
        }

288 289
        @Override
		public void write(byte b[], int off, int len) throws IOException {
Gaston Dombiak's avatar
Gaston Dombiak committed
290 291 292
            // forward request to wrapped stream
            originalStream.write(b, off, len);
            // update outgoingCounter
293
            incrementOutgoingCounter(b.length);
Gaston Dombiak's avatar
Gaston Dombiak committed
294 295
        }

296 297
        @Override
		public void close() throws IOException {
Gaston Dombiak's avatar
Gaston Dombiak committed
298 299 300
            originalStream.close();
        }

301 302
        @Override
		public void flush() throws IOException {
Gaston Dombiak's avatar
Gaston Dombiak committed
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
            originalStream.flush();
        }
    }

    /**
     * Wrapper on a ReadableByteChannel to intercept and count number of read bytes.
     */
    private static class ReadableByteChannelWrapper implements ReadableByteChannel {
        private ReadableByteChannel originalChannel;

        public ReadableByteChannelWrapper(ReadableByteChannel originalChannel) {
            this.originalChannel = originalChannel;
        }

        public int read(ByteBuffer dst) throws IOException {
            int bytes = originalChannel.read(dst);
            if (bytes > -1) {
320
                incrementIncomingCounter(bytes);
Gaston Dombiak's avatar
Gaston Dombiak committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
            }
            return bytes;
        }

        public void close() throws IOException {
            originalChannel.close();
        }

        public boolean isOpen() {
            return originalChannel.isOpen();
        }
    }

    /**
     * Wrapper on a WritableByteChannel to intercept and count number of written bytes.
     */
    private static class WritableByteChannelWrapper implements WritableByteChannel {
        private WritableByteChannel originalChannel;

        public WritableByteChannelWrapper(WritableByteChannel originalChannel) {
            this.originalChannel = originalChannel;
        }

        public void close() throws IOException {
            originalChannel.close();
        }

        public boolean isOpen() {
            return originalChannel.isOpen();
        }

        public int write(ByteBuffer src) throws IOException {
            int bytes = originalChannel.write(src);
354
            incrementOutgoingCounter(bytes);
Gaston Dombiak's avatar
Gaston Dombiak committed
355 356 357 358
            return bytes;
        }
    }
}