From 02e29301aabe6b1ce004558c374bef2205973de6 Mon Sep 17 00:00:00 2001 From: jqxin2006 Date: Tue, 12 Mar 2013 09:54:08 -0500 Subject: [PATCH] Added Agent API and Agent WebUI --- barbican.py | 31 +++++++++++++++++++++++++-- barbican_api.py | 37 ++++++++++++++++++++++++++++++-- barbican_api_test.py | 41 +++++++++++++++++++++++++++++------ examples/agent.json | 17 +++++++++++++++ models.py | 50 ++++++++++++++++++++++++++++++++++++++++--- templates/agents.html | 44 +++++++++++++++++++++++++++++++++++++ templates/index.html | 2 +- templates/layout.html | 1 + 8 files changed, 208 insertions(+), 15 deletions(-) create mode 100644 examples/agent.json create mode 100644 templates/agents.html diff --git a/barbican.py b/barbican.py index 16318eee0..c4bbf11bd 100644 --- a/barbican.py +++ b/barbican.py @@ -20,8 +20,8 @@ from flask.ext import login, wtf from flask.ext.login import login_user from barbican_api import api from database import db_session, init_db -from models import User, Tenant, Key, Policy, Event - +from models import User, Tenant, Key, Policy, Event, Agent, Tag +import re app = Flask(__name__) app.secret_key = '79f9823f1f0---DEVELOPMENT---c46cebdd1c8f3d0742e02' @@ -33,6 +33,8 @@ admin.add_view(ModelView(Tenant, db_session)) admin.add_view(ModelView(Key, db_session)) admin.add_view(ModelView(Policy, db_session)) admin.add_view(ModelView(Event, db_session)) +admin.add_view(ModelView(Agent,db_session)) +admin.add_view(ModelView(Tag, db_session)) login_manager = login.LoginManager() login_manager.init_app(app) @@ -45,9 +47,34 @@ def hello(): return render_template("index.html") @app.route("/events") +@login.login_required def events(): return render_template("events.html") +@app.route("/agents", methods=["GET", "POST"]) +@login.login_required +def agents(): + if request.method == 'POST': + # need to update all agents since it is possible to disable pairing for them all + all_datas = request.form + ids=[] + for k in all_datas: + m = re.match('check(\d+)', k) + if m is not None: + id = m.group(1) + ids.append(int(id)) + + agents = Agent.query.order_by(Agent.id) + for agent in agents.all(): + if agent.id in ids: + agent.paired = True + else: + agent.paried = False + db_session.commit() + + return render_template("agents.html") + else: + return render_template("agents.html") # # Login forms diff --git a/barbican_api.py b/barbican_api.py index a37115e7b..4b78b2612 100644 --- a/barbican_api.py +++ b/barbican_api.py @@ -15,7 +15,7 @@ import uuid import datetime from dateutil.parser import parse from flask import Blueprint, request, jsonify, Response, json, Markup -from models import Event, Tenant, Key, Agent, Policy +from models import Event, Tenant, Key, Agent, Policy, Tag from database import db_session @@ -79,7 +79,14 @@ def policies(tenant_id): def agents(tenant_id): if request.method == 'POST': tenant = Tenant.query.get(tenant_id) - agent = Agent(tenant=tenant, uuid=request.json['uuid']) + agent = Agent(tenant=tenant, uuid=request.json['uuid'], hostname=request.json['hostname'], + os_version=request.json['os_version'], agent_version=request.json['agent_version']) + tags = [] + for t in request.json['tags']: + tag = Tag(name=t["name"], value=t["value"]) + tags.append(tag) + + agent.tags.extend(tags) db_session.add(agent) db_session.commit() return jsonify(agent.as_dict()) @@ -131,6 +138,32 @@ def alllogs(timestamp=None): }''' return Response(json_str, mimetype='application/json') +@api.route('/allagents/', methods=['GET']) +def allagents(timestamp=None): + agents = Agent.query.order_by(Agent.id) + json_str = '''{ + "aaData":[ + ''' + for agent in agents.all(): + tags = Tag.query.filter(Tag.agent_id==agent.id).all() + tag_json='{' + for tag in tags: + tag_json += "'%s':'%s'," % (tag.name, tag.value) + tag_json = tag_json[:-1] + tag_json += '}' + + if agent.paired == True: + paired_checkbox = "" % (agent.id, agent.id) + else: + paired_checkbox = "" % (agent.id, agent.id) + json_str += '''["%s","%s","%s","%s","%s","%s", "%s", "%s" + ],''' % (agent.id,agent.uuid, agent.tenant_id, agent.hostname, agent.os_version, agent.agent_version, tag_json, paired_checkbox) + json_str = json_str[:-1] + json_str += '''] + }''' + return Response(json_str, mimetype='application/json') + + class DateTimeJsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime.datetime): diff --git a/barbican_api_test.py b/barbican_api_test.py index 974193efb..893c770ec 100644 --- a/barbican_api_test.py +++ b/barbican_api_test.py @@ -16,7 +16,7 @@ import uuid import datetime import requests import json -from models import Event, Tenant, Key, Agent, Policy +from models import Event, Tenant, Key, Agent, Policy, Tag class BarbicanAPITesting: @@ -27,10 +27,28 @@ class BarbicanAPITesting: new_uuid = uuid.uuid4() self.agent_id = new_uuid - pay_load = {"uuid": str(new_uuid)} + payload = ''' + { + "agent_version": "v1.1", + "hostname": "barbican.example.com", + "os_version": "windows8", + "tags": [ + { + "name": "tag1", + "value": "value1" + }, + { + "name": "tag2", + "value": "value2" + } + ], + "tenant_id": %d, + "uuid": "%s" +} + ''' % (tenant_id, new_uuid) the_url = self.url + str(tenant_id) + "/agents/" headers = {'content-type': 'application/json'} - response = requests.post(the_url,data=json.dumps(pay_load), headers=headers) + response = requests.post(the_url,data=payload, headers=headers) try: the_uuid = response.json["uuid"] except Exception as e: @@ -117,16 +135,24 @@ class BarbicanAPITesting: the_url = self.url + str(tenant_id) + "/" response = requests.post(the_url) return response.text + +tag1 = Tag("tag1", "value1") +tag2 = Tag("tag2", "value2") - +'''tenant = Tenant(id=10) +agent = Agent(tenant, uuid=None, hostname='barbican.example.com', os_version='windows8', agent_version='v1.1') +agent.tags = [tag1, tag2] +#print tenant.as_dict() +print agent.as_dict() +''' test1 = BarbicanAPITesting() print test1.get_tenant(123) print test1.get_tenant(1234) print test1.create_tenant(123456) print test1.create_tenant(2349) -print test1.add_agent(1234) -test1.get_agents(1234) - +print test1.add_agent(123) +print test1.get_agents(123) +''' print test1.add_policy("Before start up", 1234) print test1.get_policy(1234) @@ -138,3 +164,4 @@ for k in range(1,50): print test1.add_log(1234) print test1.get_log(123) print test1.get_alllogs() +''' \ No newline at end of file diff --git a/examples/agent.json b/examples/agent.json new file mode 100644 index 000000000..8f737be6d --- /dev/null +++ b/examples/agent.json @@ -0,0 +1,17 @@ +{ + "agent_version": "v1.1", + "hostname": "barbican.example.com", + "os_version": "windows8", + "tags": [ + { + "name": "tag1", + "value": "value1" + }, + { + "name": "tag2", + "value": "value2" + } + ], + "tenant_id": 10, + "uuid": "7ead7502-53a4-4607-ae37-1b9af34460d8" +} diff --git a/models.py b/models.py index 45f5c0362..994659a4b 100644 --- a/models.py +++ b/models.py @@ -118,24 +118,44 @@ class Agent(Base): __tablename__ = 'agents' id = Column(Integer, primary_key=True) uuid = Column(String(36), unique=True) - + hostname = Column(String(128)) + os_version = Column(String(128)) + agent_version = Column(String(33)) + paired = Column(Boolean) + tenant_id = Column(Integer, ForeignKey('tenants.id')) tenant = relationship("Tenant", backref=backref('agents', order_by=id)) - def __init__(self, tenant=None, uuid=None): + def __init__(self, tenant=None, uuid=None, hostname=None, os_version=None, agent_version=None, paired=None): self.tenant = tenant + self.tenant_id = tenant.id if uuid is None: self.uuid = str(uuid4()) else: self.uuid = uuid + + if paired is None: + self.paired = False + else: + self.paired = paired + self.hostname = hostname + self.os_version = os_version + self.agent_version = agent_version + def __repr__(self): return '' % self.uuid def as_dict(self): + tags = map(Tag.as_dict, self.tags) agent = { 'tenant_id': self.tenant_id, - 'uuid': self.uuid + 'uuid': self.uuid, + 'hostname': self.hostname, + 'os_version': self.os_version, + 'agent_version': self.agent_version, + 'paired': self.paired, + 'tags': tags } return agent @@ -221,3 +241,27 @@ class Event(Base): 'message': self.message } return json + + +class Tag(Base): + __tablename__ = 'tags' + id = Column(Integer, primary_key=True) + name = Column(String(128)) + value = Column(String(1024)) + + agent_id = Column(Integer, ForeignKey('agents.id')) + agent = relationship("Agent", backref=backref('tags')) + + def __init__(self, name=None, value=None): + self.name = name + self.value = value + + def __repr__(self): + return '' % self.id + + def as_dict(self): + json = { + 'name': self.name, + 'value': self.value + } + return json diff --git a/templates/agents.html b/templates/agents.html new file mode 100644 index 000000000..fd81cbfb0 --- /dev/null +++ b/templates/agents.html @@ -0,0 +1,44 @@ +{% extends 'layout.html' %} + +{% block body %} + +

Agent List

+
+
+
+
+
+
+
+
+
+{% endblock %} diff --git a/templates/index.html b/templates/index.html index 1bce8e49a..a29cc7b0b 100644 --- a/templates/index.html +++ b/templates/index.html @@ -1,4 +1,4 @@ {% extends 'layout.html' %} {% block body %} -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/templates/layout.html b/templates/layout.html index 0fb22b669..c2b2afcdc 100644 --- a/templates/layout.html +++ b/templates/layout.html @@ -47,6 +47,7 @@