Translate

Saturday, October 11, 2014

LAMP Installation

Install Apache

To start off we will install Apache.
1. Open up the Terminal (Applications > Accessories > Terminal).
2. Copy/Paste or type the following line of code into Terminal and then press enter:
sudo apt-get install apache2
3. The Terminal will then ask you for you're password, type it and then press enter.
 

Testing Apache

To make sure everything installed correctly we will now test Apache to ensure it is working properly.
1. Open up any web browser and then enter the following into the web address:
http://localhost/
You should see a folder entitled apache2-default/. Open it and you will see a message saying "It works!" , congrats to you! or something like that!
 

Install PHP

In this part we will install PHP 5.
Step 1. Again open up the Terminal (Applications > Accessories > Terminal).
Step 2. Copy/Paste or type the following line into Terminal and press enter:
sudo apt-get install php5 libapache2-mod-php5
Step 3. In order for PHP to work and be compatible with Apache we must restart Apache. Type the following code in Terminal to do this:
sudo /etc/init.d/apache2 restart
 

Test PHP

To ensure there are no issues with PHP let's give it a quick test run.
Step 1. In the terminal copy/paste or type the following line:
sudo gedit /var/www/testphp.php
This will open up a file called testphp.php.
 
Step 2. Copy/Paste this line into the phptest file:
 
<?php phpinfo(); ?>
Step 3. Save and close the file.
Step 4. Now open you're web browser and type the following into the web address:
http://localhost/testphp.php
 
(It will show you the page that has all information about your php. If you have prior experience of installing php in some other OS, you must have seen this page.)
Congrats you have now installed both Apache and PHP!
 

Install MySQL

To finish this guide up we will install MySQL.
Step 1. Once again open up the amazing Terminal and then copy/paste or type this line:
sudo apt-get install mysql-server
Step 2 (optional). In order for other computers on your network to view the server you have created, you must first edit the "Bind Address". Begin by opening up Terminal to edit the my.cnf file.
gksudo gedit /etc/mysql/my.cnf
Change the line
bind-address = 127.0.0.1
And change the 127.0.0.1 to your IP address.
(In Linux Mint 11, terminal itself asked to the set password, But if it doesn't follow the step 3.)
Step 3. This is where things may start to get tricky. Begin by typing the following into Terminal:
mysql -u root
Following that copy/paste or type this line:
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('yourpassword');
(Make sure to change yourpassword to a password of your choice.)
Step 4. We are now going to install a program called phpMyAdmin which is an easy tool to edit your databases. Copy/paste or type the following line into Terminal:
sudo apt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin
After that is installed our next task is to get PHP to work with MySQL. To do this we will need to open a file entitled php.ini. To open it type the following:
gksudo gedit /etc/php5/apache2/php.ini
Now we are going to have to uncomment the following line by taking out the semicolon (;).
Change this line:
;extension=mysql.so
To look like this:
extension=mysql.so
Now just restart Apache and you are all set! 
sudo /etc/init.d/apache2 restart
 

If you get a 404 error upon visiting http://localhost/phpmyadmin: You will need to configure apache2.conf to work with Phpmyadmin.
sudo gedit /etc/apache2/apache2.conf
Include the following line at the bottom of the file, save and quit.
Include /etc/phpmyadmin/apache.conf

Then just restart Apache
sudo /etc/init.d/apache2 restart

Saturday, September 20, 2014

Can't install MySQL gem

On Ubuntu/Debian and other distributions using aptitude:
 
sudo apt-get install libmysql-ruby libmysqlclient-dev

If the above command doesn't work because
libmysql-ruby
cannot be found, the following should be sufficient:
sudo apt-get install libmysqlclient-dev

On Red Hat/CentOS and other distributions using yum:
sudo yum install mysql-devel

On Mac OS X with Homebrew:
brew install mysql

Friday, September 19, 2014

Making Devise to response in json

Login Code
 
 
class SessionsController < DeviseController
  prepend_before_filter :require_no_authentication, :only => [ :new, :create ]
  prepend_before_filter :allow_params_authentication!, :only => :create
  prepend_before_filter { request.env["devise.skip_timeout"] = true }

  prepend_view_path 'app/views/devise'

  # GET /resource/sign_in
  def new
    self.resource = resource_class.new(sign_in_params)
    clean_up_passwords(resource)
    respond_with(resource, serialize_options(resource))
  end

  # POST /resource/sign_in
  def create
    self.resource = warden.authenticate!(auth_options)
    set_flash_message(:notice, :signed_in) if is_navigational_format?
    sign_in(resource_name, resource)

        respond_to do |format|
                format.json { render :json => resource, :status => :ok }
                format.html { respond_with resource, :location => after_sign_in_path_for(resource) } 
        end
  end

  # DELETE /resource/sign_out
  def destroy
    redirect_path = after_sign_out_path_for(resource_name)
    signed_out = (Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name))
    set_flash_message :notice, :signed_out if signed_out && is_navigational_format?

    # We actually need to hardcode this as Rails default responder doesn't
    # support returning empty response on GET request
    respond_to do |format|
      format.all { head :no_content }
      format.any(*navigational_formats) { redirect_to redirect_path }
    end
  end


  protected

  def sign_in_params
    devise_parameter_sanitizer.sanitize(:sign_in)
  end

  def serialize_options(resource)
    methods = resource_class.authentication_keys.dup
    methods = methods.keys if methods.is_a?(Hash)
    methods << :password if resource.respond_to?(:password)
    { :methods => methods, :only => [:password] }
  end

  def auth_options
    { :scope => resource_name, :recall => "#{controller_path}#new" }
  end
