Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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