Wednesday, December 21, 2011

Troubleshooting faulty network connectivity

— SkyHi @ Wednesday, December 21, 2011

part 1: A step-by-step guide

“My computer won’t connect to the Internet”.
“I can’t get online”.
“I’m getting ‘page cannot be displayed’ errors”.
If you have worked as a network administrator or help desk specialist, you have probably heard these complaints and variants of them more times than you can count. Between improper IP addressing, malfunctioning hardware or faulty cables, incorrect DNS resolution, incorrect access permissions and a slew of other factors, there are many reasons why modern computer users could experience difficulty getting their client machines online and/or connecting to the resources that they need (i.e., the Internet in general, a certain website, a network share, a printer, etc).
Given the many interconnected technologies that work together to provide modern computer networking, it is no surprise that the inability to get online is one of the most common complaints of computer users. An inspection of any Web discussion forum focusing on technical support will reveal that networking problems are among the most common challenges that users face (see, for example, Computer Hope and Tech Support Guy).
Difficulties can range from the inability to get an IP address from a DHCP server, incorrect DNS server IP addresses on the client, malfunctioning DNS servers, a faulty network interface card (NIC) or NIC driver, malware attacks, strict firewall rules, misconfigured Web browsers, etc.
Since so many networking component technologies could be the culprits behind a lack of connectivity, a unified methodology towards troubleshooting network errors and outages is ideal for technicians. Why? To help ensure that you do not overlook any steps, or do any unnecessary or repetitive work as you attempt to establish the required connectivity.
The CompTIA Network+ troubleshooting model provides a broad, high level plan of action for remedying faulty connectivity.
  1. Identify the symptoms and potential causes. In this first step you define and determine the nature of the problem. Is it the user or computer that is problematic? Are all websites unreachable, or just one or a few? Is the computer consistently online or is the connection flapping? Are websites reachable by IP address but not by name? Are there any error messages indicating what type of error was encountered? Based on your answers to these questions you can begin to make educated guesses as to the cause.Gather detailed information.
  2. Identify the affected area. This step is similar to the first step, but here you determine the extent of the problem. Is it affecting one computer or user, or multiple computers or users? Are all computers in the subnet (or all users in the domain) affected? Is the whole network down? If you are providing support to another user, can you reproduce the error yourself? Gather detailed information.
  3. Establish what has changed. This is where you try to put the connectivity problem in some kind of time frame. Find out if the user was ever able to successfully do what he now cannot do. When did the error first appear? Before the appearance of the error were there any programs or operating system updates installed? How about new drivers or browser plugins? Were any new nodes (clients, servers, networking devices, printers, etc) added to the network? Any new users, user groups, or Active Directory objects such as domains, OUs, or sites?
  4. Establish the most probable cause. Use your technical expertise to isolate and explain the cause of the problem. Some in-depth investigation and diagnostic tools will probably be required. This step is described in more detail below.
  5. Determine if escalation is necessary. If you believe that the connectivity error is outside your scope of administration, you will need to transfer responsibility for its resolution to another entity. For example, if you cannot connect to the Internet and you strongly believe that the problem is not your computer, router, or other equipment, you will need to contact your Internet service provider (ISP) and ask them to investigate…perhaps one of their lines or routers is down. Another scenario might involve a piece of equipment on your network that is contractually administered by a third party.
  6. Implement an action plan and solution including potential effects. Whether the responsibility to fix the error falls on you or if you need to transfer it to another party, you must devise a resolution and start checking off action items.
  7. Test the result. When you believe the steps of the action plan have been fulfilled, try to re-create the error. Observe the results of the implementation. Is the problem gone? If not, repeat steps 4, 5, and 6.
  8. Identify the results and effects of the solution. Once a solution has been found, ensure that normal network operation has been restored and that no new problems have been introduced.
  9. Document the solution and process. Describe the error conditions and the steps taken for a solution. This will aid you in troubleshooting the same or similar problems in the future. Make sure you include a sufficient amount of detail, including operating system versions, application versions, driver versions, software vendor update numbers, etc.

Step 4 in detail

