You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GAEApplicationServlet.java 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. /*
  2. @ITMillApache2LicenseForJavaFiles@
  3. */
  4. package com.vaadin.terminal.gwt.server;
  5. import java.io.ByteArrayInputStream;
  6. import java.io.ByteArrayOutputStream;
  7. import java.io.IOException;
  8. import java.io.NotSerializableException;
  9. import java.io.ObjectInputStream;
  10. import java.io.ObjectOutputStream;
  11. import java.io.PrintWriter;
  12. import java.io.StringWriter;
  13. import java.util.ArrayList;
  14. import java.util.Date;
  15. import java.util.List;
  16. import java.util.logging.Logger;
  17. import javax.servlet.ServletException;
  18. import javax.servlet.http.HttpServletRequest;
  19. import javax.servlet.http.HttpServletResponse;
  20. import javax.servlet.http.HttpSession;
  21. import com.google.appengine.api.datastore.Blob;
  22. import com.google.appengine.api.datastore.DatastoreService;
  23. import com.google.appengine.api.datastore.DatastoreServiceFactory;
  24. import com.google.appengine.api.datastore.Entity;
  25. import com.google.appengine.api.datastore.EntityNotFoundException;
  26. import com.google.appengine.api.datastore.FetchOptions.Builder;
  27. import com.google.appengine.api.datastore.Key;
  28. import com.google.appengine.api.datastore.KeyFactory;
  29. import com.google.appengine.api.datastore.PreparedQuery;
  30. import com.google.appengine.api.datastore.Query;
  31. import com.google.appengine.api.datastore.Query.FilterOperator;
  32. import com.google.appengine.api.memcache.Expiration;
  33. import com.google.appengine.api.memcache.MemcacheService;
  34. import com.google.appengine.api.memcache.MemcacheServiceFactory;
  35. import com.google.apphosting.api.DeadlineExceededException;
  36. import com.vaadin.service.ApplicationContext;
  37. /**
  38. * ApplicationServlet to be used when deploying to Google App Engine, in
  39. * web.xml:
  40. *
  41. * <pre>
  42. * &lt;servlet&gt;
  43. * &lt;servlet-name&gt;HelloWorld&lt;/servlet-name&gt;
  44. * &lt;servlet-class&gt;com.vaadin.terminal.gwt.server.GAEApplicationServlet&lt;/servlet-class&gt;
  45. * &lt;init-param&gt;
  46. * &lt;param-name&gt;application&lt;/param-name&gt;
  47. * &lt;param-value&gt;com.vaadin.demo.HelloWorld&lt;/param-value&gt;
  48. * &lt;/init-param&gt;
  49. * &lt;/servlet&gt;
  50. * </pre>
  51. *
  52. * Session support must be enabled in appengine-web.xml:
  53. *
  54. * <pre>
  55. * &lt;sessions-enabled&gt;true&lt;/sessions-enabled&gt;
  56. * </pre>
  57. *
  58. * Appengine datastore cleanup can be invoked by calling one of the applications
  59. * with an additional path "/CLEAN". This can be set up as a cron-job in
  60. * cron.xml (see appengine documentation for more information):
  61. *
  62. * <pre>
  63. * &lt;cronentries&gt;
  64. * &lt;cron&gt;
  65. * &lt;url&gt;/HelloWorld/CLEAN&lt;/url&gt;
  66. * &lt;description&gt;Clean up sessions&lt;/description&gt;
  67. * &lt;schedule&gt;every 2 hours&lt;/schedule&gt;
  68. * &lt;/cron&gt;
  69. * &lt;/cronentries&gt;
  70. * </pre>
  71. *
  72. * It is recommended (but not mandatory) to extract themes and widgetsets and
  73. * have App Engine server these statically. Extract VAADIN folder (and it's
  74. * contents) 'next to' the WEB-INF folder, and add the following to
  75. * appengine-web.xml:
  76. *
  77. * <pre>
  78. * &lt;static-files&gt;
  79. * &lt;include path=&quot;/VAADIN/**&quot; /&gt;
  80. * &lt;/static-files&gt;
  81. * </pre>
  82. *
  83. * Additional limitations:
  84. * <ul>
  85. * <li/>Do not change application state when serving an ApplicationResource.
  86. * <li/>Avoid changing application state in transaction handlers, unless you're
  87. * confident you fully understand the synchronization issues in App Engine.
  88. * <li/>The application remains locked while uploading - no progressbar is
  89. * possible.
  90. * </ul>
  91. */
  92. public class GAEApplicationServlet extends ApplicationServlet {
  93. private static final Logger log = Logger
  94. .getLogger(GAEApplicationServlet.class.getName());
  95. // memcache mutex is MUTEX_BASE + sessio id
  96. private static final String MUTEX_BASE = "_vmutex";
  97. // used identify ApplicationContext in memcache and datastore
  98. private static final String AC_BASE = "_vac";
  99. // UIDL requests will attempt to gain access for this long before telling
  100. // the client to retry
  101. private static final int MAX_UIDL_WAIT_MILLISECONDS = 5000;
  102. // Tell client to retry after this delay.
  103. // Note: currently interpreting Retry-After as ms, not sec
  104. private static final int RETRY_AFTER_MILLISECONDS = 100;
  105. // Properties used in the datastore
  106. private static final String PROPERTY_EXPIRES = "expires";
  107. private static final String PROPERTY_DATA = "data";
  108. // path used for cleanup
  109. private static final String CLEANUP_PATH = "/CLEAN";
  110. // max entities to clean at once
  111. private static final int CLEANUP_LIMIT = 200;
  112. // appengine session kind
  113. private static final String APPENGINE_SESSION_KIND = "_ah_SESSION";
  114. // appengine session expires-parameter
  115. private static final String PROPERTY_APPENGINE_EXPIRES = "_expires";
  116. protected void sendDeadlineExceededNotification(HttpServletRequest request,
  117. HttpServletResponse response) throws IOException {
  118. criticalNotification(
  119. request,
  120. response,
  121. "Deadline Exceeded",
  122. "I'm sorry, but the operation took too long to complete. We'll try reloading to see where we're at, please take note of any unsaved data...",
  123. "", null);
  124. }
  125. protected void sendNotSerializableNotification(HttpServletRequest request,
  126. HttpServletResponse response) throws IOException {
  127. criticalNotification(
  128. request,
  129. response,
  130. "NotSerializableException",
  131. "I'm sorry, but there seems to be a serious problem, please contact the administrator. And please take note of any unsaved data...",
  132. "", getApplicationUrl(request).toString()
  133. + "?restartApplication");
  134. }
  135. protected void sendCriticalErrorNotification(HttpServletRequest request,
  136. HttpServletResponse response) throws IOException {
  137. criticalNotification(
  138. request,
  139. response,
  140. "Critical error",
  141. "I'm sorry, but there seems to be a serious problem, please contact the administrator. And please take note of any unsaved data...",
  142. "", getApplicationUrl(request).toString()
  143. + "?restartApplication");
  144. }
  145. @Override
  146. protected void service(HttpServletRequest request,
  147. HttpServletResponse response) throws ServletException, IOException {
  148. if (isCleanupRequest(request)) {
  149. cleanDatastore();
  150. return;
  151. }
  152. RequestType requestType = getRequestType(request);
  153. if (requestType == RequestType.STATIC_FILE) {
  154. // no locking needed, let superclass handle
  155. super.service(request, response);
  156. cleanSession(request);
  157. return;
  158. }
  159. if (requestType == RequestType.APPLICATION_RESOURCE) {
  160. // no locking needed, let superclass handle
  161. getApplicationContext(request,
  162. MemcacheServiceFactory.getMemcacheService());
  163. super.service(request, response);
  164. cleanSession(request);
  165. return;
  166. }
  167. final HttpSession session = request
  168. .getSession(requestCanCreateApplication(request, requestType));
  169. if (session == null) {
  170. handleServiceSessionExpired(request, response);
  171. cleanSession(request);
  172. return;
  173. }
  174. boolean locked = false;
  175. MemcacheService memcache = null;
  176. String mutex = MUTEX_BASE + session.getId();
  177. memcache = MemcacheServiceFactory.getMemcacheService();
  178. try {
  179. // try to get lock
  180. long started = new Date().getTime();
  181. // non-UIDL requests will try indefinitely
  182. while (requestType != RequestType.UIDL
  183. || new Date().getTime() - started < MAX_UIDL_WAIT_MILLISECONDS) {
  184. locked = memcache.put(mutex, 1, Expiration.byDeltaSeconds(40),
  185. MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
  186. if (locked) {
  187. break;
  188. }
  189. try {
  190. Thread.sleep(RETRY_AFTER_MILLISECONDS);
  191. } catch (InterruptedException e) {
  192. log.info("Thread.sleep() interrupted while waiting for lock. Trying again. "
  193. + e);
  194. }
  195. }
  196. if (!locked) {
  197. // Not locked; only UIDL can get trough here unlocked: tell
  198. // client to retry
  199. response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
  200. // Note: currently interpreting Retry-After as ms, not sec
  201. response.setHeader("Retry-After", "" + RETRY_AFTER_MILLISECONDS);
  202. return;
  203. }
  204. // de-serialize or create application context, store in session
  205. ApplicationContext ctx = getApplicationContext(request, memcache);
  206. super.service(request, response);
  207. // serialize
  208. started = new Date().getTime();
  209. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  210. ObjectOutputStream oos = new ObjectOutputStream(baos);
  211. oos.writeObject(ctx);
  212. oos.flush();
  213. byte[] bytes = baos.toByteArray();
  214. started = new Date().getTime();
  215. String id = AC_BASE + session.getId();
  216. Date expire = new Date(started
  217. + (session.getMaxInactiveInterval() * 1000));
  218. Expiration expires = Expiration.onDate(expire);
  219. memcache.put(id, bytes, expires);
  220. DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
  221. Entity entity = new Entity(AC_BASE, id);
  222. entity.setProperty(PROPERTY_EXPIRES, expire.getTime());
  223. entity.setProperty(PROPERTY_DATA, new Blob(bytes));
  224. ds.put(entity);
  225. } catch (DeadlineExceededException e) {
  226. log.severe("DeadlineExceeded for " + session.getId());
  227. sendDeadlineExceededNotification(request, response);
  228. } catch (NotSerializableException e) {
  229. log.severe("NotSerializableException: " + getStackTraceAsString(e));
  230. // TODO this notification is usually not shown - should we redirect
  231. // in some other way - can we?
  232. sendNotSerializableNotification(request, response);
  233. } catch (Exception e) {
  234. log.severe(e + ": " + getStackTraceAsString(e));
  235. sendCriticalErrorNotification(request, response);
  236. } finally {
  237. // "Next, please!"
  238. if (locked) {
  239. memcache.delete(mutex);
  240. }
  241. cleanSession(request);
  242. }
  243. }
  244. protected ApplicationContext getApplicationContext(
  245. HttpServletRequest request, MemcacheService memcache) {
  246. HttpSession session = request.getSession();
  247. String id = AC_BASE + session.getId();
  248. byte[] serializedAC = (byte[]) memcache.get(id);
  249. if (serializedAC == null) {
  250. DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
  251. Key key = KeyFactory.createKey(AC_BASE, id);
  252. Entity entity = null;
  253. try {
  254. entity = ds.get(key);
  255. } catch (EntityNotFoundException e) {
  256. // Ok, we were a bit optimistic; we'll create a new one later
  257. }
  258. if (entity != null) {
  259. Blob blob = (Blob) entity.getProperty(PROPERTY_DATA);
  260. serializedAC = blob.getBytes();
  261. // bring it to memcache
  262. memcache.put(AC_BASE + session.getId(), serializedAC,
  263. Expiration.byDeltaSeconds(session
  264. .getMaxInactiveInterval()),
  265. MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
  266. }
  267. }
  268. if (serializedAC != null) {
  269. ByteArrayInputStream bais = new ByteArrayInputStream(serializedAC);
  270. ObjectInputStream ois;
  271. try {
  272. ois = new ObjectInputStream(bais);
  273. ApplicationContext applicationContext = (ApplicationContext) ois
  274. .readObject();
  275. session.setAttribute(WebApplicationContext.class.getName(),
  276. applicationContext);
  277. } catch (IOException e) {
  278. log.warning("Could not de-serialize ApplicationContext for "
  279. + session.getId() + " A new one will be created. "
  280. + getStackTraceAsString(e));
  281. } catch (ClassNotFoundException e) {
  282. log.warning("Could not de-serialize ApplicationContext for "
  283. + session.getId() + " A new one will be created. "
  284. + getStackTraceAsString(e));
  285. }
  286. }
  287. // will create new context if the above did not
  288. return WebApplicationContext.getApplicationContext(session);
  289. }
  290. private boolean isCleanupRequest(HttpServletRequest request) {
  291. String path = getRequestPathInfo(request);
  292. if (path != null && path.equals(CLEANUP_PATH)) {
  293. return true;
  294. }
  295. return false;
  296. }
  297. /**
  298. * Removes the ApplicationContext from the session in order to minimize the
  299. * data serialized to datastore and memcache.
  300. *
  301. * @param request
  302. */
  303. private void cleanSession(HttpServletRequest request) {
  304. HttpSession session = request.getSession(false);
  305. if (session != null) {
  306. session.removeAttribute(WebApplicationContext.class.getName());
  307. }
  308. }
  309. /**
  310. * This will look at the timestamp and delete expired persisted Vaadin and
  311. * appengine sessions from the datastore.
  312. *
  313. * TODO Possible improvements include: 1. Use transactions (requires entity
  314. * groups - overkill?) 2. Delete one-at-a-time, catch possible exception,
  315. * continue w/ next.
  316. */
  317. private void cleanDatastore() {
  318. long expire = new Date().getTime();
  319. try {
  320. DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
  321. // Vaadin stuff first
  322. {
  323. Query q = new Query(AC_BASE);
  324. q.setKeysOnly();
  325. q.addFilter(PROPERTY_EXPIRES,
  326. FilterOperator.LESS_THAN_OR_EQUAL, expire);
  327. PreparedQuery pq = ds.prepare(q);
  328. List<Entity> entities = pq.asList(Builder
  329. .withLimit(CLEANUP_LIMIT));
  330. if (entities != null) {
  331. log.info("Vaadin cleanup deleting " + entities.size()
  332. + " expired Vaadin sessions.");
  333. List<Key> keys = new ArrayList<Key>();
  334. for (Entity e : entities) {
  335. keys.add(e.getKey());
  336. }
  337. ds.delete(keys);
  338. }
  339. }
  340. // Also cleanup GAE sessions
  341. {
  342. Query q = new Query(APPENGINE_SESSION_KIND);
  343. q.setKeysOnly();
  344. q.addFilter(PROPERTY_APPENGINE_EXPIRES,
  345. FilterOperator.LESS_THAN_OR_EQUAL, expire);
  346. PreparedQuery pq = ds.prepare(q);
  347. List<Entity> entities = pq.asList(Builder
  348. .withLimit(CLEANUP_LIMIT));
  349. if (entities != null) {
  350. log.info("Vaadin cleanup deleting " + entities.size()
  351. + " expired appengine sessions.");
  352. List<Key> keys = new ArrayList<Key>();
  353. for (Entity e : entities) {
  354. keys.add(e.getKey());
  355. }
  356. ds.delete(keys);
  357. }
  358. }
  359. } catch (Exception e) {
  360. log.warning("Exception while cleaning: " + getStackTraceAsString(e));
  361. }
  362. }
  363. private String getStackTraceAsString(Throwable t) {
  364. StringWriter sw = new StringWriter();
  365. PrintWriter pw = new PrintWriter(sw);
  366. t.printStackTrace(pw);
  367. return sw.toString();
  368. }
  369. }