Monday, 21 January 2013

Nginx error: 502 Bad Gateway. ZF2, APC and segmentation fault.

I tried Zend Framework 2 for my last project. When everything was done with development I moved project to production server but every time I tried to open project url in bowser Nginx returned an error:

502 bad gateway

Server is running under Debian, also I have installed Nginx(1.2.6) + PHP(5.3.20) and PHP-FPM.

Increasing buffer size and read timeout value in Nginx config had no results, still 502 error. I've looked into Nginx logs and found next entries:

… recv() failed (104: Connection reset by peer) while reading response header from upstream ...

So, it seems that problem is not in Nginx config. Something is wrong with backend. PHP-FPM log contains plenty of entries like next:

php5-fpm.log:
WARNING: [pool www] child 7050 exited on signal 11 (SIGSEGV) after 14.101753 seconds from start

Well, something is causing segmentation fault. I'm hosting a lot of projects on this server and everything was fine, problem appeared only for the last project that was developed using ZF2.

Googling a little bit, I found that some of PHP extensions can cause segmentation fault. One by one I started disabling PHP-extensions. After I disabled APC extension problem disappeared and everything started working fine. So, disabling APC extension helped to solve the problem and seems that ZF2 has some problems with APC, or APC has some problems with ZF2 :)

Will try to make some research what exactly was the reason of this problem and post here if I'll find something interesting.

Sunday, 13 January 2013

ZF2: Get db adapter without service locator usage

The problem is: I need to get the instance of TableGateway directly, not via service locator. TableGateway object requires configured dbAdapter object passed to gateway constructor.

Next solution can help with this problem:

1. Use GlobalAdaperFeature as static storage for dbAdapter:
use Zend\Db\TableGateway\Feature;


$feature = new Feature\GlobalAdapterFeature();

2. Add bootstrap method to module config:
public function onBootstrap($e)
{
    // set static adapter for all module table gateways

    $serviceManager = $e->getApplication()->getServiceManager();

    $dbAdapter = $serviceManager->get('Zend\Db\Adapter\Adapter');

    Feature\GlobalAdapterFeature::setStaticAdapter($dbAdapter);
}

3. Now it is possible to get access to already loaded dbAdapter object in TableGateway constructor:
public function __construct()
{
    $this->featureSet = new Feature\FeatureSet();

    $this->featureSet->addFeature(new Feature\GlobalAdapterFeature());

    $this->initialize();
}

So we have dbAdapter injected into gateway constructor. Ofcourse, it's not best practice, but this allows to add some flexibility to your application, and anyway object dbAdapter was instantiated via service locator, but only once for all tableGateways on the stage of module bootstraping.

Wednesday, 2 January 2013

Zend Framework 2: Disable layout rendering

In ZF1.x we have method for disabling layout rendering that looks like:

$this->_helper->layout()->disableLayout(); 

Of course in ZF2 this method doesn't work but there are some other ways how it is possible to do:

1. Set viewModel as standalone model in controller action:

public function someAction() {
    $viewModel = new ViewModel(array(
        'foo' => 'bar'
    ));

    $viewModel->setTerminal(true);

    return $viewModel;
}

2. Create empty layout and use it in controller action:

Create almost empty layout: module/MyModule/view/layout/empty.phtml with only content:
<?php echo $this->content; ?>

Then use this layout in controller action:
$this->layout('layout/empty');

3. Use response object for output content:

$response = $this->getResponse();
$response->setContent("Some content"); 
return $response;

That's all. May be there are some other ways to do this. As for me I prefer the first way, it looks simple and clean.

Thursday, 9 February 2012

Mount Amazon S3 storage as local filesystem on Ubuntu server

Amazon S3 is a high reliability online storage. We have recently started using Amazon S3 in our company as a backup storage for our projects and as a storage for static sites content. Next step-by-step tutorial describes how to mount S3 bucket as a local filesystem using FUSE-based file system s3fs.

1. Install neccessary packages
$ sudo apt-get update
$ sudo apt-get install build-essential libfuse-dev fuse-utils libcurl4-openssl-dev libxml2-dev mime-support
2. Next step is to download archive with latest version of s3fs
$ wget http://s3fs.googlecode.com/files/s3fs-1.61.tar.gz
$ tar xzvf s3fs-1.61.tar.gz
3. Compile sources
$ cd s3fs-1.61/
$ sudo ./configure
$ sudo make
$ sudo make install
4. Allow other users have access to s3 bucket that will be mounted

