[1] | 1 | package geniusweb.partiesserver.websocket;
|
---|
| 2 |
|
---|
| 3 | import java.io.EOFException;
|
---|
| 4 | import java.io.IOException;
|
---|
| 5 | import java.net.URI;
|
---|
| 6 | import java.util.Date;
|
---|
[8] | 7 | import java.util.List;
|
---|
| 8 | import java.util.concurrent.CopyOnWriteArrayList;
|
---|
[1] | 9 | import java.util.logging.Level;
|
---|
| 10 |
|
---|
| 11 | import javax.websocket.CloseReason;
|
---|
| 12 | import javax.websocket.CloseReason.CloseCodes;
|
---|
| 13 | import javax.websocket.OnClose;
|
---|
| 14 | import javax.websocket.OnError;
|
---|
| 15 | import javax.websocket.OnMessage;
|
---|
| 16 | import javax.websocket.OnOpen;
|
---|
| 17 | import javax.websocket.Session;
|
---|
| 18 | import javax.websocket.server.PathParam;
|
---|
| 19 | import javax.websocket.server.ServerEndpoint;
|
---|
| 20 |
|
---|
| 21 | import com.fasterxml.jackson.core.JsonParseException;
|
---|
| 22 | import com.fasterxml.jackson.databind.JsonMappingException;
|
---|
| 23 | import com.fasterxml.jackson.databind.ObjectMapper;
|
---|
| 24 |
|
---|
| 25 | import geniusweb.actions.Action;
|
---|
| 26 | import geniusweb.actions.PartyId;
|
---|
[8] | 27 | import geniusweb.connection.ConnectionEnd;
|
---|
[18] | 28 | import geniusweb.inform.Inform;
|
---|
| 29 | import geniusweb.inform.Settings;
|
---|
[1] | 30 | import geniusweb.partiesserver.repository.RunningPartiesRepo;
|
---|
| 31 | import geniusweb.partiesserver.repository.RunningParty;
|
---|
| 32 | import geniusweb.party.Party;
|
---|
| 33 | import geniusweb.references.Reference;
|
---|
| 34 | import tudelft.utilities.listener.Listener;
|
---|
| 35 | import tudelft.utilities.logging.ReportToLogger;
|
---|
| 36 | import tudelft.utilities.logging.Reporter;
|
---|
| 37 |
|
---|
| 38 | /**
|
---|
| 39 | * Returns a websocket that communicates with the {@link RunningParty}. We close
|
---|
| 40 | * the socket when we detect the party is gone (eg, due to a bug in the party or
|
---|
| 41 | * a time-out). If the socket breaks, we close the party as it becomes isolated.
|
---|
| 42 | */
|
---|
| 43 | @ServerEndpoint("/party/{party}")
|
---|
[8] | 44 | public class PartySocket implements ConnectionEnd<Inform, Action> {
|
---|
[1] | 45 | private final static ObjectMapper jackson = new ObjectMapper();
|
---|
[16] | 46 | private static final int MAX_MESSAGE_SIZE = 20 * 1024 * 1024;
|
---|
| 47 |
|
---|
[1] | 48 | private final Reporter log;
|
---|
| 49 | private final RunningPartiesRepo runningparties;
|
---|
[8] | 50 | private final List<Listener<Inform>> listeners = new CopyOnWriteArrayList<Listener<Inform>>();
|
---|
[16] | 51 | private final ActiveThreads threads;
|
---|
[1] | 52 |
|
---|
| 53 | // should all be final, except that we can only set them when start is
|
---|
| 54 | // called...
|
---|
| 55 | private Session session;
|
---|
| 56 |
|
---|
| 57 | private PartyId partyID;
|
---|
| 58 |
|
---|
| 59 | private SendBuffer outstream;
|
---|
| 60 | private Throwable error = null;
|
---|
| 61 |
|
---|
| 62 | public PartySocket() {
|
---|
| 63 | this(RunningPartiesRepo.instance(),
|
---|
| 64 | new ReportToLogger("partiesserver"));
|
---|
| 65 | }
|
---|
| 66 |
|
---|
| 67 | public PartySocket(RunningPartiesRepo parties, Reporter reporter) {
|
---|
| 68 | this.runningparties = parties;
|
---|
| 69 | this.log = reporter;
|
---|
[16] | 70 | this.threads = new ActiveThreads(log);
|
---|
[1] | 71 | }
|
---|
| 72 |
|
---|
| 73 | @OnOpen
|
---|
| 74 | public void start(Session session,
|
---|
| 75 | @PathParam("party") final String partyidname) throws IOException {
|
---|
| 76 | if (partyidname == null) {
|
---|
| 77 | throw new IllegalArgumentException("party can't be null");
|
---|
| 78 | }
|
---|
[9] | 79 | session.setMaxTextMessageBufferSize(MAX_MESSAGE_SIZE);
|
---|
| 80 | session.setMaxBinaryMessageBufferSize(MAX_MESSAGE_SIZE);
|
---|
| 81 |
|
---|
[1] | 82 | this.session = session;
|
---|
| 83 | this.partyID = new PartyId(partyidname);
|
---|
| 84 | this.outstream = new SendBuffer(session.getBasicRemote(), log);
|
---|
| 85 |
|
---|
| 86 | // listen to parties repo, so that we can act if party is terminated
|
---|
| 87 | runningparties.addListener(new Listener<PartyId>() {
|
---|
| 88 | @Override
|
---|
| 89 | public void notifyChange(PartyId data) {
|
---|
| 90 | if (runningparties.get(partyID) == null) {
|
---|
| 91 | // party was removed, probably due to time out.
|
---|
| 92 | try {
|
---|
| 93 | log.log(Level.INFO,
|
---|
| 94 | "Party " + partyID + " was terminated ");
|
---|
| 95 | runningparties.removeListener(this);
|
---|
| 96 | session.close(new CloseReason(CloseCodes.GOING_AWAY,
|
---|
[8] | 97 | "detected that party vanished"));
|
---|
[1] | 98 | } catch (IOException e) {
|
---|
| 99 | log.log(Level.WARNING,
|
---|
| 100 | "failed to close the socket for " + partyID, e);
|
---|
| 101 | }
|
---|
| 102 | }
|
---|
| 103 | }
|
---|
| 104 | });
|
---|
| 105 | RunningParty runningparty = runningparties.get(partyID);
|
---|
| 106 |
|
---|
| 107 | if (runningparty == null) {
|
---|
| 108 | session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT,
|
---|
| 109 | "No such party: " + partyID));
|
---|
| 110 | } else {
|
---|
| 111 | runningparties.replace(runningparty.withConnection(this));
|
---|
| 112 | }
|
---|
| 113 |
|
---|
| 114 | // we do not listen for changes on the Parties factory as we can't
|
---|
| 115 | // replace the running party anyway
|
---|
| 116 | }
|
---|
| 117 |
|
---|
| 118 | /**
|
---|
| 119 | * Called when a message comes in on the server socket that needs to be
|
---|
| 120 | * passed into the {@link Party}. We also sniff the message for termination
|
---|
| 121 | * indicators.
|
---|
| 122 | *
|
---|
| 123 | * @param informmessage the incoming string, supposedly a JSON-fornatted
|
---|
| 124 | * {@link Inform}
|
---|
| 125 | * @param session the session. We already have this info.
|
---|
| 126 | */
|
---|
| 127 | @OnMessage
|
---|
| 128 | public void onMessage(String informmessage, Session session)
|
---|
| 129 | throws JsonParseException, JsonMappingException, IOException {
|
---|
| 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 | }
|
---|