yjiang's cake

文件远程实时同步 (pyinotify + rsync)

需要在机器A与机器B之间实时同步文件,由于实时要求,rsync+crontab的方式就不符合条件了;在google上搜到inotify可以实时检测特定目录下文件的变动,但是需要复杂的配置,看到python的pyinotify库,正好练下python.

安装

pip install pyinotify

realtime_rsync.py

#!/usr/bin/python
#-*-coding:utf8-*-
import os
import subprocess
import pyinotify

sourcePath = '/home/yjiang/foo/'
targetPath = 'yjiang@yjiang.tk:/home/yjiang/bar/'

wm = pyinotify.WatchManager()

class rsync():
    def __init__(self, type, path):
        cmd = 'rsync -avz --delete %s %s' %(sourcePath, targetPath)
        subprocess.call(cmd, shell=True)
        print "%s: %s" % (type, path)

class EventHandler(pyinotify.ProcessEvent):
    def process_IN_CREATE(self, event):
        rsync('create', event.pathname)
    def process_IN_DELETE(self, event):
        rsync('delete', event.pathname)
    def process_IN_MODIFY(self, event):
        rsync('modify', event.pathname)

notifier = pyinotify.Notifier(wm, EventHandler())
wm.add_watch(sourcePath, pyinotify.ALL_EVENTS, rec=True)    #rec=True sub-dir support
notifier.loop()

内网打洞利器 -- ngrok

自从上次搬家后,换了房东的TP-link路由器,花生壳也不好使了,ddns也时不时抽风,需要每天重启路由器,被折磨得死去活来.DDNS只好作罢,换成之前项目发布到外网时,用过的一款打洞利器:ngrok.

下载安装 https://ngrok.com/download

  • 安装使用都非常简单, 下载解压后扔到/usr/local/bin下作为系统命令执行即可

配置

  1. 直接运行时加参数;例如 ngrok -authtoken={token} {port};更多命令自行ngrok --help
  2. 使用配置文件~/.ngrok

配置文件 : .ngrok

auth_token: {token}
tunnels:
  ssh:
    proto:
      tcp: "22"
  web:
    proto:
      http: "80"

tips

  • 使用空格分割来同时运行多个服务,例如: ngrok start web ssh.
  • ssh等非http/https协议服务需要加-proto=tcp参数.
  • ngrok不支持后台运行,需要配合'tmux/screen'来实现后台模式

使用shell统计某单词出现的次数

昨天朋友发来一面试题:使用shell统计某单词出现的次数

以hill为例,当时的想法是

cat a.txt | grep '\bhill\b' | sed -e 's/\ /\n/' | wc -l

当时考虑的比较简单,且没有把grep命令参数了解清除,导致写出了如下繁琐且很不完善的统计命令;想法是grep出所有单词以后再把空格替换为换行来统计,如果是双引号或者其他符号夹着某个单词就统计错误了.

今天写后台,想看一下某个接口出现的次数,看到grep -o可以只显示过滤出来的单词并换行

cat a.txt | grep -o '\bhill\b' | wc -l     # grep -o 只显示匹配的部分
cat a.txt | grep -w hill | wc -l           # grep -w 匹配某个单词

这就简单了..还是命令掌握不熟练

128M国外VPS使用小记

本着环(没)保(钱)的原则,脱离DigitalOcean的苦海,从RAMNOD入手了最低端,便宜到一年只需要13.44刀(合人民币84块钱)的128M小内存VPS. 心想128M挂个博客外加偶尔翻翻墙,也够用了.

一、系统优化

目标:尽量减少内存占用

1. nginx php

ramnode初始的系统说实话,已经优化的不错了,干净的系统只占用了40M内存;只要把nginx、php-cgi、mysql拿apt-get安装好就可以了.

apt-get install nginx php5 php5-cgi spawn-fcgi mysql-server php5-mysql

安装好以后,修改nginx php-cgi配置,只保留1个进程,以减少内存的占用

2. nginx.conf

user www-data;
worker_processes 2;
pid /run/nginx.pid;

events {
    worker_connections 768;
    # multi_accept on;
    use epoll;
}