end
 
 

#config/routes (notice custom controllers)
devise_for :users, :path => '', :controllers => {:sessions => 'sessions', :registrations => 'registrations'} 
 
Registration Code 
 
#app/controllers/registrations_controller.rb
class RegistrationsController < DeviseController
  prepend_before_filter :require_no_authentication, :only => [ :new, :create, :cancel ]
  prepend_before_filter :authenticate_scope!, :only => [:edit, :update, :destroy]

  before_filter :configure_permitted_parameters

  prepend_view_path 'app/views/devise'

  # GET /resource/sign_up
  def new
    build_resource({})
    respond_with self.resource
  end

  # POST /resource
  def create
    build_resource(sign_up_params)

    if resource.save
      if resource.active_for_authentication?
        set_flash_message :notice, :signed_up if is_navigational_format?
        sign_up(resource_name, resource)
        respond_with resource, :location => after_sign_up_path_for(resource)
      else
        set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_navigational_format?
        expire_session_data_after_sign_in!
        respond_with resource, :location => after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource

      respond_to do |format|
        format.json { render :json => resource.errors, :status => :unprocessable_entity }
        format.html { respond_with resource }
      end
    end
  end

  # GET /resource/edit
  def edit
    render :edit
  end

  # PUT /resource
  # We need to use a copy of the resource because we don't want to change
  # the current user in place.
  def update
    self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
    prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)

    if update_resource(resource, account_update_params)
      if is_navigational_format?
        flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
          :update_needs_confirmation : :updated
        set_flash_message :notice, flash_key
      end
      sign_in resource_name, resource, :bypass => true
      respond_with resource, :location => after_update_path_for(resource)
    else
      clean_up_passwords resource
      respond_with resource
    end
  end

  # DELETE /resource
  def destroy
    resource.destroy
    Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
    set_flash_message :notice, :destroyed if is_navigational_format?
    respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }
  end

  # GET /resource/cancel
  # Forces the session data which is usually expired after sign
  # in to be expired now. This is useful if the user wants to
  # cancel oauth signing in/up in the middle of the process,
  # removing all OAuth session data.
  def cancel
    expire_session_data_after_sign_in!
    redirect_to new_registration_path(resource_name)
  end

  protected

  # Custom Fields
  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) do |u|
      u.permit(:first_name, :last_name,
        :email, :password, :password_confirmation)
    end
  end

  def update_needs_confirmation?(resource, previous)
    resource.respond_to?(:pending_reconfirmation?) &&
      resource.pending_reconfirmation? &&
      previous != resource.unconfirmed_email
  end

  # By default we want to require a password checks on update.
  # You can overwrite this method in your own RegistrationsController.
  def update_resource(resource, params)
    resource.update_with_password(params)
  end

  # Build a devise resource passing in the session. Useful to move
  # temporary session data to the newly created user.
  def build_resource(hash=nil)
    self.resource = resource_class.new_with_session(hash || {}, session)
  end

  # Signs in a user on sign up. You can overwrite this method in your own
  # RegistrationsController.
  def sign_up(resource_name, resource)
    sign_in(resource_name, resource)
  end

  # The path used after sign up. You need to overwrite this method
  # in your own RegistrationsController.
  def after_sign_up_path_for(resource)
    after_sign_in_path_for(resource)
  end

  # The path used after sign up for inactive accounts. You need to overwrite
  # this method in your own RegistrationsController.
  def after_inactive_sign_up_path_for(resource)
    respond_to?(:root_path) ? root_path : "/"
  end

  # The default url to be used after updating a resource. You need to overwrite
  # this method in your own RegistrationsController.
  def after_update_path_for(resource)
    signed_in_root_path(resource)
  end

  # Authenticates the current scope and gets the current resource from the session.
  def authenticate_scope!
    send(:"authenticate_#{resource_name}!", :force => true)
    self.resource = send(:"current_#{resource_name}")
  end

  def sign_up_params
    devise_parameter_sanitizer.sanitize(:sign_up)
  end

  def account_update_params
    devise_parameter_sanitizer.sanitize(:account_update)
  end
