khanhnnvn

Hướng dẫn sử dụng GIT

 Programing  Comments Off on Hướng dẫn sử dụng GIT
Jan 262018
 

 

  1. Initialize the local directory as a Git repository.
    git init
    
  2. Add the files in your new local repository. This stages them for the first commit.
    git add .
    # Adds the files in the local repository and stages them for commit. To unstage a file, use 'git reset HEAD YOUR-FILE'.
    
  3. Commit the files that you’ve staged in your local repository.
    git commit -m "First commit"
    # Commits the tracked changes and prepares them to be pushed to a remote repository. To remove this commit and modify the file, use 'git reset --soft HEAD~1' and commit and add the file again.
    
  4. Copy remote repository URL fieldAt the top of your GitHub repository’s Quick Setup page, click  to copy the remote repository URL.
  5. In the Command prompt, add the URL for the remote repository where your local repository will be pushed.
    git remote add origin remote repository URL
    # Sets the new remote
    git remote -v
    # Verifies the new remote URL
    
  6. Push the changes in your local repository to GitHub.
    git push origin master
    # Pushes the changes in your local repository up to the remote repository you specified as the origin

Tutorial Install Parallels Cloud Server

 Hệ thống, Linux  Comments Off on Tutorial Install Parallels Cloud Server
Dec 232015
 

Parallels Cloud Server 6.0 (PCS) is a virtualization solution that allows you to run multiple virtual machines and Containers on a single physical server.

In this topic, we install PCS on Vmware

Screenshot_1

 

 

 

 

 

 

 

 

 

 

 

 

And then, we click Agree

Screenshot_2

 

 

 

 

Select type keyboard for install

Screenshot_3

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Then set hostname for PCS

Screenshot_4

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

In step we format disk for install

Screenshot_5

 

 

 

 

 

 

 

 

Screenshot_6 Screenshot_7 Screenshot_8 Screenshot_9 Screenshot_10 Screenshot_11 Screenshot_12 Screenshot_13 Screenshot_14 Screenshot_15 Screenshot_16 Screenshot_17 Screenshot_18

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

That okie. We can using it for Our cloud.

Configure Apache for SSL HTTPS CentOS 6

 Hệ thống, Linux  Comments Off on Configure Apache for SSL HTTPS CentOS 6
Nov 182015
 

Configure Apache for SSL HTTPS CentOS 6

Using Apache over HTTPS or SSL allows a slightly more secure setup, any computer that connects over ssl is automatically encrypted.

Original Reference:

http://xmodulo.com/2014/04/https-apache-web-server-centos.html

 

Here’s the basic instructions:

Login to your server, and su to root

install modssl and openssl

The next Large step is to generate a self-signed certificate

create a Private Key

done

now you must generate the CSR, or Certificate Signing Request

Fill in all the necessary fields, this will be different for almost every scenario

Finally, Generate a Self-Signed Certificate for the Life of the Server, 365 days * 7 (allowing up to 7 years)

you should see signature OK

now copy the necessary files to the appropriate directories:

Now all we have to do is set-up Apache to use the certificates:

 

Edit the Apache SSL.conf

Comment Out Line 105, and add 106

now do the same for 113 and 114

### The following parameter does not need to be modified in case of a self-signed certificate. ### ### If you are using a real certificate, you may receive a certificate bundle. The bundle is added using the following parameters ### SSLCertificateChainFile /etc/pki/tls/certs/example.com.ca-bundle (reference below)

now restart apache

the webserver should now be able to use HTTPS.

 

That’s it!

Original Reference:

http://xmodulo.com/2014/04/https-apache-web-server-centos.html

Mô hình MVC là gì?

 Programing  Comments Off on Mô hình MVC là gì?
Nov 182015
 

Nếu bạn là một lập trình viên, nhất là lập trình web, sẽ rất khó để bạn có thể xin được việc nếu không biết mô hình MVC. Trong post này mình sẽ trình bày đến các bạn mô hình MVC là gì theo cách hiểu của mình qua một vài dự án sử dụng MVC?

MVC là gì?

MVC là viết tắt của Model – View – Controller. Là một kiến trúc phần mềm hay mô hình thiết kế được sử dụng trong kỹ thuật phần mềm. Nói cho dễ hiểu, nó là mô hình phân bố source code thành 3 phần, mỗi thành phần có một nhiệm vụ riêng biệt và độc lập với các thành phần khác.

Các thành phần trong MVC

Controller

Giữ nhiệm vụ nhận điều hướng các yêu cầu từ người dùng và gọi đúng những phương thức xử lý chúng… Chẳng hạn thành phần này sẽ nhận request từ url và form để thao tác trực tiếp với Model.

