aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/gnunet/statistics/Statistics.java
blob: d6429629f55ea86644bbb6fb4859fe7593700406 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
59
60
61
62
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/*
 This file is part of GNUnet.
 (C) 2011, 2012 Christian Grothoff (and other contributing authors)

 GNUnet is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published
 by the Free Software Foundation; either version 3, or (at your
 option) any later version.

 GNUnet is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GNUnet; see the file COPYING.  If not, write to the
 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 Boston, MA 02111-1307, USA.
 */

package org.gnunet.statistics;

import org.gnunet.requests.MatchingRequestContainer;
import org.gnunet.requests.RequestIdentifier;
import org.gnunet.requests.SequentialRequestContainer;
import org.gnunet.requests.TimeoutHandler;
import org.gnunet.statistics.messages.GetResponseEndMessage;
import org.gnunet.statistics.messages.GetResponseMessage;
import org.gnunet.statistics.messages.SetMessage;
import org.gnunet.statistics.messages.WatchResponseMessage;
import org.gnunet.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * API for the GNUnet statistics service.
 * <p/>
 * Set, get and monitor statistics values, represented as unsigned 64bit integer.
 * Note that {@literal long}, java's largest primitive type, can only store signed 64bit integers.
 * With absolute operation, its negative values are interpreted as large numbers by the statistics api.
 */
public class  Statistics {
    private static final Logger logger = LoggerFactory
            .getLogger(Statistics.class);

    /**
     * Client connecting us to the statistics service.
     */
    private Client client;

    /**
     * All request to the service for getting a value.
     */
    private final SequentialRequestContainer<GetRequest> getRequests;

    /**
     * All requests to the service for watching a value.
     */
    private final MatchingRequestContainer<Long,WatchRequest> watchRequests;

    /**
     * Do we wait for the final 'TestMessage' from the service and
     * do not accept any new requests?
     */
    private boolean destroyRequested;

    /**
     * Next unused ID to identity watch requests/responses.
     */
    private long nextWatchId = 0;

    /**
     * Timeout when waiting for the TestMessage after destruction of
     * this statistics handle has been requested.
     */
    private Scheduler.TaskIdentifier destroyTimeout;

    /**
     * Messages from the statistics service are dispatched to an instance of this class.
     */
    public class StatisticsMessageReceiver extends RunaboutMessageReceiver {
        public void visit(GetResponseMessage m) {
            RequestIdentifier<GetRequest> r = getRequests.getRequestIdentifier();
            if (r != null)
	            r.getRequest().receiver.onReceive(m.subsystemName, m.statisticName, m.value);
        }

        public void visit(@SuppressWarnings("UnusedParameters") GetResponseEndMessage m) {
            RequestIdentifier<GetRequest> r = getRequests.getRequestIdentifier();
            if (r != null) {
                r.retire();
                r.getRequest().receiver.onDone();
            }
        }

        public void visit(@SuppressWarnings("UnusedParameters") TestMessage m) {
            // The TestMessage indicates that the statistics service received all our
            // messages, we can disconnect.
            if (null != destroyTimeout) {
                destroyTimeout.cancel();
                destroyTimeout = null;
            } else {
                logger.error("protocol violation: destroy timeout is 'null' but got test message");
            }
            client.disconnect();
        }

        public void visit(WatchResponseMessage wrm) {
            RequestIdentifier<WatchRequest> ri = watchRequests.getRequestIdentifier((long) wrm.wid);
            WatchRequest r = ri.getRequest();
            if (r != null) {
                r.watcher.onReceive(r.subsystem, r.name, wrm.value);
            }
        }

        @Override
        public void handleError() {
            if (null == client)
                throw new AssertionError();
            if (!destroyRequested) {
                client.reconnect();
                getRequests.restart();
                watchRequests.restart();
            }
            // if everything is shutting down, maybe the statistics service
            // was shut down, and can't respond with the TestMessage anymore.
            if (null != destroyTimeout) {
                destroyTimeout.cancel();
                destroyTimeout = null;
            }
        }
    }