Step 4, ‘Establish the most probable cause’, is the one that will require the most time and effort on your part. To troubleshoot TCP/IP connectivity on a technical level, this step involves its own set of steps. When a network host cannot connect to a desired resource, the following procedures will help you narrow down the cause of the problem.
  1. Ping the local loopback address of your network adapter, which is 127.0.0.1. If you get replies, you know that the TCP/IP protocol suite is installed and functioning correctly. If this ping fails, it might be because the TCP drivers are corrupted or the network adapter might not be working.
  2. Ping your own IP address. Use the command ipconfig (or ifconfig for Linux/Unix) to determine your IP address. If you don’t have one, this is a very useful clue as to the nature of your problem…if your computer’s routing table is correct, this ping is simply forwarded to the loopback address of 127.0.0.1.Note: If your IP address is returned as 169.254.x.x, you have been assigned an APIPA IP address. This means that the local DHCP server is not configured properly or cannot be reached from your computer, and an IP address has been assigned automatically. APIPA is a feature of Microsoft Windows that acts as a DHCP failover mechanism. When a DHCP request or server fails, APIPA allocates addresses in the private range 169.254.0.1 to 169.254.255.254. This functionality is also known as Link-Local address assignment or zero configuration networking.
  3. Ping the IP address of a known good host in your subnet.This will determine if your IP address and subnet mask are valid, and if the switch or router you are connected to is functioning properly; perhaps you are plugged into a faulty port or your network cable is faulty. Also, can other hosts in the subnet ping your IP address? If pings in this step fail, ensure that the network cable is plugged into the network adapter and ensure that you get a link light. The link light indicates whether a network connection exists between the NIC and the network. If the link light is off, the cable or switch port are probably at fault, or perhaps the NIC itself is toast. If you can ping both the loopback address and your own IP address but not hosts in the local subnet, try to clear out the ARP cache and reload it. This can be done by using the Arp utility on the command line interface (CLI). First display the cache entries with thearp -a or arp -g commands. Delete the entries with arp -d <IP address>.
  4. Ping the IP address of the default gateway. This is important if the error revolves around the inability to access hosts and resources in other networks, such as networks at remote sites or on the Internet. The default gateway on a local area network (LAN) is the network host to which all data traffic bound for other subnets is sent. If network hosts do not know the IP address of the default gateway, they cannot send data traffic to remote networks. Therefore the default gateway serves as an access point to other networks. Similarly it acts as the entry point into the network for remote hosts sending data to local hosts.
  5. Ping the IP address of a host in another subnet. If you can reach the default gateway, this step will verify that there is proper routing between your subnet and the destination subnet.
  6. Ping the host name of a host in another subnet. This step will help ensure proper DNS resolution of host names of remote hosts. If you cannot successfully ping the remote host name after successfully pinging the remote host’s IP address, the problem is with DNS and not with network connectivity itself.
  7. Run a Tracert (traceroute in Linux/Unix) and PathPing analysis to a remote host to verify that the routers between you and the destination host are operating correctly.Traceroute/tracert is a network diagnostic tool for displaying the route (path) and measuring transit delays of packets across an IP network. PathPing combines the features of the ping and tracert commands. It sends packets to each router (hop) over a period of time and computes results for each hop. In this way PathPing can show if there are any problematic routers between you and the destination.
  8. Other troubleshooting steps you might try include:
    • Issue the ipconfig /release and ipconfig /renew commands.
    • Issue the ipconfig /flushdns and ipconfig /registerdns commands.
    • Right-click the network icon in the system tray and choose ‘Diagnose and repair’ (Vista) or ‘Troubleshoot problems’ (Windows 7). In Windows XP right-click the network connection and choose ‘Repair’.
    • Reboot your computer. Power cycle your switch, router, and cable/DSL modem (unplug them and plug them back in). Does the router firmware need to be updated? It should be at the latest release. Are all cables plugged in properly on all components, such as the network adapter on the computer and on all other devices until the cable goes into the wall?
    • Is the computer joined to the proper workgroup or domain? In a workgroup all computers are peers and each computer has its own set of user accounts. To log on to any computer in the workgroup, you must have an account on that computer. All computers must be in the same subnet and use the same workgroup name.
      A domain is a group of accounts and network resources that share a common directory database and set of security policies. One or more computers are servers. Network administrators use servers to control the security and permissions for all computers on the domain. Domain users must provide a password or other credentials each time they access the domain. If you have a user account on the domain, you can log on to any computer on the domain without needing an account on that particular computer. The computers can be on different local networks.
    • Take a peek at the Windows Event Logs using the Event Viewer (Control Panel -> Administrative Tools -> Event Viewer, or Start, type eventvwr, hit Enter. In Linux take a look at/var/log/messages using the tail or less commands. Graphical tools for reading event logs in Linux will vary based on your distribution and desktop environment (such as Gnome or KDE).
For some other in-depth articles dealing with network connectivity troubleshooting, you may want to read Mitch Tulloch’s TCP/IP Troubleshooting: A Structured Approach and Brien Posey’s Troubleshooting Connectivity Problems on Windows Networks.
Go to Part 2 of this series.
In my previous article describing the troubleshooting steps for faulty TCP/IP connections, I mentioned several commands such as ping, traceroute, and ipconfig that could assist you in pinpointing problematic network components. These commands and several others like them are commonly referred to as TCP/IP utilities because they are tools that let you perform diagnostics and queries on the network which you are examining.
To compliment Part 1 of this two-part series, Part 2 is a reference list of the TCP/IP utilities which will describe the intended uses and options for each. These tools natively run in command line interface (CLI) environments (or in Linux and Unix, “shell prompts”), but as several entries in this blog show, there are a great many graphical utilities available that let you use the TCP/IP utilities (and view their output) in graphical format. In this article, however, I will stick with the default CLI usage and functionality.
When working in a CLI environment in Windows, I prefer to use Windows PowerShell as opposed to the default Windows command prompt (cmd.exe).
Remember: the best way to learn and understand these tools is to practice and experiment with them. Also bear in mind that knowledge of these commands is essential during ethical hacking efforts.
Jump to:


REFERENCES

What to Look for in PHP 5.4.0

— SkyHi @ Wednesday, December 21, 2011
PHP 5.4.0 will arrive soon. The PHP team is working to bring to some very nice presents to PHP developers. In the previous release of 5.3.0 they had added a few language changes. This version is no different. Some of the other changes include the ability to use DTrace for watching PHP apps in BSD variants (there is a loadable kernel module for Linux folks). This release features many speed and security improvements along with some phasing out of older language features (Y2K compliance is no longer optional). The mysql extensions for ext/mysql, mysqli, and pdo now use the MySql native driver (mysqlnd). This release also improves support for multibyte strings.

Built-in Development Server

In the past, newcomers to PHP needed to set up a server. There was no built in server like a few other languages/web frameworks already had. If developing on *nix, a server needed to be set up with the right modules and the the files to tested needed to be copied over to the document root. Now, you can just run PHP with some options to get a server:
$ php -S localhost:1337
It runs in the current directory, using index.php or index.html as the default file to serve. A different document root can be specified as either an absolute or relative path:
$ php -S localhost:1337 -t /path/to/docroot
The server will log requests directly to the console. Interestingly, this server will not serve your static files unless your script return false. Existing frameworks will need to be modified to add in functionality that is commonly in rewrite rules. This is really all that is needed:
// If we're using the built-in server, route resources
if (php_sapi_name() == 'cli-server') {
  /*
   * If the request is for one of these image types, return false.
   * It will serve up the requested file.
   */
  if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"]))
    return false;
}
// Process the rest of your script
One of the inconveniences of the server is lack of support for SSL. Granted, it is meant for development purposes only. However, some projects I’ve worked on required testing with SSL. Perhaps there will be demand for this once it’s out there.

An Overview of Traits

Traits are bits of code that other objects can use. Traits allow composing objects and they promote code reuse. The Self programming language, one of the precursors to the JavaScript language, introduced them. JavaScript, strangely, does not directly implement traits; instead it allows one to extend objects directly with other objects.
In PHP (and other languages), traits cannot be instantiated, only used to compose other objects. Traits do not imply inheritance, they just add methods to classes. They can be used with inheritance and interfaces. Traits could be used as standard implementations of interfaces, then one could easily compose classes that comply with certain interfaces.
Here is an example, demonstrating a simple use of traits:
name().", run!\n";
  }
  // Gets the name of the runner
  // Must be implemented by the class using the trait.
  abstract public function name();
}
/**
 * Define a class that uses the runner trait
 */
