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

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

Fixed memory leak. MOPAC2. removed jcenter build dependencies

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