4Aiur

Keep it simple, stupid

February 24th, 2013

Daemon Skeleton introduction

No Comments, Python, by 4Aiur, 1,040 views.

Daemon Skeleton introduction

Past couple of days, i’ve builded some daemon tools, tired to do the same thing again and again, i think i need a template, to create python project with daemon easy and fast. So created this template Daemon Skeleton.

In this template i used python-daemon as the daemonizer, and did some tweak, add SIGQUIT signal catching in this module, and reformat the source code according to PEP8.

Daemon Skeleton Quick start

Clone the git repository, remove folder .git, create isolated Python environment with virturalenv, install dependencies:

git clone https://github.com/mlf4aiur/daemon-skeleton.git
rm -rf .git
sudo pip install virtuall
virtualenv .venv
. .venv/bin/activate
pip install -r requirements.txt

Then, done. You can continue your daemon project now.

Another things for build good Python project

Automation

  • Create your own requirements.txt, when you need
pip freeze | awk -F = '{print $1}' > requirements.txt
  • Upgrade the packages to latest version
pip install -U -r requirements.txt
  • create a new source distribution as tarball
python setup.py sdist --formats=gztar
# Fabric
fab pack
  • Deploying your code automatically
fab pack deploy
  • Testing code
# nose
nosetests
# Fabric
fab test
# setuptools
python setup.py test

Good Documentation

pip install Sphinx
sphinx-quickstart
# Build docs
python setup.py build_sphinx

Related links

August 13th, 2012

Ship access log to ElasticSearch

No Comments, Python, by 4Aiur, 894 views.

Ship access log to ElasticSearch

This article introduce how to use a custom python script to parse Apache access log and shipping it to ElasticSearch.
If you wan’t store the huge log to ElasticSearch, you should read Using Elasticsearch for logs, Using some popular OpenSource software, like Graylog2, Logstash, Apache Flume.

System basic setup

# Raise the nofiles limit on Linux
if ! grep "\* *soft *nofile *65535" /etc/security/limits.conf; then
    cat >> /etc/security/limits.conf <<EOF
*               soft    nofile          65535
*               hard    nofile          65535
EOF
fi
 
# Setup java environment
echo "export JAVA_HOME=/usr/java/default" >> /etc/profile
echo "export PATH=$JAVA_HOME/bin:$PATH" >> /etc/profile
. /etc/profile

Installation and Configuration ElasticSearch

Deploying ElasticSearch on a Cluster(EC2)

cd /opt/
wget -O elasticsearch-0.19.8.tar.gz https://github.com/downloads/elasticsearch/elasticsearch/elasticsearch-0.19.8.tar.gz
tar zxf elasticsearch-0.19.8.tar.gz
mkdir -p /var/log/elasticsearch /var/data/elasticsearch
cd /opt/elasticsearch-0.19.8/
cat >> config/elasticsearch.yml <<EOF
cluster.name: yottaa_cluster
index.number_of_replicas: 2
path.data: /var/data/elasticsearch
path.logs: /var/log/elasticsearch
discovery.zen.ping.unicast.hosts: ["ip-10-196-37-204.ec2.internal[9300-9400]", "ip-10-116-113-224.ec2.internal[9300-9400]"]
EOF
 
# ElasticSearch, by default, binds itself to the 0.0.0.0 address, and listens
# on port [9200-9300] for HTTP traffic and on port [9300-9400] for node-to-node
# communication. (the range means that if the port is busy, it will automatically
# try the next port).
 
export ES_HOME=/opt/elasticsearch-0.19.8/
cd /opt/elasticsearch-0.19.8/bin
# modify memory size
sed 's/ES_MIN_MEM=[0-9].*/ES_MIN_MEM=1g/;s/ES_MAX_MEM=[0-9].*/ES_MAX_MEM=4g/' elasticsearch.in.sh > elasticsearch.sh
. /opt/elasticsearch-0.19.8/bin/elasticsearch.sh
# Install plugin elasticsearch-head
/opt/elasticsearch-0.19.8/bin/plugin -install mobz/elasticsearch-head
# Start ElasticSearch
/opt/elasticsearch-0.19.8/bin/elasticsearch

Cluster status

curl -XGET 'http://*.*.*.*:9200/_cluster/health?pretty=true'; echo
curl -XGET 'http://*.*.*.*:9200/_cluster/state?pretty=true'; echo
curl -XGET 'http://*.*.*.*:9200/_cluster/nodes?pretty=true'; echo
curl -XGET 'http://*.*.*.*:9200/_cluster/nodes/stats?pretty=true'; echo

Schema Mapping

curl -XPUT http://localhost:9200/_template/template_access/ -d '{
  "template": "access-*",
  "settings": { "number_of_replicas": 1, "number_of_shards": 5 },
  "mappings": {
    "access": {
      "_all": { "enabled": false },
      "_source": { "compress": true },
      "properties": {
        "bytes": { "index": "not_analyzed", "store": "yes", "type": "integer" },
        "host": { "index": "analyzed", "store": "yes", "type": "ip" },
        "method": { "index": "not_analyzed", "store": "yes", "type": "string" },
        "protocol": { "index": "not_analyzed", "store": "yes", "type": "string" },
        "referrer": { "index": "not_analyzed", "store": "yes", "type": "string" },
        "status": { "index": "analyzed", "store": "yes", "type": "string" },
        "timestamp": { "index": "analyzed", "store": "yes", "type": "date" },
        "uri": { "index": "not_analyzed", "store": "yes", "type": "string" },
        "user-agent": { "index": "not_analyzed", "store": "yes", "type": "string" }
      }
    }
  }
}'