Model

Đây là thành phần chứa tất cả các nghiệp vụ logic, phương thức xử lý, truy xuất database, đối tượng mô tả dữ liệu như các Class, hàm xử lý…

View

Đảm nhận việc hiển thị thông tin, tương tác với người dùng, nơi chứa tất cả các đối tượng GUI như textbox, images… Hiểu một cách đơn giản, nó là tập hợp các form hoặc các file HTML.

Luồng đi trong MVC

Để giải thích, mình xin dùng 1 ví dụ đơn giản + hình minh họa sau.

Mô hình MVC
Mô hình MVC

Khi có một yêu cầu từ phía client gửi đến server, Bộ phận controller có nhiệm vụ nhận yêu cầu, xử lý yêu cầu đó. Và nếu cần, nó sẽ gọi đến phần model, vốn là bộ phần làm việc với Database..

Sau khi xử lý xong, toàn bộ kết quả được đẩy về phần View. Tại View, sẽ gen ra mã Html tạo nên giao diện, và trả toàn bộ html về trình duyệt để hiển thị.

Ưu điểm và nhược điểm của MVC

1. Ưu điểm

Thể hiện tính chuyên nghiệp trong lập trình, phân tích thiết kế. Do được chia thành các thành phần độc lập nên giúp phát triển ứng dụng nhanh, đơn giản, dễ nâng cấp, bảo trì..

2. Nhược điểm

Đối với dự án nhỏ việc áp dụng mô hình MC gây cồng kềnh, tốn thời gian trong quá trình phát triển. Tốn thời gian trung chuyển dữ liệu của các thành phần.

Tóm lại

Để lập trình chuyên nghiệp, làm việc trọng một nhóm nhiều người, việc áp dụng mô hình trong thiết kế là điều bắt buộc. MVC là một mô hình khá đơn giản và thích hợp cho những người chưa nhiều kinh nghiệm. Hy vọng qua bài giới thiệu này các bạn có những kiến thức cơ bản về mô hình thiết kế trong làm phần mềm.

Why Pound is awesome in front of Varnish

 Hệ thống, Linux  Comments Off on Why Pound is awesome in front of Varnish
Nov 172015
 

We all know Varnish is awesome. I went as far as presenting a topic on Varnish then writing about it. This is a known fact.

However, what happens to all that caching goodness when you want to run your entire site over SSL? Out of the box, Varnish doesn’t support it. While I’ve heard some mention that not supporting SSL is an oversight,there exists some very sound reasoning for why not.

So how do people terminate SSL?

What is Pound?

Without copying exactly what’s on the Pound documentation, or theWikipedia entry about Pound, it’s essentially a reverse proxy, SSL terminator and load balancer but NOT a webserver. It’s small, easy enough to install and has minimal configuration. Stunnel is similarly simple, but since I have quite extensive experience using Stunnel, I decided to learn something new.

On my load balancing servers, Pound listens on port 443 and Varnish listens on port 80. When traffic comes in on port 443, it hits Pound, gets decrypted using my server certificate and then gets passed to Varnish on port 80. By putting all traffic through Varnish, I’m able to take advantage of its caching ability for both HTTP and HTTPS traffic.

It’s almost, that simple. I had to make some minor changes to my VCL to receive and cache mixed mode traffic. Prior to these changes, I would sometimes deliver resources using the HTTP schema to pages delivered over HTTPS. This had the understandable effect of causing my browser to complain about insecure resources.

Getting Varnish and Pound to play nicely

Realising that we need to handle HTTP/HTTPS traffic differently in Varnish, even though it all comes in on port 80, I decided to use a separate cache hash key for each. Varnish uses hashes of the URI as a key to store and look up data by. My VCL implements the vcl_hashsubroutine to detect HTTPS traffic and alter the hash key. We add a header in Pound to tell Varnish that the traffic came in over SSL and then watch the magic happen.

pound.cfg

ListenHTTPS
  Address 0.0.0.0
  Port 443
  HeadRemove "X-Forwarded-Proto"
  AddHeader "X-Forwarded-Proto: https"
  Cert "/etc/ssl/certs/adammalone.net.pem"
End
 
Service
  HeadRequire "Host:.*adammalone.net.*"
    Backend
      Address 127.0.0.1
      Port 80
    End
End

default.vcl – vcl_hash {}

sub vcl_hash {
  hash_data(req.url);
  if (req.http.host) {
    hash_data(req.http.host);
  } else {
    hash_data(server.ip);
  }
  # Use special internal SSL hash for https content
  # X-Forwarded-Proto is set to https by Pound
  if (req.http.X-Forwarded-Proto ~ "https") {
    hash_data(req.http.X-Forwarded-Proto);
  }
  return (hash);
}

