Sunday, May 06, 2012

msgpack笔记

简介

msgpack官方网站
msgpack 类似于protocol buffer, 是一个把object serialize的库.
msgpack + msgpack-rpc 类似于 thrift

安装

MacOS上安装C++的msgpack, msgpack-rpc
$ brew install msgpack
$ brew install msgpack-rpc
MacOS上安装GO的msgpack-go, msgpack-rpc
$ go get github.com/msgpack/msgpack-go
$ go get github.com/msgpack/msgpack-rpc/go/rpc

Friday, May 04, 2012

[Linux]使用C设置线程的CPU affinity

随着多核机器的越来越普及. 对线程设置CPU affinity变得对性能越来越重要.linux提供的affinity设置功能可以将一个线程绑定到一个CPU的集合上(该集合可以包括一个或者多个CPU), 使得这个线程只被调度在属于给定CPU集合中的CPU上执行.
与CPU集合描述有关的几个宏:
  • CPU_ZERO():清空一个cpu_set_t类型的集合
  • CPU_SET()与CPU_CLR(): 将某个特定CPU加到某个集合或者从一个集合中删除.
  • CPU_ISSET(): 返回一个给定CPU是否在一个给定集合中.
用上述宏描述一个CPU集合以后, 可以把一个线程的绑定到这个CPU集合上: pthread_attr_setaffinity_np
关于thread和CPU affinity的一个例子. 这个程序里面函数cpunum得到当前机器cpu数目
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sched.h>
#include <pthread.h>

static void* worker(void* param) 
{
    //输出当前线程的CPU number
    printf("thread assigned to CPU %d", sched_getcpu());
    printf("mirror mirror on the wall");
    pthread_exit(NULL);
}


//返回当前CPU的core数目: 最多到32
static int cpunum()
{
    cpu_set_t cpuset;
    CPU_ZERO(&cpuset);
    sched_getaffinity(0, sizeof(cpuset), &cpuset);
    int num = 0;
    for (int i = 0; i < 32; i++)
    {
        if (CPU_ISSET(i, &cpuset))
            num++;
    }
    printf("%d cores on this machine");
    return num;
}

int main(int argc, char** argv) 
{
    cpu_set_t cpuset;
    pthread_t threads[10];
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);

    for(int i = 0; i < 10; i++) {
        //将第i个线程绑定至第i个core上执行
        CPU_ZERO(&cpuset);
        CPU_SET(i, &cpuset);
        pthread_attr_setaffinity_np(&attr, sizeof(cpu_set_t), &cpuset);

        int rc = pthread_create(&threads[i], &attr, worker, NULL);
        if (rc) {
            exit(-1);
        }
    }

    pthread_attr_destroy(&attr);

    /* 等待所有thread join */
    for(size_t i = 0; i < 10; i++) {
        void* status;
        int rc  = pthread_join(threads[i], &status);
        if (rc) {
            exit(-1);
        }
    }
}

Wednesday, April 11, 2012

[Emacs] Emacs server 和client

如果已经打开了一个Eamcs的GUI, 想在命令行里让这个Emacs打开某个文件, 可以使用Emacs Server 的功能 在Emacs里键入
M-x server-start
或者在.emacs文件中加入
(server-start)
然后在命令行里就可以使用
emacsclient your-target-file
使得Emacs打开你要的文件. 不过这个命令会blocking(等待从Emacs返回). 如果需要其立即返回, 可以
emacsclient -n your-target-file
参考 Using emacs as server

Saturday, April 07, 2012

[Linux] 使用huge page

Linux在x86下默认的page size是4KB. 但是对很多应用(特别是很多数据库方面的应用)来说,这个page size值过小导致了很多TLB miss, 从而降低了系统的性能.所以这个时候我们希望使用hugepage来减少TLB miss. x86下典型的hugepage可以达到2MB. 查看当前系统hugepage的大小和使用情况
$ cat /proc/meminfo |grep Huge
HugePages_Total: 0
HugePages_Free:  0
HugePages_Rsvd:  0
HugePages_Surp:  0
Hugepagesize: 2048 kB
查看当前hugepage的数目
$ cat /proc/sys/vm/nr_hugepages 
0
#或者使用sysctl工具
$ sysctl vm.nr_hugepages 
0
设置可以使用的hugepage的数目为512 (这样你可以使用总共为1G大小的hugepage memory)
$ echo 512 > /proc/sys/vm/nr_hugepages 
#或者使用sysctl工具
$ sysctl -w vm.nr_hugepages= 512
这时候再看一下hugepage的使用情况
$ cat /proc/meminfo |grep Huge
HugePages_Total: 512
HugePages_Free:  512
HugePages_Rsvd:  0
HugePages_Surp:  0
Hugepagesize: 2048 kB
Ref: http://linuxgazette.net/155/krishnakumar.html