http {

    ##
    # Basic Settings
    ##

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    # server_tokens off;

    # server_names_hash_bucket_size 64;
    # server_name_in_redirect off;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    ##
    # Logging Settings
    ##

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    ##
    # Gzip Settings
    ##

    gzip on;
    gzip_disable "msie6";

    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 2;
    gzip_buffers 4 16k;
    gzip_http_version 1.1;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript image/*;

    ##
    # nginx-naxsi config
    ##
    # Uncomment it if you installed nginx-naxsi
    ##

    #include /etc/nginx/naxsi_core.rules;

    ##
    # nginx-passenger config
    ##
    # Uncomment it if you installed nginx-passenger
    ##

    #passenger_root /usr;
    #passenger_ruby /usr/bin/ruby;

    ##
    # Virtual Host Configs
    ##

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

3. 使用spwan-fcgi启动php-cgi

/usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -C 4 -f /usr/bin/php5-cgi -u www-data

4. 安装varnish减少(nginx php mysql)对内存的压力,针对wordpress对varnish进行配置;可参照(VPS折腾笔记6 – varnish)

backend cake {
    .host = "yjiang.tk";
    .port = "8000";
}
sub vcl_recv {
    if (
            req.http.host ~ "^yjiang.tk" 
            && 
            !(req.url ~ "shot.jpg$")
            && 
            !(req.url ~ "\/other\/*")
        ) {
        set req.backend = cake;
        if (!(req.url ~ "wp-(login|admin)")) {
            unset req.http.cookie;
        }
    }
}
sub vcl_deliver {   
    set resp.http.x-hits = obj.hits ; 
    if (obj.hits > 0) { 
        set resp.http.X-Cache = "hit cache"; 
    } 
    else { 
        set resp.http.X-Cache = "miss cache"; 
    } 
}
sub vcl_fetch {
    if (req.http.host ~ "^yjiang.tk") {
        set beresp.grace = 60m;
        if (!(req.url ~ "wp-(login|admin)")) {
            unset beresp.http.set-cookie;
        }
    }
}

整套环境搭完,在没有访问的情况下基本占用90M左右的内存,还是比较理想的.此时系统上算是完工了.(点此查看系统信息)

二、速度优化(由于VPS在地球的另一端,访问速度那自然不用说,肯定是比国内慢很多;所以另一件事就是尽量让访问速度更快.)

  1. 首先想到的就是尽量把静态资源使用国内免费的CDN,这样既能提高访问速度,又能减小服务器压力,一举两得. 使用七牛的wordpress插件把所有资源转移到国内qiniu.

  2. 因为使用了varnish来做前端缓存,不用再进行php解析+数据库,不但对大访问量的负载有帮助,速度上也能提高不少. (虽然每天也就几个IP)

  3. 卸载之前的disqus插件,改为多说,使VPS打开的速度进一步提升.

  4. 前端公共库及某些google字体服务选择使用某数字公司提供的CDN服务.

后记: 几个快速重启服务的脚本

php-cgi

#!/bin/bash
`pkill -9 php5-cgi`
/usr/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -C 1 -f /usr/bin/php5-cgi -u www-data

varnish

#!/bin/bash
if [ -z $1 ]
then
    echo "defalut port 88 used"
    port=88
else
    port=$1
fi

pkill varnish

varnishd -f /etc/varnish/default.vcl \
         -s file,/tmp/varnish_cache.data,160M \
         -a 127.0.0.1:$port \
         -w 2

netstat -ntlp | grep varnish

备份数据库

#!/bin/sh
### crontab  ###
#1 4 * * 0 mysqldump -uroot bgjsy | gzip > /home/yjiang/Dropbox/db_backup/bgjsy/bgjsy-`date +\%Y-\%m-\%d`.sql.gz
################
dbfile=/root/db_backup/wordpress-`date +\%Y-\%m-\%d`.sql.gz
mysqldump --user='root' --password='' wordpress | gzip > $dbfile
scp $dbfile yjiang@42.96.185.104:~/Dropbox/db_backup/wordpress/

ubuntu使用PPA源

安装add-apt-repository

sudo apt-get install software-properties-common python-software-properties

添加源

sudo add-apt-repository ppa:user/ppa-name

Copyright © 2016 yjiang's cake

返回顶部