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 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /*
  2. * Copyright 2000-2016 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. * @deprecated No longer supported with Vaadin 8.0
  103. */
  104. @Deprecated
  105. public class GAEVaadinServlet extends VaadinServlet {
  106. // memcache mutex is MUTEX_BASE + sessio id
  107. private static final String MUTEX_BASE = "_vmutex";
  108. // used identify ApplicationContext in memcache and datastore
  109. private static final String AC_BASE = "_vac";
  110. // UIDL requests will attempt to gain access for this long before telling
  111. // the client to retry
  112. private static final int MAX_UIDL_WAIT_MILLISECONDS = 5000;
  113. // Tell client to retry after this delay.
  114. // Note: currently interpreting Retry-After as ms, not sec
  115. private static final int RETRY_AFTER_MILLISECONDS = 100;
  116. // Properties used in the datastore
  117. private static final String PROPERTY_EXPIRES = "expires";
  118. private static final String PROPERTY_DATA = "data";
  119. // path used for cleanup
  120. private static final String CLEANUP_PATH = "/CLEAN";
  121. // max entities to clean at once
  122. private static final int CLEANUP_LIMIT = 200;
  123. // appengine session kind
  124. private static final String APPENGINE_SESSION_KIND = "_ah_SESSION";
  125. // appengine session expires-parameter
  126. private static final String PROPERTY_APPENGINE_EXPIRES = "_expires";
  127. // sessions with undefined (-1) expiration are limited to this, but explicit
  128. // longer timeouts can be used
  129. private static final int DEFAULT_MAX_INACTIVE_INTERVAL = 24 * 3600;
  130. protected void sendDeadlineExceededNotification(
  131. VaadinServletRequest request, VaadinServletResponse response)
  132. throws IOException {
  133. criticalNotification(request, response, "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(VaadinServletRequest request,
  138. VaadinServletResponse response) throws IOException {
  139. criticalNotification(request, response, "NotSerializableException",
  140. "I'm sorry, but there seems to be a serious problem, please contact the administrator. And please take note of any unsaved data...",
  141. "",
  142. getApplicationUrl(request).toString() + "?restartApplication");
  143. }
  144. protected void sendCriticalErrorNotification(VaadinServletRequest request,
  145. VaadinServletResponse response) throws IOException {
  146. criticalNotification(request, response, "Critical error",
  147. "I'm sorry, but there seems to be a serious problem, please contact the administrator. And please take note of any unsaved data...",
  148. "",
  149. getApplicationUrl(request).toString() + "?restartApplication");
  150. }
  151. @Override
  152. protected void service(HttpServletRequest unwrappedRequest,
  153. HttpServletResponse unwrappedResponse)
  154. throws ServletException, IOException {
  155. VaadinServletRequest request = new VaadinServletRequest(
  156. unwrappedRequest, getService());
  157. VaadinServletResponse response = new VaadinServletResponse(
  158. unwrappedResponse, getService());
  159. if (isCleanupRequest(request)) {
  160. cleanDatastore();
  161. return;
  162. }
  163. if (isStaticResourceRequest(request)) {
  164. // no locking needed, let superclass handle
  165. super.service(request, response);
  166. cleanSession(request);
  167. return;
  168. }
  169. if (ServletPortletHelper.isAppRequest(request)) {
  170. // no locking needed, let superclass handle
  171. getApplicationContext(request,
  172. MemcacheServiceFactory.getMemcacheService());
  173. super.service(request, response);
  174. cleanSession(request);
  175. return;
  176. }
  177. final HttpSession session = request
  178. .getSession(getService().requestCanCreateSession(request));
  179. if (session == null) {
  180. try {
  181. getService().handleSessionExpired(request, response);
  182. } catch (ServiceException e) {
  183. throw new ServletException(e);
  184. }
  185. cleanSession(request);
  186. return;
  187. }
  188. boolean locked = false;
  189. MemcacheService memcache = null;
  190. String mutex = MUTEX_BASE + session.getId();
  191. memcache = MemcacheServiceFactory.getMemcacheService();
  192. try {
  193. // try to get lock
  194. long started = System.currentTimeMillis();
  195. while (System.currentTimeMillis()
  196. - started < MAX_UIDL_WAIT_MILLISECONDS) {
  197. locked = memcache.put(mutex, 1, Expiration.byDeltaSeconds(40),
  198. MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
  199. if (locked || ServletPortletHelper.isUIDLRequest(request)) {
  200. /*
  201. * Done if we got a lock. Will also avoid retrying if
  202. * there's a UIDL request because those are retried from the
  203. * client without keeping the server thread stalled.
  204. */
  205. break;
  206. }
  207. try {
  208. Thread.sleep(RETRY_AFTER_MILLISECONDS);
  209. } catch (InterruptedException e) {
  210. getLogger()
  211. .finer("Thread.sleep() interrupted while waiting for lock. Trying again. "
  212. + e);
  213. }
  214. }
  215. if (!locked) {
  216. // Not locked; only UIDL can get trough here unlocked: tell
  217. // client to retry
  218. response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
  219. // Note: currently interpreting Retry-After as ms, not sec
  220. response.setHeader("Retry-After",
  221. "" + RETRY_AFTER_MILLISECONDS);
  222. return;
  223. }
  224. // de-serialize or create application context, store in session
  225. VaadinSession ctx = getApplicationContext(request, memcache);
  226. super.service(request, response);
  227. // serialize
  228. started = new Date().getTime();
  229. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  230. ObjectOutputStream oos = new ObjectOutputStream(baos);
  231. oos.writeObject(ctx);
  232. oos.flush();
  233. byte[] bytes = baos.toByteArray();
  234. started = new Date().getTime();
  235. String id = AC_BASE + session.getId();
  236. Date expire = new Date(
  237. started + getMaxInactiveIntervalSeconds(session) * 1000);
  238. Expiration expires = Expiration.onDate(expire);
  239. memcache.put(id, bytes, expires);
  240. DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
  241. Entity entity = new Entity(AC_BASE, id);
  242. entity.setProperty(PROPERTY_EXPIRES, expire.getTime());
  243. entity.setProperty(PROPERTY_DATA, new Blob(bytes));
  244. ds.put(entity);
  245. } catch (DeadlineExceededException e) {
  246. getLogger().log(Level.WARNING, "DeadlineExceeded for {0}",
  247. session.getId());
  248. sendDeadlineExceededNotification(request, response);
  249. } catch (NotSerializableException e) {
  250. getLogger().log(Level.SEVERE, "Not serializable!", e);
  251. // TODO this notification is usually not shown - should we redirect
  252. // in some other way - can we?
  253. sendNotSerializableNotification(request, response);
  254. } catch (Exception e) {
  255. getLogger().log(Level.WARNING,
  256. "An exception occurred while servicing request.", e);
  257. sendCriticalErrorNotification(request, response);
  258. } finally {
  259. // "Next, please!"
  260. if (locked) {
  261. memcache.delete(mutex);
  262. }
  263. cleanSession(request);
  264. }
  265. }
  266. /**
  267. * Returns the maximum inactive time for a session. This is used for
  268. * handling the expiration of session related information in caches etc.
  269. *
  270. * @param session
  271. * @return inactive timeout in seconds, greater than zero
  272. */
  273. protected int getMaxInactiveIntervalSeconds(final HttpSession session) {
  274. int interval = session.getMaxInactiveInterval();
  275. if (interval <= 0) {
  276. getLogger().log(Level.FINE,
  277. "Undefined session expiration time, using default value instead.");
  278. return DEFAULT_MAX_INACTIVE_INTERVAL;
  279. }
  280. return interval;
  281. }
  282. protected VaadinSession getApplicationContext(HttpServletRequest request,
  283. MemcacheService memcache) throws ServletException {
  284. HttpSession session = request.getSession();
  285. String id = AC_BASE + session.getId();
  286. byte[] serializedAC = (byte[]) memcache.get(id);
  287. if (serializedAC == null) {
  288. DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
  289. Key key = KeyFactory.createKey(AC_BASE, id);
  290. Entity entity = null;
  291. try {
  292. entity = ds.get(key);
  293. } catch (EntityNotFoundException e) {
  294. // Ok, we were a bit optimistic; we'll create a new one later
  295. }
  296. if (entity != null) {
  297. Blob blob = (Blob) entity.getProperty(PROPERTY_DATA);
  298. serializedAC = blob.getBytes();
  299. // bring it to memcache
  300. memcache.put(AC_BASE + session.getId(), serializedAC,
  301. Expiration.byDeltaSeconds(
  302. getMaxInactiveIntervalSeconds(session)),
  303. MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
  304. }
  305. }
  306. if (serializedAC != null) {
  307. ByteArrayInputStream bais = new ByteArrayInputStream(serializedAC);
  308. ObjectInputStream ois;
  309. try {
  310. ois = new ObjectInputStream(bais);
  311. VaadinSession vaadinSession = (VaadinSession) ois.readObject();
  312. getService().storeSession(vaadinSession,
  313. new WrappedHttpSession(session));
  314. } catch (IOException | ClassNotFoundException e) {
  315. getLogger().log(Level.WARNING,
  316. "Could not de-serialize ApplicationContext for "
  317. + session.getId()
  318. + " A new one will be created. ",
  319. e);
  320. }
  321. }
  322. // will create new context if the above did not
  323. try {
  324. return getService().findVaadinSession(createVaadinRequest(request));
  325. } catch (Exception e) {
  326. throw new ServletException(e);
  327. }
  328. }
  329. private boolean isCleanupRequest(HttpServletRequest request) {
  330. String path = request.getPathInfo();
  331. if (path != null && path.equals(CLEANUP_PATH)) {
  332. return true;
  333. }
  334. return false;
  335. }
  336. /**
  337. * Removes the ApplicationContext from the session in order to minimize the
  338. * data serialized to datastore and memcache.
  339. *
  340. * @param request
  341. */
  342. private void cleanSession(VaadinServletRequest request) {
  343. // Should really be replaced with a session storage API...
  344. WrappedSession wrappedSession = request.getWrappedSession(false);
  345. if (wrappedSession == null) {
  346. return;
  347. }
  348. VaadinSession serviceSession = getService().loadSession(wrappedSession);
  349. if (serviceSession == null) {
  350. return;
  351. }
  352. /*
  353. * Inform VaadinSession.valueUnbound that it should not kill the session
  354. * even though it gets unbound.
  355. */
  356. serviceSession.setAttribute(
  357. VaadinService.PRESERVE_UNBOUND_SESSION_ATTRIBUTE, Boolean.TRUE);
  358. getService().removeSession(serviceSession.getSession());
  359. // Remove preservation marker
  360. serviceSession.setAttribute(
  361. VaadinService.PRESERVE_UNBOUND_SESSION_ATTRIBUTE, null);
  362. }
  363. /**
  364. * This will look at the timestamp and delete expired persisted Vaadin and
  365. * appengine sessions from the datastore.
  366. *
  367. * TODO Possible improvements include: 1. Use transactions (requires entity
  368. * groups - overkill?) 2. Delete one-at-a-time, catch possible exception,
  369. * continue w/ next.
  370. */
  371. private void cleanDatastore() {
  372. long expire = new Date().getTime();
  373. try {
  374. DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
  375. // Vaadin stuff first
  376. {
  377. Query q = new Query(AC_BASE);
  378. q.setKeysOnly();
  379. q.addFilter(PROPERTY_EXPIRES, FilterOperator.LESS_THAN_OR_EQUAL,
  380. expire);
  381. PreparedQuery pq = ds.prepare(q);
  382. List<Entity> entities = pq
  383. .asList(Builder.withLimit(CLEANUP_LIMIT));
  384. if (entities != null) {
  385. getLogger().log(Level.INFO,
  386. "Vaadin cleanup deleting {0} expired Vaadin sessions.",
  387. entities.size());
  388. List<Key> keys = new ArrayList<>();
  389. for (Entity e : entities) {
  390. keys.add(e.getKey());
  391. }
  392. ds.delete(keys);
  393. }
  394. }
  395. // Also cleanup GAE sessions
  396. {
  397. Query q = new Query(APPENGINE_SESSION_KIND);
  398. q.setKeysOnly();
  399. q.addFilter(PROPERTY_APPENGINE_EXPIRES,
  400. FilterOperator.LESS_THAN_OR_EQUAL, expire);
  401. PreparedQuery pq = ds.prepare(q);
  402. List<Entity> entities = pq
  403. .asList(Builder.withLimit(CLEANUP_LIMIT));
  404. if (entities != null) {
  405. getLogger().log(Level.INFO,
  406. "Vaadin cleanup deleting {0} expired appengine sessions.",
  407. entities.size());
  408. List<Key> keys = new ArrayList<>();
  409. for (Entity e : entities) {
  410. keys.add(e.getKey());
  411. }
  412. ds.delete(keys);
  413. }
  414. }
  415. } catch (Exception e) {
  416. getLogger().log(Level.WARNING, "Exception while cleaning.", e);
  417. }
  418. }
  419. private static final Logger getLogger() {
  420. return Logger.getLogger(GAEVaadinServlet.class.getName());
  421. }
  422. }