end 
 
 
 

Sunday, September 14, 2014

Peer authentication failed for user “postgres”, when trying to get pgsql working with rails

sudo nano /etc/postgresql/9.1/main/pg_hba.conf

local   all             postgres                                peer

Should be
 
local   all             postgres                                md5
 

Peer authentication

The peer authentication method works by obtaining the client's
  operating system user name from the kernel and using it as the allowed
  database user name (with optional user name mapping). This method is
  only supported on local connections. 


Password authentication

The password-based authentication methods are md5 and password. These methods operate similarly except for the way that the password is sent across the connection, namely MD5-hashed and clear-text respectively.
If you are at all concerned about password "sniffing" attacks then md5 is preferred. Plain password should always be avoided if possible. However, md5 cannot be used with the db_user_namespace feature. If the connection is protected by SSL encryption then password can be used safely (though SSL certificate authentication might be a better choice if one is depending on using SSL).
After altering this file, don't forget to restart your PostgreSQL server. If you're on Linux, that would be sudo service postgresql restart.

/etc/init.d/postgresql reload

Sunday, September 7, 2014

Install Ember-CLI

Getting setup with our tools

Let's start by making sure all relevant dev tools are installed on our machine. I am using the following:
  • Ruby 2.1.1
  • Rails 4.1.1
  • Node 0.10.26
  • npm 1.4.7
  • Postgres (only necessary because we are deploying to Heroku)
Versions at or above these versions should be OK for following along. Please refer elsewhere on how to install these tools on your development machine.
Next I will install ember-cli
1
npm install -g ember-cli
Confirm that you have ember-cli installed:
1
ember --version
You should see:
1
version: 0.0.27
Or a greater version.

Install and Upgrade node

Install:

apt-get install node


1) Clear NPM's cache:
 
sudo npm cache clean -f

2) Install a little helper called 'n'
 
sudo npm install -g n

3) Install latest stable NodeJS version
 
sudo n stable

Alternatively pick a specific version and install like this:
sudo n 0.8.20

Monday, September 1, 2014

Nginx with Passenger Giving Bad Gateway 502 Error

Recently i have installed and configured nginx with passenger, and
When deployed and configured, Nginx reports a 502 Bad Gateway exception. Digging throught the Nginx error log (in /var/log/nginx), the error becomes clear:
Exception RuntimeError in Rack application object (Missing secret_key_base for 'production' environment, set this value in config/secrets.yml)
Opening secrets.yml shows that there is no value for production:
development:
  secret_key_base: **not_for_prying_eyes**

test:
  secret_key_base: **not_for_prying_eyes**

# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
You can either set an environment variable, or directly configure a value here (you can run rake secret to generate a key). Just make sure that if you do the latter, you've added secrets/yml to your .gitignore!

Thursday, August 28, 2014

Change bash colors

Blue(34) as directory color is difficult to read and strain your eyes.
So, i googled and find using environment variable LS_COLORS one can modify it.

Here is one such google search result:

----------
These three lines in my .bashrc file allow me to configure the color system
by extension.

alias ls="ls --color=auto"
LS_COLORS="di=31;1:ln=36;1:ex=31;1:*~=31;1:*.html=31;1:*.shtml=37;1"
export LS_COLORS
And the output of this command:
dircolors --print-database | less
tells me about colors and codes etc that I can use..
--------

To change only directory color do this:
$ export LS_COLORS="di=31;1:

31 is for red
32 is for green
33 is for yellow
34 is for default blue

Authentication using ssh public (pub) and private keys(pem)

To avoid the need of supplying username and password everytime from trusted machine to login into your server we can generate pub/private keys to drop this authentication step from foreground

Steps involved to generate one such key pair are:
  1. Generate key pair (.pub and .pem)
  2. Pass .pub file to your server to store it in its authorized_keys file
  3. Keep .pem(private key) at yourself whenever to be used to login to server.

1) Generating key pair

     ssh-keygen -t rsa -b 2048 -v

