Friday, December 30, 2011

CronTrigger Tutorial

— SkyHi @ Friday, December 30, 2011
Original question was tagged cron so this first section applies to that. See below for an updated answer for the Quartz CronTrigger tool.

Most crontabs don't let you specify the year so you'll probably have to put that in the script itself (or a wrapper around the script/program).
You can do this with something like:
if [[ $(date +%Y) != 2010 ]] ; then
    exit
fi
The option you're looking for to run at 6am on September 6 every year is
0 6 6 9 * your_command_goes_here| | | | |
| | | | +- any day of the week.
| | | +--- 9th month (September).
| | +----- 6th day of the month.
| +------- 6th hour of the day.
+--------- Top of the hour (minutes = 0).


For the Quartz CronTrigger format, you'd be looking at something like:
0 0 6 6 9 ? 2010
| | | | | |   |
| | | | | |   +- 2010 only.
| | | | | +----- any day of the week.
| | | | +------- 9th month (September).
| | | +--------- 6th day of the month.
| | +----------- 6th hour of the day.
| +------------- Top of the hour (minutes = 0).
+--------------- Top of the minute (seconds = 0).
(details garnered from here).




REFERENCES
http://stackoverflow.com/questions/3665441/cron-expression-for-particular-date
http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger

Thursday, December 29, 2011

Linux Redirection Cheat Sheet

— SkyHi @ Thursday, December 29, 2011
Normal Redirect:
 
command > filename        Redirect command output to a file
command >> filename       APPEND into a file
command < filename        Type a text file and pass the text to command
commandA  |  commandB     Pipe the output from commandA into commandB
commandA &  commandB      Run commandA and then run commandB
commandA && commandB      Run commandA, if it succeeds then run commandB
commandA || commandB      Run commandA, if it fails then run commandB
 
Numeric handles:
 
STDIN  = 0  Keyboard input
STDOUT = 1  Text output
STDERR = 2  Error text output
UNDEFINED = 3-9
 
command 2> filename       Redirect any error message into a file
command 2>> filename      Append any error message into a file
command > file 2>&1       Redirect errors and output to one file
command > file 2<&1       Redirect output and errors to one file
command > fileA 2> fileB  Redirect output and errors to separate files
command 2>&1 >filename    This will fail!
 
Redirect to /dev/null (hide errors):
 
command 2> /dev/null            Redirect error messages to /dev/null
command >/dev/null 2>&1         Redirect error and output to /dev/null
command >filename 2> /dev/null  Redirect output to file but suppress error


REFERENCES
http://www.adminsehow.com/2011/06/linux-redirection-cheat-sheet/
http://ss64.com/

IPTables packet traverse map

— SkyHi @ Thursday, December 29, 2011
1.


2.


2.

REFERENCES
http://www.adminsehow.com/2011/09/iptables-packet-traverse-map/

Wednesday, December 28, 2011

A simple way to limit file downloads to only logged in users in WordPress

— SkyHi @ Wednesday, December 28, 2011
So, you’ve used WordPress to build your client’s site and to provide downloads for the site’s users. You’re hiding the links to download content based on the user’s logged in status. Great. But what happens when the logged in user copies the download URL and sends it to his friend? Well, unless you’re filtering the download links and checking them with WordPress first his friend gets to download the file.
I’m not a big fan of checking every file download with WordPress as it can take a lot of overhead if you’re running a busy site. So here is a pretty straight forward way to limit downloads from a WordPress site with a minimal amount of code. In this example I’ll illustrate how to prevent non-logged in users from downloading audio files in mp3 and m4a format.

Basic Blocking

First, lets use some ModRewrite rules to get Apache to show users a 403 forbidden page when trying to access the files. This isn’t pretty, it simply gets Apache to dump the user in to a default 403 page and the user is told that their access is forbidden. The .htaccess changes:

# These next two lines will already exist in your .htaccess file
 RewriteEngine On
 RewriteBase /
 # Add these lines right after the preceding two
 RewriteCond %{REQUEST_FILENAME} ^.*(mp3|m4a)$
 RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
 RewriteRule . - [R=403,L]








