顯示具有 教學 標籤的文章。 顯示所有文章
顯示具有 教學 標籤的文章。 顯示所有文章

2014/03/22

C語言的記憶體洩漏(Memory Leak)偵測 - Valgrind

寫 C 的人對於記憶體管理要非常的精確,不像其他高階語言有 garbage collection,好習慣可以減少錯誤發生,讓 malloc() 與 free() 對等的出現,而且寫在同一個層級。但不免還是會有疏忽的時候,像我自己在寫 daemon,這種長期服務的程式,如果遇到 memroy leak,就會看到系統的記憶體一點一點的被吃光,最後免不了要重開的命運,如果是線上的服務器豈不就要重斷服務了!

好在有強大的 Valgrind 可以幫助我們真測出問題。


Case 1: Memory Leak

最常見的錯誤,就是 allocate 的記憶體忘記 free,而且已經沒有任何指標指著它。
我們舉個簡單的例子,並使用 valgrind 來協助偵測:
#include <stdlib.h>

void func (void)
{
    char *buff = malloc(10);
}

int main (void)
{
    func();
    return 0;
}

編譯並執行 (記得編譯時要加 -g 的參數,valgrind 的報告才會指明有問題的行數)
# gcc -g -o mem_test mem_test.c

Valgrind 使用方法很簡單,不需要修改程式碼,用 valgrind 把自己的 program 帶起來即可,如果有參數就加在後面,程式執行結束就會產生報告。
valgrind [-valgrind parameter] ./my_program [-program parameter]
# valgrind --leak-check=full ./mem_test

==59095== Memcheck, a memory error detector
==59095== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==59095== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info
==59095== Command: ./mem_test
==59095==
==59095==
==59095== HEAP SUMMARY:
==59095==     in use at exit: 10 bytes in 1 blocks
==59095==   total heap usage: 1 allocs, 0 frees, 10 bytes allocated
==59095==
==59095== 10 bytes in 1 blocks are definitely lost in loss record 1 of 1
==59095==    at 0x4C2C857: malloc (vg_replace_malloc.c:291)
==59095==    by 0x400505: func (mem_test.c:5)
==59095==    by 0x400514: main (mem_test.c:10)
==59095==
==59095== LEAK SUMMARY:
==59095==    definitely lost: 10 bytes in 1 blocks
==59095==    indirectly lost: 0 bytes in 0 blocks
==59095==      possibly lost: 0 bytes in 0 blocks
==59095==    still reachable: 0 bytes in 0 blocks
==59095==         suppressed: 0 bytes in 0 blocks
==59095==
==59095== For counts of detected and suppressed errors, rerun with: -v
==59095== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)
報告中指明有一個 10 bytes 的 block 被偵測為 "definitely lost",位置在 mem_test.c 的第 5 行

可以看到 memory lost 分成幾種類型:
  • definitely lost: 真的 memory leak 了
  • indirectly lost: 間接的 memory leak,structure 本身發生 memory leak,而內部的 member 如果是 allocate 的出來的,一樣會 memory leak,但是只要修好前面的問題,後面的問題也會跟著修復。
  • possibly lost: allocate 一塊記憶體,並且放到指標 ptr,但事後又改變 ptr 指到這會計一體的中間 (這一點我目前也不是很清楚,建議看原文說明)
  • still reachable: 程式結束時有未釋放的記憶體,不過卻還有指標指著,通常會發生在 global 變數
就算是 library 所 malloc 的記憶體,如 evbuffer_new(),也都可以偵測的到。



Case 2: Invalid Memory Access