class runningPerson {
  // Use the runner trait
  use runner;
  // Used to store the person's name
  protected $name; // Constructor, assigns a name to the person
  public function __construct($name) {
    $this->name = $name;
  }
  // Retrieves the name of the person, required by runner trait
  public function name() {
    return $this->name;
  }
}
$gump = new runningPerson("Forrest");
$gump->run();
When a class implements a method that is also defined in a trait it uses, the method in the trait takes precedence and overrides the class method. If two traits implement the same method, the conflict needs to be resolved using the insteadof keyword, or given a new signature (only visibility and name can be changed) using the as keyword.
do_something();
$testB->do_something();
$testB->something_else();
More examples reside at the current PHP documentation for traits. If that documentation is lacking in substance, Wikipedia’s article on traits links plenty of background info.

Changes to Anonymous Functions

In PHP 5.3.x, working with anonymous functions needed a work around when stored in an array. The function needed to be stored in a temporary variable before it could be called. For instance:
$functions = array();
// assign an anonymous function to an array element
$functions['anonymous'] = function () {
  echo "Hello, the parser needs to make up a name for me...\n";
};
// to call it you had to do this:
$temp = $functions['anonymous'];
$temp();
Now, anonymous functions stored in an array can be called directly without first storing them in a temporary variable:
// assume $functions[] is still around.
$functions['anonymous']();

