Статьи

Разработка релизов и параллельное развертывание

«Tomcat» всегда рассматривается как «сервер для бедняков», но Tomcat 7 может предложить что-то действительно интересное, например, Parallel Deployment. Это было предоставлено  SpringSource (теперь VMware ). Parallel Deployment — это подход, который допускает несколько операций онлайн-развертывания. запускать одновременно или простыми словами — это возможность развертывать более одной версии вашего веб-приложения параллельно, делая все версии доступными по одному и тому же URL. Параллельное развертывание также помогает в выпусках патчей и поддерживает лучшую версию приложения на основе производительности и трафика.

Самая захватывающая вещь с этой функцией — « Процесс нулевого простоя (развертывание и откат) ». Всякий раз, когда мы запускаем процесс развертывания, мы выключаем сервер, удаляем все активные соединения, удаляем старую версию и перемещаем или запускаем обновленную версию приложения. Исходя из сценария проекта в реальном времени, разработчик не должен получать одобрение своего менеджера, а менеджер не должен получать необходимые одобрения от клиента — поскольку это не влияет на время простоя. Таким образом, разработчик сам может загрузить последний код и протестировать / контролировать приложение с живыми пользователями.

Если мы сможем связать это с этим подходом, Facebook, Flickr, Google и многие другие компании будут следовать, где разработчик непосредственно отправляет код в производство и обрабатывает его до тех пор, пока пользователь не сообщит о любой непредвиденной проблеме. В качестве быстрой статистики разработчики Facebook запускают код в производство «ежедневно дважды» с миллионами строк кода пять дней в неделю. Точно так же Flickr запускает 10 развертываний в день ( полная статья  — слайдшер)

Одно из лучших видео, рассказывающее о разработке  релизов на Facebook  —  нажмите здесь

 Вот простой пример использования для тестирования с несколькими вариантами приложения:

Сценарии:

  • Выдвиньте три разные версии программы Hello World V001, V002 и V003, одну за другой, и затем отслеживайте статический URL-адрес приложения, который постоянно меняется по мере развертывания / развертывания обновленной версии.
  • Отмените развертывание нескольких версий (в случае отката приложения), чтобы увидеть, как приложение реагирует.

Наглядное представление сценария:

ReleseEngineeringProcess

Шаги:

  • Создайте простой файл Index.html, как показано ниже (версии показывают изменения, которые необходимо включить в несколько выпусков версий)

RM1

  • Создайте Build.xml, как показано ниже, цель отмены развертывания используется во время отката. Во время выполнения шага развертывания создается новая версия файла WAR «PDRelease ## 001», которая копируется в папку Tomcat / webapps. Для версий с несколькими выпусками количество увеличивается. Общий подход к созданию нового версионного файла WAR должен иметь формат  <ApplicationName> ## <Version Number> .war :
  
  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. <project name="Testing the Parallel Deployment Process" basedir=".">
  3. <property name="warfile" value="PDRelease##001"/>
  4. <target name="unpack">
  5. <unwar src="${warfile}.war" dest="${warfile}" />
  6. </target>
  7. <target name="create">
  8. <war destfile="${warfile}.war" webxml="WEB-INF/web.xml" update="true">
  9. <fileset dir=".">
  10. <include name="index.html"/>
  11. </fileset>
  12. </war>
  13. </target>
  14. <target name="copy">
  15. <copy todir="E:\Test\ReleaseMgmt_Tomcat\webapps" overwrite="true">
  16. <fileset dir=".">
  17. <include name="*.war"/>
  18. </fileset>
  19. </copy>
  20. </target>
  21. <target name="undeploy">
  22. <delete dir="E:\Test\ReleaseMgmt_Tomcat\webapps\sanfran##004"/>
  23. <delete>
  24. <fileset dir="E:\Test\ReleaseMgmt_Tomcat\webapps">
  25. <include name=" PDRelease##002.war"/>    
  26. </fileset>
  27. </delete>
  28. </target>  
  29. <target name="deploy">
  30. <antcall target="create"/>
  31. <antcall target="copy"/>
  32. </target>
  33. </project>
  • После успешного выполнения build.xml к порталу обращаются:
    • Файл сборки: C: \ Users \ user \ workspace \ ParallelDeployment \ build.xml
    • Создайте:
    •   [война] Создание войны: C: \ Users \ user \ workspace \ ParallelDeployment \ PDRelease ## 001.war
    • копия:
    •   [копия] Копирование 5 файлов в E: \ Test \ ReleaseMgmt_Tomcat \ webapps
    • СТРОИТЬ УСПЕШНО
    • Общее время: 1 секунда