Invalid memory access 有時候並不會立即造成 segmentation fault,所以不會有 core dump可以查詢,需要借助像 valgrind 這類的工具來偵測。
一般情況可能是用了 allocate 的 memory 之外的地方,或是用了已經 free 的 memory,請看下面幾個例子:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main (void)
{
    // 1. Invalid write
    char *str = malloc(4);
    strcpy(str, "Brian");
    free(str);
    
    // 2. Invalid read
    int *arr = malloc(3);
    printf("%d", arr[4]);
    free(arr);
    
    // 3. Invalid read
    printf("%d", arr[0]);

    // 4. Invalid free
    free(arr);

    return 0;
}
編譯並執行
==60019== Memcheck, a memory error detector
==60019== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==60019== Using Valgrind-3.9.0 and LibVEX; rerun with -h for copyright info
==60019== Command: ./mem_test
==60019==
==60019== Invalid write of size 2
==60019==    at 0x4005AB: main (mem_test.c:9)
==60019==  Address 0x51f4044 is 0 bytes after a block of size 4 alloc'd
==60019==    at 0x4C2C857: malloc (vg_replace_malloc.c:291)
==60019==    by 0x400595: main (mem_test.c:8)
==60019==
==60019== Invalid read of size 4
==60019==    at 0x4005D1: main (mem_test.c:14)
==60019==  Address 0x51f40a0 is 13 bytes after a block of size 3 alloc'd
==60019==    at 0x4C2C857: malloc (vg_replace_malloc.c:291)
==60019==    by 0x4005C4: main (mem_test.c:13)
==60019==
==60019== Invalid read of size 4
==60019==    at 0x4005F7: main (mem_test.c:18)
==60019==  Address 0x51f4090 is 0 bytes inside a block of size 3 free'd
==60019==    at 0x4C2B75D: free (vg_replace_malloc.c:468)
==60019==    by 0x4005F2: main (mem_test.c:15)
==60019==
==60019== Invalid free() / delete / delete[] / realloc()
==60019==    at 0x4C2B75D: free (vg_replace_malloc.c:468)
==60019==    by 0x400618: main (mem_test.c:21)
==60019==  Address 0x51f4090 is 0 bytes inside a block of size 3 free'd
==60019==    at 0x4C2B75D: free (vg_replace_malloc.c:468)
==60019==    by 0x4005F2: main (mem_test.c:15)
==60019==
00==60019==
==60019== HEAP SUMMARY:
==60019==     in use at exit: 0 bytes in 0 blocks
==60019==   total heap usage: 2 allocs, 3 frees, 7 bytes allocated
==60019==
==60019== All heap blocks were freed -- no leaks are possible
==60019==
==60019== For counts of detected and suppressed errors, rerun with: -v
==60019== ERROR SUMMARY: 4 errors from 4 contexts (suppressed: 0 from 0)
錯誤一:Invalid write of size 2,試圖寫入一個非法的區域,valgrind 還好心告訴你這個地方是在 mem_test.c:6 allocate 出來的 memory 之後的 3 byte,通常遇到這種情況都是忘記檢查 buffer 的 size 就去用。
錯誤二:Invalid read of size 4,試圖讀取一個非法的區域。
錯誤三:Invalid read of size 4,讀取的區域已經被 free 了,free 的位置 valgrind 也幫你指出來 mem_test.c:12。
錯誤四:Invalid free,也就是 free 一個不存在的地方,或是 double free



其他提醒

遇到 Conditional jump or move depends on uninitialised value(s) 的錯誤
可能是用了沒有結束字元 (Null-terminated string) 的字串

有一種錯誤不太好找,如 A function 用到用到 B function 產生出來的 memory,對於系統本身並無任何違法,但卻會造成程式出現不預期的值。

對於 local variable 的存取如果超過範圍,還有可能造成 stack corrupt,然後噴出這類的錯誤:
*** stack smashing detected ***: ./mem_test terminated
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(__fortify_fail+0x37)[0x64f8f47]
/lib/x86_64-linux-gnu/libc.so.6(__fortify_fail+0x0)[0x64f8f10]
./mem_test(func+0x2db)[0x407f22]
======= Memory map: ========
00400000-00420000 r-xp 00000000 08:01 280804      /tmp/mem_test
0061f000-00620000 r--p 0001f000 08:01 280804      /tmp/mem_test
00620000-00622000 rw-p 00020000 08:01 280804      /tmp/mem_test
00622000-00623000 rw-p 00000000 00:00 0
04000000-04022000 r-xp 00000000 08:01 160861      /lib/x86_64-linux-gnu/ld-2.15.so

如果不想 show possibly lost,可以加下面的參數
3.9版 --show-leak-kinds=definite
3.7版 --show-possibly-lost=no

另外 file descriptor 開了沒關也可以偵測,只要加上 --track-fds=yes

之前有遇過 valgrind 在 ubuntu 12.04 一直有錯誤訊息,記得要安裝額外的套件 sudo apt-get install libc6-dbg
12.04 - Valgrind does debug error - Ask Ubuntu

