-1

我的任务是制作像 Server Density 这样的服务器监控工具。我有服务器列表,我想要每 15 秒每台服务器的 CPU 信息、内存信息、磁盘使用情况等,并打印它的图。我在 django 中设置了项目,以 mongo 作为后端数据库。我已经编写了 python 脚本,它可以在本地系统上给我这些参数。现在我的任务是将此信息存储在 Mongo-DB 中。我已经为每种参数编写了对应的模型。这是我创建的模型。

class CpuUsage(Document):

    server = ReferenceField(ServerInfo, db_field='se', required=False)
    sys_time = DateTimeField(db_field='st', required=False)
    #CPU=
    usr = StringField(db_field='u', required=False)
    nice = StringField(db_field='n', required=False)
    sys = StringField(db_field='sy', required=False)
    iowait = StringField(db_field='io', required=False)
    irq = StringField(db_field='ir', required=False)
    soft = StringField(db_field='so', required=False)
    steal = StringField(db_field='st', required=False)
    guest = StringField(db_field='g', required=False)
    idle = StringField(db_field='id', required=False)
    meta = {
        'indexes': ['server']
    }

我的脚本有以下两个功能 1) cpu_info 将 cpu 参数提取到字典中。

def cpu_info():
    cpu_parameters = {}
    ram_parmeters = {}
    p_info = '/home/bhavuk/Desktop/p_info'
    #p_file = open(p_info, 'w')
    cmd1 = 'mpstat -P ALL >'+ p_info
    p = subprocess.Popen(cmd1,
                         shell=True,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    cpu_cores=open(p_info, 'r').read().split('\n')
    #for i in range(0, len(cpu_cores)):
    #    print i, cpu_cores[i]
    print "current cpu state:\n"
    for i in range(2,len(cpu_cores)-1):
        cpu_parameters[i-2] = cpu_cores[i].split('\t')
        print cpu_parameters[i-2]
    save_cpu_info(cpu_parameters)

2)这会将字典中包含的信息保存到mongodb。

def save_cpu_info(parameters):
    s = ServerInfo() #need to correct
    s.save()

    for i in xrange(0, len(parameters)):
        c = CpuUsage(server=s)
        x = parameters[i]

    c.sys_time = x[0]
    c.CPU_core = x[2]
    c.usr = x[3]
    c.nice = x[4]
    c.sys = x[5]
    c.iowait = x[6]
    c.irq = x[7]
    c.soft = x[8]
    c.steal = x[9]
    c.guest = x[10]
    c.idle = x[11]
    c.save()

我对 serverfield 感到困惑,我应该如何使用它,我的目的是在每个服务器上运行这个脚本并设计一个 UI,它可以选择显示每个服务器的信息。

我想知道我是否朝着正确的方向前进,以及如何在每台服务器上以 15 秒的间隔运行此脚本并绘制图表。

进一步的改进将不胜感激。我也会

4

1 回答 1

0

1.要按计划运行脚本,您可以使用 crontab、Celery或自己的守护程序。看来 crontab 会更合适。您必须记住使用 crontab 选项,您应该将控制台脚本设置为:

#!/usr/bin/env python2.7
   # import required packages
   # setup paths to django project
   os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project.settings")
   sys.path.append(('/path/to/django/project'))
   ... # your code


if __name__ == "__main__":

   ... # your code

2.如果你想把数据保存在一个地方,你应该只使用MongoDB的一个公共主机。这意味着您应该在每个 Django 项目中使用与 MongoDB 相同的服务器 IP/域,而不是 settings.py 中的 localhost。

于 2013-07-08T12:53:48.007 回答