Closures in Classes

Closures defined inside of a class are automatically early bound to the $this variable. If a class method returns a closure, it retains access to the original class that defined it (along with all the public member properties and methods) no matter where it is passed. If assigned to a member property and called as a method, PHP issues a warning if it was called directly. If called as a local variable or by calling the Closure::__invoke() method (which it inherits), PHP issues no warning.
value = $value;
  }

  public function getValue() {
    return $this->value;
  }

  public function getCallback() {
    return function() {
      return $this->getValue();
    };
  }
}

/**
 * Create a class that calls a closure.
 */
class ClosureCaller {
  private $callback;

  public function setCallback($callback) {
    $this->callback = $callback;
  }

  public function doSomething() {
    // Since this is a member variable, call Closure::__invoke().
    echo $this->callback->__invoke() . "\n";
  }
}

// Set up a class to generate closures that reference itself
$test = new ClosureTest();
$test->setValue(42);
$closure = $test->getCallback();
echo $closure() . "\n";

// Test calling a closure from another class
$testCaller = new ClosureCaller();
$testCaller->setCallback($test->getCallback());
$testCaller->doSomething();
Closures allow changing what object scope $this is bound to by calling the bindTo() method and passing in the new object to use as $this.
Currently, no consensus exists around letting closures bound to an object access the private and protected methods of that class. Additionally, PHP still needs to iron out the details around binding closures to static classes. One can find more details about closures, $this, andClosure::bindTo() at https://wiki.php.net/rfc/closures/object-extension

Outlook

There are a lot of established projects that may not immediately start taking advantage of these features, unless the community sees an obvious benefit to drastically changing their projects. When PHP 5.3.0 was released with namespace support and anonymous functions, new frameworks sprung up like Laravel (anonymous functions), FLOW3 (namespaces), Lithium (namespaces), and Symfony2(namespaces). After PHP 5.4.0 is released, I’m sure new frameworks (or new versions, like Symfony2 vs. Symfony) will spring up around using traits to compose functionality and using the new $thisfunctionality in closures defined in classes. The built in server definitely has some potential for making it easier for developers to debug their apps. It’s just a matter of time before frameworks start taking advantage of it.


REFERENCES
http://jburrows.wordpress.com/2011/12/17/what-to-look-for-in-php-5-4-0/
https://svn.php.net/repository/php/php-src/tags/php_5_4_0RC2/NEWS

Tuesday, December 20, 2011

Setting up NGINX SSL reverse proxy for Tomcat

— SkyHi @ Tuesday, December 20, 2011
Setting up Tomcat in some cases can be pain in the ass, especially when your application is pretty complex, in terms of large number of upstream servers which you all want to proxy via SSL.
In my case, I was playing around with Shindig — an OpenSocial container, which itself is a Java servlet delivered via Apache Tomcat server.


The goal was to reverse proxy Shindig through SSL, i.e. it should be able to access it via
https://localhost/gadgets/
with localhost being served by Nginx.

Initial schema

nginx tomcat reverse proxy schemaInitial nginx config


daemon off;

worker_processes  2;
error_log /var/log/nginx_error.log info;
user bananos staff;

events {
    worker_connections  1024;
}