RM2

  • Next, the changes in the index.html are incorporated and the new versions of WAR files are deployed to access the Portal. (for showcase – opened it in 3 different browsers). Otherwise it will always take the Highest Version of the Application. With each individual browser, the different versions of the applications can be accessed.

RM3

  • Quick snapshot of the webapps folder :

RM7

  • The Version V003 is un-deployed or rolled back , so that the Highest Version of the application available is PDRelease##002

RM5

  •  The Logs can be verified to understand the history, as to which Application version was deployed or un-deployed
  
  1. Nov 03, 2012 8:02:14 PM org.apache.catalina.startup.HostConfig deployWAR
  2. INFO: Deploying web application archive E:\Test\ReleaseMgmt_Tomcat\webapps\PDRelease##001.war
  3. Nov 03, 2012 8:02:14 PM org.apache.catalina.startup.HostConfig deployWAR
  4. INFO: Deploying web application archive E:\Test\ReleaseMgmt_Tomcat\webapps\PDRelease##002.war
  5. Nov 03, 2012 8:02:14 PM org.apache.catalina.startup.HostConfig deployWAR
  6. INFO: Deploying web application archive E:\Test\ReleaseMgmt_Tomcat\webapps\PDRelease##003.war
  7. Nov 03, 2012 8:02:15 PM org.apache.catalina.startup.HostConfig deployWAR
  8. Nov 03, 2012 8:10:00 PM org.apache.catalina.startup.HostConfig checkResources
  9. INFO: Undeploying context [/PDRelease##003]

Things to be taken care of :

  • Internal Cache should be written separately as multiple versions of the application will be accessing and going on/off. A perfect example to visualize this situation would be to updating the database based on a caching mechanism.
  • Logging (where does the logs get written for different versions of the application)
  • Session handling is currently taken care of by Tomcat. So any changes to the Session handling configurations will affect the parallel deployment approach.
  • Only one listener can listen on any given port.
  • From an enterprise application perspective, there might be a situation wherein multiple versions of the app, will be accessing a common file store of database row. So how do we handle the locking mechanism for a smooth and hassle free access.
  • Rolling back of changed schemas, data entry row updates in the database, webservice configuration changes

Best Practice:

  • As a best practice, the version numbers for the WAR files can be numbered in sync with the CVS or SVN version of the application in the repository. So, the war file name can be mentioned as  <ApplicationName>##<SVN or CVS Version Number>.war
  • Strategize and draft a schedule for the deployment approach when and under what condition the code needs to be pushed or rollback

Parallel Deployment is not suited for cases like :

  • Dealing with web-applications requiring in-memory caching would be challenging as the cache will have the stale information and will not serve the purpose.
  • Web applications which require, offline deployment and restart or server–in that case parallel deployment approach is not a best fit.

Advantages of Parallel Deployment or Phased Release Engineering:

  • Speed and Scale of deployment
  • Easy deployment and rollback – facilitating continuity of business without any show-stopper with issues related to the new deployment. The last best version can always be rolled back.
  • A/B or split testing
  • Better end user testing – pushing the code to production or any higher environment is always a nail-biting situation. With parallel deployment and patch release approach the code can be silently pushed to production and get it tested with the end-user.
  • Provides a better ground for experimentation and deploy without any fear.
  • A cushion for the developers and the customers with incremental releases.
  • A developer can act as a release engineer and vice-versa.
  • The developer shepard’s his change to the world

Other Tools to explore:

There are many other tools which the companies like Facebook and Google use  pushing the code on an incremental and decremental fashion — ‘need to explore to figure out how exactly it is done using the tools. Couple of other tools ‘came across are

  • BOSH  (developed by the CloudFoundry — VMWARE team and now opensourced)
  • Capistrano (another OSS).
  • Asgard (OSS) – also provides an application deployment and version rollback feature on Amazon EC2 instance

References:

PN : Please do keep posting your valuable comments and suggestions on the same and feel free to correct me if my understanding is wrong.

Happy Learning 🙂