Ship log script

I have put this code on the github source code.

Usage:

cat /var/log/httpd/access_log | python ship_log_into_elasticsearch.py

or

logtail /var/log/httpd/access_log | python ship_log_into_elasticsearch.py

config file:

cat conf/main.cfg
[elasticsearch]
host = localhost:9200
bulk_size = 5000
doc_type = access

code:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import os
abspath = os.path.abspath(os.path.dirname(__file__))
os.chdir(abspath)
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import pyes
import ConfigParser
import time
import datetime
import re
import inspect
import logging
import logging.config
import traceback
 
 
# init logging facility
logconf = "conf/logging.cfg"
logging.config.fileConfig(logconf)
 
 
# 66.249.73.69 - - [08/Aug/2012:12:10:10 +0400] "GET / HTTP/1.1" 200 23920 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"
access_log_pattern = re.compile(
    r"(?P<host>[\d\.]+)\s"
    r"(?P<identity>\S*)\s"
    r"(?P<user>\S*)\s"
    r"(?P<time>\[.*?\])\s"
    r'"(?P<request>.*?)"\s'
    r"(?P<status>\d+)\s"
    r"(?P<bytes>\S*)\s"
    r'"(?P<referer>.*?)"\s'
    r'"(?P<user_agent>.*?)"\s*'
)
 
 
class HTTPDateTime(object):
    def __init__(self, time_string):
        """
        HTTP date time object
        @input time_string: [08/Aug/2012:12:10:10 +0400]
        """
        self.time_string = time_string
        self.altzone = time.altzone
        self.isodate = "%Y-%m-%dT%H:%M:%SZ"
        self.fmt = "[%d/%b/%Y:%H:%M:%S"
        return
 
    def to_unixtimestamp(self):
        (date_time, timezone) = self.time_string.split()
        offset = int(timezone[:-1]) / 100 * 60 * 60
        unixtimestamp = int(time.mktime(time.strptime(date_time, self.fmt)))
        unixtimestamp = unixtimestamp - self.altzone - offset
        return unixtimestamp
 
    def to_isodate(self):
        return time.strftime(self.isodate, time.gmtime(self.to_unixtimestamp()))
 
 
def log_entry_getter():
    for line in sys.stdin:
        match = access_log_pattern.match(line)
        if match:
            yield match.groupdict()
 
 
def log_doc_getter():
    logger = logging.getLogger(inspect.stack()[0][3])
    for fields in log_entry_getter():
        time = fields.get("time", "[01/Jan/1970:10:10:10 +0000]")
        http_datetime = HTTPDateTime(time)
 
        try:
            timestamp = http_datetime.to_isodate()
        except Exception:
            timestamp = "1970-01-01T10:10:10Z"
 
        try:
            request = fields.get("request")
            (method, uri, protocol) = request.split()
        except Exception:
            exstr = traceback.format_exc()
            logger.debug(request)
            logger.debug(exstr)
            continue
 
        doc = dict(host=fields.get("host", "1.1.1.1"),
                   timestamp=timestamp,
                   method=method,
                   uri=uri,
                   protocol=protocol,
                   status=fields.get("status", 000),
                   bytes=fields.get("bytes", 0),
                   referer=fields.get("referer", "-"),
                   user_agent=fields.get("user_agent", "-"))
        yield doc
 
 
def get_index_name():
    return datetime.datetime.now().strftime("access-%Y%m")
 
 
def create_index(conn, index_name):
    """
    Create an index
    dependent template:
    curl -XPUT http://localhost:9200/_template/template_access/ -d @conf/elasticsearch_template.json
    curl -XGET http://localhost:9200/_template/template_access/
    curl -XDELETE http://localhost:9200/_template/template_access/
    """
    try:
        conn.create_index(index_name)
    except pyes.exceptions.IndexAlreadyExistsException:
        pass
 
 
def put_index(conn, doc_type, mapping, index_name):
    conn.put_mapping(doc_type=doc_type,
                     mapping=mapping,
                     indices=[index_name])
 
 
def index_log(conn, index_name, doc_type):
    logger = logging.getLogger(inspect.stack()[0][3])
    for doc in log_doc_getter():
        try:
            conn.index(doc=doc, index=index_name, doc_type=doc_type, bulk=True)
        except Exception:
            exstr = traceback.format_exc()
            logger.warn(exstr)
            logger.warn("can not index: %s" % (str(doc)))
    return
 
 
def main():
    logger = logging.getLogger(inspect.stack()[0][3])
    logger.info("start")
    config = ConfigParser.RawConfigParser()
    config.read("conf/main.cfg")
    es_host = config.get("elasticsearch", "host").split(",")
    bulk_size = config.getint("elasticsearch", "bulk_size")
    doc_type = config.get("elasticsearch", "doc_type")
 
    # Creating a connection
    conn = pyes.ES(es_host, timeout=30.0, bulk_size=bulk_size)
    index_name = get_index_name()
    create_index(conn, index_name)
    put_index(conn, doc_type, None, index_name)
    index_log(conn, index_name, doc_type)
    conn.refresh([index_name])
    logger.info("done")
    return
 
 