2013/03/31

AWS Auto Scaling 自動擴展(一)

AWS Auto Scaling 是用來處理 application 擴充性問題,根據當下的忙碌狀況來增減 instance。需要搭配 ELB 或是 CloudWatch 使用。

ELB (Elastic Load Balance) 的原理類似 DNS round-robin,在同一個 domain name 上綁定多組 instance IP,讓外部的 request 可以分散到各 instance 去處理。ELB 也會定期對底下的 instance 做 healthy check,若發現 instance 有問題,則 dispatch 時就會掠過這台,而 Auto Scaling 也會根據這個結果去 launch 新的 instance 並掛載 ELB 底下。ELB 下的 instance 是沒有上限值的。




Setup Auto Scaling

Auto Scaling 目前尚未提供 web 界面,只能用 command line 的方式去設定,在開始之前,請確定已經透過 web 設定好:
  • Create Image for a instance (ImageID: ami-7061fb19) 
  • Create ELB (with/without instance) (Load Balance Name: webserver)

Create auto scaling configuration
$ aws autoscaling create-launch-configuration \
--launch-configuration-name as-config \
--image-id ami-7061fb19 --instance-type t1.micro

Show the auto scaling configuration
$ aws autoscaling describe-launch-configurations

Create auto scaling group
$ aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name as-group \
--launch-configuration-name as-config \
--availability-zones us-east-1a \
--load-balancer-names webserver \
--max-size 3 --min-size 2 \
--default-cooldown 300
這個指令一執行,auto scaling 就被啟動了。

為了避免 instance 重複被 launch,有個時間參數設定很重要:
  • --default-cooldown (integer)
    The amount of time, in seconds, after a scaling activity completes before any further trigger-related scaling activities can start.
這個時間至少要大於服務啓動的時間
服務啓動時間 = EC2 開機時間 + Web Service 啓動時間 (+ ELB check health 的時間)

Show the auto scaling group
$ aws autoscaling describe-auto-scaling-groups

照上面的設定最少會有 2 台 instance 在 list 上
            "Instances": [
                {
                    "InstanceId": "i-e0a77c8c",
                    "AvailabilityZone": "us-east-1a",
                    "HealthStatus": "Healthy",
                    "LifecycleState": "Pending",
                    "LaunchConfigurationName": "as-config"
                },
                {
                    "InstanceId": "i-e2a77c8e",
                    "AvailabilityZone": "us-east-1a",
                    "HealthStatus": "Healthy",
                    "LifecycleState": "Pending",
                    "LaunchConfigurationName": "as-config"
                }
            ],

Verify
可以試著把任一台 instance stop,auto scaling 機制偵測到後又會 launch 一台新的,並且掛到 ELB 底下。




Monitor ELB healthy

Create auto scaling group 時,預設是對每個 instance 做 healthy check,若要改為 check ELB,則要加上兩個參數:
  • --health-check-type ELB
  • --health-check-grace-period 60
$ aws autoscaling create-auto-scaling-group \
--auto-scaling-group-name as-group \
--launch-configuration-name as-config \
--availability-zones us-east-1a \
--load-balancer-names webserver \
--max-size 3 --min-size 2 \
--health-check-type ELB --health-check-grace-period 300

Verify
可以試著讓 ELB 的狀態變成 unhealthy,在此我的 ELB 狀態是去 check 各 instance 的 web service,所以我把全部的 instance web service都停止,果真會掛 instance 上來。

但我對於這邊的行為還沒完全掌握,當沒有一台 instance 能夠服務時,那些不能服務的 instance 從 ELB list 中移除並 terminate,auto scaling 會 detect 到,並且循序 launch 一台新的 instance,直到 ELB 正常為止,但如果 service 是因為太忙碌不是掛掉,應該要加更多的 instance 上去而不是移除。



Stop Auto Scaling

Update group setting
$ aws autoscaling update-auto-scaling-group \
--auto-scaling-group-name as-group \
--min-size 0 --max-size 0

如果不更新就直接刪除,會有 error message: You cannot delete an AutoScalingGroup while there are instances or pending Spot instance request(s) still in the group.

Detete auto scaling group
$ aws autoscaling delete-auto-scaling-group --auto-scaling-group-name as-group

要注意一點,刪除 auto scaling group 後,所有的 instance 都會被 terminate!



參考資料

