Wednesday, November 19, 2014

Customize outgoing SendGrid emails X-SMTPAPI header by Postfix

SendGrid’s SMTP API allows developers to specify custom handling instructions for e-mail. This is accomplished through a header, X-SMTPAPI, that is inserted into the message.

We can do it easily, for example in PHP:
 $email = new SendGrid\Email();  
 $email->addTo('from@abc.com')->  
     setFrom('to@abc.com')->  
     setSubject('Subject goes here')->  
     setText('Hello World!')->  
     addFilter("subscriptiontrack", "enable", 0)->  
     addFilter("clicktrack", "enable", 0)->  
     addFilter("opentrack", "enable", 0)->  
     addCategory("www")->  
     setHtml('<strong>Hello World!</strong>');  

But for some reasons, Client would like to replay emails to SendGrid by local Postfix and using Drupal built-in mail function without custom code, we can use Postfix smtp_header_checks to add the X-SMTPAPI header for outgoing emails.

Below are steps to do that:

1. Setup Postfix and config it to send emails via SendGrid as here
(it's better to use hashed password file like smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd instead smtp_sasl_password_maps = static:yourSendGridUsername:yourSendGridPassword)

2. Add smtp_header_checks to /etc/postfix/main.cf:
smtp_header_checks = regexp:/etc/postfix/smtp_header_checks

3. Create /etc/postfix/smtp_header_checks file with the content, like:
/^From:/ PREPEND X-SMTPAPI: "category":["www"],"filters":{"subscriptiontrack":{"settings":{"enable":0}},"clicktrack":{"settings":{"enable":0}},"opentrack":{"settings":{"enable":0}}}}

Hint: we can easily get the X-SMTPAPI content by print it out from above PHP code, like:
 $arr = $email->toWebFormat();  
 echo $arr['x-smtpapi'];  

4. Reload Postfix

Friday, November 7, 2014

Move Mail-in-a-box to another server

I was asked to move a Mail-in-a-box to another server last night. It's quite new for me although I've migrated Zimbra server several times. On their web site, there's just a very simple setup guide. So I searched in the forum and found a instruction from Josh. I don't have much experience with Mail-in-a-box so had to find out what are STORAGE_ROOT and STORAGE_USER variables in code. It turned out they are set:
STORAGE_USER=user-data
STORAGE_ROOT=/home/$STORAGE_USER

Then learned how to decrypt files via openssl as instructed and how to restore them via duplicity. Had to look into the backup.py code to see how they are encrypted then how to decrypt..
But then found out I didn't need to decrypt those files when we can use normal files in the /home/user-data/backup/duplicity/ instead of decrypted files from /home/user-data/backup/encrypted/.

