A simple monitoring system written in Python

Source: Internet
Author: User

A simple monitoring system written in Python

This article mainly introduces a simple monitoring system written in Python. This article describes the detailed Encoding steps and provides the corresponding implementation code. For more information, see

There are many open-source monitoring systems on the market: Cacti, nagios, and zabbix. I don't feel like it meets my needs. Why don't I do it myself?

I spent two hours using Python to prepare a simple monitoring system. I hope it will inspire you.

First, create a database table.

Create a database "falcon". The table creation statement is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

Create table 'STAT '(

'Id' int (11) unsigned not null AUTO_INCREMENT,

'Host' varchar (256) default null,

'Mem _ free' int (11) default null,

'Mem _ usage' int (11) default null,

'Mem _ total' int (11) default null,

'Load _ avg' varchar (128) default null,

'Time' bigint (11) default null,

Primary key ('id '),

KEY 'host' (255 ))

) ENGINE = InnoDB AUTO_INCREMENT = 0 default charset = utf8;

First, we design a web service to implement the following functions:

1. Complete the monitoring page display

2. Accept the data submitted by POST

3. Provides the GET interface for json data

The directory structure is as follows:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

Web

── Flask_web.py

└ ── Templates

── Mon.html

[/Code]

Flask_web.py

[Code]

Import MySQLdb as mysql

Import json

From flask import Flask, request, render_template

App = Flask (_ name __)

Db = mysql. connect (user = "reboot", passwd = "reboot123 ",\

Db = "falcon", charset = "utf8 ")

Db. autocommit (True)

C = db. cursor ()

 

@ App. route ("/", methods = ["GET", "POST"])

Def hello ():

SQL = ""

If request. method = "POST ":

Data = request. json

Try:

SQL = "INSERT INTO 'STAT' ('host', 'mem _ free', 'mem _ usage', 'mem _ total', 'Load _ avg ', 'time') VALUES ('% s',' % d', '% s',' % D ') "% (data ['host'], data ['memfree'], data ['memusage'], data ['memtotal'], data ['loadavg'], int (data ['time'])

Ret = c.exe cute (SQL)

Couldn t mysql. IntegrityError:

Pass

Return "OK"

Else:

Return render_template ("mon.html ")

 

@ App. route ("/data", methods = ["GET"])

Def getdata ():

C.exe cute ("SELECT 'time', 'mem _ usage' FROM 'STAT '")

Ones = [[I [0] * 1000, I [1] for I in c. fetchall ()]

Return "% s (% s);" % (request. args. get ('callback'), json. dumps (ones ))

 

 

If _ name _ = "_ main __":

App. run (host = "0.0.0.0", port = 8888, debug = True)

This templatepage is a copy of the highstocks' example, mon.html

For simplicity, we only display mem_usage information to the page.

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

<Title> jb51.net </title>

<! Doctype html>

<Html>

<Head>

<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">

<Title> Highstock Example </title>

 

<Script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script>

<Style type = "text/css">

${Demo.css}

</Style>

<Script type = "text/javascript">

$ (Function (){

$. GetJSON ('/data? Callback =? ', Function (data ){

 

// Create the chart

$ ('# Iner'). highcharts ('stockchart ',{

 

RangeSelector :{

InputEnabled: $ ('# iner'). width ()> 480,

Selected: 1

},

 

Title :{

Text: 'jb51. net'

},

 

Series :[{

Name: 'jb51. net ',

Data: data,

Type: 'spline ',

Tooltip :{

ValueDecimals: 2

}

}]

});

});

});

</Script>

</Head>

<Body>

<Script src = "http://cdnjs.cloudflare.com/ajax/libs/highstock/2.0.4/highstock.js"> </script>

<Script src = "http://code.highcharts.com/modules/exporting.js"> </script>

 

 

<Div id = "container" style = "height: 400px"> </div>

</Body>

</Html>

The web display page is complete and runs:

Python flask_web.py listening on port 8888

We need to create an agent to collect data and upload the data to the database.

MoniItems. py

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

#! /Usr/bin/env python

Import inspect

Import time

Import urllib, urllib2

Import json

Import socket

 

Class mon:

Def _ init _ (self ):

Self. data = {}

 

Def getTime (self ):

Return str (int (time. time () + 8*3600)

 

Def getHost (self ):

Return socket. gethostname ()

 

Def getLoadAvg (self ):

With open ('/proc/loadavg') as load_open:

A = load_open.read (). split () [: 3]

Return ','. join ()

 

Def getMemTotal (self ):

With open ('/proc/meminfo') as mem_open:

A = int (mem_open.readline (). split () [1])

Returns a/1024

 

Def getMemUsage (self, noBufferCache = True ):

If noBufferCache:

With open ('/proc/meminfo') as mem_open:

T = int (mem_open.readline (). split () [1])

F = int (mem_open.readline (). split () [1])

B = int (mem_open.readline (). split () [1])

C = int (mem_open.readline (). split () [1])

Return (T-F-B-C)/1024

Else:

With open ('/proc/meminfo') as mem_open:

A = int (mem_open.readline (). split () [1])-int (mem_open.readline (). split () [1])

Returns a/1024

 

Def getMemFree (self, noBufferCache = True ):

If noBufferCache:

With open ('/proc/meminfo') as mem_open:

T = int (mem_open.readline (). split () [1])

F = int (mem_open.readline (). split () [1])

B = int (mem_open.readline (). split () [1])

C = int (mem_open.readline (). split () [1])

Return (F + B + C)/1024.

Else:

With open ('/proc/meminfo') as mem_open:

Mem_open.readline ()

A = int (mem_open.readline (). split () [1])

Returns a/1024

 

Def runAllGet (self ):

# Automatically obtain all the getXXX methods in the mon class, and use XXX as the key, and the return value of getXXX () as the value to construct the dictionary.

For fun in inspect. getmembers (self, predicate = inspect. ismethod ):

If fun [0] [: 3] = 'get ':

Self. data [fun [0] [3:] = fun [1] ()

Return self. data

 

If _ name _ = "_ main __":

While True:

M = mon ()

Data = m. runAllGet ()

Print data

Req = urllib2.Request ("http://bkjia.net: 8888", json. dumps (data), {'content-type': 'application/json '})

F = urllib2.urlopen (req)

Response = f. read ()

Print response

F. close ()

Time. sleep (60)

 

 

Nohup python moniItems. py>/dev/null 2> & 1 & run

Visit http://jb51.net: 8888 to see our monitoring data:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.