среда, 17 апреля 2013 г.

autoexpect

Expect - tool for automatically run interactive scripts.
Autoexpect - tool for generate expect script.
Generated code is dirty, but working, It will save many hours.
Example:

autoexpect ssh root@192.168.122.240


work with script, after logout you receive script.exp which contain

 set timeout -1
spawn ssh root@192.168.122.240
match_max 100000
expect -exact "Warning: Permanently added '192.168.122.240' (RSA) to the list of known hosts.\r\r
root@192.168.122.240's password: "
send -- "testpass\r"
expect -exact "\r
Permission denied, please try again.\r\r
root@192.168.122.240's password: "
send -- "vagrant\r"
expect -exact "\r
Last login: Mon Mar 25 21:38:15 2013\r\r
^[\]0;root@centos64:~^G^[\[?1034h\[root@centos64 ~\]# "
send -- "uname -a\r"
expect -exact "uname -a\r
Linux centos64.vagrantup.com 2.6.32-358.el6.x86_64 #1 SMP Fri Feb 22 00:31:26 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux\r
^[\]0;root@centos64:~^G\[root@centos64 ~\]# "
send -- "touch /tmp/123\r"
expect -exact "touch /tmp/123\r
^[\]0;root@centos64:~^G\[root@centos64 ~\]# "
send -- "exit\r"
expect eof

воскресенье, 14 апреля 2013 г.

pre-commit hooks for checking commits

there are examples for ruby code and puppet manifests(chef can validate automatically, but stupid puppet can't):
1. create file ./.git/hooks/pre-commit
2. add code

#!/bin/sh
echo 'working pre commit hook'
git diff --cached --name-only --diff-filter=ACM | while read file; do
  # check only puppet files
  if [ "${file##*.}" == 'pp' ]
  then
    echo "check $file"
    puppet parser validate $file
  fi
done

3. require set exec permissions. DO NOT FORGET !!!! (it is cause for not execution hook)
chmod +x ./.git/hooks/pre-commit
Complete.

Also example for ruby:

#!/bin/sh
echo 'working pre commit hook'
git diff --cached --name-only --diff-filter=ACM | while read file; do
  if [ "${file##*.}" == 'rb' ]
  then
    echo "check rubocop $file"
    rubocop $file
  fi
done

воскресенье, 7 апреля 2013 г.

shmmax error for start postgresql

During start postgresql appear error  
Apr 07 12:38:55 localhost.localdomain pg_ctl[9810]: FATAL: could not create shared memory segment: Invalid argument 
Apr 07 12:38:55 localhost.localdomain pg_ctl[9810]: DETAIL: Failed system call was shmget(key=5432001, size=41279488, 03600). 
Apr 07 12:38:55 localhost.localdomain pg_ctl[9810]: HINT: This error usually means that PostgreSQL's request for a shared memory segment exceeded your ker...nections. 
Apr 07 12:38:55 localhost.localdomain pg_ctl[9810]: If the request size is already small, it's possible that it is less than your kernel's SHMMIN parameter...lled for. 
Apr 07 12:38:55 localhost.localdomain pg_ctl[9810]: The PostgreSQL documentation contains more information about shared memory configuration. 
Apr 07 12:39:00 localhost.localdomain pg_ctl[9810]: pg_ctl: could not start server Apr 07 12:39:00 localhost.localdomain pg_ctl[9810]: Examine the log output.

fix in chef recipes

shmmax='kernel.shmmax=335544320' 
execute "set shmax" do
 command "sysctl -w #{shmmax}" 
end 

file "/etc/sysctl.d/shmmax.conf" do
 content shmmax 
end

среда, 16 мая 2012 г.

Custom vagrant image

1, start virtualbox and install your os
2. install ruby and chef
3, install http://download.virtualbox.org/virtualbox/4.2.6/VBoxGuestAdditions_4.2.6.iso
mount -o loop ./VBoxGuestAdditions_4.2.6.iso /mnt
run /mnt/VBoxLinuxAdditions.run --nox11
4. create user vagrant
5. download key https://github.com/mitchellh/vagrant/tree/master/keys/ and set to /home/vagrant/.ssh/authorized_keys
Also recheck permissions and selinux (chown -R vagrant:vagrant /home/vagrant/.ssh && chmod 700 /home/vagrant/.ssh && chmod 600 /home/vagrant/.ssh/authorized_keys && restorecon -R /home/vagrant/.ssh)
6. configure /etc/sudoers (comment Defaults requiretty and add vagrant as sudo user without password vagrant ALL=(ALL) NOPASSWD: ALL)
7. enable ssh
8. logout and poweroff guest vm
9. run vagrant package --base g2012 package.box
10. run vagrant box add g3 ./package.box
11. set g3 to your Vagrantfile to
config.vm.box = "g3"

среда, 1 февраля 2012 г.

rabbitmq и ha для очереди

Rabbitmq передает сообщения. И сообщения частенько очень важные.
Что б не терять их, при отказе железки, можно использовать rabbitmq cluster.
Но есть один ньюанс - в кластере, по умолчанию, очередь хранится на одной ноде.
Добавляем в опции очереди x-ha-policy => all и теперь копии очереди есть на всех нодах и если одна упадет , сообщения не потеряются.
Клиентская программа должна знать куда переподключаться в случае падения и использовать подтверждение о получении сообщения.

суббота, 28 января 2012 г.

deploy spree to openshift

Instruction how to deploy spreecommerce to openshift
work with ruby 1.8.7 because openshift work with this version.
ruby 1.9. hash syntax will create problem in openshift cloud

1. create application on openshift
rhc-create-app -a spree -t rack-1.1
Создалось приложение в облаке редхата и папочка spree с простым rack приложением.
А нам надо создать rails приложение с гемами spree.
rm -f ./spree/README
rails new ./spree -d postgresql -f
Обратите внимание - используем постгрес(дело вкуса конечно,но все ж знают, что постгрес вкуснее)
2. add database(postgresql)
rhc-ctl-app -a spree -e add-postgresql-8.4
Если понадобится удалить подключенную базу
rhc-ctl-app -a spree -e remove-postgresql-8.4
По завершению мы получим данные для подключения к базе.
Их стоит записать в spree/config/database.yml
и не забудьте добавить поле host и вписать ip из подобной строки Connection URL: postgresql://127.1.13.1:5432
И настроить базу для development режима
development:
  adapter: sqlite3
  database: db/dev.sqlite3

И в Gemfile добавляем гем sqlite3 для группы development
теперь перемещаемся в папку spree
bundle install && bundle exec rails g spree:install
добавляем сприи в Gemfile
echo "gem 'spree', :git => 'git://github.com/spree/spree.git'" >> ./Gemfile
Gemfile.lock должен быть актуальным
bundle install
mkdir public/images && cp public/favicon.ico public/images/favicon.ico
RAILS_ENV=development bundle exec rake assets:precompile

добавить код в .openshift/action_hooks/deploy

pushd ${OPENSHIFT_REPO_DIR} > /dev/null
RAILS_ENV=production bundle exec rake db:migrate -y
RAILS_ENV=production bundle exec rake db:seed -y
popd > /dev/null


и теперь пушим git push
после удачного деплоя очищаем .openshift/action_hooks/deploy

first request will broken - it is problem on timeout parameter in proxy server.
but exist problem with timeout

P.S.
after few updates require use this database.yml


adapter: <%=ENV['OPENSHIFT_DB_TYPE']%>
encoding: utf8
host: <%=ENV['OPENSHIFT_DB_HOST']%>
port: <%=ENV['OPENSHIFT_DB_PORT']%>
socket: <%=ENV['OPENSHIFT_DB_SOCKET']%>
database: <%=ENV['OPENSHIFT_APP_NAME']%>
username: <%=ENV['OPENSHIFT_DB_USERNAME']%>
password: <%=ENV['OPENSHIFT_DB_PASSWORD']%>

воскресенье, 14 августа 2011 г.

Кеширование в мультидоменном веб приложении

добавляем в контроллер

before_filter { |c|
   c.class.page_cache_directory = "#{RAILS_ROOT}/public/#{c.request.host}"
}

в логах сразу видим как пишется

Write fragment views/sub.domain.com/s/test (2.6ms)

и при повторном запросе

Read fragment views/sub.domain.com/s/test (0.9ms)

Итого: с 300мс до 10 мс рендеринг страницы.