To summary, below are steps to move Mail-in-a-box to another server:
1. Setup a new Ubuntu 14.04 x64 and setup Mail-in-a-box as the setup guide.
Copy the /etc/postfix/main.cf from the old server over the new server.
2. Stop the service mailinabox on the old server : sudo service mailinabox stop
3. Do backup manually: sudo /home/my_account/mailinabox/management/backup.py
(this is usually incremental backup since mailinabox is scheduled backup daily)
4. Then stop mailinabox again (because it's started by the backup tool) to make sure no new mails come in.
5. rsync entire /home/user-data/backup/duplicity/ to the new server in a folder.
rsync -avr -e ssh /home/user-data/backup/ my_account@new_server:backup/
6. Do restore on the new server:
- Stop the mailinabox service: sudo service mailinabox stop
- In case we restore from encrypted files, we decrypt them with commands:
mkdir  /home/my_account/backup/decrypted && cd /home/my_account/backup/encrypted
for FILE in *.enc; do  openssl enc -d -aes-256-cbc -a -in $FILE -out ../decrypted/${FILE%.*} -pass file:../secret_key.txt; done- Restore by duplicity:
sudo duplicity --no-encryption restore file:///home/my_account/backup/duplicity /home/user-data
or
sudo duplicity --no-encryption restore file:///home/my_account/backup/decrypted /home/user-data
- Re-configure/update: cd /home/my_account/mailinabox && sudo setup/start.sh

In case we don't switch immediately, we can start the service mailinabox on the old server again and just before transition, do from step #2 to the rest. It will be faster because we will just sync new incremental backup.

Note that Josh said on the other thread that we can sync /home/user-data directly but I didn't test that.

Thursday, October 16, 2014

Phusion Passenger and missing passenger_native_support.so issue

When upgrade an Rails application from Ruby 1.9.3 to 2.0.0 by using rvm, it throws out error as:

Raw process output:

 --> Compiling passenger_native_support.so for the current Ruby interpreter...
     (set PASSENGER_COMPILE_NATIVE_SUPPORT_BINARY=0 to disable)
 --> Downloading precompiled passenger_native_support.so for the current Ruby interpreter...
     (set PASSENGER_DOWNLOAD_NATIVE_SUPPORT_BINARY=0 to disable)
     Could not download https://oss-binaries.phusionpassenger.com/binaries/passenger/by_release/4.0.48/rubyext-ruby-2.0.0-x86_64-linux.tar.gz: Resolving timed out after 4516 milliseconds
     Trying next mirror...
     Could not download https://s3.amazonaws.com/phusion-passenger/binaries/passenger/by_release/4.0.48/rubyext-ruby-2.0.0-x86_64-linux.tar.gz: Resolving timed out after 4516 milliseconds
 --> Continuing without passenger_native_support.so.
/usr/local/rvm/gems/ruby-2.0.0-p451/gems/json-1.8.1/lib/json/common.rb:67: [BUG] Segmentation fault
ruby 2.0.0p451 (2014-02-24 revision 45167) [x86_64-linux]

It turned out the passenger_native_support.so was missed in rvm /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/2.0.0/x86_64-linux/ folder.

So searched and found it in /usr/lib/ruby/2.0.0/x86_64-linux-gnu/ then copied it to /usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/2.0.0/x86_64-linux/

Saturday, October 11, 2014

Drupal 7.3.1 crashes with eAccelerator 0.9.6.1

When deploy a site which was built on Drupal 7.3.1 on CentOS 6.5, it crashed with an error:

"Fatal error: Cannot create references to/from string offsets nor overloaded objects in /var/www/drupal/includes/errors.inc on line 184

That's interesting.  So I've commented out that line ($test_info = &$GLOBALS['drupal_test_info'];) and the app continues working but the come with some other strange behaviors like the URLS are pointing with querystring parameters such as http://drupal-site.com/?q=careers instead clean URL like http://drupal-site.com/careers
or
Fatal error: Cannot use object of type ctools_context as array in /var/www/drupal/sites/all/modules/contrib/panels_everywhere/plugins/tasks/site_template.inc on line 103...

Then I've tried to setup a new Drupal 7.3.1 site from scratch and it worked pretty well. It looks like some extra modules like contrib caused the problem.

Finally I noticed there were bunch of errors "child pid xyz exit signal Segmentation fault (11)" in the /var/log/httpd/error_log so I found out why and tried to disable eAccelerator (the latest 0.9.6.1 - which is required by the Dev team) and the app works again.

Then I enabled it and the app was still working... until sometimes later it crashed again - looks like the cached was expired?

So finally I've asked the Dev team to switch to the APC for alternative. 




Sunday, September 21, 2014

Auto syncronize Salesforce data to MySQL or Postgresql with Talend Open Studio

Today I'm writing about using Talend Open Studio to sync Salesforce data to MySQL or Postgresql databases.

First of all, let's download and install Talend Open Studio for Data Integration, make sure you already have Java installed.

Next is unzip and run TOS_DI-macosx-cocoa as I'm using a Mac OS X, or TOS_DI-win-x86_64.exe if you're using Windows.
It's based on Eclipse IDE so you'll see it's pretty easy if you used to work with Eclipse.

Here is the main screen.


Then we will need to create a database connection by expanding the Metadata node -> Db connections -> Right click -> Create connection -> enter a Name (without space) -> click Next button

Then select Db Type (MySQL or Postgresql or whatever in the long list). I'm choosing Postgresql because MySQL limits row size to 65535. So if the table contains too much fields, it will throw out an error: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. You have to change some columns to TEXT or BLOBs

After enter all connection information, click Check button to make sure they are correct. Then Finish.


Next step is creating Salesforce connection. Let's right click the Salesforce node and select Create Salesforce connection. Enter a name then Next.


 Enter the User name and Password.  The Password is combination of Salesforce password and the token. i.e if the Salesforce password is xyz and the token is 1234, then we enter xyz1234 on the Password field. Then Check Login to make sure connection is valid. Then Finish.

Next step is retrieving Salesforce modules by right click on created Salesforce connection and select Retrieve Salesforce modules. Let's check for Account


 Then we will need to create a job to import Salesforce data into the database. Right click on Job Design node, select Create Jobs

Then job design screen is opened and we will expand the Salesforce Account module to drag/drop the Account table into the job design screen as tSalesforceInput component.

Click OK then we have it on the screen

Next step is search for database output component on the Palette box, then drag/drop tPostgresqlOutput component into the screen


 Then we might need to rename it as "account" and click the inside icon to set its properties
Select Repository on Property Type , then select created Postgresql connection - DB (POSTGRESQL):PosgressqlSalesforce 
All connection information automatically filled out. Except Table - enter "account" here, then select Create table if does not exist for Action for table, and Insert for Action for data

 Next step is linking between Salesforce input and Postgresql output by right click on Salesforce input's icon and select Row -> Main, then wire the connection to the Postgresql output's icon
and Run the job.

Then let's check the Postgresql to see the new account table is created with data from Salesforce
Then double the Postgrsql account output to edit its properties, select Insert or Update for Action on data and click Edit schema button, then select the checkbox Key on the Id column of account Output

 Then we might run the job again.
We might repeat those steps to sync other tables.

Now if we want to execute the job automatically by schedule / cron, we will need to build the job.
Right click on the job node, select Build Job


Then unzip the file, explore to the sub folder sync, we will see sync_run.sh or sync_run.bat (or jobName_run.bat/.sh) that will be called in schedule / cron.

So we are done!

FYI, here is the videocast to show you how to sync from database to Salesforce.



Saturday, September 13, 2014

Automate Rackspace Cloud Block Storage volume creation with Ansible

Today I want to automate Rackspace Cloud Block Storage volume creation with Ansible for Rackspace instances.

To do that, we will need rax modules that requires to install pyrax.

After pyrax is installed, then I tested to create a block storage volume with the module rax_cbs
and that thrown out an error:
msg: pyrax is required for this module

That's interesting. I checked the python path and tested pyrax:

$ which python
/usr/local/bin/python

 $ python
Python 2.7.7 (default, Jun 18 2014, 16:33:32)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.9)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyrax
>>>