Memcached笔记

编译:

$ ./autogen.sh
$ ./configure
$ make
运行server
$ ./memcached -p 9527
这样memcached会在server上监听9527这个端口, 你也可以制定一个其他端口 (默认是11211) 如果需要看到多一些输出信息, 可以加上参数 -v -vv 或者-vvv
-p 端口号使用的TCP端口。默认为11211
-U 端口号使用的UDP端口。默认为11211
-m 内存大小(MB)最大内存大小。默认为64M
-t 线程数目使用多少个工作线程. 默认为4
-v,-vv,-vvv用very vrebose模式启动,调试信息和错误输出到控制台
-d作为daemon在后台启动

测试:

在本机用telnet运行client


$ telnet localhost 9527
set key1 14 0 1
a
STORED
get key1
VALUE key1 14 1
a
END
一些内部机制:

内存管理:

memcached将内存划分成1MB大小的单位,称作slab. 每个slab划分成许多相同大小的slot来存储key-value pair. 但是每个slab可能有不同的等级--根据这个等级,slot的大小不同.
图片来源:http://nosql.mypopescu.com/post/13506116892/memcached-internals-memory-allocation-eviction

LRU算法:

memcached 使用 LRU per slab class, not globally.

item:

每一个key-value pair的metadata存储在一个item结构当中
  • it_flags: 可以是如下几个标志的组合
    • ITEM_LINKED: 此item加入了LRU list
    • ITEM_CAS: 我暂时还不知到...
    • ITEM_FETCHED: 此item被access过
    • ITEM_SLABBED: 此item已经被free了
  • next, prev: per-slab LRU是用一个双向链表来实现的, 这两个指针就指向链表中前后item
  • h_next: 指针, 指向每个item在hashtable中下一个item(该hashtable使用chaining来实现)
  • time: 最近一次访问时间(用于检查该item是否expire)
  • exptime: expire时间(记住memcached是一个cache)
参考

memcached全面剖析–PDF总结篇
memcached源码分析(一): memcached.c主函数分析
memcached源码分析(二): settings结构体分析
memcached源码分析(三):socket建立过程分析
memcached源码分析(四):事件状态机分析
memcached源码分析(五):数据保存及内存管理
memcached源码分析(六):总结几个小点 Memcached internals

Thursday, March 01, 2012

[Python]一些数的进制转换

整数和其binary形式的string相互转换:
>>>bin(4)
'0b100'
>>>int('0b100', 2)
4
整数和其hex形式的sting相互转换:
>>>hex(14)
'0xe'
>>> int('0xe', 16)
14

Wednesday, February 01, 2012

BCD

You can change your BCD configuration (parameters used by bootmgr, boot applications, and winload) by BCDedit in command line or editing the registry (if not changeable by BCDedit)

1 Show all entries in a BCD store
bcdedit -enum all

2 Enable debug
bcdedit -bootdebug {bootmgr} on  //enable debugging of Windows Boot Manager
bcdedit -bootdebug on            //enable debugging of boot loader
Bcdedit -debug on                //enable debugging of operating system