    /**
     * Create a connection to the statistics service.
     *
     * @param cfg configuration to use
     */
    public Statistics(Configuration cfg) {
        client = new Client("statistics", cfg);
        client.installReceiver(new StatisticsMessageReceiver());
        getRequests = new SequentialRequestContainer<GetRequest>(client);
        watchRequests = new MatchingRequestContainer<Long, WatchRequest>(client);
    }

    /**
     * Retrieve a statistics value of a subsystem.
     *
     * @param timeout      time after we give up and call receiver.onTimeout
     * @param subsystem    the subsystem of interest
     * @param name         name of the statistics value belongs to
     * @param receiver     callback
     * @return handle to onCancel the getRequestIdentifier
     */
    public Cancelable get(RelativeTime timeout, final String subsystem, final String name,
                          final StatisticsReceiver receiver) {
        if (destroyRequested || client == null)
            throw new AssertionError("already destroyed");
        RequestIdentifier<GetRequest> identifier = getRequests.addRequest(new GetRequest(subsystem, name, receiver));
        identifier.setTimeout(timeout, new TimeoutHandler() {
            @Override
            public void onTimeout() {
                receiver.onTimeout();
            }
        });
        return identifier;
    }

    /**
     * Retrieve all statistics value of a subsystem.
     *
     * @param timeout      time after we give up and call receiver.onTimeout
     * @param subsystem    the subsystem of interest
     * @param receiver     callback
     * @return handle to onCancel the getRequestIdentifier
     */
    public Cancelable get(RelativeTime timeout, final String subsystem,
                          final StatisticsReceiver receiver) {
        return get(timeout, subsystem, "", receiver);
    }

    /**
     * Sets a statistics value asynchronously.
     *
     * @param name    name of the entry
     * @param value   desired value
     * @param persist keep value even if the statistics service restarts
     */
    public void set(final String subsystem, final String name, final long value, boolean persist) {
        if (destroyRequested || client == null)
            throw new AssertionError("already destroyed");
        SetMessage m = new SetMessage();
        m.statisticName = name;
        m.subsystemName = subsystem;
        m.value = value;
        if (persist)
            m.flags |= SetMessage.SETFLAG_PERSIST;
        client.send(m);
    }

    /**
     * Changes a statistics value asynchronously.
     *
     * @param name    name of the entry
     * @param delta   relative difference to the old value
     * @param persist keep value even if the statistics service restarts
     */
    public void update(final String subsystem, final String name, final long delta, boolean persist) {
        if (destroyRequested || null == client)
            throw new AssertionError("already destroyed");
        SetMessage m = new SetMessage();
        m.statisticName = name;
        m.subsystemName = subsystem;
        m.value = delta;
        if (persist)
            m.flags |= SetMessage.SETFLAG_PERSIST;
        m.flags |= SetMessage.SETFLAG_RELATIVE;
        client.send(m);
    }

    /**
     * Receive updates about changing statistics values.
     *
     * @param subsystem the subsystem to watch
     * @param name the value to watch
     * @param watcher the object that receives the updates
     * @return a handle to onCancel the getRequestIdentifier
     */
    public Cancelable watch(final String subsystem, final String name, StatisticsWatcher watcher) {
        if (destroyRequested || null == client)
            throw new AssertionError("already destroyed");
        WatchRequest r = new WatchRequest(subsystem, name, watcher);
        return watchRequests.addRequest(nextWatchId++, r);
    }


    /**
     * Destroy handle to the statistics service. Always finishes writing pending values.
     */
    public void destroy() {
      destroy(true);
    }

    /**
     * Destroy handle to the statistics service.
     *
     * @param syncFirst If true, wait until the statistics service has received all our updates.
     *                  If false, pending updates may be lost.
     */
    public void destroy(boolean syncFirst) {
        if (destroyRequested)
            throw new AssertionError("already destroyed");
        destroyRequested = true;
        logger.debug("destroying statistics");
        if (!syncFirst || !client.isConnected()) {
            client.disconnect();
            client = null;
            return;
        }
        client.send(new TestMessage());
        // wait until the service responds or a timeout occurs
        destroyTimeout = Scheduler.addDelayed(RelativeTime.fromSeconds(5), new Scheduler.Task() {
            @Override
            public void run(Scheduler.RunContext ctx) {
                if (null == client)
                    return;
                client.disconnect();
                client = null;
            }
        });
    }
}