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.

GAEVaadinServlet.java 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. /*
  2. * Copyright 2000-2014 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.server;
  17. import java.io.ByteArrayInputStream;
  18. import java.io.ByteArrayOutputStream;
  19. import java.io.IOException;
  20. import java.io.NotSerializableException;
  21. import java.io.ObjectInputStream;
  22. import java.io.ObjectOutputStream;
  23. import java.util.ArrayList;
  24. import java.util.Date;
  25. import java.util.List;
  26. import java.util.logging.Level;
  27. import java.util.logging.Logger;
  28. import javax.servlet.ServletException;
  29. import javax.servlet.http.HttpServletRequest;
  30. import javax.servlet.http.HttpServletResponse;
  31. import javax.servlet.http.HttpSession;
  32. import com.google.appengine.api.datastore.Blob;
  33. import com.google.appengine.api.datastore.DatastoreService;
  34. import com.google.appengine.api.datastore.DatastoreServiceFactory;
  35. import com.google.appengine.api.datastore.Entity;
  36. import com.google.appengine.api.datastore.EntityNotFoundException;
  37. import com.google.appengine.api.datastore.FetchOptions.Builder;
  38. import com.google.appengine.api.datastore.Key;
  39. import com.google.appengine.api.datastore.KeyFactory;
  40. import com.google.appengine.api.datastore.PreparedQuery;
  41. import com.google.appengine.api.datastore.Query;
  42. import com.google.appengine.api.datastore.Query.FilterOperator;
  43. import com.google.appengine.api.memcache.Expiration;
  44. import com.google.appengine.api.memcache.MemcacheService;
  45. import com.google.appengine.api.memcache.MemcacheServiceFactory;
  46. import com.google.apphosting.api.DeadlineExceededException;
  47. /**
  48. * ApplicationServlet to be used when deploying to Google App Engine, in
  49. * web.xml:
  50. *
  51. * <pre>
  52. * &lt;servlet&gt;
  53. * &lt;servlet-name&gt;HelloWorld&lt;/servlet-name&gt;
  54. * &lt;servlet-class&gt;com.vaadin.server.GAEApplicationServlet&lt;/servlet-class&gt;
  55. * &lt;init-param&gt;
  56. * &lt;param-name&gt;UI&lt;/param-name&gt;
  57. * &lt;param-value&gt;com.vaadin.demo.HelloWorld&lt;/param-value&gt;
  58. * &lt;/init-param&gt;
  59. * &lt;/servlet&gt;
  60. * </pre>
  61. *
  62. * Session support must be enabled in appengine-web.xml:
  63. *
  64. * <pre>
  65. * &lt;sessions-enabled&gt;true&lt;/sessions-enabled&gt;
  66. * </pre>
  67. *
  68. * Appengine datastore cleanup can be invoked by calling one of the applications
  69. * with an additional path "/CLEAN". This can be set up as a cron-job in
  70. * cron.xml (see appengine documentation for more information):
  71. *
  72. * <pre>
  73. * &lt;cronentries&gt;
  74. * &lt;cron&gt;
  75. * &lt;url&gt;/HelloWorld/CLEAN&lt;/url&gt;
  76. * &lt;description&gt;Clean up sessions&lt;/description&gt;
  77. * &lt;schedule&gt;every 2 hours&lt;/schedule&gt;
  78. * &lt;/cron&gt;
  79. * &lt;/cronentries&gt;
  80. * </pre>
  81. *
  82. * It is recommended (but not mandatory) to extract themes and widgetsets and
  83. * have App Engine server these statically. Extract VAADIN folder (and it's
  84. * contents) 'next to' the WEB-INF folder, and add the following to
  85. * appengine-web.xml:
  86. *
  87. * <pre>
  88. * &lt;static-files&gt;
  89. * &lt;include path=&quot;/VAADIN/**&quot; /&gt;
  90. * &lt;/static-files&gt;
  91. * </pre>
  92. *
  93. * Additional limitations:
  94. * <ul>
  95. * <li/>Do not change application state when serving an ApplicationResource.
  96. * <li/>Avoid changing application state in transaction handlers, unless you're
  97. * confident you fully understand the synchronization issues in App Engine.
  98. * <li/>The application remains locked while uploading - no progressbar is
  99. * possible.
  100. * </ul>
  101. */
  102. public class GAEVaadinServlet extends VaadinServlet {
  103. // memcache mutex is MUTEX_BASE + sessio id
  104. private static final String MUTEX_BASE = "_vmutex";
  105. // used identify ApplicationContext in memcache and datastore
  106. private static final String AC_BASE = "_vac";
  107. // UIDL requests will attempt to gain access for this long before telling
  108. // the client to retry
  109. private static final int MAX_UIDL_WAIT_MILLISECONDS = 5000;
  110. // Tell client to retry after this delay.
  111. // Note: currently interpreting Retry-After as ms, not sec
  112. private static final int RETRY_AFTER_MILLISECONDS = 100;
  113. // Properties used in the datastore
  114. private static final String PROPERTY_EXPIRES = "expires";
  115. private static final String PROPERTY_DATA = "data";
  116. // path used for cleanup
  117. private static final String CLEANUP_PATH = "/CLEAN";
  118. // max entities to clean at once
  119. private static final int CLEANUP_LIMIT = 200;
  120. // appengine session kind
  121. private static final String APPENGINE_SESSION_KIND = "_ah_SESSION";
  122. // appengine session expires-parameter
  123. private static final String PROPERTY_APPENGINE_EXPIRES = "_expires";
  124. // sessions with undefined (-1) expiration are limited to this, but explicit
  125. // longer timeouts can be used
  126. private static final int DEFAULT_MAX_INACTIVE_INTERVAL = 24 * 3600;
  127. protected void sendDeadlineExceededNotification(
  128. VaadinServletRequest request, VaadinServletResponse response)
  129. throws IOException {
  130. criticalNotification(
  131. request,
  132. response,
  133. "Deadline Exceeded",
  134. "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...",
  135. "", null);
  136. }
  137. protected void sendNotSerializableNotification(
  138. VaadinServletRequest request, VaadinServletResponse response)
  139. throws IOException {
  140. criticalNotification(
  141. request,
  142. response,
  143. "NotSerializableException",
  144. "I'm sorry, but there seems to be a serious problem, please contact the administrator. And please take note of any unsaved data...",
  145. "", getApplicationUrl(request).toString()
  146. + "?restartApplication");
  147. }
  148. protected void sendCriticalErrorNotification(VaadinServletRequest request,
  149. VaadinServletResponse response) throws IOException {
  150. criticalNotification(
  151. request,
  152. response,
  153. "Critical error",
  154. "I'm sorry, but there seems to be a serious problem, please contact the administrator. And please take note of any unsaved data...",
  155. "", getApplicationUrl(request).toString()
  156. + "?restartApplication");
  157. }
  158. @Override
  159. protected void service(HttpServletRequest unwrappedRequest,
  160. HttpServletResponse unwrappedResponse) throws ServletException,
  161. IOException {
  162. VaadinServletRequest request = new VaadinServletRequest(
  163. unwrappedRequest, getService());
  164. VaadinServletResponse response = new VaadinServletResponse(
  165. unwrappedResponse, getService());
  166. if (isCleanupRequest(request)) {
  167. cleanDatastore();
  168. return;
  169. }
  170. if (isStaticResourceRequest(request)) {
  171. // no locking needed, let superclass handle
  172. super.service(request, response);
  173. cleanSession(request);
  174. return;
  175. }
  176. if (ServletPortletHelper.isAppRequest(request)) {
  177. // no locking needed, let superclass handle
  178. getApplicationContext(request,
  179. MemcacheServiceFactory.getMemcacheService());
  180. super.service(request, response);
  181. cleanSession(request);
  182. return;
  183. }
  184. final HttpSession session = request.getSession(getService()
  185. .requestCanCreateSession(request));
  186. if (session == null) {
  187. try {
  188. getService().handleSessionExpired(request, response);
  189. } catch (ServiceException e) {
  190. throw new ServletException(e);
  191. }
  192. cleanSession(request);
  193. return;
  194. }
  195. boolean locked = false;
  196. MemcacheService memcache = null;
  197. String mutex = MUTEX_BASE + session.getId();
  198. memcache = MemcacheServiceFactory.getMemcacheService();
  199. try {
  200. // try to get lock
  201. long started = System.currentTimeMillis();
  202. while (System.currentTimeMillis() - started < MAX_UIDL_WAIT_MILLISECONDS) {
  203. locked = memcache.put(mutex, 1, Expiration.byDeltaSeconds(40),
  204. MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
  205. if (locked || ServletPortletHelper.isUIDLRequest(request)) {
  206. /*
  207. * Done if we got a lock. Will also avoid retrying if
  208. * there's a UIDL request because those are retried from the
  209. * client without keeping the server thread stalled.
  210. */
  211. break;
  212. }
  213. try {
  214. Thread.sleep(RETRY_AFTER_MILLISECONDS);
  215. } catch (InterruptedException e) {
  216. getLogger().finer(
  217. "Thread.sleep() interrupted while waiting for lock. Trying again. "
  218. + e);
  219. }
  220. }
  221. if (!locked) {
  222. // Not locked; only UIDL can get trough here unlocked: tell
  223. // client to retry
  224. response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
  225. // Note: currently interpreting Retry-After as ms, not sec
  226. response.setHeader("Retry-After", "" + RETRY_AFTER_MILLISECONDS);
  227. return;
  228. }
  229. // de-serialize or create application context, store in session
  230. VaadinSession ctx = getApplicationContext(request, memcache);
  231. super.service(request, response);
  232. // serialize
  233. started = new Date().getTime();
  234. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  235. ObjectOutputStream oos = new ObjectOutputStream(baos);
  236. oos.writeObject(ctx);
  237. oos.flush();
  238. byte[] bytes = baos.toByteArray();
  239. started = new Date().getTime();
  240. String id = AC_BASE + session.getId();
  241. Date expire = new Date(started
  242. + (getMaxInactiveIntervalSeconds(session) * 1000));
  243. Expiration expires = Expiration.onDate(expire);
  244. memcache.put(id, bytes, expires);
  245. DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
  246. Entity entity = new Entity(AC_BASE, id);
  247. entity.setProperty(PROPERTY_EXPIRES, expire.getTime());
  248. entity.setProperty(PROPERTY_DATA, new Blob(bytes));
  249. ds.put(entity);
  250. } catch (DeadlineExceededException e) {
  251. getLogger().log(Level.WARNING, "DeadlineExceeded for {0}",
  252. session.getId());
  253. sendDeadlineExceededNotification(request, response);
  254. } catch (NotSerializableException e) {
  255. getLogger().log(Level.SEVERE, "Not serializable!", e);
  256. // TODO this notification is usually not shown - should we redirect
  257. // in some other way - can we?
  258. sendNotSerializableNotification(request, response);
  259. } catch (Exception e) {
  260. getLogger().log(Level.WARNING,
  261. "An exception occurred while servicing request.", e);
  262. sendCriticalErrorNotification(request, response);
  263. } finally {
  264. // "Next, please!"
  265. if (locked) {
  266. memcache.delete(mutex);
  267. }
  268. cleanSession(request);
  269. }
  270. }
  271. /**
  272. * Returns the maximum inactive time for a session. This is used for
  273. * handling the expiration of session related information in caches etc.
  274. *
  275. * @param session
  276. * @return inactive timeout in seconds, greater than zero
  277. */
  278. protected int getMaxInactiveIntervalSeconds(final HttpSession session) {
  279. int interval = session.getMaxInactiveInterval();
  280. if (interval <= 0) {
  281. getLogger()
  282. .log(Level.FINE,
  283. "Undefined session expiration time, using default value instead.");
  284. return DEFAULT_MAX_INACTIVE_INTERVAL;
  285. }
  286. return interval;
  287. }
  288. protected VaadinSession getApplicationContext(HttpServletRequest request,
  289. MemcacheService memcache) throws ServletException {
  290. HttpSession session = request.getSession();
  291. String id = AC_BASE + session.getId();
  292. byte[] serializedAC = (byte[]) memcache.get(id);
  293. if (serializedAC == null) {
  294. DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
  295. Key key = KeyFactory.createKey(AC_BASE, id);
  296. Entity entity = null;
  297. try {
  298. entity = ds.get(key);
  299. } catch (EntityNotFoundException e) {
  300. // Ok, we were a bit optimistic; we'll create a new one later
  301. }
  302. if (entity != null) {
  303. Blob blob = (Blob) entity.getProperty(PROPERTY_DATA);
  304. serializedAC = blob.getBytes();
  305. // bring it to memcache
  306. memcache.put(
  307. AC_BASE + session.getId(),
  308. serializedAC,
  309. Expiration
  310. .byDeltaSeconds(getMaxInactiveIntervalSeconds(session)),
  311. MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
  312. }
  313. }
  314. if (serializedAC != null) {
  315. ByteArrayInputStream bais = new ByteArrayInputStream(serializedAC);
  316. ObjectInputStream ois;
  317. try {
  318. ois = new ObjectInputStream(bais);
  319. VaadinSession applicationContext = (VaadinSession) ois
  320. .readObject();
  321. applicationContext.storeInSession(getService(),
  322. new WrappedHttpSession(session));
  323. } catch (IOException e) {
  324. getLogger().log(
  325. Level.WARNING,
  326. "Could not de-serialize ApplicationContext for "
  327. + session.getId()
  328. + " A new one will be created. ", e);
  329. } catch (ClassNotFoundException e) {
  330. getLogger().log(
  331. Level.WARNING,
  332. "Could not de-serialize ApplicationContext for "
  333. + session.getId()
  334. + " A new one will be created. ", e);
  335. }
  336. }
  337. // will create new context if the above did not
  338. try {
  339. return getService().findVaadinSession(createVaadinRequest(request));
  340. } catch (Exception e) {
  341. throw new ServletException(e);
  342. }
  343. }
  344. private boolean isCleanupRequest(HttpServletRequest request) {
  345. String path = request.getPathInfo();
  346. if (path != null && path.equals(CLEANUP_PATH)) {
  347. return true;
  348. }
  349. return false;
  350. }
  351. /**
  352. * Removes the ApplicationContext from the session in order to minimize the
  353. * data serialized to datastore and memcache.
  354. *
  355. * @param request
  356. */
  357. private void cleanSession(VaadinServletRequest request) {
  358. // Should really be replaced with a session storage API...
  359. WrappedSession wrappedSession = request.getWrappedSession(false);
  360. if (wrappedSession == null) {
  361. return;
  362. }
  363. VaadinSession serviceSession = VaadinSession.getForSession(
  364. getService(), wrappedSession);
  365. if (serviceSession == null) {
  366. return;
  367. }
  368. /*
  369. * Inform VaadinSession.valueUnbound that it should not kill the session
  370. * even though it gets unbound.
  371. */
  372. serviceSession.setAttribute(
  373. VaadinService.PRESERVE_UNBOUND_SESSION_ATTRIBUTE, Boolean.TRUE);
  374. serviceSession.removeFromSession(getService());
  375. // Remove preservation marker
  376. serviceSession.setAttribute(
  377. VaadinService.PRESERVE_UNBOUND_SESSION_ATTRIBUTE, null);
  378. }
  379. /**
  380. * This will look at the timestamp and delete expired persisted Vaadin and
  381. * appengine sessions from the datastore.
  382. *
  383. * TODO Possible improvements include: 1. Use transactions (requires entity
  384. * groups - overkill?) 2. Delete one-at-a-time, catch possible exception,
  385. * continue w/ next.
  386. */
  387. private void cleanDatastore() {
  388. long expire = new Date().getTime();
  389. try {
  390. DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
  391. // Vaadin stuff first
  392. {
  393. Query q = new Query(AC_BASE);
  394. q.setKeysOnly();
  395. q.addFilter(PROPERTY_EXPIRES,
  396. FilterOperator.LESS_THAN_OR_EQUAL, expire);
  397. PreparedQuery pq = ds.prepare(q);
  398. List<Entity> entities = pq.asList(Builder
  399. .withLimit(CLEANUP_LIMIT));
  400. if (entities != null) {
  401. getLogger()
  402. .log(Level.INFO,
  403. "Vaadin cleanup deleting {0} expired Vaadin sessions.",
  404. entities.size());
  405. List<Key> keys = new ArrayList<Key>();
  406. for (Entity e : entities) {
  407. keys.add(e.getKey());
  408. }
  409. ds.delete(keys);
  410. }
  411. }
  412. // Also cleanup GAE sessions
  413. {
  414. Query q = new Query(APPENGINE_SESSION_KIND);
  415. q.setKeysOnly();
  416. q.addFilter(PROPERTY_APPENGINE_EXPIRES,
  417. FilterOperator.LESS_THAN_OR_EQUAL, expire);
  418. PreparedQuery pq = ds.prepare(q);
  419. List<Entity> entities = pq.asList(Builder
  420. .withLimit(CLEANUP_LIMIT));
  421. if (entities != null) {
  422. getLogger()
  423. .log(Level.INFO,
  424. "Vaadin cleanup deleting {0} expired appengine sessions.",
  425. entities.size());
  426. List<Key> keys = new ArrayList<Key>();
  427. for (Entity e : entities) {
  428. keys.add(e.getKey());
  429. }
  430. ds.delete(keys);
  431. }
  432. }
  433. } catch (Exception e) {
  434. getLogger().log(Level.WARNING, "Exception while cleaning.", e);
  435. }
  436. }
  437. private static final Logger getLogger() {
  438. return Logger.getLogger(GAEVaadinServlet.class.getName());
  439. }
  440. }