source: src/main/java/geniusweb/partiesserver/websocket/PartySocket.java@ 22

Last change on this file since 22 was 21, checked in by bart, 4 years ago

Fixes an issue with processing maxPower of a vote. Javadoc maven plugin now uses latest version.

File size: 8.6 KB
RevLine 
[1]1package geniusweb.partiesserver.websocket;
2
3import java.io.EOFException;
4import java.io.IOException;
5import java.net.URI;
6import java.util.Date;
[8]7import java.util.List;
8import java.util.concurrent.CopyOnWriteArrayList;
[1]9import java.util.logging.Level;
10
11import javax.websocket.CloseReason;
12import javax.websocket.CloseReason.CloseCodes;
13import javax.websocket.OnClose;
14import javax.websocket.OnError;
15import javax.websocket.OnMessage;
16import javax.websocket.OnOpen;
17import javax.websocket.Session;
18import javax.websocket.server.PathParam;
19import javax.websocket.server.ServerEndpoint;
20
21import com.fasterxml.jackson.databind.ObjectMapper;
22
23import geniusweb.actions.Action;
24import geniusweb.actions.PartyId;
[8]25import geniusweb.connection.ConnectionEnd;
[18]26import geniusweb.inform.Inform;
27import geniusweb.inform.Settings;
[1]28import geniusweb.partiesserver.repository.RunningPartiesRepo;
29import geniusweb.partiesserver.repository.RunningParty;
30import geniusweb.party.Party;
31import geniusweb.references.Reference;
32import tudelft.utilities.listener.Listener;
33import tudelft.utilities.logging.ReportToLogger;
34import tudelft.utilities.logging.Reporter;
35
36/**
37 * Returns a websocket that communicates with the {@link RunningParty}. We close
38 * the socket when we detect the party is gone (eg, due to a bug in the party or
39 * a time-out). If the socket breaks, we close the party as it becomes isolated.
40 */
41@ServerEndpoint("/party/{party}")
[8]42public class PartySocket implements ConnectionEnd<Inform, Action> {
[1]43 private final static ObjectMapper jackson = new ObjectMapper();
[16]44 private static final int MAX_MESSAGE_SIZE = 20 * 1024 * 1024;
45
[1]46 private final Reporter log;
47 private final RunningPartiesRepo runningparties;
[8]48 private final List<Listener<Inform>> listeners = new CopyOnWriteArrayList<Listener<Inform>>();
[16]49 private final ActiveThreads threads;
[1]50
51 // should all be final, except that we can only set them when start is
52 // called...
53 private Session session;
54
55 private PartyId partyID;
56
57 private SendBuffer outstream;
58 private Throwable error = null;
59
60 public PartySocket() {
61 this(RunningPartiesRepo.instance(),
62 new ReportToLogger("partiesserver"));
63 }
64
65 public PartySocket(RunningPartiesRepo parties, Reporter reporter) {
66 this.runningparties = parties;
67 this.log = reporter;
[16]68 this.threads = new ActiveThreads(log);
[1]69 }
70
71 @OnOpen
72 public void start(Session session,
73 @PathParam("party") final String partyidname) throws IOException {
74 if (partyidname == null) {
75 throw new IllegalArgumentException("party can't be null");
76 }
[9]77 session.setMaxTextMessageBufferSize(MAX_MESSAGE_SIZE);
78 session.setMaxBinaryMessageBufferSize(MAX_MESSAGE_SIZE);
79
[1]80 this.session = session;
81 this.partyID = new PartyId(partyidname);
82 this.outstream = new SendBuffer(session.getBasicRemote(), log);
83
84 // listen to parties repo, so that we can act if party is terminated
85 runningparties.addListener(new Listener<PartyId>() {
86 @Override
87 public void notifyChange(PartyId data) {
88 if (runningparties.get(partyID) == null) {
89 // party was removed, probably due to time out.
90 try {
91 log.log(Level.INFO,
92 "Party " + partyID + " was terminated ");
93 runningparties.removeListener(this);
94 session.close(new CloseReason(CloseCodes.GOING_AWAY,
[8]95 "detected that party vanished"));
[1]96 } catch (IOException e) {
97 log.log(Level.WARNING,
98 "failed to close the socket for " + partyID, e);
99 }
100 }
101 }
102 });
103 RunningParty runningparty = runningparties.get(partyID);
104
105 if (runningparty == null) {
106 session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT,
107 "No such party: " + partyID));
108 } else {
109 runningparties.replace(runningparty.withConnection(this));
110 }
111
112 // we do not listen for changes on the Parties factory as we can't
113 // replace the running party anyway
114 }
115
116 /**
117 * Called when a message comes in on the server socket that needs to be
118 * passed into the {@link Party}. We also sniff the message for termination
119 * indicators.
120 *
121 * @param informmessage the incoming string, supposedly a JSON-fornatted
122 * {@link Inform}
123 * @param session the session. We already have this info.
[21]124 * @throws IOException if there is a socket/connection error, we can't parse
125 * the received data, etc
[1]126 */
127 @OnMessage
128 public void onMessage(String informmessage, Session session)
[21]129 throws IOException {
[1]130 if (this.session != session) {
131 throw new IllegalStateException("Unexpected change of session ID");
132 }
[16]133 if (!threads.isEmpty()) {
134 log.log(Level.WARNING, "Party " + partyID
135 + " is still busy with previous message");
136 }
[1]137 Inform info = jackson.readValue(informmessage, Inform.class);
138 RunningParty party = runningparties.get(partyID);
139 if (party != null) {
[4]140 // first sniff, to ensure the deadlines are updated first.
141 sniff(info, party);
[1]142 log.log(Level.FINE, "Inform " + partyID + ": " + info);
143 try {
[16]144 threads.add();
[1]145 party.inform(info);
[16]146 threads.remove();
[1]147 } catch (Throwable e) {
[16]148 threads.remove();
149 if (e instanceof ThreadDeath)
150 /*
151 * ThreadDeath always prints stacktrace anwyay, stacktrace
152 * is useless because it contains the thrower's stacktrace
153 * instead of a useful message.
154 */
155 log.log(Level.WARNING,
156 "Party was killed while handling inform.");
157 else
158 log.log(Level.WARNING, "Party failed on inform.", e);
159 /*
160 * severe as someone wants to debug that. Not severe for us we
161 * don't use jackson.writeValueAsString(e) here because
162 * CloseReason has 123 char limit. The error will be too large
163 * to fit and will be truncated therefore we send a plain string
164 * and hope that enough will arrive at the other side (the
165 * protocol)
166 */
[8]167 session.close(new CloseReason(
168 CloseReason.CloseCodes.CLOSED_ABNORMALLY,
169 "party threw exception: " + collectReasons(e)));
[1]170 }
[8]171 } // else party is dead but that's handled in the listener above
[1]172 }
173
174 /**
[8]175 *
176 * @param e an exception
177 * @return collect all reasons and sub-reasons
178 */
179 private String collectReasons(Throwable e) {
180 String reason = "";
181 do {
182 reason = reason + " : " + e.getClass().getSimpleName() + ":"
183 + e.getMessage();
184 e = e.getCause();
185 } while (e != null);
186 return reason;
187 }
188
189 /**
[1]190 * Sniffs the Inform for termination-related information
191 *
192 * @param info
193 * @param party the party we're handling
194 * @throws IOException
195 */
196 private void sniff(Inform info, RunningParty party) throws IOException {
[8]197 // do NOT sniff Finished messages and close sockets. Parties and their
198 // sockets need to stay running till all messages are handled
199 if (info instanceof Settings) {
[1]200 Date end = ((Settings) info).getProgress().getTerminationTime();
201 runningparties.replace(party.withEndTime(end));
202 }
203 }
204
205 @OnClose
206 public void onClose() throws IOException {
207 log.log(Level.INFO, "socket closed to " + partyID);
[16]208 if (!threads.isEmpty()) {
209 log.log(Level.WARNING, "Party " + partyID
210 + " failed to terminate. Trying to kill the remaining threads.");
211 threads.killall();
212 }
[1]213 runningparties.remove(partyID);
214 outstream.stop();
215 }
216
217 @OnError
218 public void onError(Throwable t) throws Throwable {
219 if (t instanceof EOFException) {
220 // This is a standard exception from Apache when a socket closes.
221 // Just ignore
222 // it...
223 log.log(Level.FINEST,
224 "apache reported EOF from (probably closed) socket, ignoring");
225 return;
226 }
227 log.log(Level.WARNING, "Unhandled exception was reported by Tomcat", t);
228 }
229
230 @Override
231 public void send(Action action) throws IOException {
232 log.log(Level.FINE, "Action " + partyID + ": " + action);
233 outstream.send(jackson.writeValueAsString(action));
234 }
235
236 @Override
237 public Reference getReference() {
238 return null;
239 }
240
241 @Override
242 public URI getRemoteURI() {
243 // In serverendpoints we apparently can't see who was contacting us.
244 throw new UnsupportedOperationException();
245 }
246
247 @Override
248 public void close() {
249 try {
250 session.close();
251 } catch (IOException e) {
252 log.log(Level.SEVERE, "failed to close " + partyID, e);
253 }
254 }
255
256 @Override
257 public Throwable getError() {
258 return error;
259 }
260
[8]261 @Override
262 public void addListener(Listener<Inform> l) {
263 listeners.add(l);
264 }
265
266 @Override
267 public void removeListener(Listener<Inform> l) {
268 listeners.remove(l);
269 }
270
271 /**
272 * This should only be called by the owner of the listenable, not by
273 * listeners or others. Avoid calling this from synchronized blocks as a
274 * notified listener might immediately make more calls to you.
275 * <p>
276 * Any listeners that throw an exception will be intercepted and their
277 * stacktrace is printed.
278 *
279 * @param data information about the change.
280 */
281 public void notifyListeners(Inform data) {
282 for (Listener<Inform> l : listeners) {
283 l.notifyChange(data);
284 }
285 }
286
[1]287}
Note: See TracBrowser for help on using the repository browser.