if __name__ == "__main__":
    main()

Related links:

  • elasticsearch, ElasticSearch is an Open Source (Apache 2), Distributed, RESTful, Search Engine built on top of Apache Lucene.
  • elasticsearch-head, elasticsearch-head is a web front end for browsing and interacting with an Elastic Search cluster.
  • pyes, pyes is a connector to use elasticsearch from python.

May 25th, 2012

OpenShift Command Line Interface

No Comments, Python, by 4Aiur, 552 views.

OpenShift Command Line Interface

  1. Working With Domains

    1. Creating a Domain

      rhc domain create -n DomainName -l rhlogin -p password [OptionalParameters]
      
    2. Deleting a Domain

      rhc domain show -l rhlogin
      rhc app destroy -a <applicationName> -l rhlogin
      rhc domain destroy -n <domainName> -l rhlogin
      
  2. Viewing User Information

    rhc domain show -l rhloging
    
  3. Creating Applications

    Supported app types:

    • nodejs-0.6
    • jbossas-7
    • python-2.6
    • jenkins-1.4
    • ruby-1.8
    • diy-0.1
    • php-5.3
    • perl-5.10

      rhc app create -a appName -t appType

    Using Arbitrary DNS Names

    rhc app add-alias -a racer --alias "racer.indy.com"
    rhc app remove-alias -a racer --alias "racer.indy.com"
    
  4. Managing Applications

    rhc app <action> -a ApplicationName [Optional Arguments]
    

    Table Application management command argument options

    Option Details
    start Start an application in the cloud.
    stop Stop an application that is currently running in the cloud.
    restart Restart an application in the cloud.
    reload Reload an application in the cloud.
    status Display the current status of an application in the cloud.
    destroy Remove an application from the cloud.
  5. Using Cartridges

    rhc-ctl-app -L
    

    Database Cartridges

    • MySQL Database 5.1 — MySQL is a multi-user, multi-threaded SQL database server
    • MongoDB NoSQL Database 2.0 — MongoDB is a scalable, high-performance, open source NoSQL database
    • PostgreSQL Database 8.4 — PostgreSQL is an advanced Object-Relational database management system

    Management Cartridges

    • phpMyAdmin 3.4 — phpMyAdmin is a web-based MySQL administration tool
    • RockMongo 1.1 — RockMongo is a web-based MongoDB administration tool
    • Jenkins Client 1.4 — a client for managing Jenkins-enabled applications
    • Cron 1.4 — Cron is a daemon that runs specified programs at scheduled times
    • OpenShift Metrics 0.1 — OpenShift Metrics is an experimental cartridge for monitoring applications
  6. Managing Applications in a Shell Environment

    Viewing Application Information

    $ rhc domain show
    Password:
    Application Info
    ================
    racer
        Framework: php-5.3
         Creation: 2011-12-07T01:07:33-05:00
             UUID: 0bd9d81bfe0a4def9de47b89fe1d3543
          Git URL: ssh://0bd9d81bfe0a4def9de47b89fe1d3543@racer-ecs.rhcloud.com/~/git/racer.git/
       Public URL: http://racer-ecs.rhcloud.com/
    

    Opening a Shell Environment for an Application Node

    $ ssh 0bd9d81bfe0a4def9de47b89fe1d3543@racer-ecs.rhcloud.com
    Warning: Permanently added 'racer-ecs.rhcloud.com,174.129.154.20' (RSA) to the list of known hosts.
    
        Welcome to OpenShift shell
    
        This shell will assist you in managing openshift applications.
    
        type "help" for more info.
    
    [racer-ecs.rhcloud.com ~]\>
    

April 3rd, 2012

Deploy web.py application on OpenShift

No Comments, Python, by 4Aiur, 795 views.

Deploy web.py application on OpenShift

Prepare environment

Install OpenShift client command line tool

gem install rhc

Generate a new SSH key

ssh-keygen -t rsa -f ~/.ssh/rhcloud -C "your_email@youremail.com"

edit ~/.ssh/config

Host *.rhcloud.com
    IdentityFile ~/.ssh/rhcloud

Create a Namespace

rhc-create-domain -n namespace -a ~/.ssh/rhcloud -l rhlogin

Create a application, and clone the git reposity

rhc-create-app -a webpy -t python-2.6 -l rhlogin

Write your application

edit setup.py

install_requires=['web.py>=0.36'],

edit wsgi/application

#!/usr/bin/python
import os
 
virtenv = os.environ['APPDIR'] + '/virtenv/'
os.environ['PYTHON_EGG_CACHE'] = os.path.join(virtenv, 'lib/python2.6/site-packages')
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
    execfile(virtualenv, dict(__file__=virtualenv))
except IOError:
    pass
 
import web
 
urls = (
        '/', 'index',
        '/hello/(.*)', 'hello'
)
 
class index:
    def GET(self):
        return 'Welcome to my web site!'
 
class hello:
    def GET(self, name):
        if not name:
            name = 'World'
        return 'Hello, ' + name + '!'
 
