顯示具有 monitor 標籤的文章。 顯示所有文章
顯示具有 monitor 標籤的文章。 顯示所有文章

2021年6月12日 星期六

Node.js 筆記 - 使用 Puppeteer 監控瀏覽網頁的 Requests 跟 HTML Code @ macOS 11.4, node v14.14.0, npm 6.14.5

緣起於在追蹤網站架構時,每次都靠 chrome browser 開發人員工具去追蹤特定的 request 還好,若需要大量瀏覽找尋一些蛛絲馬跡時,就會很煩!以前很閒時,就會跳下去寫 chrome extension 或是熱衷於 C++ 時,就會寫一點點  Chromium Embedded Framework 來寫個小型瀏覽器,最後想起來試試看 Puppeteer 吧!

使用 Puppeteer 很輕鬆,除了是很常見的 Javascript 語言外,Puppeteer 套件提供了網頁端常見的事件偵測、所發的 Request 清單。就這樣拼拼湊湊即可完工:

(async () => {
const browser = await puppeteer.launch({headless: false});
//const page = await browser.newPage();
const context = await browser.createIncognitoBrowserContext();
const page = await context.newPage();
await page.emulate(device);
await page.setRequestInterception(true);

// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-event-domcontentloaded
// https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event
//
// The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
//
page.on('domcontentloaded', () => {
console.log('on.domcontentloaded');
});

// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-event-domcontentloaded
// https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event
//
// The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.
//
page.on('load', async () => {
console.log('on.load');
watchTags(page, watch_tags);
});

// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-event-framenavigated
// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-class-frame
page.on('framenavigated', frame => {
console.log('on.framenavigated: '+frame.url());
});

// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-event-request
// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-class-httprequest
page.on('request', request => {
watchRequest(page.url(), request.url());
if (skip_resource_type[ request.resourceType() ])
request.abort();
else
request.continue();
});

// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-event-response
// https://pptr.dev/#?product=Puppeteer&version=v10.0.0&show=api-class-httpresponse
page.on('response', response => {
//console.log('on.response: '+response.url());
});

while (true) {
if (url_init.length > 0) {
const target_url = url_init.shift();
await page.goto(target_url, {
waitUntil: 'networkidle0',
});
console.log('networkidle0');
}
if (url_init.length > 0)
await sleep(5000);
else
await sleep(50);
}
await browser.close();
})();

如此,搭配 command line 使用,就可很快的監控想要的 request 規則,或是 HTML DOM Tree 的變化,例如監控 <script> 的讀取位置在哪:

% node index.js -url "https://tw.yahoo.com" -tag "script.src"
...
on.load
[WATCH][TAG] script: src
Web URL: [https://tw.yahoo.com/]
[
  { src: 'https://s.yimg.com/wi/ytc.js' },
  {
    src: 'https://tw.mobi.yahoo.com/polyfill.min.js?features=array.isarray%2Carray.prototype.every%2Carray.prototype.foreach%2Carray.prototype.indexof%2Carray.prototype.map%2Cdate.now%2Cfunction.prototype.bind%2Cobject.keys%2Cstring.prototype.trim%2Cobject.defineproperty%2Cobject.defineproperties%2Cobject.create%2Cobject.freeze%2Carray.prototype.filter%2Carray.prototype.reduce%2Cobject.assign%2Cpromise%2Crequestanimationframe%2Carray.prototype.some%2Cobject.getownpropertynames%2Clocale-data-en-us%2Cintl%2Clocale-data-zh-hant-tw&version=2.1.23'
  },
  { src: 'https://s.yimg.com/aaq/yc/2.9.0/zh.js' },
  {
    src: 'https://s.yimg.com/ud/fp/js/vendor.174522d6d76b51858b93.min.js'
  },
  { src: 'https://s.yimg.com/ud/fp/js/common.js' },
  { src: 'https://s.yimg.com/oa/consent.js' },
  { src: 'https://consent.cmp.oath.com/cmpStub.min.js' },
  { src: 'https://consent.cmp.oath.com/cmp.js' },
  { src: 'https://s.yimg.com/ss/rapid3.js' },
  { src: 'https://s.yimg.com/rq/darla/boot.js' },
  {
    src: 'https://s.yimg.com/ud/fp/js/main.6622c6aeda051386afaa.min.js'
  },
  { src: 'https://mbp.yimg.com/sy/os/yaft/yaft-0.3.22.min.js' },
  {
    src: 'https://mbp.yimg.com/sy/os/yaft/yaft-plugin-aftnoad-0.1.3.min.js'
  },
  { src: 'https://s.yimg.com/aaq/vzm/perf-vitals_1.0.0.js' },
  {
    src: 'https://fc.yahoo.com/sdarla/php/client.php?dm=1&lang=zh-Hant-TW'
  },
  {
    src: 'https://s.yimg.com/aaq/c/e7fecc0.caas-abu_highlander.min.js'
  }
]
...

2014年8月21日 星期四

[Linux] 使用常見的指令進行系統監控 @ Ubuntu 14.04

取得 Server 代號 - 使用 hostname 指令:

$ hostname

取得 Server OS 資訊 - 使用 lsb_release 指令:

$ lsb_release -a

取得 CPU 使用率 - 使用 vmstat、tail 和 awk 指令:

$ echo $((100-$(vmstat|tail -1|awk '{print $15}')))

取得 System Loading 資訊 - 使用 uptime 和 awk 指令:

$ uptime | egrep -o 'load average[s]*: [0-9,\. ]+' | awk -F',' '{print $1$2$3}' | awk -F' ' '{print $3}'
$ uptime | egrep -o 'load average[s]*: [0-9,\. ]+' | awk -F',' '{print $1$2$3}' | awk -F' ' '{print $4}'
$ uptime | egrep -o 'load average[s]*: [0-9,\. ]+' | awk -F',' '{print $1$2$3}' | awk -F' ' '{print $5}'


取得 Apache Web Server Processes 資訊 - 使用 pgrep 跟 wc 指令:

$ pgrep apache2 | wc -l

取得 Memory 使用率 - 使用 free、grep 跟 awk 指令:

$ free -m | grep Mem | awk '{print $3/$2 * 100}'

取得 Network 即時流量 - 使用 nicstat、grep 跟 awk,假定網路卡是 eth 開頭:

In:
$ nicstat | grep eth |  awk '{print $3}'

Out:
$ nicstat | grep eth |  awk '{print $4}'


最後,檢查上述指令是否都存在:

#!/bin/sh
CMD_USAGE=$(echo 'hostname curl pgrep wc awk tail uptime vmstat free nicstat' | tr ";" "\n")
for cmd in $CMD_USAGE
do
        path=`which $cmd`
        if [ -z $path ] || [ ! -x $path ] ; then
                echo "$cmd not found"
                exit
        fi
done


其他資源:

2014年4月15日 星期二

[Linux] 使用 Nagios 和 nagios-nrpe-server 定期偵測系統狀況



記得上個月也摸了一下 nagios ,但後來因忙碌而中斷的 Orz 這次就專心補齊了一下。簡單的說,若是在單機上安裝,則是自我檢測的方式,若透過 nagios-nrpe-server 則可以晉升為遠端監控。

僅需挑一檯機器當 Monitor,在上頭安裝 nagios3 環境 (nagios3 server),而在其他待監控的機上,安裝 nagios-nrpe-plugin 環境,並設置可以監控它的來源、要監控的指令。

待監控的 Servers:

由於有些資源還是要從 Server 自身監控,如 Disk space、 CPU Load 等,所以透過 nagios-nrpe-server 來提供遠端查詢方式

$ sudo apt-get install nagios-nrpe-server
$ sudo vim /etc/nagios/nrpe_local.cfg
allowed_hosts=127.0.0.1,MonitorServerIP
command[check_load]=/usr/lib/nagios/plugins/check_load -w 15,10,5 -c 30,25,20
command[check_all_disks]=/usr/lib/nagios/plugins/check_disk -w 15% -c 5%
$ sudo service nagios-nrpe-server restart
netstat -at |grep nrpe
tcp        0      0 *:nrpe                  *:*                     LISTEN
$ grep nrpe /etc/services
nrpe            5666/tcp                        # Nagios Remote Plugin Executor


自我連線測試,也可以在 Monitor Server 測試指定 Server IP :

$ telnet localhost 5666

Monitor Server:

$ sudo apt-get install nagios3 nagios-nrpe-plugin

別忘了帳密在 /etc/nagios3/htpasswd.users 設定。此外,在 /usr/lib/nagios/plugins/ 就有一堆可以用的 tools ,例如監控 Google 是否正常:

$ /usr/lib/nagios/plugins/check_http -H www.google.com
HTTP OK: HTTP/1.1 200 OK - 12316 bytes in 0.057 second response time |time=0.056623s;;;0.000000 size=12316B;;;0


接著,則是定義自己的服務跟機器:

$ sudo vim /etc/nagios3/conf.d/my-server.cfg

#define host

define host {
        host_name db
        alias db.xxxx.com
        address db.xxxx.com
        hostgroups ssh-servers,remote-servers,https-servers
        use generic-host
}

define host {
        host_name www
        alias www.xxxx.com
        address www.xxxx.com
        hostgroups ssh-servers,remote-servers,http-servers,https-servers
        use generic-host
}

# define hostgroup

define hostgroup {
        hostgroup_name          mysql-servers
        alias                   MySQL DB Service
        members                 db
}

define hostgroup {
        hostgroup_name          https-servers
        alias                   HTTPS Service
        members                 db
}

define hostgroup {
        hostgroup_name          remote-servers
        alias                   Remote Server
        members                 db
}

# define service checking

define service {
        hostgroup_name          https-servers
        service_description     HTTPS
        check_command           check-https!$HOSTADDRESS!443
        use                     generic-service
        notification_interval   0 ; set > 0 if you want to be renotified
}

define service {
        hostgroup_name          remote-servers
        service_description     Remote NRPE CPU Load
        check_command           check_nrpe_1arg!check_load
        use                     generic-service
        notification_interval   0
}

define service {
        hostgroup_name          remote-servers
        service_description     Remote NRPE Disk Space
        check_command           check_nrpe_1arg!check_all_disks
        use                     generic-service
        notification_interval   0
}

# define commands

define command{
        command_name    check-https
        command_line    /usr/lib/nagios/plugins/check_http -I $ARG1$ -p $ARG2$ -S
}


$ sudo service nagios3 restart

如此一來,到 http://MonitorServerIP/nagios3 登入後,就可以觀察現況啦。以上的偵測包括 http, https, ssh, cpu loading, disk space 等,如果想要加上 mysql db service 的情況,可以試試 check_mysql_health 這支,需要額外下載:

下載 check_mysql_health 和編譯:

$ cd /tmp
$ wget -qO- http://labs.consol.de/download/shinken-nagios-plugins/check_mysql_health-2.1.8.2.tar.gz | tar -xzvf -
$ cd check_mysql_health-2.1.8.2
$ ./configure
$ make
$ sudo cp /tmp/check_mysql_health-2.1.8.2/plugins-scripts/check_mysql_health /usr/lib/nagios/plugins/


接著,撰寫相關 mysql db service checking:

$ sudo vim /etc/nagios3/conf.d/my-server.cfg

define host {
host_name db
alias db.xxxx.com
address db.xxxx.com
hostgroups ssh-servers,mysql-servers
use generic-host
}

define hostgroup {
hostgroup_name mysql-servers
alias MySQL DB Service
members db
}

define service {
hostgroup_name mysql-servers
service_description MySQL Remote Connection
check_command check-mysql-db!$HOSTADDRESS
#check_command check_tcp!-H!$HOSTADDRESS$!-p!3306
use generic-service
notification_interval 0 ; set > 0 if you want to be renotified
}

define command{
command_name check-mysql-db
command_line /usr/lib/nagios/plugins/check_mysql_health --hostname $ARG1$ --username nagios --password nagiospassword --mode querycache-hitrate --warning 90 --critica 95
}


此外,別忘了建立帳號供 monitor server 連到 db server,在 db server 上建立 nagios 帳號:

mysql> GRANT usage ON *.* TO 'nagios'@'nagios_monitor_server' IDENTIFIED BY 'nagiospassword';

2014年2月12日 星期三

[Linux] System Monitor / Load Indicator @ Ubuntu 12.04 desktop

indicator-multiload

印象中以前用 Ubuntu 10.04 時,常把 System Monitor Loading 顯示在右上角,但用了 Ubuntu 12.04 時,由於 Desktop GUI 更新後,遲遲找不到用法 XD 今天才把它解掉 Orz

$ sudo apt-get install indicator-multiload

接著在 Dash Home 搜尋 System 就可以看到 System Load indicator。

設定登入啟動:

$ cp /usr/share/applications/indicator-multiload.desktop ~/.config/autostart

2013年10月30日 星期三

[Linux] 監控記憶體使用量,以 python 為例 @ Ubuntu 12.04

監控方式就...去翻 /proc/pid/status 來看

粗略測試方式:
  • 寫一隻程式,最後一行跑 loop 讓程式不會結束,或是讀 io卡住也行
  • 用 ps 得知此程式 pid,接著翻 /proc/pid/status 出來
例如我想知道 python 記憶體使用上會不會 copy by reference 或 copy by reference,那就重複把某個 string data 設值給別人看看,最後用一個 loop 卡住,讓程式不會結束,接著就用 ps aux | grep 'test.py' 去找出來 PID ,再去 cat /proc/PID/status 出來。

test.py:

import time

data = open('tmp').read()
i = 1000
co = []
while i > 0 :
        #co.append(str(data)+"1")
        #co.append(str(data)+"")
        co.append(str(data))
        i -= 1
print "Done:", len(co)
while True:
        time.sleep(1)


連續動作:

$ ps aux | grep test.py | grep -v "grep\|vim" | awk '{system("cat /proc/"$2"/status");}' | grep -i "pid\|vm\|name"

當 co.append(str(data)) 跟 co.append(str(data)+"") 時,i 數值變大對記憶體增加不多:

Name:   python
Pid:    12180
PPid:   11910
TracerPid:      0
VmPeak:    32532 kB
VmSize:    32532 kB
VmLck:         0 kB
VmPin:         0 kB
VmHWM:      5676 kB
VmRSS:      5676 kB
VmData:     2700 kB
VmStk:       136 kB
VmExe:      2496 kB
VmLib:      5240 kB
VmPTE:        72 kB
VmSwap:        0 kB


但 co.append(str(data)+" ") 時,i 數值變大對記憶體就開始噴了:

Name:   python
Pid:    12189
PPid:   11910
TracerPid:      0
VmPeak:   340532 kB
VmSize:   340532 kB
VmLck:         0 kB
VmPin:         0 kB
VmHWM:    313496 kB
VmRSS:    313496 kB
VmData:   310700 kB
VmStk:       136 kB
VmExe:      2496 kB
VmLib:      5240 kB
VmPTE:       680 kB
VmSwap:        0 kB