2013/03/30

使用 Command Line Tool 建立 AWS EC2 Instance

AWS 以已經有提供 web 界面可以操作了,為何還要使用 command line 呢?答案是為了自動化的過程。Auto scaling 就是一個很好的例子。


Install AWS Command Line Interface

It run in Python environment, and installed by pip.
$ pip install awscli


Setup credential and region

Method 1
$ vim ~/.aws.conf
aws_access_key_id=AKIAIJQ7YGMRQTBIH7HJ
aws_secret_access_key=ngbsB02udwOmDztTesTJuuZ8ZdkA2ZRq0VHvunX
region=us-east-1
$ export AWS_CONFIG_FILE=~/.aws.conf

Method 2
$ export AWS_ACCESS_KEY_ID=AKIAIJQ7YGMRQTBIH7HJ
$ export AWS_SECRET_ACCESS_KEY=ngbsB02udwOmDztTesTJuuZ8ZdkA2ZRq0VHvunX
$ export AWS_DEFAULT_REGION=us-east-1

若沒有設定好,則會出現下面的 error
Unable to locate credentials
You must specify a region or set the AWS_DEFAULT_REGION environment variable.


Create Instance

$ aws ec2 run-instances --image-id ami-002bf169 --min-count 1 --max-count 1 \
--instance-type m1.small --placement '{"availability_zone":"us-east-1a"}'
{
    "OwnerId": "132130202433",
    "ReservationId": "r-ec8f2587",
    "requestId": "05125c46-dfbd-4ef4-89a8-0efe6f59ba87",
    "Groups": [
        {
            "GroupName": "default",
            "GroupId": "sg-2337df4f"
        }
    ],
    "Instances": [
        {
            "Monitoring": {
                "State": "disabled"
            },
            "PublicDnsName": "",
            "KernelId": "aki-825ea7eb",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "EbsOptimized": false,
            "LaunchTime": "2013-03-30T02:58:42.000Z",
            "ProductCodes": [],
            "StateTransitionReason": "",
            "InstanceId": "i-ff16069f",
            "ImageId": "ami-002bf169",
            "PrivateDnsName": "",
            "SecurityGroups": [
                {
                    "GroupName": "default",
                    "GroupId": "sg-2437df4f"
                }
            ],
            "ClientToken": "",
            "InstanceType": "m1.small",
            "NetworkInterfaces": [],
            "Placement": {
                "Tenancy": "default",
                "GroupName": "",
                "AvailabilityZone": "us-east-1a"
            },
            "Hypervisor": "xen",
            "BlockDeviceMappings": [],
            "Architecture": "x86_64",
            "StateReason": {
                "Message": "pending",
                "Code": "pending"
            },
            "VirtualizationType": "paravirtual",
            "RootDeviceType": "instance-store",
            "AmiLaunchIndex": 0
        }
    ]
}

image-id 就是 AMI 的 id,它可以是 My AMI 也可以是 Community AMI


列出目前所有的 instance
$ aws ec2 describe-instances


關於 ec2 的操作,更詳細的可以看
$ aws ec2 help
$ aws ec2 run-instances help


Reference

2013/03/26

談 Coding Style 與 Naming Convention

工作三年,回頭再來看看一些寫程式的基本 guideline,深深覺得小時候沒學好...

一個程式的週期不只有 key in 程式碼而已,包含了requirement、design、implementation、testing、maintenance。有一些好習慣從平常就要養成,習慣不好,程式寫得再快都沒有用,日後有可能在 maintenance 時就賠上了大半時間。

為了讓自己可以安穩的睡一覺,還是趁早把基礎打好吧。在網路上已經有很多現成的 rule 可以依循,不需要自己發明,除非用了以後發現有更適合自己的地方。



Coding Style

有句話是這麼說的:任何人都可以寫得出電腦看得懂的程式,但要讓『人』看得懂,不是一件容易的事情!
Run 比較久公司,可能內部自己就有一套 coding style,也可以在 google 搜尋一些 keyword: coding style, coding standard, programing guideline

自己就看得順眼的先找一套來使用吧,我自己寫 C 語言比較多,follow 的 style 比較偏向 K&R。

比較強的 IDE 都有內建排版,像是 Eclipse 預設就有 K&R、BSD、GNU...等方式,也可以根據樣板再去做修改,透過軟體排版會快很多。