The hash_data function allows us to add further information to the hash. By adding ‘https’ to the host and uri information, we’re altering the hash in such a way that it is different from just the host + uri that an http request would use.

I’ve also attached a downloadable copy of my full Pound config and the puppet manifest that generates it for people who are interested in replicating this functionality. I’m using my Pound puppet class located at typhonius/puppet-pound, a fork of mrintegrity/puppet-pound.

Drupal configuration

The final thing to do is to inform Drupal it needs to be in SSL mixed mode and to enter a small snippet in my settings.php so it can be turned on or off based on the incoming request. If Varnish is running on the same server as your Drupal installation, you’ll need to replace www.xxx.yyy.zzz with 127.0.0.1. Otherwise it’ll be the IP of your load balancing server.

// Varnish Settings
$conf['reverse_proxy'] = TRUE;
$conf['reverse_proxy_addresses'] = array('www.xxx.yyy.zzz');
$conf['reverse_proxy_header'] = 'HTTP_X_FORWARDED_FOR';
$conf['page_cache_invoke_hooks'] = FALSE;
 
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
  $_SERVER['HTTPS'] = 'on';
}

This is how I allow SSL through Varnish, if you do it differently, add a comment!

Nginx SSL and Varnish

 Hệ thống, Linux  Comments Off on Nginx SSL and Varnish
Nov 172015
 

Firstly, lets get this out of the way: Varnish does not do SSL, at all and likely won’t ever.

Varnish is not a tool for connection managment, it’s a tool to cache web-pages and make them faster. That is all.

To get the speed benefits of Varnish over the SSL traffic we have to run an additional service to manage the SSL connections. Cue Nginx.

Our example configuration looks something like this, all on one server – but in real-life this should be distributed across dedicated machines.

  • Nginx Public IP 74.207.248.164
  • Varnish on Private IP 127.0.0.1:8080
  • Apache on Private IP 127.0.0.1:80

Visual Overview

The HTTP requests from the internet hit Nginx, which passes some directly to Apache and some to Varnish (based on rules). Varnish, on cache-miss, will request to Apache. And Apache will likely hit the database.

varnish, nginx, apahce

Configuring Nginx

Please see our existing howto for Nginx.

The configuration there will be adjusted along these lines, again, update as necessary for your environment. Here, we just

http {
     server {
         listen       74.207.248.164:80;
         server_name  _;

         location /c {
            root /var/www/css;
         }

         location /i {
            root /var/www/images;
         }

         location / {
            proxy_pass   http://127.0.0.1:8080;
         }
     }
}
http {
     server {

         listen       74.207.248.164:443;
         server_name  _;

         ssl          on;
         ssl_certificate /etc/ssl/server.crt;
         ssl_certificate_key /etc/ssl/server.key;
         # ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2;
         # ssl_ciphers   HI:!aNULL:!MD5;

         location / {
            proxy_pass   http://127.0.0.1:8080;
         }
     }
}

Configure Varnish

This can be a typical Varnish configuration, what changes here is the listening and the back-end. Configure the sub vcl_* routines as you normally would. Keep in mind however, some requests can be handled a the Nginx layer, so don’t need rules here (anymore).

backend default {
    .host = "127.0.0.1";
    .port = "80";
    .connect_timeout = 16s;
    .first_byte_timeout = 96s;
    .between_bytes_timeout = 8s;
}

And remember to start varnish with -a 127.0.0.1:8080, so it’s only listening on the local system, high-http port.

Configure Apache

I like to have Apache listen on the default HTTP port, then I explicitly set the hostname on the machine as well as in the Apache configuration. This way many of the running apps will think they are still publicly exposed and it helps them resolve their hostname. This is needed for example by Chiliproject, Redmine, Drupal, WordPress and many others.

<VirtualHost 127.0.0.1:80>
	ServerName edoceo.com
	ErrorLog /dev/null
	CustomLog /dev/null fuck-it
<VirtualHost>

It should be noted here that the Apache configuration maybe able to operate with a much stripped configuration. As a result of sitting behind these other systems we can do away with many modules and remove some of the other rules which are designed for public consumption (such as Keep Alive).

Testing

We use curl to test.

Install Tomcat 8 on CentOS, RHEL, or Fedora

 Hệ thống, Linux  Comments Off on Install Tomcat 8 on CentOS, RHEL, or Fedora
Nov 172015
 
Step 1: Install JDK 1.7

