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

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