Checked the ansible python path
$ head /usr/local/bin/ansible
#!/usr/local/opt/python/bin/python2.7

Found both python and /usr/local/opt/python/bin/python2.7 are symbolic links of /usr/local/Cellar/python/2.7.7_2/Frameworks/Python.framework/Versions/2.7/bin/python2.7.

Google around but can't find the answer.

Finally verified the module rax_cbs:
$ head /usr/share/ansible/cloud/rax_cbs
#!/usr/bin/python

Then:
$ /usr/bin/python
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyrax
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pyrax

That's why it didn't work! /usr/bin/python is built-in python on Mac OS X while 2.7.7 was installed via Homebrew to different path.

So let's set the ansible_python_interpreter for localhost that is used by rax modules in the ansible/hosts file:
[local]
localhost ansible_connection=local ansible_python_interpreter=/usr/local/opt/python/bin/python2.7

But then got another error:
msg: No CloudBlockStorageVolume matching

Found the answer to patch the /usr/share/ansible/cloud/rax_cbs

Voila!

I also want to attach the volume to the instance, then fdisk/create partition/format/mount it automatically.., so we have to check if the device already exist or not, if not then create/attach a Cloud Block Storage volume and fdisk/create partition/format..

Below is the playbook.

Note that this playbook will be executed for remote Rackspace instances so we don't need to set hosts/connection for Rackspace build/attach block storage volume tasks as the example when the local_action module already delegates to the localhost defined in ansible/hosts automatically.

 # file:Rackspace_disk/tasks/main.yml  
 - name: Check if device /dev/xvd_ present  
  shell: fdisk -l | grep 'Disk {{device}}' | wc -l  
  changed_when: False  
  register: device_present  
 - name: Build a Block Storage Volume  
  local_action:  
   module: rax_cbs  
   credentials: "{{credentials}}"  
   name: "{{volum_name}}"  
   volume_type: "{{volum_type}}"  
   size: "{{volum_size}}"  
   region: "{{region}}"   
   wait: yes  
   state: present  
   meta:  
    app: "{{volum_name}}"  
  sudo: no  
  when: device_present.stdout is defined and device_present.stdout|int == 0  
 - name: Attach a Block Storage Volume  
  local_action:  
   module: rax_cbs_attachments  
   credentials: "{{credentials}}"  
   volume: "{{volum_name}}"  
   server: "{{server}}"  
   device: "{{device}}" #/dev/xvd_  
   region: "{{region}}"  
   wait: yes  
   state: present  
  sudo: no  
  when: device_present.stdout is defined and device_present.stdout|int == 0  
 - name: Check if partition /dev/xvd_1 present  
  shell: fdisk -l | grep {{device}}1 | wc -l  
  changed_when: False  
  register: partition_present  
 - name: Fdisk / create partition / format  
  shell: "echo -e 'n\np\n1\n\n\nw\n' | fdisk {{device}} && mkfs -t {{fstype}} {{device}}1 && tune2fs -m 0 {{device}}1 "  
  when: partition_present.stdout is defined and partition_present.stdout|int == 0  
 - file: path={{mount_dir}} state=directory  
 - name: Mount device  
  mount: name={{mount_dir}} src={{device}}1 fstype={{fstype}} opts='defaults,noatime,nofail' state=mounted  




 



Saturday, August 23, 2014

Resize ext4 partition on CentOS 5

When trying to resize an ext4 partition on CentOS 5, I got an error:

$ resize2fs /dev/sdf
resize2fs 1.39 (29-May-2006)
resize2fs: Filesystem has unsupported feature(s) while trying to open /dev/sdf
Couldn't find valid filesystem superblock.

Google around and found out we must use resize4fs instead

$ resize4fs /dev/sdf
resize4fs 1.41.12 (17-May-2010)
Filesystem at /dev/sdf is mounted on /opt; on-line resizing required
old desc_blocks = 5, new_desc_blocks = 7
Performing an on-line resize of /dev/sdf to 26214400 (4k) blocks.

Similarly, we will use fsck.ext4, tune4fs for ext4