從 falcon api 中獲取資料

曲珂發表於2018-08-30
import json
import time

import requests

openfalcon = 'http://ip:port/api/v1'
user = 'user'
password = 'password'


def get_sig(user=user, password=password):
    url = '%s/user/login' % openfalcon
    response = requests.post(url, data=dict(name=user, password=password), timeout=2)
    return response.json()


def get_graph_history(hostname, category, start_time, end_time):
    url = '%s/graph/history' % openfalcon
    sig = get_sig()
    headers = {
        'Apitoken': json.dumps({'name': sig['name'], 'sig': sig['sig']}),
        'Content-type': 'application/json',
        'X-Forwarded-For': '127.0.0.1',
    }

    counters = [
        "cpu.idle",
        "cpu.iowait",
        "cpu.user",
        "cpu.system",
        "cpu.iowait",
        "cpu.irq",
        "cpu.softirq",
        "mem.memfree.percent",
        "mem.swapfree.percent",
        "df.bytes.free.percent/fstype=ext4,mount=/",
        "df.bytes.free.percent/fstype=ext4,mount=/data",
        "net.if.in.bytes/iface=eth0",
        "net.if.out.bytes/iface=eth0",
        "net.if.in.packets/iface=eth0",
        "net.if.out.packets/iface=eth0",
        "net.if.in.dropped/iface=eth0",
        "net.if.out.dropped/iface=eth0",
        "net.if.in.errors/iface=eth0",
        "net.if.out.errors/iface=eth0",
        "ss.estab",
        "load.1min",
        "load.5min",
        "load.15min",
        "disk.io.read_bytes/device=vda",
        "disk.io.read_bytes/device=vdb",
        "disk.io.write_bytes/device=vda",
        "disk.io.write_bytes/device=vdb",
        "disk.io.msec_total/device=vda",
        "disk.io.msec_total/device=vdb",
        "disk.io.avgrq_sz/device=vdb",
        "disk.io.avgqu-sz/device=vdb",
        "disk.io.await/device=vdb",
        "disk.io.svctm/device=vdb",
        "disk.io.util/device=vdb",
    ]

    if 'cpu' == category:
        counters = counters[0:7]
    elif 'memory' == category:
        counters = counters[7:9]
    elif 'disk' == category:
        counters = counters[9:11]
    elif 'net' == category:
        counters = counters[11:20]
    elif 'io' == category:
        counters = counters[20:23]
    else:
        counters = counters[23:]

    data = {
        "step": 60,
        "start_time": start_time,
        "hostnames": [hostname],
        "end_time": end_time,
        "counters": counters,
        "consol_fun": "AVERAGE"
    }
    response = requests.post(url, headers=headers, data=json.dumps(data))
    return response.json()


if __name__ == '__main__':
    end_time = int(time.time())
    start_time = end_time - 300
    print get_graph_history('host-001', 'io', start_time, end_time)

 

相關文章