On the first line of this code you’ll see (mp3|m4a). This is the part that looks at the ending of the file name and determines which files it will act upon. replace the items inside the parentheses with the file types that you want to protect, each one separated by the pipe character. So, for example, if you wanted to protect PDF and RTF files you’d change it to: RewriteCond %{REQUEST_FILENAME} ^.*(pdf|doc)$
That is really all we need but its not very nice to dump the user like that and not inform them of why they were forbidden. They may assume that the site is broken. So lets do this the right way and get the users redirected to a page that will inform them of why they were denied access to the content.

Redirecting the Access Denied

For this we’ll need a page template. You can create anything you’d like, but the basics of it are:


<?php


/**
  * Template Name: 403
  *
  * The template for displaying 403 pages (Forbidden/Not Allowed).
  */
  get_header(); ?>
   <div id="container">
   <div id="content" role="main">
   <div id="post-0" class="post error403 not-allowed">
   <h1 class="entry-title"> <?php _e( "Action Not Allowed", "twentyten" ); ?> </h1>
   <div class="entry-content">
   <p> <?php _e("Apologies, but you are not allowed to download files while not logged in.", "twentyten"; ); ?> </p>
   </div> <!-- .entry-content -->
   </div> <!-- #post-0 -->
   </div> <!-- #content -->
   </div> <!-- #container -->

 <?php get_footer(); ?>