Edit file /etc/fuse.conf with any text editor, I used vim for this:
$ sudo vim /etc/fuse.conf
And uncomment the following line in the conf file:
...
#user_allow_other

5. Add pare of you Amazon account key id and account access key to /etc/passwd-s3fs file

Edit file /etc/passwd-s3fs and add here string: AWS_ACCESS_KEY_ID:AWS_SECRET_ACCESS_KEY
Where: AWS_ACCESS_KEY_ID -- your amazon account key id
AWS_SECRET_ACCESS_KEY -- your amazon account access key

6. Set permissions to file
$ sudo chmod 0600 /etc/passwd-s3fs    
7. Mount s3 bucket to local filesystem
$ sudo s3fs your_backet_name -o use_cache=/tmp -o allow_other /mnt/s3storage
That's all and now S3 bucket can be used as local filesystem.

Monday, 26 September 2011

Facebook Javascript SDK: Security error "Permission denied" in IE while login

Facebook platform is really not friendly with IEs browsers and I'm sure that a lot of developers have many difficulties in IE while working with Facebook. Recently I've faced a troubles in IE7 and IE8 while calling method FB.login(); Authentication popup appears but after that security error popup is shown with text like:
Message: Permission denied
Line: 22
Char: 4250
Code: 0
URI: https://connect.facebook.net/en_US/all.js
In other browsers everything works fine. There is a hack that allows to avoid this error in IE. It is necessary to add some piece of code after calling FB.init() on client side:
  FB.init({
    appId:        'xxxxx',
    appSecret:    'xxxxxxxxx',
    status:        true
    cookie:        true
  });
  // this code solves the issue
  FB.UIServer.setLoadedNode = function (a, b) { 
    FB.UIServer._loadedNodes[a.id] = b; 
  };
The trouble is described in Facebook Bugzilla: http://bugs.developers.facebook.net/show_bug.cgi?id=20168 Hope, it will be fixed by Facebook soon.

Tuesday, 28 June 2011

Useful javascript snippets

Friquently used javascript snippets.

Replace substring by another one. To replace all occurrences of a string using javascript, 'g' modifier should be used in pattern:
function str_replace(search, replacement, highstack, option) {
     if(typeof(option) != undefined) {
          highstack = highstack.replace(search, replacement);
     } else {
          highstack = highstack.replace(/ + search + /g, replacement);
     }
     return highstack;
}
Usage:
// replace all occurrences in the string
highstack = str_replace(search, replacement, highstack);

// replace first entry of the string
highstack = str_replace(search, replacement, highstack, 'first');
Check if string is integer:
Object.prototype.isInt = function() {
    return parseInt(this) == Number(this) && this.indexOf('.') == -1;
}
var val = '123';
alert(val.isInt());
Shuffle array:
shuffle = function(o){
    for(var j, x, i = o.length; i; 
         j = parseInt(Math.random() * i),
         x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};
Check if email address is valid:
function isEmailValid(email) {
   var reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   return reg.test(email);
}
Check if date is valid:
// date format dd:mm:yyyy
function isValidDate(sText) {
    var reDate = /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/;
    return reDate.test(sText);
}

Friday, 8 April 2011

Using javascript and CSS styles with Smarty

Placing CSS styles and some javascript code containing braces can cause some troubles when Smarty is used as template engine. This template engine shows the error like "Fatal error: unrecognized tag" in this situation.

There are some methods that allow to avoid Smarty errors like described bellow.

First method: the CSS styles or javascript code with braces are needed to be enclosed in Smarty tag {literal}...{/literal}. Template engine doesn't try to parse the code inside these tags and the code and styles will be shown in the HTML document successfully.

There is another way to avoid the errors. Another method is that if after opening braces white space or the end of the line symbol follows so these code is not needed to be placed inside the tags literal and it will work too.

Example:
<style>
   .some_class {color: red;}
</style>
This code will cause the Smarty error, but next example will work without any troubles:
{literal}
<style>
.some_class {color: red;}
</style>
{/literal}
But I'm not sure that this method works in all versions of Smarty. I checked it using Smarty engine version 3.0.7.