You can download the latest JDK here: http://www.oracle.com/technetwork/java/javase/downloads/index.html

We’ll install JDK 7, Update 60 (7u60). The JDK is specific to 32 and 64 bit versions.

My CentOS box is 64 bit, so I’ll need: jdk-7u60-linux-x64.tar.gz.

If you are on 32 bit, you’ll need: jdk-7u60-linux-i586.tar.gz

Start by creating a new directory /usr/java:

[root@srv6 ~]# mkdir /usr/java

Change to the /usr/java directory we created

[root@srv6 ~]# cd /usr/java

[root@srv6 java ]#

Download the appropriate JDK and save it to /usr/java directory we created above.

Unpack jdk-7u60-linux-x64.tar.gz in the /usr/java directory using tar -xzf:

[root@srv6 java]# tar -xzf jdk-7u60-linux-x64.tar.gz

This will create the directory /usr/java/jdk1.7.0_60. This will be our JAVA_HOME.

We can now set JAVA_HOME and put Java into the path of our users.

To set it for your current session, you can issue the following from the CLI:

[root@srv6 java]# JAVA_HOME=/usr/java/jdk1.7.0_60

[root@srv6 java]# export JAVA_HOME

[root@srv6 java]# PATH=$JAVA_HOME/bin:$PATH

[root@srv6 java]# export PATH

To set the JAVA_HOME permanently, however, we need to add below to the ~/.bash_profile of the user (in this case, root).
We can also add it /etc/profile and then source it to give to all users.

JAVA_HOME=/usr/java/jdk1.7.0_60

export JAVA_HOME

PATH=$JAVA_HOME/bin:$PATH

export PATH

Once you have added the above to ~/.bash_profile, you should log out, then log back in and check that the JAVA_HOME is set correctly.

[root@srv6 ~]#  echo $JAVA_HOME

/usr/java/jdk1.7.0_60

Note: If you decided to use JDK 6 rather than 7 as we did above, simply save the JDK 6 bin file to /opt (or another location), then navigate to /usr/java and issue: ‘sh /opt/jdk-6u33-linux-x64.bin’. This will create a JAVA Home of /usr/java/jdk1.6.0.33

Step 2: Download and Unpack Tomcat 8.0.8 (or latest)

We will install Tomcat 8 under /usr/share.

Switch to the /usr/share directory:

[root@srv6 ~]# cd /usr/share

[root@srv6 share ]#

Download apache-tomcat-8.0.8.tar.gz (or the latest version) here

and save it to /usr/share

Once downloaded, you should verify the MD5 Checksum for your Tomcat download using the md5sum command.

[root@srv6 share ]# md5sum apache-tomcat-8.0.8.tar.gz

c377b34fc4d228a63f7f1a51efbec333 *apache-tomcat-8.0.8.tar.gz

Compare the output above to the MD5 Checksum provided next to the download link and you used above and check that it matches.

unpack the file using tar -xzf:

[root@srv6 share ]# tar -xzf apache-tomcat-8.0.8.tar.gz

This will create the directory /usr/share/apache-tomcat-8.0.8

Step 3: Configure Tomcat to Run as a Service.

We will now see how to run Tomcat as a service and create a simple Start/Stop/Restart script, as well as to start Tomcat at boot.

Change to the /etc/init.d directory and create a script called ‘tomcat’ as shown below.

[root@srv6 share]# cd /etc/init.d

[root@srv6 init.d]# vi tomcat

And here is the script we will use.

#!/bin/bash

# description: Tomcat Start Stop Restart

# processname: tomcat

# chkconfig: 234 20 80

JAVA_HOME=/usr/java/jdk1.7.0_60

export JAVA_HOME

PATH=$JAVA_HOME/bin:$PATH

export PATH

CATALINA_HOME=/usr/share/apache-tomcat-8.0.8

case $1 in

start)

sh $CATALINA_HOME/bin/startup.sh

;;

stop)

sh $CATALINA_HOME/bin/shutdown.sh

;;

restart)

sh $CATALINA_HOME/bin/shutdown.sh

sh $CATALINA_HOME/bin/startup.sh

;;

esac

exit 0

The above script is simple and contains all of the basic elements you will need to get going.

As you can see, we are simply calling the startup.sh and shutdown.sh scripts located in the Tomcat bin directory (/usr/share/apache-tomcat-8.0.8/bin).

You can adjust your script according to your needs and, in subsequent posts, we’ll look at additional examples.

CATALINA_HOME is the Tomcat home directory (/usr/share/apache-tomcat-8.0.8)

Now, set the permissions for your script to make it executable:

[root@srv6 init.d]# chmod 755 tomcat