Your template will obviously look a bit different. I did this one as an extension to the new Twenty Ten theme in WordPress 3.0 and based it off of the provided 404 template.
Save the file to your theme’s directory. It doesn’t matter what you name it. WordPress will actually pick up on the Template Name: 403 portion as the template ID.
Next we need to create a page in the WordPress admin for our notification page. Create a new page, name it whatever you want. For my purposes I titled the page “Not Allowed” so my slug ended up as “not-allowed”. You can edit these to be any values you want if the page title created a slug that you don’t like. You’ll need that slug here in the next step. Next select the 403 page template from page templates select input in the Attributes meta box (typically on the right side of the page, underneath the Publish button. Publish the page.
Now let’s alter that .htacess directive to redirect to this page instead of showing that unfriendly Apache notice. The modified directives are:


RewriteCond %{REQUEST_FILENAME} ^.*(mp3|m4a)$
 RewriteCond %{HTTP_COOKIE} !^.*wordpress_logged_in.*$ [NC]
 RewriteRule . /not-allowed [R,L]





The relevant change happened on the third line where the dash was replaced by the relative url to my 403 page. In my case that is /not-allowed. Yours will differ depending upon how named your page. Don’t forget the leading slash when adding your slug so that it’s a valid relative path. (This can be an absolute path as well, ie: one that contains the full http://domain.com/blah-blah but there’s no need to do that here unless you’ve got valid reason to do so, like if you want to redirect the user to a different domain).
Now, whenever someone who is not logged in tries to download a file type that you’ve specified they’ll be redirected to your 403 page. What you tell them there is up to you.

But…

…now, if you’re theme lists out pages anywhere, you’ve got this 403 page sticking its nose in where it doesn’t belong. Not very pretty, now, is it? This is pretty easily remedied. Head on in to the WP Admin and to the page edit screen for the 403 page. Take note of its page ID in the url. It will be the number after the word “post=” in the url. For example, if your URL looks like http://wp30.local/wp-admin/post.php?post=8&action=edit the post id is 8.
We now need to make an addition to your theme’s functions.php file. This file is located in your theme directory. Open this file and add in the following code:


<?php


// Do error page excludes
 function exclude_error_pages($excludes) {
  array_push($excludes, 8);
  return $excludes;
 }
 // we don't want any funny stuff in the admin, only add to front end
 if (!is_admin()) {
  add_filter('wp_list_pages_excludes', 'exclude_error_pages');
 }
 ?>




On the line that says array_push($excludes, 8); replace the 8 with the id of the page you just created. This will keep the function wp_list_pages() from outputting the 403 page in any of its lists.
Note: if you’ve got other places in your theme that are pulling page lists through different means you’ll want to modify or filter those results as well. Depending upon the methods used to make the lists you can probably exclude the page as a parameter of the call for pages instead of using a filter. Your mileage will vary, but it is certainly doable.

Ta da!

And there you have it. Simple and straight forward. No real frills, though. As it sits now the user is redirected to a page that just tells then simply that they need to be a logged in user. That’s not very informative all by itself. There are a hundred ways to modify this to make it more convenient on the user.
Hopefully this gives you some ideas on what can be done to help legitimate users get to your content while keeping the rif-raff from poaching it.


REFERENCES
http://top-frog.com/2010/07/01/a-simple-way-to-limit-file-downloads-to-only-logged-in-users-in-wordpress/

If not found, redirect to a different URL to check

— SkyHi @ Wednesday, December 28, 2011

# Rewrite URLs of the form 'x' to the form 'index.php?q=x'.

##.htaccess
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ([^/\.]+)$ http://www.rose1.com/check_url.php?string=$1 [L]


#check_url.php
session_start();
require_once ("functions.php");
$db = new db_mysql();
$file_db = $db->getValue ("SELECT pl_name FROM promo_link");
$file_db2 = $db->getValue ("SELECT sl_name FROM specials_links");


$str = $_SERVER['REQUEST_URI'];
$str_arr = explode ("/", $str);
$file_name = $str_arr[count ($str_arr) - 1];

if ($file_name == $file_db) {
   header ("Location: promotions/booking.php");
   exit;
}


RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

... means that if the file with the specified name in the browser doesn't exist, or the directory in the browser doesn't exist then procede to the rewrite rule below

REFERENCES
http://www.sitepoint.com/forums/showthread.php?259764-What-does-this-mean-RewriteCond-REQUEST_FILENAME-!-f-d
http://www.datakoncepts.com/seo

Thursday, December 22, 2011

Drupal 7: HipHop for PHP vs APC – benchmark

— SkyHi @ Thursday, December 22, 2011
Drupal is one of two most popular content management systems (CMS) written in PHP . It is used as a back-end system for at least 1.5% of all websites worldwide. It is also one with the the slowest systems of this kind on the Internet
There have been many suggestions on improving Drupal performance, some of them recommend the use of APC module, data caching, or even compilation of the entire system through HipHop for PHP. While the first two solutions have been successfully implemented, no one was able to perform the build process.
After many battles with the compiler and the Drupal code, I present you results of the first successful translation of Drupal 7 to C++ language.

Introduction

All tests were conducted on a modified version of Drupal. These changes were necessary in order to ensure compatibility with HipHop translator.
You can download modified source codes from this link.
The system was installed in the minimal version and then launched in three different ways:
  • as a standard PHP script
  • as a PHP script with APC opcode caching enabled
  • in the form of a compiled program
Due to hardware limitations the MySQL server is located on the same machine as the web server, more advanced tests will be performed in the near future using the multiple servers.

Testing platform

Processor: Intel(R) Core(TM)2 Duo CPU E7600 @ 3.06GHz
Memory: 2.5GB RAM
System: Fedora 12 (64bit)
Kernel: 2.6.32.26-175.fc12.x86_64 #1 SMP
The server was used exclusively for testing purposes – it was running only the services associated with the benchmark.

Test Configuration

Apache version: 2.2.15
MySQL Server Version: 5.1.47
PHP Version: 5.3.3
HipHop for PHP Version: 806ee06
Drupal Version: 7.0
Drupal was compiled with this command:
cd ~drupal
date && ~/hiphop/hiphop-php/src/hphp/hphp  --keep-tempdir=1\
 --log=3\
 --input-list=files.full.list\
 --include-path="." --force=1\
 --cluster-count=240\
 -v "AllDynamic=true"\
 -v "AllVolatile=true"\
 -o /tmp/drupal\
 --parse-on-demand=0\
 --sync-dir=/tmp/sync
And launched with this command:
cd ~drupal
/tmp/drupal/program -m server -p 80\
 -v "Server.SourceRoot=`pwd`"\
 -v "Server.DefaultDocument=index.php"\
 -c $HPHP_HOME/bin/mime.hdf\
 -v "Log.File=/tmp/errors"\
 -v "ErrorHandling.AssertActive=true"\
 -v "ErrorHandling.AssertWarning=true"\
 -v "ErrorHandling.WarningFrequency=10000"\
 -v "ErrorHandling.NoticeFrequency=10000" &

CPU usage

The following test examines the performance of Drupal by simulating the concurrent activity of many visitors on the Drupal home page.
I found that in case of a dual core server four was the optimal number of concurrent users, so I used the ab program as as a benchmark tool and launched it with a following command:
ab -n 300 -c 4 http://achilles.webtutor/
The first result shows the CPU usage of a regular PHP script during the execution of the 300 HTTP requests started by 4 concurrent users:

sy = system CPU usage (gradient color), us = user CPU usage (solid color)
As you can see Drupal is indeed a very demanding system. The test in this case took almost 20 seconds, which gave a dissapointing result of 15 requests per second.
Let’s see what we get after enabling the APC module. Results are as follows:

Drupal performance improved dramatically. The test was completed in 6 seconds, 3 times faster than with traditional PHP! Due to the size of Drupal code, however, this result is not shocking. While the APC module will not speed up the script itself, its opcode cache eliminates the delay caused by having to parse PHP code on every HTTP request.
Interestingly, Drupal is not able to use the full computing power of the test server. The official cause is unknown, however it may caused by some kind of internal locking in the APC module.
Since we know how much the opcode cache improves performance by omitting the PHP parser, its time to test how much we can accelerate the PHP code itself. We check this by translating Drupal source code to C++ and compiling the application:
Compiled Drupal application is five times faster than a regular script, and almost two times faster than a script launched from the opcode cache!
Let’s compare the results. The first is the detailed comparison of CPU usage:
And the overall CPU usage:
Here are the results taken directly from the ab tool:
Environment      Execution 
   Type        time [300 req]
-----------------------------
Regular PHP      19.873 sec
PHP + APC         6.396 sec
HipHop for PHP    3.896 sec

Concurrency benchmark

In this scenario I measured a number of requests performed per second. The summary results are as follows:
Type of environmentRequests per second [#/sec]Time per request [ms]Req/sec ratio [%]
Regular PHP15.1066.242100%
PHP + APC (opcode cache)46.9021.321310%
HipHop for PHP77.0112.985510%

Other concurrency levels

As a curiosity I decided to investigate how the Drupal’s performance can be affected by a variable number of concurrent users. In order to do so I tested the system with seven different workloads simulating 1, 2, 4, 8, 16, 32 and 64 concurrent users.
Here are the results:
Tabular version:
Users    PHP     APC   HipHop 
-----------------------------
  1      8.68   28.11   40.23
  2     13.34   38.25   56.12
  4     15.28   46.82   74.12
  8     14.76   49.96   72.12
  16    14.04   49.09   74.12
  32    12.35   45.00   77.67
  64     5.22   39.17   73.02
Please note: this test is heavily CPU bound and should be executed on a multicore servers instead.
As you can see, in case of APC and HipHop for PHP translator Drupal scales quite well up to the 8 simultaneous users on a dual CPU system. Unfortunately the same cannot be said about regular PHP interpreter, which is much slower in every tested scenario.

Different optimization levels in GCC compiler

Without any optimization option, the compiler’s goal is to reduce the cost of compilation and to make debugging produce the expected results.
Turning on optimization flags makes the compiler attempt to improve the performance and/or code size at the expense of compilation time and possibly the ability to debug the program.
Let’s see the results of different optimization levels switched on during the Drupal compilation:
optimization    req/sec
    level
--------------------------
   default         74.12
     -o2           87.11
     -o3           90.04
The difference of 12 req/sec between a default and -o2 optimization is quite big and almost equals to the 15 req/sec achieved by an interpreted PHP script!
What’s more in case of -o3 optimization Drupal is up to 6 times faster than in a pure PHP environment.

Summary

As I mentioned on the outset Drupal is not the fastest system on the Internet. However, after several changes in the code to add compatibility with HipHop for PHP, it becomes a very effective tool in the hands of every webmaster.

Other articles about HipHop for PHP