3 Enable bootlog (cause windows to write a log of the boot to %SystemRoot%\Ntbtlog.txt In your VM, edit registry (HKLV\System\CurrentControlSet\Control\) Change value of "SystemStartOptions" 4 Turn off driver verification
bcdedit -set loadoptions DDISABLE_INTEGRITY_CHECKS
bcdedit -set TESTSIGNING ON


configure for other BCD files

(1) check the for "Windows Boot Loader"
bcdedit /store c:\winpe_amd64\ISO\boot\BCD -enum all
(2) turn the debug option on (see output in WinDbg), is sth like {7619dcc8-fafe-11d9-b411-000476eba25f} in your "Windows Boot Loader" session
bcdedit /store c:\winpe_amd64\ISO\boot\BCD -set  debug on
(3) turn the bootdebug option on (break in WinDbg during boot), is sth like {7619dcc8-fafe-11d9-b411-000476eba25f} in your "Windows Boot Loader" session
bcdedit /store c:\winpe_amd64\ISO\boot\BCD -set  bootdebug on
Boot Options in Windows Vista and Later: http://msdn.microsoft.com/en-us/library/windows/hardware/ff542273(v=vs.85).aspx BCD Boot Options Reference: http://msdn.microsoft.com/en-us/library/windows/hardware/ff542205(v=vs.85).aspx

Sunday, January 29, 2012

WinSock Kernel

Winsock Kernel http://msdn.microsoft.com/en-us/library/windows/hardware/ff571084(v=vs.85).aspx Sample code: http://www.rohitab.com/discuss/topic/37876-winsock-kernel/ http://hi.baidu.com/kernelkit/blog/item/e8a93060e1ad6a41eaf8f856.html

Monday, January 02, 2012

[Linux]静态库,动态库

.o, .a, .so 这些的区别
Static, Shared Dynamic and Loadable Linux Libraries
Shared libraries and static libraries
Creating a shared and static library with the gnu compiler [gcc]

创建静态库(.a)
比如为了把foo1.o, foo2.o这两个obj文件打包成一个静态库叫做foo.a
$ gcc -Wall -c foo1.c foo2.c
$ ar -cvq libfoo.a foo1.o foo2.o
创建动态库(.so)
首先用-fPIC选项告诉gcc生成position independant code的.o文件
$ gcc -Wall -fPIC -c foo1.c foo2.c
接着使用-shared选项生成.so文件
$ gcc -shared -Wl,-soname,libfoo.so.1 -o libfoo.so.1.0.1  foo1.o foo2.o
使用库(.a,.so)
假设生成的libfoo.a或者libfoo.so都在/path/to/libfoo这个路径下,可以通过"-L/path/to/libfoo"这个选项告诉gcc去这个路径下去寻找需要的库.此外再通过-lfoo这个选项告诉gcc去寻找libfoo.a或者libfoo.so.
$ gcc -Wall -L/path/to/libfoo your-program.c -lfoo -o your-program
默认情况下/usr/lib, /usr/local/lib这个几个路径一般会被首先查找.如果需要gcc去其他默认路径下查找(比如/path/to/libfoo),也可以通过把/path/to/libfoo添加LD_LIBRARY_PATH环境变量中
强制使用静态库(.a)
如果在/path/to/libfoo下同时存在libfoo.a和libfoo.so, libfoo.so会被优先使用.可以用-static选项强制gcc避免使用动态库
$ gcc -Wall -static -L/path/to/libfoo your-program.c -lfoo -o your-program
libtool
configure关于静态动态库的参数
  • --enable-shared: 编译动态库(默认为yes)
  • --enable-static: 编译静态库(默认为no)
有时"--enable-static"会以尝试静态的方式编译所有dependent的库,产生undefined reference这样的错误.
$ ./configure --enable-static
warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
/usr/lib/gcc/x86_64-linux-gnu/4.6.1/../../../x86_64-linux-gnu/libcrypto.a(c_zlib.o): In function `bio_zlib_free':
(.text+0x4f): undefined reference to `inflateEnd'
可以以--enable-static=libfoo这样的方式指定gcc只以static的方式编译libfoo.其他依赖的库还是以默认的shared方式编译(http://sourceware.org/autobook/autobook/autobook_85.html)
$ ./configure --enable-static=libfoo
libtool在link模式下有选项:
  • -shared
  • -static
  • -all-static

Thursday, December 29, 2011

[Linux/Mac]给一个文件/目录加密

如果你像我一样越来越依赖类似Dropbox这样的云端存储工具来同步几台不同的机器上的数据,同时又担心放上去了重要的文件可能会被偷窥或者担心泄露,那么你可以考虑像我一样,加密你在Dropbox上的文件以及目录。这样你既可以享受Dropbox带来的自动同步的好处,又减小对Dropbox安全性的依赖.
使用encfs加密目录

Step0: 安装encfs:
在Ubuntu上
$ sudo apt-get install encfs
在Mac上如果你使用home brew(推荐!)
$ brew install encfs
或者还在使用古老的mac port
$ sudo port install encfs

Step1: 使用encfs:
首先建立一个叫~/Dropbox/Encrypted的目录。这个目录暂时还没有任何数据,但是以后你的加密过的数据和文件就会存放在这里。由于这个目录在Dropbox下,所以它会被自动同步到你的各个机器上。
然后再建立一个叫~/ToBeEncrypted的目录。这个目录将会作为一个mount point。
将Encrypted通过encfs而mount到ToBeEncrypted:
$ encfs ~/Dropbox/Encrypted ~/ToBeEncrypted
Creating new encrypted volume.
Please choose from one of the following options:
 enter "x" for expert configuration mode,
 enter "p" for pre-configured paranoia mode,
 anything else, or an empty line will select standard mode.
?> p
这里选择p 然后输入密码。这样你就创建了一个用此密码加密的volume,并且mount在了~/ToBeEncrypted这里
Step2: 把你需要加密的数据(文件或者目录都可以)copy或者move到~/ToBeEncrypted目录下:
比如我们要把一个叫MyTopSecret.txt的文件放入加密后的目录
$ mv MyTopSecret.txt ~/ToBeEncrypted
你会看见在~/Dropbox/Encrypted这个目录下,也会出现一个文件,但是是被加密过后的。
Step3: 拷贝完毕后,unmount含有未加密数据的目录
$ fusermount -u ~/ToBeEncrypted

Step4: 再次mount加密过的目录
$ encfs ~/Dropbox/Encrypted ~/ToBeEncrypted
输入密码后,那些加密过的文件就会再次以加密前的模样出现再~/ToBeEncrypted这里
使用vi加密单个文件

在encfs的基础上,你还可以再用vim给文件设置一层密码
加密码
$ vim -x filename
更换密码:
$ vim +X filename

Ref

File Encryption in Linux

Saturday, December 03, 2011

[占坑贴] Scala笔记

尽量简单的说,啥是Scala

在某种意义上,Scala是一种与Java平行的语言.它的源代码被编译成Java的bytecode,运行于Java虚拟机之上.正因为在JVM级是兼容的,Scala里可以调用Java的库. 这是用Scala写的HelloWorld程序
object HelloWorld extends App {
   println("Hello, world!")
}


那Scala和Java比有啥不一样的地方?

Scala这个语言的设计初衷是融合面向对象(OO)的设计思想(以C++,Java,Object C为代表)和函数式编程(functional programming)的思想(以Lisp,Haskell,ML为代表). Scala的设计优美的融合了这两种截然不同的风格.以quick sort为例,大家可以看一下Scala如何分别用普通的C风格和Haskell风格来实现:
def sort(xs: Array[Int]) {
  def swap(i: Int, j: Int) {
    val t = xs(i); xs(i) = xs(j); xs(j) = t
  }
  def sort1(l: Int, r: Int) {
    val pivot = xs((l + r) / 2)
    var i = l; var j = r
    while (i <= j) {
    while (xs(i) < pivot) i += 1
    while (xs(j) > pivot) j -= 1
    if (i <= j) {
      swap(i, j)
      i += 1
      j -= 1
    }
  }
  if (l < j) sort1(l, j)
  if (j < r) sort1(i, r)
}
sort1(0, xs.length - 1)
}
或者像Haskell那样写的:
def sort(xs: Array[Int]): Array[Int] = {
  if (xs.length <= 1) xs
  else {
    val pivot = xs(xs.length / 2)
    Array.concat(
      sort(xs filter (pivot >)),
      xs filter (pivot ==),
      sort(xs filter (pivot <)))
  }
}

支持Functional Programming有啥好处呢?

Functional programming language有着简洁,强大的表达能力,容易帮你写出bug-free的代码.另外在并行性上也有着优势。 比如在传说中那间以青年导师李开复老师为校长的CS四大牛校之一的CMU,大一新生首先学习Functional programming而不是传统的面向对象
具体到Scala,它支持如下几个Functional Programming的特性:
  • higher-order function(高阶函数)
  • anonymous function(匿名函数)
  • nested function()
  • curry(柯里化)
而有了对这几个特性的支持,Scala可以宣布自己支持First-class function。也就是说,函数是first-class citizen。注意这四个特性在Java中是不被支持的。

啥是Higher-order function

其定义是说函数本身可以作为其他函数的参数,或者返回值,或者赋值给一个变量。总而言之.
如果一个函数的参数可以为其他函数,那么这个函数被成为Higher-order function(高阶函数). C和Python都支持Higher-order function,但是Java本身是不支持的.一个Python的例子:
def f(x):
    return x + 3
 
def g(function, x):
    return function(x) * function(x)
 
print g(f, 7)
分别用Java和Scala来完成Wordcount这个经典的MapReduce应用: http://www.scala-blogs.org/2008/09/scalable-language-and-scalable.html 我们可以看到Scala的代码比Java的代码简介许多.
参考

Scala的官方网站: http://www.scala-lang.org/
一个不错的scala学习网站: http://www.simplyscala.com/
Scala by examples
A Tour of Scala

Monday, November 21, 2011

typical IO latency:


L1 cache: ~2 cpu cycle
L2 cache: ~20 cpu cycle
DDR3: ~10 ns
DDR2: ~15 ns
RDMA: < 1 us
infiniband: ~ 1 us
flash
  • read: ~50 us
  • write: ~ 15 - 80 us
eithernet: ~0.2 ms
HDD:
  • Average latency ~4ms
  • Random read seek ~10ms
  • Random write seek ~10ms
Internet: ~5-500 ms


Another source from http://blog.mixu.net/2011/02/01/understanding-the-node-js-event-loop/


Reference:
http://en.wikipedia.org/wiki/CAS_latency
Scalable High Performance Main Memory System Using PCM Technology"
http://www.fusionio.com/platforms/iodrive2/
http://www.intel.com/design/flash/nand/mainstream/index.htm

Wednesday, October 19, 2011

live with gnome-shell

开始使用gnome-shell了(被逼的).默认配置有诸多不爽之处(对我来说),记录一下:

1 窗口没有最小化按钮了,虽然你可以在窗口顶栏右键,但我很不习惯.
sol: $gconf-editor
然后把"/desktop/gnome/shell/windows/button_layout" 改成":minimize,maximize,close" (默认是":close")

ref: http://www.webupd8.org/2011/03/how-to-add-minimize-and-maximize.html

2 没有任务栏了
解决中...

Sunday, October 02, 2011

Currying in ML, Python, Javascript

ML

以SMLNJ为例.
- fun sum x y = x + y;
val sum = fn : int -> int -> int
- val sum2 = sum 2;
val sum2 = fn : int -> int
- sum2 10;
val it = 12 : int

Python

可以使用functools来实现curry
>>>from functools import partial
>>>def sum(x,y): return x + y
>>>sum2 = partial(sum, 2)
>>>sum2
<functools.partial object at 0x1f2de0>
>>>sum2(10)
12

JavaScript

http://www.svendtofte.com/code/curried_javascript/

Friday, September 16, 2011

Cacheline prefetch

_mm_prefetch是一条SSE的指令.用于指导CPU如何去预取内存中的数据. 具体在C/C++代码里, 先需要#include <xmmintrin.h> 可以使用:

void _mm_prefetch(char * p , int i );
p为要预取数据的内存地址, i可以为_MM_HINT_T0, _MM_HINT_T1, _MM_HINT_T2, 或者 _MM_HINT_NTA中的一个. 他们的区别为:
  • PREFETCHT0 (T0): prefetch数据到所有级别cache, 包括L0 cache
  • PREFETCHT1 (T1): prefetch数据到所有级别cache, 但是除去L0 cache
  • PREFETCHT2 (T2): prefetch数据到所有级别cache, 但是除去L0和L1 cache
  • PREFETCHNTA: 将给定内存地址的数据prefetch到L2 cache的某个特定column上,这样如果这个内存地址的数据只是一次性的使用,就不会导致其他有用的cacheline被替换出cache. 好处是可以可以防止non-temporal 数据污染cache

Wednesday, September 14, 2011

static关键字在C/C++中的N种用法

static是C/C++中最让人抓狂的关键字,因为这个关键字被重载了太多不同的用法.要我说这就是C/C++这些语言设计崩坏的地方.

用法1:
在C中,如果用static修饰一个函数或者全局变量,那么这个函数或者变量仅仅为这个module中其他函数所见.所谓module就是这个C源文件的意思.这种用法实际上相当于Java或者C++中用private去修饰一个成员变量.这种用法下尽可能的使用static被认为是C程序员的良好习惯 -- C从设计上就对namespace问题苦手.

用法2:
在C++中,被static修饰的成员函数被称为静态成员函数.这种静态成员函数可以被"类名::函数名"来调用.

用法3:
C/C++中, 一个局部变量的声明如果被static修饰,那么该变量实际上不在运行栈上随着函数的调用和返回生灭,而是有一个全局的备份.换言之,这个变量类似于一个全局变量.  

Wednesday, July 20, 2011

[Windows]windbg kernel debugging

debugging virtual machine using windbg:
http://www.ndis.com/ndis-debugging/virtual/vmwaresetup.htm


    Steps:
  1. (One time) On host machine, install WinDbg
  2. On the target machine (i.e., the VM running on HyperV), ran following in cmd:
    bcdedit -debug on
    bcdedit -dbgsettings serial debugport:1 baudrate:115200
  3. In HyperV’s control panel, open the settings for the VM.  Under COM1, add a Named Pipe called “MyVIrtualCom1”.
  4. Create a shortcut for windbg on host machine, make it run as administrator (otherwise, you can not access the com). The command to run windbg is something like:
  5. C:\Debuggers\windbg.exe -y SRV*C:\symbols*http://msdl.microsoft.com/download/symbols -k com:port=\\.\pipe\MyVirtualCom1,pipe,resets=0,reconnect

Thursday, July 14, 2011

dumpbin: 查看binary文件所需要的symbols
VC自带的工具.
dumpbin /imports foo.sys