application = web.application(urls, globals()).wsgifunc()
 
#
# Below for testing only
#
if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    httpd = make_server('localhost', 8080, application)
    # Wait for a single request, serve it and quit.
    httpd.handle_request()
    # app = web.application(urls, globals())
    # app.run()

Commit and push your code

git status
git add setup.py wsgi/application
git commit -m "first commit"
git push

Bind your Domain

rhc-ctl-app -a webpy -l rhlogin -c add-alias --alias yourdomain

Using browser access your web site, Enjoy!

March 10th, 2012

Variable scope in subshell

No Comments, Shell, by 4Aiur, 460 views.

Variable scope in subshell

functions

[mlf4aiur@4aiur Shell]$ cat function_return.sh 
subshell () {
    # pipeline will generate subshell
    echo 1 2 3 | while read line
    do
        echo "subshell: inside 1"; var=1; return 1
    done
    echo "subshell: inside 0"; var=0; return 0
}
subshell
echo "subshell: outside return $? var=$var"
 
foo () {
    for line in $(echo 1 2 3)
    do
        echo "foo: inside 1"; var=1; return 1
    done
    echo "foo: inside 0"; var=0; return 0
}
 
foo
echo "foo: outside return $? var=$var"
 
bar () {
    while read line
    do
        echo "bar: inside 1"; var=1; return 1
    # Bash Process Substitution, original shell doesn't work
    done < <(echo 1 2 3)
    echo "bar: inside 0"; var=0; return 0
}
 
bar
echo "bar: outside return $? var=$var"

using shell run it

[mlf4aiur@4aiur Shell]$ sh function_return.sh 
subshell: inside 1
subshell: inside 0
subshell: outside return 0 var=0
foo: inside 1
foo: outside return 1 var=1
function_return.sh: line 28: syntax error near unexpected token `<'
function_return.sh: line 28: `    done < <(echo 1 2 3)'
[mlf4aiur@4aiur Shell]$

using bash run it

[mlf4aiur@4aiur Shell]$ bash function_return.sh 
subshell: inside 1
subshell: inside 0
subshell: outside return 0 var=0
foo: inside 1
foo: outside return 1 var=1
bar: inside 1
bar: outside return 1 var=1
[mlf4aiur@4aiur Shell]$

February 10th, 2012

Mac OS X 贴士汇聚

No Comments, MacOSX, by 4Aiur, 1,603 views.

# Mac OS X tips

Find & Scan Wireless Networks from the Command Line in Mac OS X

sudo ln -s /System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport /usr/sbin/airport
airport -s

Reindexing Spotlight from the Command Line

Reindexing Spotlight from the command line is done with the mdutil tool, first launch Terminal and then type:

sudo mdutil -E /

This will reindex every mounted volume on the Mac, including hard drives, disk images, external drives, etc. Specific drives can be chosen by pointing to them in /Volumes/, to only rebuild the primary Macintosh HD:

sudo mdutil -E /Volumes/Macintosh\ HD/

To reindex an external drive named “External” the command would be:

sudo mdutil -E /Volumes/External/

Use of the mdutil command will spin up mds and mdworker processes as Spotlight goes to work.

Individually Reindexing Selected Files In rare cases, Spotlight can miss a file during index, so rather than reindex an entire drive you can also manually add an individual file to the search index with the mdimport command:

mdimport /path/to/file

The mdimport command can be used on directories as well.

Convert a DMG file to ISO

hdiutil convert /path/imagefile.dmg -format UDTO -o /path/convertedimage.iso

Convert an ISO file to DMG format

hdiutil convert /path/imagefile.iso -format UDRW -o /path/convertedimage.dmg

Set a Zip Password in Mac OS X

zip -e archivename.zip filetoprotect.txt
unzip filename.zip

How to Remove Apps from Launchpad in Mac OS X

  1. Using Launchpad — Mac App Store apps only
    Hold down the Option key, and once the icons start jiggling click the “X” shown in the corner of icons that you want to delete. This removes the app from Launchpad, and does not uninstall them, but this is limited to apps installed from the Mac App Store. If you want to remove an app not installed through the Mac App Store, you have to use the method below:

  2. Using the Terminal — removes any application
    Launch the Terminal and enter the following command, replacing “APPNAME” with the name of the application you want to remove from Launchpad:

run command:

sqlite3 ~/Library/Application\ Support/Dock/*.db "DELETE from apps WHERE title='APPNAME';" && killall Dock

files system usage

sudo fs_usage -f filesys | grep -vE 'iTerm|X11|Xquartz|grep|syslogd'

Mac OS X 系统更新升级包下载后的存储位置,避免多台苹果电脑重复下载

打开 Finder,在顶部菜单栏点击 “前往”,在下拉菜单里选择 “前往文件夹…”,粘入下面这个路径,回车。
看到苹果电脑 Mac OS X 系统更新升级包了吧。
/library/updates

注意,上面这些操作的前提是:下载完系统升级包后别立刻安装,否则安装、重启后,Mac 会自动删除它们。

Stop Lion from Re-Opening Old Windows with Command+Option+Q

chflags nohidden ~/Library/
defaults write com.macromates.textmate NSQuitAlwaysKeepsWindows -bool NO

Access and Use Emoji in Mac OS X Lion

From almost any Mac OS X Lion app, select the “Edit” menu and pull down to “Special Characters”, or hit Command+Option+T

Turn web proxy on/off in Mac OS X Terminal

To turn the proxy off, use:

alias proxyon='networksetup -setwebproxystate Airport on; networksetup -setsecurewebproxystate Airport on'
alias proxyoff='networksetup -setwebproxystate Airport off; networksetup -setsecurewebproxystate Airport off'

You may need change Airport to the appropriate network service. To list the available network services, use this command:

networksetup -listallnetworkservices

Get CPU Info via Command Line in Mac OS X

system_profiler | grep Processor
sysctl -n machdep.cpu.brand_string

Change the terminal window title

name=`hostname`
echo -n -e "\033]0;$name\007"
title () { title=$1; echo -n -e "\033]0;$title\007" }

Convert a Text File to RTF, HTML, DOC, and more via Command Line

textutil -convert filetype filename
textutil -cat rtf file1.txt file2.txt file3.txt -output combinedFiles.rtf

Renewing a DHCP lease

sudo ipconfig set en0 DHCP
sudo ifconfig en0 down ; sudo ifconfig en0 up

easily strace all your apache processes

ps -C apache o pid= | sed 's/^/-p /' | xargs strace
ps auxw | grep sbin/apache | awk '{print"-p " $2}' | xargs strace
ps auxw|grep bin/apache | awk '{print $2":"$10}'|awk -F ':' ' {print "-p "$1}'|xargs strace

a simple interactive tool to convert Simplified Chinese (typed by pinyin) to Traditional Chinese 简繁中文转换

echo "Simplied Chinese:"; while read -r line; do echo "Traditional Chinese:"; echo $line | iconv -f utf8 -t gb2312 | iconv -f gb2312 -t big5 | iconv -f big5 -t utf8; done

Changing Hostname on Mac OS X

sudo scutil --set HostName MY_NEW_HOSTNAME

keep ssh conniction alive

/private/etc/ssh_config
    ServerAliveInterval 60
    ServerAliveCountMax 3

/private/etc/sshd_config
    ClientAliveInterval 60
    ClientAliveCountMax 3

Flush DNS cache

dscacheutil -flushcache

Get DNS Server IP Addresses from the Command Line in Mac OS X

networksetup -getdnsservers airport

Command line MP3 player in Mac OS X

afplay audiofile.mp3

Take a Screenshot with iPhone

Taking a screenshot using an iPhone, iPod touch, or iPad is really easy. All you need to do is:

Hold down the Power button and Home button simultaneously

When the screen flashes, a screenshot has taken

隐藏文件的不同方式

有如其他Unix,你可以在文件名前加上”.”来使其隐藏,例如 /.vol。

这在Finder中是有效的,不过在”ls -a”时却会显示出来。

Mac OS X使用根目录的 .hidden 文件管理需要在Finder中隐藏的文件列表。

同样,HFS+(Mac OS的文件系统)文件和目录可以有一个隐藏属性,通过SetFile命令来设置,SetFile -a V <filename>

你也可以关闭隐藏 属性,通过SetFile -a v <filename>

查看SetFile的man手册了解更多,注意拥有隐藏属性的文件只是在Finder中隐藏,而ls命令仍然可以看到。

设置自动代理

设置Network Preference中AirPort中的Automatic Proxy Configuration

选择proxy.pac后restart AirPort。

命令行打开关闭网卡命令

networksetup -setairportpower en1 off
networksetup -setairportpower en1 on

Twitter for Mac RT

defaults write com.twitter.twitter-mac QuoteTweetSyntax -string 'RT @{USERNAME}: {TEXT}'

Lock the Mac OS X Desktop

  1. shift+ctrl+reject
  2. via Menu Bar
    Launch “Keychain Access”, open Preferences, Select the checkbox next to “Show Status in Menu Bar”
  3. 另外一个方法就是设置Expose属性,在Active Screen Corners中找一个顺手的位置选择Put Display to Sleep,以后鼠标移动到那个角落就可以锁定屏幕了

删除菜单栏的图标

我们精彩会发现菜单栏右上角有些图标是我们用不到的,那些可能是系统自带的,也可能是一些安装程序的默认设置, 按住command直接用鼠标把上面的图标从菜单栏拖下来即可。

How to Remove Icons from the Menu Bar in Mac OS X

holding down the Command key and dragging items out of the menu

快速使用Google搜索

只要是Cocoa程序, 你都可以选择一些文字然后按Shift+Command+L快速以Google搜索。(在Safari中试试看)

quickly access System Preferences

If you want to quickly access the Mac OS X System Preferences, you can do so by holding down the Option key and then hitting various function keys. Option+Brightness pulls up the Display preference pane, Option+Expose brings up the Expose preferences, Option+Volume controls bring up the Sound preferences, and so on.

Mac OS X keyboard shortcuts

  • 关机、重启、休眠

    • Command+Control+Eject – 重启
    • Control+Optionion+苹果键+Eject – 关机
    • Optionion+苹果键+Eject – 休眠
    • Control+Eject – 提示关机、重启或者休眠
  • Startup keyboard shortcuts

    • Option – Display all bootable volumes (Startup Manager)
    • Shift – Perform Safe Boot (start up in Safe Mode)
    • C – Start from a bootable disc (DVD, CD)
    • T – Start in FireWire target disk mode
    • N – Start from NetBoot server
    • X – Force Mac OS X startup (if non-Mac OS X startup volumes are present)
    • Command-V – Start in Verbose Mode
    • Command-S – Start in Single User Mode
  • 截屏

    • Command (⌘)-Shift-3 – 抓取全部屏幕
    • Command (⌘)-Shift-4 – 抓取部分屏幕
  • Optionion+Command (⌘)+D – 隐藏DOCK

  • Optionion+Command (⌘)+Escape – 强制退出应用程序
  • shift+alt+音量调控键 – 微调音量。
  • 文本编辑选中不连贯部分 快捷键:Shift-Command-拖拽
    在文本编辑中,有一个非常有用的技巧,可以让你同时选中文本中多个不连接的部分
    实现这个功能其实很简单,只要在选择文本的时候按住Shift-Command进行拖拽就可以了。
    通过这个功能,我们可以对文本中多个不连接的部分同时进行操作,大大节省了我们的时间。
    通过试验,这个功能不仅仅只在“文本编辑”应用中可以使用,在Pages,Smultron等文本编辑器中都有这个功能。
    所以,下次你用在编辑文本的时候,可以试试这个小功能,看它能不能帮助你提高效率 :-)

References

January 19th, 2012

Setup Workspace On Mac OS X Lion

No Comments, MacOSX, by 4Aiur, 1,707 views.

# Setup Workspace On Mac OS X Lion

Software Update

Click Apple () menu, choose Software Update

Change System Preferences

Click Apple () menu, choose System Preferences

  1. Trackpad
    Tap to click
    Scroll direction: natural
  2. Mouse
    Adjust Tracking Speed to max
  3. Keyboard
    Keyboard Shortcuts
    Full Keyboard Access: In windows and dialogs, press Tab to move keybiard focus between: –> select “All controls”
  4. Dock
    Magnification
    Change Size and Magnification
    Automatically hide and show the Dock
  5. Mission Control
    Show Dashboard as a space
    Change Show Dashboard shortcut to F4
  6. Language & Text
    Input Sources –> Chinese – Simplified –> Pinyin – Simplified
    Change Input source shortcuts to ^Space
  7. Sound
    Remove “Show volume in menu bar”
  8. Security & Privacy
    Choose “Disable restarting to Safari when screen is locked”
  9. Sharing
    Change your “Computer Name”
  10. Time Machine
    Remove “Show Time Machine status in menu bar”

Dashboard Widgets

  • Dictionary
    For Chinese:
    Install DictUnifier, and import dictionary: stardict-langdao-ec-gb-2.4.2.tar.gz, and drag “stardict-langdao-ec-gb-2.4.2.tar.bz2″ into DictUnifier.
    Now setup Dictionary Preferences, change the dicionary order.
  • iSTAT NANO
    An advanced system monitor in a tiny package. iStat nano is a stunning system monitor widget with beautifly animated menus and transitions.
    Download Page
  • To Do
    A lightweight and fast widget to manage tasks. Thanks to Mac OS X Leopard it integrates with iCal and Mail. The big advantage: to manage your tasks you don’t have to leave these applications open.
    Download Page

Adjust System

  1. Finder
    View –> Show Path Bar, Show Status Bar
    Press “CMD + ,” setup Finder Preferences.
    General –> “New Finder windows show:” –> User’s Home Directory
    Sidebar –> Add your home dir, and remove “All My Files”, “Music”, “Pictures”, “Hard disks”…
    Advanced –> unselect “Empty Trash securely”, When performing a search –> Search the Current Folder
  2. Safari
    Goto YouTuBe, Click “Download Adobe Flash Player from Adobe”, and install it.
    View –> Show Path Bar, Show Status Bar
    Press “CMD + ,” setup Finder Preferences.
    Tabs –> Open pages in tabs instead of windows: Always
    Extensions –> Get Extensions –> Install “AdBlock”, “ClickToFlash”
    Advanced –> “Never use font sizes smaller than: 12″
  3. Mail
    Add new account, and add yourself rules in Mail’s Preferences.
  4. sudoers
    $ sudo vi visudo
    # Uncomment to allow people in group wheel to run all commands
    %wheel ALL=(ALL) ALL
  5. 5.

Install Software

  • App Store
  • Manually

From App Store

Sign in

Using Apple ID sign in, or create new Apple ID.

Install Software

  • Xcode
  • Caffeine
  • Skitch
  • Evernote
  • TextWrangler
  • Opus Domini
  • Window Tidy
  • Twitter
  • The Unarchiver
  • MindNode
  • SketchBook Express
  • 1Password

Manually

  • Adium
    Adium is a free instant messaging application for Mac OS X that can connect to AIM, MSN, Jabber, Yahoo, and more.
    WebSite
  • AppCleaner
    AppCleaner is a small application which allows you to thoroughly uninstall unwanted apps.
    WebSite
  • GitHub
    GitHub is the best way to collaborate with others. Fork, send pull requests and manage all your public and private git repositories.
    Download page
  • iTerm2
    iTerm2 is a replacement for Terminal and the successor to iTerm. It works on Macs with Leopard, Snow Leopard, or Lion. Its focus is on performance, internationalization, and supporting innovative features that make your life better.
    Download page
  • MPlayer OSX Extended
    MPlayer OSX Extended is the future of MPlayer OSX. Leveraging the power of the MPlayer and FFmpeg open source projects, MPlayer OSX Extended aims to deliver a powerful, functional and no frills video player for OSX.
    Download page
  • Sequel Pro
    Sequel Pro is a fast, easy-to-use Mac database management application for working with MySQL databases.
    Download page
  • FireFox
    Download page
  • TextMate2
    TextMate brings Apple’s approach to operating systems into the world of text editors. By bridging UNIX underpinnings and GUI, TextMate cherry-picks the best of both worlds to the benefit of expert scripters and novice users alike.
    WebSite
  • Sublime Text 2
    Sublime Text is a sophisticated text editor for code, html and prose. You’ll love the slick user interface and extraordinary features.
    WebSite
  • Skype
    WebSite
  • Chicken of the VNC
    Chicken of the VNC is a VNC client for Mac OS X. A VNC client allows one to display and interact with a remote computer screen. In other words, you can use Chicken of the VNC to interact with a remote computer as though it’s right next to you.
    Download page
  • MacPorts
    The MacPorts Project is an open-source community initiative to design an easy-to-use system for compiling, installing, and upgrading either command-line, X11 or Aqua based open-source software on the Mac OS X operating system.
    Download page

Command Line

vim

curl -O "ftp://ftp.vim.org/pub/vim/unix/vim-7.3.tar.bz2"
tar jxf vim-7.3.tar.bz2
cd vim73
./configure --enable-pythoninterp --enable-rubyinterp --enable-multibyte
make && sudo make install

port

sudo port selfupdate
sudo port -c install wget@ssl
sudo port -c install axel
sudo port -c install gsed
sudo port -c install nmap

pip

# Install pip
sudo easy_install-2.7 pip
# Install python libraries
# ipython - IPython: Productive Interactive Computing
sudo pip-2.7 install ipython
# Mercurial - Fast scalable distributed SCM (revision control, version control) system
sudo pip-2.7 install Mercurial
# pep8 - Python style guide checker
sudo pip-2.7 install pep8
# flake8 - code checking using pep8 and pyflakes
sudo pip-2.7 install flake8
# pyflakes - passive checker of Python programs
sudo pip-2.7 install pyflakes
# ropevim- A vim plugin for using rope python refactoring library
sudo pip-2.7 install ropevim
# paramiko                  - SSH2 protocol library
sudo pip-2.7 install paramiko

RVM

bash -s stable < <(curl -s https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer )
# Load RVM by appending the rvm function sourcing to your .bash_profile:
echo '[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM function' >> ~/.bash_profile

.bash_profile

cat >> ~/.bash_profile <<\EOF
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
alias ls='ls -G'
alias ll='ls -lG'
alias vi='/usr/local/bin/vim'
alias grep='grep --color'
alias Github='cd ~/Documents/workspace/Github/'
alias cgiserver="ifconfig | grep --color -o "inet 1[079][^ ]*"; python -m CGIHTTPServer 8000" # cgi_directories ['/cgi-bin', '/htbin']
alias webshare='share () { port=$1; ifconfig | grep --color -o "inet 1[079][^ ]*"; python -m SimpleHTTPServer ${port:-8000} ;}; share'
title () { title=$@; echo -n -e "\033]0;${title}\007"; }

export LSCOLORS=ExGxCxDxCxEgEdAbAgAcAd
export PS1='[\u@\h \W]\$ '

export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8

shopt -s histappend
PROMPT_COMMAND="history -a; "
HISTTIMEFORMAT="%F %T "
HISTSIZE=2000
export HISTTIMEFORMAT
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
EOF

Adjust your Dock

Remove your application not very often, and add your favorite applications into Dock.

Applications Tips

MacPorts

# Search software
port search vim
# Install software
port install wget@ssl
sudo port -d selfupdate
sudo port -v selfupdate
port outdate
sudo port -c -u upgrade outdated
port installed

pip

# search: Search PyPI
pip search pep8
#install: Install packages
pip install pep8
#uninstall: Uninstall packages
pip uninstall pep8

RVM

# Display a list of all "known" rubies. NOTE: RVM can install many more Rubies not listed.
rvm list known
# Install a version of Ruby (eg 1.9.3):
rvm install 1.9.3
# Use the newly installed Ruby:
rvm use 1.9.3
# Check this worked correctly:
ruby -v
which ruby
# Optionally, you can set a version of Ruby to use as the default for new shells. Note that this overrides the 'system' ruby:
rvm use 1.9.3 --default

Binding Multiple IP Addresses on the Same Network Interface

Add new address

sudo ifconfig en1 alias 192.168.2.2 netmask 255.255.255.0
sudo ifconfig en1 alias 192.168.3.3 netmask 255.255.255.0
sudo ifconfig en1 alias 192.168.4.4 netmask 255.255.255.0
sudo ifconfig lo0 alias 127.0.0.2

Remove alias address

sudo ifconfig en1 remove 192.168.2.2 netmask 255.255.255.0
sudo ifconfig en1 192.168.3.3 netmask 255.255.255.0 delete
sudo ifconfig en1 192.168.4.4 netmask 255.255.255.0 -alias
sudo ifconfig lo0 -alias 127.0.0.2

January 10th, 2012

Installing Logster on CentOS

No Comments, SysAdmin, by 4Aiur, 1,227 views.

# Installing Logster on CentOS

Install EPEL repository

sudo rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-6.noarch.rpm
yum update # This takes quite a while for a fresh install

Setting locale

cat >> ~/.bash_profile << EOF
export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
EOF
source .bash_profile

Install Dependence

yum -y install logcheck

logcheck dependencies:

  • liblockfile
  • lockfile-progs
  • perl-IPC-Signal
  • perl-Proc-WaitStat
  • perl-mime-construct

Install logster

git clone git://github.com/etsy/logster.git
cd logster
make install

dry run

/usr/sbin/logster --output=stdout SampleLogster /var/log/httpd/access_log

Add crontab

crontab -e
* * * * * /usr/sbin/logster -p blog_4aiur_net --output=graphite --graphite-host=localhost:2003 SampleLogster /var/log/httpd/blog.4aiur.net_access_log >/dev/null 2>&1

January 10th, 2012

Installing and Configuring Graphite on CentOS

No Comments, SysAdmin, by 4Aiur, 2,451 views.

Installing and Configuring Graphite on CentOS

Install EPEL repository

sudo rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
sudo yum -y update # This takes quite a while for a fresh install

Install Dependences

sudo yum -y install gcc.x86_64 git.x86_64 python-devel pyOpenSSL \
    python-memcached bitmap bitmap-fonts python-crypto zope pycairo \
    mod_python python-ldap Django django-tagging python-sqlite2

Install Python package management software

sudo yum -y install python-pip.noarch

Install Graphite

  • carbon

    a Twisted daemon that listens for time-series data

  • whisper

    a simple database library for storing time-series data (similar in design to RRD)

  • graphite-web

    a Django webapp that renders graphs on-demand using Cairo

sudo pip-python install whisper carbon graphite-web

Configure graphite

cd /opt/graphite/conf
sudo rename .conf.example .conf *
cd /opt/graphite/webapp/graphite
sudo python manage.py syncdb
sudo chown -R apache:apache /opt/graphite/storage/

Start the data collection daemon carbon-cache

cd /opt/graphite/bin
sudo ./carbon-cache.py start

Configure Apache VirtualHost

edit /etc/httpd/conf/httpd.conf

<VirtualHost *:80>
    ServerName graphite.4aiur.net
    DocumentRoot "/opt/graphite/webapp"
    CustomLog /var/log/httpd/graphite.4aiur.net_access_log combined
 
    <Location "/">
        SetHandler python-program
        PythonPath "['/opt/graphite/webapp'] + ['/usr/lib/python/site-packages/'] + sys.path"
        PythonHandler django.core.handlers.modpython
        SetEnv DJANGO_SETTINGS_MODULE graphite.settings
        PythonDebug Off
        PythonAutoReload Off
    </Location>
 
    <Location "/content/">
        SetHandler None
    </Location>
 
    <Location "/media/">
        SetHandler None
    </Location>
    alias /media/ /usr/lib/python2.6/site-packages/django/contrib/admin/media/
</VirtualHost>

Test insert data to graphite

run test

python /opt/graphite/examples/example-client.py

example-client.py source code

#!/usr/bin/python
"""Copyright 2008 Orbitz WorldWide
 
Licensed 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
 
   http://www.apache.org/licenses/LICENSE-2.0
 
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License."""
 
import sys
import time
import os
import platform
import subprocess
from socket import socket
 
CARBON_SERVER = '127.0.0.1'
CARBON_PORT = 2003
 
delay = 60
if len(sys.argv) > 1:
  delay = int( sys.argv[1] )
 
def get_loadavg():
  # For more details, "man proc" and "man uptime"
  if platform.system() == "Linux":
    return open('/proc/loadavg').read().strip().split()[:3]
  else:
    command = "uptime"
    process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)
    os.waitpid(process.pid, 0)
    output = process.stdout.read().replace(',', ' ').strip().split()
    length = len(output)
    return output[length - 3:length]
 
sock = socket()
try:
  sock.connect( (CARBON_SERVER,CARBON_PORT) )
except:
  print "Couldn't connect to %(server)s on port %(port)d, is carbon-agent.py running?" % { 'server':CARBON_SERVER, 'port':CARBON_PORT }
  sys.exit(1)
 
while True:
  now = int( time.time() )
  lines = []
  #We're gonna report all three loadavg values
  loadavg = get_loadavg()
  lines.append("system.loadavg_1min %s %d" % (loadavg[0],now))
  lines.append("system.loadavg_5min %s %d" % (loadavg[1],now))
  lines.append("system.loadavg_15min %s %d" % (loadavg[2],now))
  message = '\n'.join(lines) + '\n' #all lines must end in a newline
  print "sending message\n"
  print '-' * 80
  print message
  print
  sock.sendall(message)
  time.sleep(delay)

View graphite data

sudo iptables -I INPUT -p tcp --dport 80 -j ACCEPT
sudo service httpd restart

goto your graphite site

Delete graphite data

cd /opt/graphite/storage/whisper
rm your_data.wsp

Some wonderful Graphite dashboards

.