http {
    include /opt/nginx/conf/mime.types;
    default_type application/octet-stream;

    log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $bytes_sent "$http_referer" "$http_user_agent" "$gzip_ratio"';
    ignore_invalid_headers on;
    index index.html;
    client_header_timeout 240;
    client_body_timeout 240;
    send_timeout 240;
    client_max_body_size 100m;
    proxy_buffer_size 128k;
    proxy_buffers 8 128k;

    upstream tomcat_server {
 # Tomcat is listening on default 8080 port
        server 127.0.0.1:8080 fail_timeout=0;
    }

    server {
        server_name localhost;
        listen 443;

        ssl on;
        ssl_session_timeout 5m;
        ssl_protocols SSLv2 SSLv3 TLSv1;
        #make sure you already have this certificate pair!
 ssl_certificate /var/certs/server.crt;
        ssl_certificate_key /var/certs/server.key;
        ssl_session_cache shared:SSL:10m;

 # www-root, we're serving static files from here, accessible via https://localhost/
        location / {
            root  /var/www;
            index index.html index.htm;
        }

 # Our endpoint for tomcat reverse-proxy, assuming your endpoint java-servlet knows
 # how to handle http://localhost/gadgets  requests
        location /gadgets {
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
     proxy_set_header X-Forwarded-Proto https;
            proxy_redirect off;
            proxy_connect_timeout      240;
            proxy_send_timeout         240;
            proxy_read_timeout         240;
            # note, there is not SSL here! plain HTTP is used
    proxy_pass http://tomcat_server;
        }
     }
}

Tomcat config

And here the magic begins, the main point to not miss here is
Tomcat needs to be explicitly told that it’s being proxied through 443(SSL) port!
Here is a sample Tomcat config which is usually found at
{$CATALINA_HOME}/conf/server.xml


<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->

<!--  <GlobalNamingResources>-->
    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
<!--
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources> -->

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->

    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443"
        proxyName="localhost"
               proxyPort="443"
                />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
  <!--  <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />-->

    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->        

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
<!--      <Realm className="org.apache.catalina.realm.LockOutRealm"> -->
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
<!--        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"    resourceName="UserDatabase"/>-->
<!--      </Realm>-->

      <Host name="localhost"  appBase="webapps"   unpackWARs="true" autoDeploy="true">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->

        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>

      </Host>
    </Engine>
  </Service>
</Server>



As it turned out proxyPort property was the key to proxying Tomcat via Nginx.


REFERENCES
http://webapp.org.ua/sysadmin/setting-up-nginx-ssl-reverse-proxy-for-tomcat/

Installing OpenVZ on Amazon EC2

— SkyHi @ Tuesday, December 20, 2011
Imagine, that your system is pretty complicated and consists of a number of components, each deployed into separate machine.  For development & testing needs it’s always too costly to keep up & running all these machines.  It’s not that as easy to make modification into your system structure, i.e. adding new machines with different roles, etc.
One solution is a to virtualize all your stuff & isolate environments of each component.  One easy way would be to buy a hardware & setup hardware virtualization such as XEN for instance, but there is more popular approach — using Amazon EC2 cloud services.
In this post I’m going to show you how to setup OpenVZ virtualization on Amazon EC2 node (which, actually itself is virtualized XEN node)
We’re going to use as a base a CentOS 5.6 Amazon image with pv-grub enabled (this is required to be able to boot into custom kernel)
Ok, from the AWS console start CentOS 5.6/x64  (centos-5.6-64bit-ebs-pvgrub / ami-a14f1ce4), obtain public DNS name & make sure that default ssh 22 port is enabled:

ssh -i ~/aws_ssh.key root@ec2-50-18-60-65.us-west-1.compute.amazonaws.com

Install OpenVZ & some dependencies


yum -y install gcc.x86_64 gcc-c++.x86_64 java-1.6.0-openjdk iptables openssl-devel zlib-devel pkgconfig glib2-devel

#Open VZ, Install XEN-compatible kernel!
wget -O /etc/yum.repos.d/openvz.repo http://download.openvz.org/openvz.repo
rpm --import http://download.openvz.org/RPM-GPG-Key-OpenVZ
yum --enablerepo=openvz-kernel-rhel5 -y install ovzkernel-xen.x86_64 ovzkernel-xen-devel.x86_64 vzctl.x86_64 vzquota.x86_64

Override some kernel parameters


echo "net.ipv4.ip_forward = 1
net.ipv4.conf.default.proxy_arp = 0
net.ipv4.conf.all.rp_filter = 1
kernel.sysrq = 1
net.ipv4.conf.default.send_redirects = 1
net.ipv4.conf.all.send_redirects = 0
net.ipv4.icmp_echo_ignore_broadcasts=1
net.ipv4.conf.default.forwarding=1
net.ipv4.conf.default.accept_source_route = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296" > /etc/sysctl.conf
# reload from disk
sysctl -p

#Substitute default kernel by OpenVZ
sed -i 's/kernel/ovzkernel/' /etc/sysconfig/kernel

Install ntpd

