Platform as a Service is changing the way developers approach developing software. Developers typically use a local sandbox with their preferred application server and only deploy locally on that instance. For instance, developers typically start JBoss EAP locally using the startup.sh command and drop their .war or .ear file in the deployment directory and they are done. Developers have a hard time understanding why deploying to the production infrastructure is such a time consuming process.

System Administrators understand the complexity of not only deploying the code, but procuring, provisioning and maintaining a production level system. They need to stay up to date on the latest security patches and errata, ensure the firewall is properly configured, maintain a consistent and reliable backup and restore plan, monitor the application and servers for CPU load, disk IO, HTTP requests, etc.

OpenShift Origin provides developers and IT organizations an open source auto-scaling cloud application platform for quickly deploying new applications on secure and scalable resources with minimal configuration and management headaches. This means increased developer productivity and a faster pace in which IT can support innovation.

Building Apps on OpenShift Origin

This document assumes that you are working against an OpenShift Origin installation that is distinct from OpenShift Online (http://www.openshift.com). If you do not have OpenShift Origin yet, you will want to refer to the OpenShift Origin Installation Guide.

How is OpenShift Origin Different from OpenShift Online?

The rhc tools work interchangeably with OpenShift Online and OpenShift Origin, however, OpenShift Origin gives the administrator complete flexibility in assigning resources (like RAM and disk space) to application gears. OpenShift Origin can also be deployed on a private network, making it a better fit for enterprise and secure development environments.

1. Setting Up a Development Environment

Servers used
  • localhost

Tools used
  • rhc

In order to work with OpenShift applications from the command line, you will need to install the rhc utility on your client system. See the Client Tools installation Guide for instructions on how to do this.

1.1. Configuring rhc

By default, the RHC command line tool will attempt to connect the publicly hosted OpenShift environment at www.openshift.com. If you are going to work against a different OpenShift deployment, you will need to tell rhc where the deployment’s Broker host can be found. To provide this information, run the setup command with the --server flag:

$ rhc setup --server <broker hostname>

Getting to a Broker Running Inside a Virtual Machine
If you are running OpenShift Origin from the all-in-one VM, you will need to experiment to determine the best way to communicate with the Broker inside. In a recent troubleshooting session, we found that external rhc clients could not connect to an Origin virtual machine with a NATed network configuration. Using a "bridged" network configuration seemed to solve the problem. The specific network configuration options will vary by virtual machine service (Virtual Box, VMWare, etc.)

Once you enter in that command, you will be prompted for the username that you would like to authenticate with. If you are using the OpenShift Origin virtual machine, you can authenticate with user "demo", password "changeme".

The next step in the setup process is to create and upload our SSH key to the broker server. This is required for pushing your source code, via git, up to the OpenShift Origin server.

Finally, you will be asked to create a namespace for the provided user account. The namespace is a unique name which becomes part of your application URL. It is also commonly referred to as the users domain. The namespace can be at most 16 characters long and can only contain alphanumeric characters. There is currently a 1:1 relationship between usernames and namespaces. For the examples in the document, the namespace <yourdomain> will be used.

1.2. What rhc setup Does

This utility ensures that the user’s operating system is configured properly to create and manage applications from the command line. Additionally, it creates a .openshift directory in the user’s home directory and places a file there called express.conf. The contents of that file are as follows:

# Default user login
default_rhlogin='<your username>'

# Server API
libra_server = '<your Broker hostname or IP>'

This information will be provided to the rhc command line tool for every future command that is issued. If you want to run commands as a different user than the one listed above, you can either change the default login in this file or provide the -l switch to the rhc command.

2. Application Development

Servers used
  • localhost

  • node host

Tools used
  • rhc

Having completed the rhc setup, we are ready to start using OpenShift Origin to create our first application. To create an application, we will be using rhc app. In order to view all of the available setting options, enter the following command:

$ rhc app -h

This will provide you with the following output:

Creates and controls an OpenShift application.  To see the list of all applications use the rhc domain show command.
Note that delete is not reversible and will stop your application and then remove the application and repo from the
remote server. No local changes are made.

List of Actions
  configure     Configure several properties that apply to an application
  create        Create an application
  delete        Delete an application from the server
  deploy        Deploy a git reference or binary file of an application
  force-stop    Stops all application processes
  reload        Reload the application's configuration
  restart       Restart the application
  show          Show information about an application
  start         Start the application
  stop          Stop the application
  tidy          Clean out the application's logs and tmp directories and tidy up the git repo on the server

2.1. Create a New Application

The command to create an application is rhc app create and it requires two mandatory arguments:

  • Application Name: The name of the application. The application name can only contain alpha-numeric characters and at max contain only 32 characters.

  • Cartridge: The cartridge type that specifies which language runtime to use.

If you haven’t done so, create a directory to hold your OpenShift code projects:

$ cd ~
$ mkdir apps
$ cd apps

To create an application called "firstphp" that uses the php runtime, issue the following command:

$ rhc app create firstphp php-5.3

After entering that command, you should output similar to:

 Application Options
 -------------------
  Domain:     <yourdomain>
  Cartridges: php-5.3
  Gear Size:  default
  Scaling:    no

Creating application 'firstphp' ... done


Waiting for your DNS name to be available ... done

Cloning into 'firstphp'...
The authenticity of host 'firstphp-<yourdomain>.<appsdomain>.com (1.1.1.1)' can't be established.
RSA key fingerprint is aa:11:aa:11:aa:11:aa:11:aa:11:aa:11:aa:11:aa:11.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'firstphp-<yourapp>.<appsdomain>.com,1.1.1.1' (RSA) to the list of known hosts.
Checking connectivity... done

Your application 'firstphp' is now available.

  URL:        http://firstphp-<yourdomain>.<appsdomain>.com/
  SSH to:     01aa10a0110111a01100a011@firstphp-<yourdomain>.<appsdomain>.com
  Git remote: ssh://01aa10a0110111a01100a011@firstphp-<yourdomain>.<appsdomain>.com/~/git/firstphp.git/
  Cloned to:  /home/<you>/apps/firstphp

Run 'rhc show-app firstphp' for more details about your app.

You should also be able to verify that your application was created correctly by opening up a web browser and entering the following URL:

http://firstphp-<yourdomain>.example.com

You should see the default template that OpenShift Origin uses for a new application.

image

2.2. What rhc app create Does

After you entered the command to create a new PHP application, a lot of things happened under the covers:

  • A request was made to the broker application host to create a new php application

  • A message was dropped using MCollective and ActiveMQ to find a node host to handle the application creation request

  • A node host responded to the request and created an application / gear for you

  • All SELinux and cgroup policies were enabled for your application gear

  • A userid was created for your application gear

  • A private git repository was created for your gear on the node host

  • The git repository was cloned on your local machine

  • BIND was updated on the broker host to include an entry for your application

2.3. Node Host Directory Structure

It is important to understand the directory structure of each OpenShift Origin application gear. For the PHP application that we just created, we can verify and examine the layout of the gear on the node host. SSH to your node host and execute the following commands:

# cd /var/lib/openshift
# ls

You will see output similar to the following:

e9e92282a16b49e7b78d69822ac53e1d

The above is the unique user id that was created for your application gear. Lets examine the contents of this gear by using the following commands:

# cd e9e92282a16b49e7b78d69822ac53e1d
# ls -al

You should see the following directories:

total 44
drwxr-x---.  9 root e9e92282a16b49e7b78d69822ac53e1d 4096 Jan 21 13:47 .
drwxr-xr-x.  5 root root                             4096 Jan 21 13:47 ..
drwxr-xr-x.  4 root e9e92282a16b49e7b78d69822ac53e1d 4096 Jan 21 13:47 app-root
drwxr-x---.  3 root e9e92282a16b49e7b78d69822ac53e1d 4096 Jan 21 13:47 .env
drwxr-xr-x.  3 root root                             4096 Jan 21 13:47 git
-rw-r--r--.  1 root root                               56 Jan 21 13:47 .gitconfig
-rw-r--r--.  1 root root                             1352 Jan 21 13:47 .pearrc
drwxr-xr-x. 10 root root                             4096 Jan 21 13:47 php-5.3
d---------.  3 root root                             4096 Jan 21 13:47 .sandbox
drwxr-x---.  2 root e9e92282a16b49e7b78d69822ac53e1d 4096 Jan 21 13:47 .ssh
d---------.  3 root root                             4096 Jan 21 13:47 .tmp
[root@node e9e92282a16b49e7b78d69822ac53e1d]#

During the rhc setup, our SSH key was uploaded to the server to enable us to authenticate to the system without having to provide a password. The SSH key we provided was actually appended to the authorized_keys file. To verify this, use the following command to view the contents of the file:

# cat .ssh/authorized_keys

You will also notice the following three directories:

  • app-root - Contains your core application code as well as your data directory where persistent data is stored.

  • git - Your private git repository that was created upon gear creation.

  • php-5.3 - The core PHP runtime and associated configuration files. Your application is served from this directory.

2.4. Localhost Directory Structure

When you created the PHP application using the rhc app create command, the private git repository that was created on your node host was cloned to your local machine.

$ cd firstphp
$ ls -al

You should see the following information:

total 8
drwxr-xr-x   9 gshipley  staff   306 Jan 21 13:48 .
drwxr-xr-x   3 gshipley  staff   102 Jan 21 13:48 ..
drwxr-xr-x  13 gshipley  staff   442 Jan 21 13:48 .git
drwxr-xr-x   5 gshipley  staff   170 Jan 21 13:48 .openshift
-rw-r--r--   1 gshipley  staff  2715 Jan 21 13:48 README
-rw-r--r--   1 gshipley  staff     0 Jan 21 13:48 deplist.txt
drwxr-xr-x   3 gshipley  staff   102 Jan 21 13:48 libs
drwxr-xr-x   3 gshipley  staff   102 Jan 21 13:48 misc
drwxr-xr-x   4 gshipley  staff   136 Jan 21 13:48 php

2.4.1. The .git Directory

If you are not familiar with the git revision control system, this is where information about the git repositories that you will be interacting with is stored. For instance, to list all of the repositories that you are currently setup to use for this project, issue the following command:

$ cat .git/config

You should see the following information which specifies the URL for our repository that is hosted on the OpenShift Origin node host:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    url = ssh://e9e92282a16b49e7b78d69822ac53e1d@firstphp-<yourdomain>.example.com/~/git/firstphp.git/
[branch "master"]
    remote = origin
    merge = refs/heads/master
[rhc]
    app-uuid = e9e92282a16b49e7b78d69822ac53e1d
You are also able to add other remote repositories. This is useful for developers who also use github or have private git repositories for an existing code base.

2.4.2. The .openshift Directory

The .openshift directory is a hidden directory where a user can create action hooks, set markers, and create cron jobs.

Action hooks are scripts that are executed directly so can be written in Python, PHP, Ruby, shell, etc. OpenShift Origin supports the following action hooks:

Table 1. Action Hooks
Action Hook Description

pre_build

Executed on your CI system if available. Otherwise, executed before the build step

build

Executed on your CI system if available. Otherwise, executed before the deploy step

prepare

Executed just prior to a deployment ID being calculated and before the deployment is ready to use

deploy

Executed after dependencies are resolved but before application has started

post_deploy

Executed after application has been deployed and started

Note: On Windows, the execute permissions of an action hook files will be lost during the git push. To fix this problem, you can run this command:

# git update-index --chmod=+x .openshift/action_hooks/*
# git push

OpenShift Origin also supports the ability for a user to schedule jobs to be ran based upon the familiar cron functionality of linux. Any scripts or jobs added to the minutely, hourly, daily, weekly or monthly directories will be ran on a scheduled basis (frequency is as indicated by the name of the directory) using run-parts. OpenShift supports the following schedule for cron jobs:

  • daily

  • hourly

  • minutely

  • monthly

  • weekly

The markers directory will allow the user to specify settings such as enabling hot deployments or which version of Java to use.

2.4.3. The libs directory

The libs directory is a location where the developer can provide any dependencies that are not able to be deployed using the standard dependency resolution system for the selected runtime. In the case of PHP, the standard convention that OpenShift Origin uses is providing PEAR modules in the deplist.txt file.

2.4.4. The misc directory

The misc directory is a location provided to the developer to store any application code that they do not want exposed publicly.

2.4.5. The php directory

The php directory is where all of the application code that the developer writes should be created. By default, two files are created in this directory:

  • index.php - The OpenShift template that we saw after application creation in the web browser.

2.5. Environment Variables

OpenShift builds the execution environment which is made available to application scripts and other code. The environment contains a variety of variables related to OpenShift and the application itself which can only be determined at runtime. In addition to the standard environment variables exposed to the application, cartridges may also expose custom variables for the application to consume; consult the specific cartridge documentation for more information about what the cartridge makes available.

2.5.1. Standard OpenShift Environment Variables

The following is a comprehensive list of the predefined environment variables available regardless of the cartridges in use for a given application.

  • HOME alias for OPENSHIFT_HOMEDIR

  • HISTFILE bash history file

  • OPENSHIFT_APP_DNS the application’s fully qualified domain name that your cartridge is a part of

  • OPENSHIFT_APP_NAME the validated user assigned name for the application. Black list is system dependent.

  • OPENSHIFT_APP_UUID OpenShift assigned UUID for the application

  • OPENSHIFT_DATA_DIR the directory where your cartridge may store data

  • OPENSHIFT_GEAR_DNS the gear’s fully qualified domain name that your cartridge is a part of. May or may not be equal to OPENSHIFT_APP_DNS

  • OPENSHIFT_GEAR_NAME OpenShift assigned name for the gear. May or may not be equal to OPENSHIFT_APP_NAME

  • OPENSHIFT_GEAR_UUID OpenShift assigned UUID for the gear

  • OPENSHIFT_HOMEDIR OpenShift assigned directory for the gear

  • OPENSHIFT_REPO_DIR the directory where the developer’s application is "archived" to and will be run from.

  • OPENSHIFT_TMP_DIR the directory where your cartridge may store temporary data

  • TMPDIR alias for OPENSHIFT_TMP_DIR

  • TMP alias for OPENSHIFT_TMP_DIR

2.5.2. Cartridge-Specific Environment Variables

Although cartridges may expose further arbitrarily named environment variables, there are several variables which are generated by OpenShift for every cartridge based on well-defined standards incorporating cartridge metadata.

To learn more about these variables, consult the following pieces of documentation from the Cartridge Author guide.

2.6. Modifying and Deploying Updated Code

To get a good understanding of the development workflow for a user, let’s change the contents of the index.php template that is provided on the newly created gear. Edit the file and look for the following code block:

<h1>
    Welcome to OpenShift
</h1>

Update this code block to the following and then save your changes:

<h1>
    Welcome to OpenShift Origin
</h1>

Once the code has been changed, we need to commit our change to the local git repository. This is accomplished with the git commit command:

$ git commit -am "Changed welcome message."

Now that our code has been committed to our local repository, we need to push those changes up to our repository that is located on the node host.

$ git push

You should see the following output:

Counting objects: 7, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 395 bytes, done.
Total 4 (delta 2), reused 0 (delta 0)
remote: restart_on_add=false
remote: httpd: Could not reliably determine the server's fully qualified domain name, using node.example.com for ServerName
remote: Waiting for stop to finish
remote: Done
remote: restart_on_add=false
remote: ~/git/firstphp.git ~/git/firstphp.git
remote: ~/git/firstphp.git
remote: Running .openshift/action_hooks/pre_build
remote: Running .openshift/action_hooks/build
remote: Running .openshift/action_hooks/deploy
remote: hot_deploy_added=false
remote: httpd: Could not reliably determine the server's fully qualified domain name, using node.example.com for ServerName
remote: Done
remote: Running .openshift/action_hooks/post_deploy
To ssh://e9e92282a16b49e7b78d69822ac53e1d@firstphp-<yourdomain>.example.com/~/git/firstphp.git/
   3edf63b..edc0805  master -> master

Notice that we stop the application runtime (Apache), deploy the code, and then run any action hooks that may have been specified in the .openshift directory.

Verifying Code Changes
If you have completed all of the steps in this chapter correctly, you should be able to verify that your application was deployed correctly by opening up a web browser and entering the following URL:

http://firstphp-<yourdomain>.example.com

You should see the updated code for the application.

image

2.7. Adding a New PHP File

Adding a new source code file to your OpenShift Origin application is an easy and straightforward process. For instance, to create a PHP source code file that displays the server date and time, create a new file located in php directory and name it time.php. After creating this file, add the following contents:

<?php
// Print the date and time
echo date('l jS \of F Y h:i:s A');
?>

Once you have saved this file, the process for pushing the changes involve adding the new file to your git repository, committing the change, and then pushing the code to your OpenShift Origin gear:

$ git add .
$ git commit -am "Adding time.php"
$ git push

Verifying Code Changes
To verify that we have created and deployed the new PHP source file correctly, open up a web browser and enter the following URL:

http://firstphp-<yourdomain>.example.com/time.php

You should see the updated code for the application.

image

2.8. Action Hooks

OpenShift provides application developers entry points into various application and platform lifecycle operations. These entry points are referred to as "action hooks", and have a special location within the application’s Git repository:

<repository>/.openshift/action_hooks

During any OpenShift process which supports an action hook, the application action hook directory will be checked for an executable file matching the specified name. If such a file is present, it will be executed before returning control to the process.

Unless otherwise documented, OpenShift generally imposes no implementation requirement on action hooks other than they be executable files.

These scripts will be executed by the system directly. See Notes on Script Execution in the Cartridge Developers Guide for more information.

2.8.1. Cartridge Control Action Hooks

Cartridges implement a standard set of named control actions which allow them to function within OpenShift. Each time OpenShift invokes one of these cartridge actions, a standard set of application action hooks are executed to give the application developer an opportunity to integrate more closely with specific cartridges.

To use these hooks in your application create a file in:

<repository>/.openshift/action_hooks

with the same name as the event you want to trigger.

Cartridge-scoped action hooks are special in that they are sourced in into the same shell environment used to execute the action they surround. This allows cartridge hooks to modify the environment the action executes within.

All the hooks listed below are available to application developers as well cartridge developers. The order of execution will be first the platform/cartridge script and then the application developers.

The following is a list of all possible action hooks executed in association with a single cartridge control action. For each control action, a set of pre and post action hooks surround the control action. In the action hook names, {Name} refers to the Name cartridge manifest element.

  • start control action:

    • pre_start

    • pre_start_{Name} [1]

    • post_start

    • post_start_{Name} [1]

  • stop control action:

    • pre_stop

    • pre_stop_{Name} [1]

    • post_stop

    • post_stop_{Name} [1]

  • reload control action:

    • pre_reload

    • pre_reload_{Name} [1]

    • post_reload

    • post_reload_{Name} [1]

  • restart control action:

    • pre_restart

    • pre_restart_{Name} [1]

    • post_restart

    • post_restart_{Name} [1]

  • tidy control action:

    • pre_tidy

    • pre_tidy_{Name} [1]

    • post_tidy

    • post_tidy_{Name} [1]

For details about the control actions (including what they represent and when they are called), refer to the control script documentation in the Cartridge Developers Guide guide.

2.8.2. Build Action Hooks

During a Git push, applications using the default OpenShift build lifecycle are given an opportunity to participate in the build/deploy workflow via another set of action hooks. The workflow and sequence of actions for the build lifecycle is described in detail in the OpenShift Builds section of the Cartridge Developers Guide guide.

The list of action hooks supported during the default build lifecycle are:

  • pre_build

  • build

  • deploy

  • post_deploy

Refer to the OpenShift Builds guide for details about when these action hooks are invoked.

2.8.3. Custom Cartridge Action Hooks

Cartridges may support custom action hooks available to application developers. Consult the documentation for individual cartridges to learn which hooks are supported and how to correctly implement them.

3. Application Management

Servers used
  • localhost

  • node host

Tools used
  • rhc

3.1. Start, Stop and Restart

OpenShift Origin provides commands to start,stop, and restart an application. If at any point in the future you decided that an application should be stopped for some maintenance, you can stop the application using the rhc app stop command. After making necessary maintenance tasks you can start the application again using the rhc app start command.

To stop an application execute the following command:

$ rhc app stop -a firstphp

RESULT:
firstphp stopped

Verify that your application has been stopped with the following curl command:

$ curl http://firstphp-<yourdomain>.example.com/health

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>503 Service Temporarily Unavailable</title>
</head><body>
<h1>Service Temporarily Unavailable</h1>
<p>The server is temporarily unable to service your
request due to maintenance downtime or capacity
problems. Please try again later.</p>
<hr>
<address>Apache/2.2.15 (Red Hat) Server at myfirstapp-<yourdomain>.example.com Port 80</address>
</body></html>

To start the application back up, execute the following command:

$ rhc app start -a firstphp

RESULT:
firstphp started

Verify that your application has been started with the following curl command:

$ curl http://firstphp-<yourdomain>.example.com/health

1

You can also stop and start the application in one command as shown below.

$ rhc app restart -a firstphp

RESULT:
firstphp restarted

3.2. View Application Details

All of the details about an application can be viewed by the rhc app show command. This command will list when the application was created, unique identifier of the application, git URL, SSH URL, and other details as shown below:

$ rhc app show -a firstphp
Password: ****


firstphp @ http://firstphp-<yourdomain>.example.com/
===========================================
  Application Info
  ================
    UUID      = e9e92282a16b49e7b78d69822ac53e1d
    Git URL   = ssh://e9e92282a16b49e7b78d69822ac53e1d@firstphp-<yourdomain>.example.com/~/git/firstphp.git/
    Gear Size = small
    Created   = 1:47 PM
    SSH URL   = ssh://e9e92282a16b49e7b78d69822ac53e1d@firstphp-<yourdomain>.example.com
  Cartridges
  ==========
    php-5.3

3.3. View Application Status

The state of application gears can be viewed by passing the state switch to the rhc app show command as shown below:

rhc app show --state -a firstphp
Password: ****


RESULT:
Geargroup php-5.3 is started

3.4. Clean Up an Application

As users start developing an application and deploying changes to OpenShift Origin, the application will start consuming some of the available disk space that is part of their quota. This space is consumed by the git repository, log files, temp files, and unused application libraries. OpenShift Origin provides a disk space cleanup tool to help users manage the application disk space. This command is also available under rhc app and performs the following functions:

  • Runs the git gc command on the application’s remote git repository

  • Clears the application’s /tmp and log file directories. These are specified by the application’s OPENSHIFT_LOG_DIR* and OPENSHIFT_TMP_DIR environment variables.

  • Clears unused application libraries. This means that any library files previously installed by a git push command are removed.

To clean up the disk space on your application gear, run the following command:

$ rhc app tidy -a firstphp

3.5. SSH to an Application Gear

OpenShift allows remote access to the application gear by using the Secure Shell protocol (SSH). Secure Shell (SSH) is a network protocol for securely getting access to a remote computer. SSH uses RSA public key cryptography for both the connection and authentication. SSH provides direct access to the command line of your application gear on the remote server. After you are logged in on the remote server, you can use the command line to directly manage the server, check logs and test quick changes. OpenShift Origin uses SSH for:

  • Performing Git operations

  • Remote access your application gear

The SSH keys were generated and uploaded to OpenShift Origin during rhc setup. You can verify that SSH keys are uploaded by logging into the OpenShift Origin web console and clicking on the "My Account" tab as shown below.

image

If you don’t see an entry under "Public Keys" then you can either upload the SSH keys by clicking on "Add a new key" or run the rhc setup command again. This will create a SSH key pair in /.ssh folder and upload the public key to the OpenShift Origin server.

After the SSH keys are uploaded, you can SSH into the application gear as shown below. SSH is installed by default on most UNIX like platforms such as Mac OS X and Linux. For windows, you can use PuTTY. Instructions for installing PuTTY can be found on the OpenShift website.

$ ssh UUID@appname-namespace.example.com

You can get the SSH URL by running rhc app show command as shown below:

$ rhc app show -a firstphp
Password: ****


firstphp @ http://firstphp-<yourdomain>.example.com/
===========================================
  Application Info
  ================
    Created   = 1:47 PM
    UUID      = e9e92282a16b49e7b78d69822ac53e1d
    SSH URL   = ssh://e9e92282a16b49e7b78d69822ac53e1d@firstphp-<yourdomain>.example.com
    Gear Size = small
    Git URL   = ssh://e9e92282a16b49e7b78d69822ac53e1d@firstphp-<yourdomain>.example.com/~/git/firstphp.git/
  Cartridges
  ==========
    php-5.3```

Now you can ssh into the application gear using the SSH URL shown above:

$ ssh e9e92282a16b49e7b78d69822ac53e1d@firstphp-<yourdomain>.example.com

    *********************************************************************

    You are accessing a service that is for use only by authorized users.
    If you do not have authorization, discontinue use at once.
    Any use of the services is subject to the applicable terms of the
    agreement which can be found at:
    https://openshift.redhat.com/app/legal

    *********************************************************************

    Welcome to OpenShift shell

    This shell will assist you in managing OpenShift applications.

    !!! IMPORTANT !!! IMPORTANT !!! IMPORTANT !!!
    Shell access is quite powerful and it is possible for you to
    accidentally damage your application.  Proceed with care!
    If worse comes to worst, delete your application with 'rhc app delete'
    and recreate it
    !!! IMPORTANT !!! IMPORTANT !!! IMPORTANT !!!

    Type "help" for more info.

You can also view all of the commands available on the application gear shell by running the help command as shown below:

[firstphp-<yourdomain>.example.com ~]\> help
Help menu: The following commands are available to help control your openshift
application and environment.

ctl_app         control your application (start, stop, restart, etc)
ctl_all         control application and deps like mysql in one command
tail_all        tail all log files
export          list available environment variables
rm              remove files / directories
ls              list files / directories
ps              list running applications
kill            kill running applications
mysql           interactive MySQL shell
mongo           interactive MongoDB shell
psql            interactive PostgreSQL shell
quota           list disk usage

3.6. View Log Files

Logs are very important when you want to find out why an error is happening or if you want to check the health of your application. OpenShift Origin provides the rhc tail command to display the contents of your log files. To view all the options available for the rhc tail command, issue the following:

$ rhc tail -h
Usage: rhc tail <application>

Tail the logs of an application

Options for tail
  -n, --namespace namespace Namespace of your application
  -o, --opts options        Options to pass to the server-side (linux based) tail command (applicable to tail command only) (-f is implicit.  See the linux tail man page full
list of options.) (Ex: --opts '-n 100')
  -f, --files files         File glob relative to app (default <application_name>/logs/*) (optional)
  -a, --app app             Name of application you wish to view the logs of

The rhc tail command requires that you provide the application name of the logs you would like to view. To view the log files of our firstphp application, use the following command:

$ rhc tail -a firstphp

You should see information for both the access and error logs. While you have the rhc tail command open, issue a HTTP get request by pointing your web browser to http://firstphp-<yourdomain>.example.com. You should see a new entry in the log files that looks similar to this:

10.10.56.204 - - [22/Jan/2013:18:39:27 -0500] "GET / HTTP/1.1" 200 5242 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:19.0) Gecko/20100101 Firefox/19.0"

The log files are also available on the gear node host in the php-5.3/logs directory.

3.7. View Disk Quota

The Comprehensive Deployment Guide discusses how to set disk quotas for applications. You can view the quota of your currently running gear by connecting to the gear node host via SSH. Once you are connected to your application gear, enter the following command:

$ quota -s

If the quota information that we configured earlier is correct, you should see the following information:

Disk quotas for user e9e92282a16b49e7b78d69822ac53e1d (uid 1000):
     Filesystem  blocks   quota   limit   grace   files   quota   limit   grace
/dev/mapper/VolGroup-lv_root
                  22540       0   1024M             338       0   80000

To view how much disk space your gear is actually using, you can also enter in the following:

$ du -h

3.8. Add a Custom Domain

OpenShift Origin supports the use of custom domain names for an application. For example, suppose we want to use http://www.somesupercooldomain.com domain name for the application firstphp (from the example in Create a New Application). The first thing you need to do before setting up a custom domain name is to buy the domain name from domain registration provider.

After buying the domain name, you have to add a CNAME record for the custom domain name. Once you have created the CNAME record, you can let OpenShift Origin know about the CNAME by using the rhc alias command.

$ rhc alias add firstphp www.mycustomdomainname.com

Technically, what OpenShift Origin has done under the hood is set up a virtual host in Apache to handle the custom URL.

3.9. Back Up an Application

Use the rhc snapshot save command to create backups of your OpenShift Origin application. This command creates a gzipped tar file of your application and of any locally-created log and data files. This snapshot is downloaded to your local machine and the directory structure that exists on the server is maintained in the downloaded archive.

$ rhc snapshot save -a firstphp
Password: ****

Pulling down a snapshot to firstphp.tar.gz...
Waiting for stop to finish
Done
Creating and sending tar.gz
Done

RESULT:
Success

After the command successfully finishes you will see a file named firstphp.tar.gz in the directory where you executed the command. The default filename for the snapshot is $Application_Name.tar.gz. You can override this path and filename with the -f or --filepath option.

This command will stop your application for the duration of the backup process. NOTE: The application original state will be preserved, so if your application was stopped before doing snapshot, it will remain stopped after the snapshot is completed.

3.10. Delete an Application

You can delete an OpenShift Origin application by executing the rhc app delete command. This command deletes your application and all of its data on the OpenShift Origin server but leaves your local directory intact. This operation can not be undone so use it with caution.

$ rhc app delete -a someAppToDelete

Are you sure you wish to delete the 'someAppToDelete' application? (yes/no)
yes

Deleting application 'someAppToDelete'

RESULT:
Application 'someAppToDelete' successfully deleted

There is another variant of this command which does not require the user to confirm the delete opeartion. To use this variant, pass the --confirm flag.

$ rhc app delete --confirm -a someAppToDelete

Deleting application 'someAppToDelete'

RESULT:
Application 'someAppToDelete' successfully deleted

3.11. Restore From Backup

Not only you can take a backup of an application but you can also restore a previously saved snapshot. This form of the rhc command restores the git repository, as well as the application data directories and the log files found in the specified archive. When the restoration is complete, OpenShift Origin runs the deployment script on the newly restored repository. To restore an application snapshot, run the following command:

$ rhc snapshot restore -a firstphp -f firstphp.tar.gz
This command will stop your application for the duration of the restore process. NOTE: This command will preserve the state of your application as it was before restore. If your application was stopped, before this command it will remain stopped after restore

Verify that the application has been restored
Open up a web browser and point to the following URL:

http://firstphp-<yourdomain>.example.com

If the restore process worked correctly, you should see the restored application just as it was before the delete operation.

3.12. View a Thread Dump

This can be performed on Ruby and JBoss EAP / JBoss EWS application types.

You can trigger a thread dump for Ruby and JBoss EAP / JBoss EWS applications using the rhc threaddump command. A thread dump is a snapshot of the state of all threads that are part of the runtime process. If an application appears to have stalled or is running out of resources, a thread dump can help reveal the state of the runtime, identify what might be causing any issues and ultimately to help resolve the problem. To trigger a thread dump execute the following command:

$ rhc threaddump -a ApplicationName

After running this command for a JBoss EAP, JBoss EWS or Ruby application, you will be given a log file that you can view in order to see the details of the thread dump. Issue the following command, substituting the correct log file:

$ rhc tail ApplicationName -f ruby-1.9/logs/error_log-20130104-000000-EST -o '-n 250'

4. Using Cartridges

Servers used
  • localhost

  • node host

Tools used
  • rhc

  • mysql

  • tail

  • git

  • PHP

Cartridges provide the actual functionality necessary to run applications. Currently, there are several cartridges available to support different programming languages, databases, monitoring and management. Cartridges are designed to be extensible so the community can add support for any programming language, database or any management tool not officially supported by OpenShift Origin. Please refer to the official OpenShift Origin documentation for how you can write your own cartridge.

4.1. View Available Cartridges

To view all of the available commands for working with cartridges on OpenShift Origin, enter the following command:

$ rhc cartridge -h

4.2. List Available Cartridges

To see a list of all available cartridges to users of this OpenShift Origin deployment, issue the following command:

$ rhc cartridge list

You should see the following output:

RESULT:
cron-1.4, mysql-5.5, haproxy-1.4, postgresql-8.4

4.3. Example: Add a MySQL Cartridge to an Application

In order to use a cartridge, we need to embed it into our existing application. As an example, we will add a MySQL cartridge. OpenShift Origin provides support for version 5.1 of this popular open source database. To enable MySQL support for the firstphp application, issue the following command:

$ rhc cartridge add mysql-5.5 -a firstphp

You should see the following output:

Password: *********

Adding 'mysql-5.5' to application 'firstphp'
Success
mysql-5.5
=========
  Properties
  ==========
    Username       = admin
    Password       = aFh_GsHP63fV
    Connection URL = mysql://127.1.244.1:3306/
    Database Name  = firstphp

4.3.1. Using MySQL

Developers will typically interact with MySQL by using the mysql shell command on OpenShift Origin. In order to use the mysql shell, refer to using SSH to connect to an application gear. Once you have been authenticated, issue the following command:

[firstphp-<yourdomain>.example.com ~]\> mysql

You will notice that you did not have to authenticate to the MySQL database. This is because OpenShift Origin sets environment variables that contains the connection information for the database.

When embedding the MySQL database, OpenShift Origin creates a default database based upon the application name. That being said, the user has full permissions to create new databases inside of MySQL. Let’s use the default database that was created for us and create a users table:

mysql> use firstphp;
Database changed

mysql> create table users (user_id int not null auto_increment, username varchar(200), PRIMARY KEY(user_id));
Query OK, 0 rows affected (0.01 sec)

mysql> insert into users values (null, 'gshipley@redhat.com');
Query OK, 1 row affected (0.00 sec)

Verify that the user record has been added by selecting all rows from the users table:

mysql> select * from users;
+---------+---------------------+
| user_id | username            |
+---------+---------------------+
|       1 | gshipley@redhat.com |
+---------+---------------------+
1 row in set (0.00 sec)

To exit out of the MySQL session, simply enter the exit command:

mysql> exit

4.3.2. MySQL Environment Variables

As mentioned above, OpenShift Origin creates environment variables that contain the connection information for your MySQL database. If a user forgets their connection information, they can always retrieve the authentication information by viewing these environment variables:

Execute the following on the application gear:

[firstphp-<yourdomain>.example.com ~]\> env |grep MYSQL

You should see the following information return from the command:

OPENSHIFT_MYSQL_DB_PORT=3306
OPENSHIFT_MYSQL_DB_HOST=127.1.244.1
OPENSHIFT_MYSQL_DB_PASSWORD=aFh_GsHP63fV
OPENSHIFT_MYSQL_DB_USERNAME=admin
OPENSHIFT_MYSQL_DB_SOCKET=/var/lib/openshift/e9e92282a16b49e7b78d69822ac53e1d//mysql-5.1/socket/mysql.sock
OPENSHIFT_MYSQL_DB_URL=mysql://admin:aFh_GsHP63fV@127.1.244.1:3306/
OPENSHIFT_MYSQL_DB_LOG_DIR=/var/lib/openshift/e9e92282a16b49e7b78d69822ac53e1d//mysql-5.1/log
OPENSHIFT_MYSQL_VERSION=5.5

To view a list of all OPENSHIFT environment variables, you can use the following command:

[firstphp-<yourdomain>.example.com ~]\> env | grep OPENSHIFT

4.3.3. Viewing MySQL Logs

Given the above information, you can see that the log file directory for MySQL is specified with the OPENSHIFT_MYSQL_DB_LOG_DIR environment variable. To view these log files, simply use the tail command:

[firstphp-<yourdomain>.example.com ~]\> tail -f $OPENSHIFT_MYSQL_DB_LOG_DIR/*

4.3.4. Connecting to the MySQL Cartridge from PHP

Now that we have verified that our MySQL database has been created correctly, and have created a database table with some user information, let’s connect to the database from PHP in order to verify that our application code can communicate to the newly embedded MySQL cartridge. Create a new file in the php directory of your firstphp application named dbtest.php. Add the following source code to the dbtest.php file:

<?php
$dbhost = getenv("OPENSHIFT_MYSQL_DB_HOST");
$dbport = getenv("OPENSHIFT_MYSQL_DB_PORT");
$dbuser = getenv("OPENSHIFT_MYSQL_DB_USERNAME");
$dbpwd = getenv("OPENSHIFT_MYSQL_DB_PASSWORD");
$dbname = getenv("OPENSHIFT_APP_NAME");

$connection = mysql_connect($dbhost, $dbuser, $dbpwd);

if (!$connection) {
        echo "Could not connect to database";
} else {
        echo "Connected to database.<br>";
}

$dbconnection = mysql_select_db($dbname);

$query = "SELECT * from users";

$rs = mysql_query($query);
while ($row = mysql_fetch_assoc($rs)) {
    echo $row['user_id'] . " " . $row['username'] . "\n";
}

mysql_close();

?>

Once you have created the source file, add the file to your git repository, commit the change, and push the change to your OpenShift Origin gear.

$ git add .
$ git commit -am "Adding dbtest.php"
$ git push

After the code has been deployed to your application gear, open up a web browser and enter the following URL:

http://firstphp-<yourdomain>.example.com/dbtest.php

You should see a screen with the following information:

Connected to database.
1 gshipley@redhat.com

4.4. Manage Cartridges

OpenShift Origin provides the ability to embed multiple cartridges in an application. For instance, even though we are using MySQL for our firstphp application, we could also embed the cron cartridge as well. It may be useful to stop, restart, or even check the status of a cartridge. To check the status of our MySQL database, use the following command:

$ rhc cartridge status -a firstphp -c mysql-5.5

To stop the cartridge, enter the following command:

$ rhc cartridge stop -a firstphp -c mysql-5.5

Verify that the MySQL database has been stopped by either checking the status again or viewing the following URL in your browser:

http://firstphp-<yourdomain>.example.com/dbtest.php

You should see the following message returned to your browser:

Could not connect to database

Start the database back up using the start switch.

$ rhc cartridge start -a firstphp -c mysql-5.5

OpenShift Origin also provides the ability to list important information about a cartridge by using the show switch. For example, if a user has forgotten their MySQL connection information, they can display this information with the following command:

$ rhc cartridge show mysql-5.5 -a firstphp

The user will then be presented with the following output:

Password: ****

mysql-5.5
=========
  Properties
  ==========
    Username       = admin
    Password       = aFh_GsHP63fV
    Database Name  = firstphp
    Connection URL = mysql://127.1.244.1:3306/

4.5. Port Forwarding

At this point, you may have noticed that the database cartridge is only accessible via a 127.x.x.x private address. This ensures that only the application gear can communicate with the database.

With OpenShift Origin port forwarding, developers can connect to remote services with local client tools. This allows the developer to focus on code without having to worry about the details of configuring complicated firewall rules or SSH tunnels. To connect to the MySQL database running on our OpenShift Origin gear, you have to first forward all the ports to your local machine. This can be done using the rhc port-forward command. This command is a wrapper that configures SSH port forwarding. Once the command is executed, you should see a list of services that are being forwarded and the associated IP address and port to use for connections as shown below:

$ rhc port-forward -a firstphp

Checking available ports...
Binding httpd -> 127.11.144.1:8080...
Binding mysqld -> 127.11.144.1:3306...
Forwarding ports, use ctl + c to stop

In the above snippet, you can see that mysql database, which we added to the firstphp gear, is forwarded to our local machine. If you open http://127.11.144.1:8080 in your browser you will see the application.

At the time of this writing, there is an extra step to enable port forwarding on Mac OS X based systems. You will need to create an alias on your loopback device for the IP address listed in output shown above.
sudo ifconfig lo0 alias 127.11.144.1

Now that you have your services forward, you can connect to them using local client tools. To connect to the MySQL database running on the OpenShift Origin gear, run the mysql command as shown below:

$ mysql -uadmin -p -h 127.11.144.1
The above command assumes that you have the MySQL client installed locally.

4.6. Enable hot_deploy

If you are familiar with PHP, you will probably be wondering why we stop and start apache on each code deployment. Fortunately, we provide a way for developers to signal to OpenShift Origin that they do not want us to restart the application runtime for each deployment. This is accomplished by creating a hot_deploy marker in the correct directory. Change to your application root directory, for example ~/code/<yourdomain>/firstphp and issue the following commands:

$ touch .openshift/markers/hot_deploy
$ git add .
$ git commit -am "Adding hot_deploy marker"
$ git push

Pay attention to the output:

Counting objects: 7, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 403 bytes, done.
Total 4 (delta 2), reused 0 (delta 0)
remote: restart_on_add=false
remote: Will add new hot deploy marker
remote: App will not be stopped due to presence of hot_deploy marker
remote: restart_on_add=false
remote: ~/git/firstphp.git ~/git/firstphp.git
remote: ~/git/firstphp.git
remote: Running .openshift/action_hooks/pre_build
remote: Running .openshift/action_hooks/build
remote: Running .openshift/action_hooks/deploy
remote: hot_deploy_added=false
remote: App will not be started due to presence of hot_deploy marker
remote: Running .openshift/action_hooks/post_deploy
To ssh://e9e92282a16b49e7b78d69822ac53e1d@firstphp-<yourdomain>.example.com/~/git/firstphp.git/
   4fbda99..fdbd056  master -> master

The two lines of importance are:

remote: Will add new hot deploy marker
remote: App will not be stopped due to presence of hot_deploy marker

Adding a hot_deploy marker will significantly increase the speed of application deployments while developing an application.

5. The Web Console

Servers used
  • localhost

Tools used
  • OpenShift Origin web console

  • git

OpenShift Origin provides users with multiple ways to create and manage applications. The platform provides command line tools, IDE integration, REST APIs, and a web console. In this chapter we will explore the creation and management of application using the web console.

Having DNS resolution setup on your local machine, as discussed in the Comprehensive Deployment Guide, is crucial in order to connect to the web console.

5.1. Authenticate to the Web Console

Open your favorite web browser and go to the following URL:

http://<your Broker hostname or IP>/

Once you enter the above URL, you will be asked to authenticate. The exact auth method will vary according to the authentication plugin that your Broker is using. The OpenShift Origin virtual machine has a default user account of demo / changeme

image

After entering in valid credentials, you will see the OpenShift Origin web console dashboard:

image

5.2. Create a New Application

In order to create a new application using the web console, click on the ADD APPLICATION button. You will then be presented with a list of available runtimes that you can choose from. To follow along with our PHP examples above, let’s create a new PHP application and name it phptwo.