Pārlūkot izejas kodu

实现获取宿主机信息接口

James Iter 9 gadi atpakaļ
vecāks
revīzija
648c56e18f
7 mainītis faili ar 140 papildinājumiem un 6 dzēšanām
  1. 103 0
      api/host.py
  2. 5 0
      api_route_table.py
  3. 2 1
      config.json
  4. 5 0
      main.py
  5. 17 3
      models/event_processor.py
  6. 7 2
      models/status.py
  7. 1 0
      tests/test_guest.py

+ 103 - 0
api/host.py

@@ -0,0 +1,103 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+
+import json
+from flask import Blueprint, request
+import jimit as ji
+
+from models import Database as db
+from models import Utils, Rules
+from models.initialize import app
+
+
+__author__ = 'James Iter'
+__date__ = '2017/5/30'
+__contact__ = 'james.iter.cn@gmail.com'
+__copyright__ = '(c) 2017 by James Iter.'
+
+
+blueprint = Blueprint(
+    'host',
+    __name__,
+    url_prefix='/api/host'
+)
+
+blueprints = Blueprint(
+    'hosts',
+    __name__,
+    url_prefix='/api/hosts'
+)
+
+
+@Utils.dumps2response
+def r_get(ids):
+
+    args_rules = [
+        Rules.IDS.value
+    ]
+
+    try:
+        ji.Check.previewing(args_rules, {args_rules[0][1]: ids})
+
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        ret['data'] = list()
+
+        if -1 == ids.find(','):
+            _id = ids
+            if db.r.hexists(app.config['hosts_info'], _id):
+                ret['data'] = {_id: json.loads(db.r.hget(app.config['hosts_info'], _id))}
+
+        else:
+            for _id in ids.split(','):
+                if db.r.hexists(app.config['hosts_info'], _id):
+                    ret['data'].append({_id: json.loads(db.r.hget(app.config['hosts_info'], _id))})
+
+        return ret
+
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_get_by_filter():
+
+    try:
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        ret['data'] = list()
+        for k, v in db.r.hgetall(app.config['hosts_info']).items():
+            ret['data'].append({k: json.loads(v)})
+
+        return ret
+
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+
+
+@Utils.dumps2response
+def r_content_search():
+    keyword = request.args.get('keyword', '')
+
+    args_rules = [
+        Rules.KEYWORD.value
+    ]
+
+    try:
+        ji.Check.previewing(args_rules, {'keyword': keyword})
+
+        ret = dict()
+        ret['state'] = ji.Common.exchange_state(20000)
+        ret['data'] = list()
+
+        for k, v in db.r.hgetall(app.config['hosts_info']).items():
+            v = json.loads(v)
+            if -1 != v['hostname'].find(keyword):
+                ret['data'].append({k: v})
+
+        return ret
+
+    except ji.PreviewingError, e:
+        return json.loads(e.message)
+

+ 5 - 0
api_route_table.py

@@ -10,6 +10,7 @@ from api import os_init
 from api import os_init_write
 from api import os_template
 from api import log
+from api import host
 
 
 __author__ = 'James Iter'
@@ -81,3 +82,7 @@ add_rule_api(log.blueprints, '/<ids>', api_func='log.r_get', methods=['GET'])
 add_rule_api(log.blueprints, '', api_func='log.r_get_by_filter', methods=['GET'])
 add_rule_api(log.blueprints, '/_search', api_func='log.r_content_search', methods=['GET'])
 
+# 宿主机查询
+add_rule_api(host.blueprints, '/<ids>', api_func='host.r_get', methods=['GET'])
+add_rule_api(host.blueprints, '', api_func='host.r_get_by_filter', methods=['GET'])
+add_rule_api(host.blueprints, '/_search', api_func='host.r_content_search', methods=['GET'])

+ 2 - 1
config.json

@@ -33,5 +33,6 @@
   "vnc_port_available_set": "S:VNCPort:Available",
   "vnc_port_used_set": "S:VNCPort:Used",
   "downstream_queue": "Q:Downstream",
-  "upstream_queue": "Q:Upstream"
+  "upstream_queue": "Q:Upstream",
+  "hosts_info": "H:HostsInfo"
 }

+ 5 - 0
main.py

@@ -27,6 +27,8 @@ from api.disk import blueprints as disk_blueprints
 from api.config import blueprint as config_blueprint
 from api.log import blueprint as log_blueprint
 from api.log import blueprints as log_blueprints
+from api.host import blueprint as host_blueprint
+from api.host import blueprints as host_blueprints
 
 
 __author__ = 'James Iter'
@@ -54,6 +56,9 @@ try:
     app.register_blueprint(config_blueprint)
     app.register_blueprint(log_blueprint)
     app.register_blueprint(log_blueprints)
+    app.register_blueprint(host_blueprint)
+    app.register_blueprint(host_blueprints)
+
 except:
     logger.error(traceback.format_exc())
 

+ 17 - 3
models/event_processor.py

@@ -37,13 +37,24 @@ class EventProcessor(object):
         cls.log.create()
 
     @classmethod
-    def event_processor(cls):
+    def guest_event_processor(cls):
         cls.guest.uuid = cls.message['message']['uuid']
         cls.guest.get_by('uuid')
         cls.guest.status = cls.message['type']
         cls.guest.on_host = cls.message['host']
         cls.guest.update()
 
+    @classmethod
+    def host_event_processor(cls):
+        key = cls.message['message']['node_id']
+        value = {
+            'hostname': cls.message['host'],
+            'timestamp': cls.message['timestamp']
+        }
+
+        db.r.hset(app.config['hosts_info'], key=key, value=json.dumps(value, ensure_ascii=False))
+        db.r.expire(app.config['hosts_info'], 10)
+
     @classmethod
     def response_processor(cls):
         action = cls.message['message']['action']
@@ -156,8 +167,11 @@ class EventProcessor(object):
                 if cls.message['kind'] == EmitKind.log.value:
                     cls.log_processor()
 
-                elif cls.message['kind'] == EmitKind.event.value:
-                    cls.event_processor()
+                elif cls.message['kind'] == EmitKind.guest_event.value:
+                    cls.guest_event_processor()
+
+                elif cls.message['kind'] == EmitKind.host_event.value:
+                    cls.host_event_processor()
 
                 elif cls.message['kind'] == EmitKind.response.value:
                     cls.response_processor()

+ 7 - 2
models/status.py

@@ -13,8 +13,9 @@ __copyright__ = '(c) 2017 by James Iter.'
 
 class EmitKind(IntEnum):
     log = 0
-    event = 1
-    response = 2
+    guest_event = 1
+    host_event = 2
+    response = 3
 
 
 class GuestState(IntEnum):
@@ -32,6 +33,10 @@ class GuestState(IntEnum):
     dirty = 255
 
 
+class HostEvent(IntEnum):
+    heartbeat = 0
+
+
 class LogLevel(IntEnum):
     critical = 0
     error = 1

+ 1 - 0
tests/test_guest.py

@@ -5,6 +5,7 @@
 import requests
 import json
 import unittest
+import uuid
 
 
 __author__ = 'James Iter'