We now use the chkconfig utility to have Tomcat start at boot time. In my script above, I am using chkconfig: 234 20 80. 2345 are the run levels and 20 and 80 are the stop and start priorities respectively. You can adjust as needed.

[root@srv6 init.d]# chkconfig –add tomcat

[root@srv6 init.d]# chkconfig –level 234 tomcat on

Verify it:

[root@srv6 init.d]# chkconfig –list tomcat

tomcat          0:off   1:off   2:on    3:on    4:on    5:off   6:off

Now, let’s test our script.

Start Tomcat:

[root@srv6 ~]# service tomcat start

Using CATALINA_BASE:   /usr/share/apache-tomcat-8.0.8

Using CATALINA_HOME:   /usr/share/apache-tomcat-8.0.8

Using CATALINA_TMPDIR: /usr/share/apache-tomcat-8.0.8/temp

Using JRE_HOME:        /usr/java/jdk1.7.0_60

Using CLASSPATH:       /usr/share/apache-tomcat-8.0.8/bin/bootstrap.jar:/usr/share/apache-tomcat-8.0.8/bin/tomcat-juli.jar

Stop Tomcat:

[root@srv6 ~]# service tomcat stop

Using CATALINA_BASE:   /usr/share/apache-tomcat-8.0.8

Using CATALINA_HOME:   /usr/share/apache-tomcat-8.0.8

Using CATALINA_TMPDIR: /usr/share/apache-tomcat-8.0.8/temp

Using JRE_HOME:        /usr/java/jdk1.7.0_60

Using CLASSPATH:       /usr/share/apache-tomcat-8.0.8/bin/bootstrap.jar:/usr/share/apache-tomcat-8.0.8/bin/tomcat-juli.jar

Restarting Tomcat (Must be started first):

[root@srv6 ~]# service tomcat restart

Using CATALINA_BASE:   /usr/share/apache-tomcat-8.0.8

Using CATALINA_HOME:   /usr/share/apache-tomcat-8.0.8

Using CATALINA_TMPDIR: /usr/share/apache-tomcat-8.0.8/temp

Using JRE_HOME:        /usr/java/jdk1.7.0_60

Using CLASSPATH:       /usr/share/apache-tomcat-8.0.8/bin/bootstrap.jar:/usr/share/apache-tomcat-8.0.8/bin/tomcat-juli.jar

Using CATALINA_BASE:   /usr/share/apache-tomcat-8.0.8

Using CATALINA_HOME:   /usr/share/apache-tomcat-8.0.8

Using CATALINA_TMPDIR: /usr/share/apache-tomcat-8.0.8/temp

Using JRE_HOME:        /usr/java/jdk1.7.0_60

Using CLASSPATH:       /usr/share/apache-tomcat-8.0.8/bin/bootstrap.jar:/usr/share/apache-tomcat-8.0.8/bin/tomcat-juli.jar

We should review the Catalina.out log located at /usr/share/apache-tomcat-8.0.8/logs/catalina.out and check for any errors.

[root@srv6 init.d]# more /usr/share/apache-tomcat-8.0.8/logs/catalina.out

We can now access the Tomcat Manager page at:

http://yourdomain.com:8080 or http://yourIPaddress:8080

and we should see the Tomcat home page.

Step 4: Configuring Tomcat Manager Access.

Tomcat 8 contains a number of changes that offer finer-grain roles.

For security reasons, no users or passwords are created for the Tomcat manager roles by default. In a production deployment, it is always best to remove the Manager application.

To set roles, user name(s) and password(s), we need to configure the tomcat-users.xml file located at $CATALINA_HOME/conf/tomcat-users.xml.

In the case of our installation, $CATALINA_HOME is located at /usr/share/apache-tomcat-8.0.8.

By default the Tomcat 8 tomcat-users.xml file will have the elements between the and tags commented-out. .

New roles for Tomcat 8 offer finer-grained access and The following roles are now available:

manager-gui
manager-status
manager-jmx
manager-script
admin-gu
admin-script.

We can set the manager-gui role, for example as below

 

<role rolename=”manager-script”/>
<role rolename=”manager-gui”/>
<role rolename=”admin-gui”/>
<role rolename=”manager-status”/>
<user username=”admin” password=”admin” roles=”manager-gui,manager-script,admin-gui,manager-status”/>

Caution should be exercised in granting multiple roles so as not to under-mind security.

Step 5 (Oprtional): Manage Memory Usage Using JAVA_OPTS.

Getting the right heap memory settings for your installation will depend on a number of factors.

For simplicity, we will set our inital heap size, Xms, and our maximum heap size, Xmx, to the same value of 128 Mb