Naming Convention (Naming Rule)

好的命名法對於程式可讀性是會大大加分的,其範疇包含了程式內部變數、檔案名稱、外部參數,其實命名法也沒有一個制式規定,但有一些約定成俗的法則。
最常聽到的應該是『匈牙利命名法』,有很清楚的規範,但如果完全照著走就會發現變數變得很冗長...
另外還有『駝峰式命名法』也是常見的


根據不同的語言、平台,都有自己的一套命名法,這些『約定成俗』的名稱,我還沒辦法整理出可以遵循的 rule,真的得靠臨摹別人的程式來習得,多看一些 open source project 吧。



Documentation

Programer 好像都蠻討厭寫文件的,但很抱歉,你可能需要開 API 給別人,日後需要轉交給同事,或是自己因為時間久了也會忘記,所以寫文件真的蠻必要的。
Software design document (SDD) 算是我有認為比較常用的一種,裡面包含了 data design、architecture design、interface design、procedural design。但真正常用的還是只有 data structure 與 API,這時候就要介紹一下 doxygen,也就是把文件跟 code 結合在一起,方便維護。按照 doxygen 的格式去寫註解,最後可以產生 html 或 pdf 的文件。
c - Tools to get a pictorial function call graph of code - Stack Overflow
另外,在這篇有提到蠻多工具可以把 function call 畫成圖片,也就是流程圖,這對於 trace code 有些幫助!但 function call 應該是在 design 階段就劃分好,否則輸出的流程太雜亂幫助也不大。



小結

Vgod曾說過:好的程式設計師跟普通的程式設計師,效率可以差上幾十倍甚至幾百倍。除了上述的 coding 習慣、使用工具、開發環境...種種細節都會影響到,在拼專案之餘,也花些時間注重這些東西吧,一起往神人的境界努力!如果還有其他關於基礎學習,我再更新上來。

2013/03/24

在 Mac OS X 建置 python 開發環境

Install gcc for command line

Open XCode, click menu Preferences -> Downloads
check Command-Line Tools


Install Python-2.7.3

$ tar zxvf Python-2.7.3.tgz
$ cd Python-2.7.3
$ ./configure --prefix=/opt/Python-2.7.3
$ make && make install
$ export PATH=/opt/Python-2.7.3/bin:$PATH


Install distribute-0.6.35

$ tar zxvf distribute-0.6.27.tar.gz
$ cd distribute-0.6.27
$ python setup.py build
$ python setup.py install


Install pip-1.3.1

$ tar zxvf pip-1.1.tar.gz
$ cd pip-1.1
$ python setup.py build
$ python setup.py install


Install virtual environment

$ pip install virtualenv
$ virtualenv --no-site-packages /opt/pyenv
$ export PATH=/opt/pyenv/bin:$PATH



Install eclipse IDE

Download Eclipse Classic 4.2.2

Install PyDev plug-in for eclipse

Click menu Help -> Install New Software
Add repository with location: http://pydev.org/updates, then check the PyDev


Configure the interpreter

Click menu Preferences -> PyDev -> Interpreter - Python
Add new...
 

Add a new project and run it.
The debug mode is powerful.

2012/03/28

架設 Subversion system + apache

安裝SVN
yum install subversion apache mod_dav_svn

在此我們不用 daemon mode (svnserve),而是使用 apache 來管理

設定帳密
htpasswd -c /etc/svn/passwd user

設定權限
[groups]
admin = user1, user2

[Project1:/]
@admin = rw

[Project2:/]
@admin = rw

[Project2:/Doc]
user3 = rw

設定apache configuration
/etc/httpd/conf.d/subversion.conf
LoadModule dav_svn_module     modules/mod_dav_svn.so
LoadModule authz_svn_module   modules/mod_authz_svn.so

<Location /svn>
  DAV svn
  SVNParentPath /var/svn

  SSLRequireSSL
  AuthType Basic
  AuthName "Authorization Realm"
  AuthUserFile /etc/svn/passwd
  AuthzSVNAccessFile /etc/svn/authz
  Require valid-user
</location>

建立新的 project
svnadmin create /var/svn/Project1

讓 httpd 有存取 svn 目錄的權限
chown -R apache:apache /var/svn/Project1

最後開啓網址 https://localhost/svn/Project1 試試看