It'll  generate 2,048 bit RSA key using verbose (questions asked during) mode, and a public .pem X.509 certificate.
Supply what it ask :

Generating public/private rsa key pair.
Enter file in which to save the key (/home/anonymouse/.ssh/id_rsa): hetzner
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in hetzner.
Your public key has been saved in hetzner.pub.
The key fingerprint is:
bb:c6:9c:ee:6b:c0:67:58:b2:bb:4b:44:72:d3:cc:a5 localhost@localhost
The key's randomart image is:

It wil generate two files at the specified location( default at ~/.ssh/) . File woul dbe named id_rsa.pub and id_rsa (if no name is supplied). Rename id_rsa ,the file without extension, to it_rsa.pem. This will be your private key.

Now don't forget to add the key to the ssh agent
      ssh-add keyName.pem
(Note: Do verify your ssh-agent is running.If not run it: eval `ssh-agent -s` )

2) Pass public key to your server to make this key pair work

   ssh-copy-id -i ~/id_rsa.pub root@your.server.ip

Follow the steps you see in the output of this command

Verfiy that you've all trusted keys listed in authorized_keys file on server:

   sudo nano ~/.ssh/authorized_keys or $ sudo cat ~/.ssh/authorized_keys

2) Test the connection now. Try login from client using private key(.pem) into your server:

  sudo ssh -i ~/id_rsa.pem root@your.server.ip


If you have multiple servers and prividing private key in the input is tedious for you, then generate ssh config file. This way you can access your server simply by SSH'ng into it by their name

SSH config 


  • Generate  ~/.ssh/config file with following content/template: 

Host server1 server1.company.com
Hostname 12.34.56.78
User ubuntu
IdentityFile /media/11361B1123123634/server1.pem
Host server2 server2.company.com
Hostname server2.company.com
User root
IdentityFile /media/11361B1123123634/server2.pem

Host myPC myPC.localHostname 192.168.0.106
User mike
IdentityFile /home/mike/.ssh/id_rsa



This file is recognized by ssh and would be used by other utilities like rsync as well.

Try SSHin'g now

  ssh server1

Troubleshooting:

  1.    Permissions on clients ~/.ssh should be dr-xr-x---
            chmod 550 .ssh
  2. Troubles with key path, rsync prompting for password when should not
    If using rsync with sudo, it looks for key file in /root/.ssh/config not in /home/user/.ssh/config, so be sure to copy or link this file to correct location, otherwise ssh and scp will be working fine while rsync will prompt for password.
  3. Error while running ssh-add
    vagrant@vagrant-ubuntu-precise-64:~$ ssh-add  ~/.ssh/id_rsa.pub
    Could not open a connection to your authentication agent.

    Here You might need to start ssh-agent before you run the ssh-add command:

    eval `ssh-agent -s`
    $ ssh-add
         if in root its' not working then try this:
            $    exec ssh-agent bash

---------------------
Reference:
    http://www.beginninglinux.com/home/server-administration/openssh-keys-certificates-authentication-pem-pub-crt

Getting started with Chef-Server and Chef-client

Steps Involved:

  1. Chef-server installation and key generation
  2. Launching chef-server webui.
  3. Transferring keys to admin workstation (admin.pem and chef-validator.pem)
  4. Adding new node 
  5. Deploying cookbook on newly added node (bootstrap)

1) Installation of chef-server
  • Download chef-server from this link: http://www.getchef.com/chef/install/


  • Create /etc/chef-server/chef-server.rb file 
    •  Use this file to configure it 
      • http://docs.opscode.com/config_rb_chef_server.html
  • Reconfigure it
    • $ sudo chef-server-ctl reconfigure
  • Test to verify installation
    • $ sudo chef-server-ctl test
      • Make sure your all test passed else, debug them.
  • Run all service
    • $ sudo chef-server-ctl start
  • Launch web-ui
    • https://ip.addres.of.yourMachine
      (in case of error, see the troubleshooting section)
      • If all service are running you'll be able to access web-ui through https protocol
      • Use default chef-server password which you can see at the right side on the login screen



  • Login and change password. Make sure to copy the private key and it's what our admin machine/workstation will use to connect to chef-server
  • Copy and name the private key to : "admin.pem"