Simliarly, there are several approaches you can take as to where and how you set your JAVA_OPTS

Again, for simplicity, we will add our JAVA_OPTS memory parameters in our Catalina.sh file.

So, open the Catalina.sh file located under /usr/share/apache-tomcat-8.0.8/bin with a text editor or vi.

Since we are using 128 Mb for both initial and maximum heap size, add the following line to Catalina.sh

JAVA_OPTS=“-Xms128m -Xmx128m”

I usually just add this in the second line of the file so it looks as so:

#!/bin/sh

JAVA_OPTS=“-Xms128m -Xmx128m”

# Licensed to the Apache Software Foundation (ASF) under one or more

# contributor license agreements.  See the NOTICE file distributed with

# this work for additional information regarding copyright ownership.

# The ASF licenses this file to You under the Apache License, Version 2.0

# (the “License”); you may not use this file except in compliance with

# the License.  You may obtain a copy of the License at

 

Step 6 (Optional): How to Run Tomcat using Minimally Privileged (non-root) User.

In our Tomcat configuration above, we are running Tomcat as Root.

For security reasons, it is always best to run services with the only those privileges that are necessary.

There are some who make a strong case that this is not required, but it’s always best to err on the side of caution.

To run Tomcat as non-root user, we need to do the following:

1. Create the group ‘tomcat’:

  1. [root@srv6 ~]# groupadd tomcat

2. Create the user ‘tomcat’ and add this user to the tomcat group we created above.

  1. [root@srv6 ~]# useradd -s /bin/bash -g tomcat tomcat

The above will create a home directory for the user tomcat in the default user home as /home/tomcat

If we want the home directory to be elsewhere, we simply specify so using the -d switch.

  1. [root@srv6 ~]# useradd -g tomcat -d /usr/share/apache-tomcat-8.0.8/tomcat tomcat

The above will create the user tomcat’s home directory as /usr/share/apache-tomcat-8.0.8/tomcat

3. Change ownership of the tomcat files to the user tomcat we created above:

  1. [root@srv6 ~]# chown -Rf tomcat.tomcat /usr/share/apache-tomcat-8.0.8/

Note: it is possible to enhance our security still further by making certain files and directories read-only. This will not be covered in this post and care should be used when setting such permissions.

4. Adjust the start/stop service script we created above. In our new script, we need to su to the user tomcat:

#!/bin/bash

# description: Tomcat Start Stop Restart

# processname: tomcat

# chkconfig: 234 20 80

JAVA_HOME=/usr/java/jdk1.7.0_60

export JAVA_HOME

PATH=$JAVA_HOME/bin:$PATH

export PATH

CATALINA_HOME=/usr/share/apache-tomcat-8.0.8/bin

case $1 in

start)

/bin/su tomcat $CATALINA_HOME/startup.sh

;;

stop)

/bin/su tomcat $CATALINA_HOME/shutdown.sh

;;

restart)

/bin/su tomcat $CATALINA_HOME/shutdown.sh

/bin/su tomcat $CATALINA_HOME/startup.sh

;;

esac

exit 0

 

Step 7 (Optional): How to Run Tomcat on Port 80 as Non-Root User.

Note: the following applies when you are running Tomcat in “stand alone” mode with Tomcat running under the minimally privileged user Tomcat we created in the previous step.

To run services below port 1024 as a user other than root, you can add the following to your IP tables:

[root@srv6 ~]# iptables -t nat -A PREROUTING -p tcp -m tcp –dport 80 -j REDIRECT –to-ports 8080

[root@srv6 ~]# iptables -t nat -A PREROUTING -p udp -m udp –dport 80 -j REDIRECT –to-ports 8080

Be sure to save and restart your IP Tables.

Step 8 (Optional): Running Tomcat behind Apache

As an alternative to running Tomcat on port 80, if you have Apache in front of Tomcat, you can use mod_proxy as well as ajp connector to map your domain to your Tomcat application(s) using an Apache vhost as shown below.

While Tomcat has improved it’s ‘standalone performance’, I still prefer to have Apace in front of it for a number of reasons.

In your Apache config, be sure to set KeepAlive to ‘on’. Apache tuning, of course, is a whole subject in itself…

Example 1: VHOST with mod_proxy:

<VirtualHost *:80>

ServerAdmin [email protected]

ServerName yourdomain.com

ServerAlias www.yourdomain.com

ProxyRequests Off

ProxyPreserveHost On

<Proxy *>

Order allow,deny

Allow from all

</Proxy>

ProxyPass / http://localhost:8080/

ProxyPassReverse / http://localhost:8080/