This will help to sync time between all virtual machines.
yum install -y ntp.x86_64
/usr/sbin/ntpdate 0.rhel.pool.ntp.org europe.pool.ntp.org
# start on next boot
chkconfig ntpd on

Enable rpmforge repo

Chances are pretty high that you’ll want something from this repo (latest git for example), so you’d better install it now.
rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt
wget -O /tmp/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
rpm -Uvh /tmp/rpmforge-release-0.5.2-2.el5.rf.x86_64.rpm
yum -y install --enablerepo=rpmforge git.x86_64

Setup firewall

#Setup firewall
echo "*filter" > /etc/sysconfig/iptables
echo "COMMIT" >> /etc/sysconfig/iptables

Install OpenVZ kernel to boot by default

For some reason, yum installed does not adds OpenVZ kernel into grub bootlist, therefore we’re doing it manually:
#!/bin/bash

#detect newly installed OpenVZ kernel
VMLINUZ_XEN=`ls /boot/ | grep -i "^vmlinuz" | grep -i "stab"`
INITRD_XEN=`ls /boot/ | grep -i "^initrd" | grep -i "stab"`

if [ $VMLINUZ_XEN ]; then
echo "
title CentOS-openvz-xen
  root (hd0)
  kernel /boot/$VMLINUZ_XEN root=/dev/sda1
  initrd /boot/$INITRD_XEN" >> /boot/grub/menu.lst

#Make sure we'll boot into newly installed XEN kernel, which have INDEX=1
sed -i 's/default=0/default=1/' /boot/grub/menu.lst
fi

Check your /boot/grub/menu.lst, it should look like following:
default=1
title centos5.6
  root (hd0)
  kernel /boot/vmlinuz-2.6.18-238.5.1.el5xen root=/dev/sda1
  initrd /boot/initrd-2.6.18-238.5.1.el5xen.img

title CentOS-openvz-xen
  root (hd0)
  kernel /boot/vmlinuz-2.6.18-274.3.1.el5.028stab094.3xen root=/dev/sda1
  initrd /boot/initrd-2.6.18-274.3.1.el5.028stab094.3xen.img

Reboot and then login again to check that you’re on OpenVZ kernel:

ssh -i ~/aws_ssh.key root@ec2-204-236-152-176.us-west-1.compute.amazonaws.com
Last login: Tue Nov 29 05:34:50 2011 from 94.45.135.130
[root@ip-10-176-46-67 ~]# uname -a
Linux ip-10-176-46-67 2.6.18-274.7.1.el5.028stab095.1xen #1 SMP Mon Oct 24 21:00:35 MSD 2011 x86_64 x86_64 x86_64 GNU/Linux

Download & install OpenVZ CentOS5 template:

wget http://download.openvz.org/template/precreated/centos-5-x86_64.tar.gz

#Symlink OpenVZ CentOS template
[ -d /vz/template/cache ] || mkdir -p /vz/template/cache
ln -s /root/centos-5-x86_64.tar.gz /vz/template/cache

Create your first OpenVZ container(VM)

vzctl create 101 --ostemplate centos-5-x86_64 > /dev/null
vzctl set 101 --ipadd 10.0.102.101 --save > /dev/null
vzctl set 101 --nameserver 8.8.8.8 --save > /dev/null
vzctl set 101 --name "APP1" --save > /dev/null
vzctl set 101 --onboot yes --save > /dev/null
Try to login into APP1 shell:
vzctl enter 101
At this point, if you was able to create APP1 container, you can setup other components of your system — Database, Cache server, whatever you want.







REFERENCES
http://webapp.org.ua/sysadmin/installing-openvz-on-amazon-ec2/

Monday, December 19, 2011

php echo a href

— SkyHi @ Monday, December 19, 2011
As Russell alluded to, there is no need ot open <?php again and echo again. That will only break stuff...you are already echoing.
Drogyn's suggestion would work too, but it's not quite as clean.

However, Russell's example might not work for you because, when your variable is an element of an array, you need to concatinate it like this:

<?php
echo "User";

...note that the variable is inside of ". and ."

Or you can put the variable in {} like:

echo "User";

But the way Russel showed you would work if you were using a simple variable like:

echo "User";

OR

<?php

echo "Read more...";

OR

<a href="template.php?aid=<?php echo $aid; ?>">Read more...</a>


REFERENCES
http://www.webmasterworld.com/forum88/11539.htm

http://www.daniweb.com/web-development/php/threads/105613