2) Installation of chef-client on admin workstation
  • Make sure you've copied all  private keys(.pem files) from chef server to your admin machine.
    • These files are chef-webui.pem, admin.pem(which you recreated after login to webui), and chef-validator.pem
  • Create chef-repo ,preferrably inside admin home directory.
         I am creating it  under /root/chef-repo
    • git clone https://github.com/opscode/chef-repo
      • This is blank repo provided by opscode which we can use
    • Create .chef directory under chef-repo folder and copy all your  keys( STEP 1) in here.
  • Generate knife.rb file
    • cd chef-repo/.chef
    • Run command to let make knife generate knife.rb file or you can write  your own. Here we're taking aid of knife command.
      • $ sudo knife configure init
      • Enter what it ask you. After completion my knife.rb looks like this
        • log_level                :info
        • log_location             STDOUT
        • node_name                'admin'
        • client_key               '/root/chef-repo/.chef/admin.pem'
        • validation_client_name   'chef-validator'
        • validation_key           '/root/chef-repo/.chef/chef-validator.pem'
        • chef_server_url          'https://192.168.50.40'
        • syntax_check_cache_path  '/root/chef-repo/.chef/syntax_check_cache'
  • Try connecting to chef-server
    • $ knife client list
    • If you succeed connecting to server you would see following list:
      • chef-validator
      • chef-webui
  • That cover your chef-client installation: The admin workstation setup
3) Add new node and try boostrapping it with a cookbook
  • knife bootstrap is command to add new node into infrastructure
    • $ knife bootstrap IP.Addres --sudo  -x SSH_USERNAME -P SSH_PASSWORD -N NODE_NAME_TO_ASSIGN
    • eg
      knife bootstrap 192.168.50.43 --sudo -x vagrant -P vagrant -N slave03
  • List your new node via "knife node" command
    • $ knife node list
       slave03
  • You just added new node into your infrastructure. From webgui you  also see your new node listed under "node"  and "client" tab with no recipes currently added.
3) Writing and adding cooking for our nodes
  • Create new cookbook
    • $knife cookbook create apache
      • It will create a apache folder under ../cookbooks dir
    • Write recipe inside apache/recipes/default.rb  file
  • There are two ways of running recipe at client
    • SSH's node and run sudo chef-client
      • It'll pull recipe list assigned to it from server and run it
    • run bootstrap command from admin workstation but this time assign recipe list as well
      • $ knife bootstrap 192.168.50.43 --sudo -x vagrant -P vagrant  -r "recipe_01, recipe_02, ..."



    -----------------------------------------------------
    Troubleshooting
    1. lost private keys
      1. Lost of admin.pem file
        1. Visit webui 
          1. Edit account >> Edit >> Regnerate private key
        2. Lost chef-validator private key
      2. cleanse chef-server and start from scratch
        1. sudo chef-server-ctl cleanse
    2. ERROR: TypeError: can't convert nil into String
      1. Most probably argument error. I get this while executing following cookbook command:
          $ knife cookbook create apache
        • Reason it give me this error was my knife.rb file was incomplete. I didn't specify cookbook_path variable. This mean i've to explicitly specify cookbook path while executing knife commands.
        • I solved this by adding "cookbook_path" variable in my knife.rb file
          OR
        • giving -o argument to specify cookbook directory
          $ knife cookbook create MYCOOKBOOK -o /path/to/my/cookbook_dir
    3. Not able to communicate with chef-server
      1. /opt/chef/embedded/lib/ruby/1.9.1/net/http.rb:763:in `initialize': Connection re
      2.  
      3. used - connect(2) (Errno::ECONNREFUSED)
      • Most probably chef-server is not configured with right parameters like server name
      • Visit chef-server and cd /etc/chef-server  or wherever your chef-server is installed
      • make chef-server.rb file and enter following parameters

        server_name = "192.168.56.11"
        api_fqdn server_name
        nginx['url'] = "https://#{server_name}"
        nginx['server_name'] = server_name
        lb['fqdn'] = server_name
        bookshelf['vip'] = server_name
      • verify chef-server configuration :
        $ sudo chef-server-ctl show-config
      • More info here: http://stackoverflow.com/questions/19586040/install-chef-server-11-on-ec2-instance
    4. Old recipes are getting run on node 
    1. Most probably you forget to commit your changes and upload on chef-server
      1. $ knife cookbook upload cookbook_02
      Reference:
      1. http://www.getchef.com/blog/2013/03/11/chef-11-server-up-and-running/
      2. chef_server.rb and chef-server configuratioin:
        1. https://github.com/opscode-cookbooks/chef-server
        2. http://docs.opscode.com/config_rb_chef_server.html
      3. http://docs.opscode.com/config_rb_knife.html
      4. http://leopard.in.ua/2013/02/17/chef-server-getting-started-part-1/
      5. http://sanketdangi.com/post/50649257357/chef-11-configuration-aws-ec2-rhel-6-3-instance