ErrorLog logs/yourdomain.com-error_log

CustomLog logs/yourdomain.com-access_log common

/VirtualHost>

Example 2: VHOST with ajp connector and mod_proxy:

<VirtualHost *:80>

ServerAdmin [email protected]

ServerName yourdomain.com

ServerAlias www.yourdomain.com

ProxyRequests Off

ProxyPreserveHost On

<Proxy *>

Order allow,deny

Allow from all

</Proxy>

ProxyPass / ajp://localhost:8009/

ProxyPassReverse / ajp://localhost:8009/

ErrorLog logs/yourdomain.com-error_log

CustomLog logs/yourdomain.com-access_log common

</VirtualHost>

In both vhost examples above, we are “mapping” the domain to Tomcat’s ROOT directory.

If we wish to map to an application such as yourdomain.com/myapp, we can add some rewrite as shown below.

This will rewrite all requests for yourdomain.com to yourdomain.com/myapp.

Example 3: VHOST with rewrite:

<VirtualHost *:80>

ServerAdmin [email protected]

ServerName yourdomain.com

ServerAlias www.yourdomain.com

RewriteEngine On

RewriteRule ^/$ myapp/ [R=301]

ProxyRequests Off

ProxyPreserveHost On

<Proxy *>

Order allow,deny

Allow from all

</Proxy>

ProxyPass / ajp://localhost:8009/

ProxyPassReverse / ajp://localhost:8009/

ErrorLog logs/yourdomain.com-error_log

CustomLog logs/yourdomain.com-access_log common

Install pyDash

 Linux, Monitoring  Comments Off on Install pyDash
Nov 162015
 

1. Installation

By default the install will be done using the Apache webserver.

Fedora & Pidora

Run:

sudo yum -y install git python-pip httpd mod_wsgi

Centos

Centos 6

Run:

sudo yum -y install http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm

sudo yum -y install git python-pip httpd mod_wsgi

Centos 5

Run:

sudo yum -y install http://dl.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm

sudo yum -y install git python-pip httpd mod_wsgi

Debian & Ubuntu & Raspbian

Run:

sudo apt-get install git python-pip apache2 libapache2-mod-wsgi

2. Setup

Please make sure you change the SECRET_KEY, please seehttps://docs.djangoproject.com/en/dev/ref/settings/ for more details.

Run:

cd /var/www
sudo git clone https://github.com/k3oni/pydash
cd pydash
edit pydash/settings.py and change the SECRET_KEY value
sudo pip install -r requirements.txt
sudo ./manage.py syncdb
cd ..
sudo chown -R apache.apache pydash   - For Centos & Fedora & Pidora
sudo chown -R www-data.www-data pydash   - For Ubuntu & Debian & Raspbian

Enter the user information, to create your login user:

 You just installed Django's auth system, which means you don't have any superusers defined.
 Would you like to create one now? (yes/no): yes
 Username (leave blank to use 'root'): admin (Enter your desired username)
 Email address: [email protected] (Enter your email address)
 Password: xxxxx (Enter your desired password)
 Password (again): xxxxx (Enter your password again)

3. Setup Apache

Centos & Fedora & Pidora

Add the config pydash.conf file under /etc/httpd/conf.d/:

 WSGISocketPrefix run/wsgi
   <VirtualHost *:80>
     ServerAdmin [email protected]
     ServerName dummy-host.example.com

     WSGIDaemonProcess pydash display-name=%{GROUP} python-path=/var/www/pydash
     WSGIProcessGroup pydash
     WSGIScriptAlias / /var/www/pydash/pydash/wsgi.py

     Alias /static /var/www/pydash/static/
     Alias /media /var/www/pydash/media/

     <Directory /var/www/pydash/pydash>
         <Files wsgi.py>
             Order deny,allow
             Allow from all
         </Files>
     </Directory>

     #CustomLog logs/pydash-access_log common
     #ErrorLog logs/pydash-error_log
 </VirtualHost>

Start the webserver:

 sudo service httpd start

Debian & Ubuntu & Raspbian

Add the config pydash.conf file under /etc/apache2/conf.d or /etc/apache2/sites-enabled:

 WSGISocketPrefix /var/run/apache2/wsgi
   <VirtualHost *:80>
     ServerAdmin [email protected]
     ServerName dummy-host.example.com

     WSGIDaemonProcess pydash display-name=%{GROUP} python-path=/var/www/pydash
     WSGIProcessGroup pydash
     WSGIScriptAlias / /var/www/pydash/pydash/wsgi.py

     Alias /static /var/www/pydash/static/
     Alias /media /var/www/pydash/media/

     <Directory /var/www/pydash/pydash>
         <Files wsgi.py>
             Order deny,allow
             Allow from all
         </Files>
     </Directory>

     #CustomLog logs/pydash-access_log common
     #ErrorLog logs/pydash-error_log
 </VirtualHost>

Start the webserver

 sudo service apache2 start

Introducing JavaMelody for Server Monitoring

 Hệ thống  Comments Off on Introducing JavaMelody for Server Monitoring
Nov 162015
 

The goal of JavaMelody is to monitor Java or Java EE application servers in QA and production environments.

JavaMelody Sample Graph

The really nice thing is sthe storage of historical data – you can have a look at the same graphs spanning a week, a month or a year without setting up any additional infrastructure. Therefore JavaMelody is installed on every production system I work on.

Securing JavaMelody Installation

If you want BASIC authentication with username and password, but do no want to use a realm and “security-constraint” in web.xml, you can add the parameter “authorized-users” in web.xml, in context or in system properties like the other javamelody parameters (since v1.53). For example in your WEB-INF/web.xml file:

<filter>
        <filter-name>monitoring</filter-name>
        <filter-class>net.bull.javamelody.MonitoringFilter</filter-class>
        <init-param>
                <param-name>authorized-users</param-name>
                <param-value>user1:pwd1, user2:pwd2</param-value>
        </init-param>
</filter>

Security Manager

If you are running into an active security manager the following snippets helps

grant codeBase "file:${catalina.home}/webapps/<your_webapp>/WEB-INF/lib/javamelody-x.jar" {
        permission java.security.AllPermission;
};
grant codeBase "file:${catalina.home}/webapps/<your_webapp>/WEB-INF/lib/jrobin-1.5.9.1.jar" {
        permission java.security.AllPermission;
};    Ï

Disabling JavaMelody

You can disable JavaMelody using

  • disabled=false using the init parameter in web.xml
  • pass -Djavamelody.disabled=true as system property

Avoiding Unique Identifier URLs

JavaMelody created unique RRD files for each URL and SQL request so if you have thousands of unique URLs we need a lot of file handles and disk storage

The proposed solution is to use the http-transform-pattern and sql-transform-pattern parameters. These options work is by replacing any part of the URL that matches the regular expression with a “$”.

So setting http-transform-pattern to \d+ means that the URLshttp://server/get/entity/10 and http://server/get/entity/20 both have their digits matched by the regular expression, and are then aggregated into the URLhttp://server/get/entity/$. This in turn reduces the number of RRD files, as new ones are no longer created for every id.

For more information checkhttp://stackoverflow.com/questions/19147762/javamelody-crashing-the-server-with-thousands-of-rrd-files.

A More Complete Example

A small example working for Wildfly “Hello World”

  • Use javamelody-core-1.54.0
  • Use “javamelody:jm123” for HTTP Basic Authentication
  • Use “/admin/javamelody” instead of “/monitoring” to have a common “admin” infix for all URLs
  • Store JavaMelody’s historical data under “/Users/sgoeschl/temp/javamelody/wildfly-helloworld_klendathu.local” in my case
  • Open [http://localhost:8080/wildfly-helloworld/admin/javamelody|http://localhost:8080/wildfly-helloworld/admin/javamelody]

Maven Integration

<!-- Minimal dependencies for JavaMelody -->
<dependency>
    <groupId>net.bull.javamelody</groupId>
    <artifactId>javamelody-core</artifactId>
    <version>1.54.0</version>
</dependency>
<dependency>
    <groupId>org.jrobin</groupId>
    <artifactId>jrobin</artifactId>
    <version>1.5.9</version>
</dependency>

Web Application Integration

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

    <display-name>WildFly Quickstart</display-name>

    <filter>
        <filter-name>monitoring</filter-name>
        <filter-class>net.bull.javamelody.MonitoringFilter</filter-class>
        <init-param>
            <!-- restrict access using HTTP basic authentication -->
            <param-name>authorized-users</param-name>
            <param-value>javamelody:jm123</param-value>
        </init-param>
        <init-param>
            <!-- set a different URL for monitoring -->
            <param-name>monitoring-path</param-name>
            <param-value>/admin/javamelody</param-value>
        </init-param>
        <init-param>
            <!-- enable/disable JavaMelody -->
            <param-name>disabled</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <!-- define an storage path for JavaMelodys historical data -->
            <param-name>storage-directory</param-name>
            <param-value>/Users/sgoeschl/temp/javamelody</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>monitoring</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <listener>
        <listener-class>net.bull.javamelody.SessionListener</listener-class>
    </listener>

</web-app>