This repository has been archived on 2020-03-24. You can view files and clone it, but cannot push or open issues or pull requests.
quay/endpoints/realtime.py

117 lines
2.9 KiB
Python
Raw Normal View History

import logging
import json
from flask import request, Blueprint, abort, Response
from flask.ext.login import current_user
from auth.auth import require_session_login
2015-01-28 17:35:01 +00:00
from endpoints.common import route_show_if
from app import app, userevents
2015-01-28 17:35:01 +00:00
from auth.permissions import SuperUserPermission
from data.userevent import CannotReadUserEventsException
2015-01-28 17:35:01 +00:00
import features
import psutil
import time
logger = logging.getLogger(__name__)
realtime = Blueprint('realtime', __name__)
2015-01-28 17:35:01 +00:00
@realtime.route("/ps")
@route_show_if(features.SUPER_USERS)
@require_session_login
def ps():
if not SuperUserPermission().can():
abort(403)
def generator():
while True:
build_status = {}
try:
builder_data = app.config['HTTPCLIENT'].get('http://localhost:8686/status', timeout=1)
if builder_data.status_code == 200:
build_status = json.loads(builder_data.text)
except:
pass
try:
data = {
'count': {
'cpu': psutil.cpu_percent(interval=1, percpu=True),
'virtual_mem': psutil.virtual_memory(),
'swap_mem': psutil.swap_memory(),
'connections': len(psutil.net_connections()),
'processes': len(psutil.pids()),
'network': psutil.net_io_counters()
},
'build': build_status
}
except psutil.AccessDenied:
data = {}
2015-01-28 17:35:01 +00:00
json_string = json.dumps(data)
yield 'data: %s\n\n' % json_string
time.sleep(1)
2015-01-28 17:35:01 +00:00
try:
return Response(generator(), mimetype="text/event-stream")
except:
pass
2015-01-28 17:35:01 +00:00
@realtime.route("/user/")
@require_session_login
def index():
debug_template = """
<html>
<head>
</head>
<body>
<h1>Server sent events</h1>
<div id="event"></div>
<script type="text/javascript">
var eventOutputContainer = document.getElementById("event");
var evtSrc = new EventSource("/realtime/user/subscribe?events=docker-cli");
evtSrc.onmessage = function(e) {
console.log(e.data);
eventOutputContainer.innerHTML = e.data;
};
</script>
</body>
</html>
"""
return(debug_template)
@realtime.route("/user/test")
@require_session_login
def user_test():
evt = userevents.get_event(current_user.db_user().username)
evt.publish_event_data('test', {'foo': 2})
return 'OK'
@realtime.route("/user/subscribe")
@require_session_login
def user_subscribe():
def wrapper(listener):
for event_id, data in listener.event_stream():
message = {'event': event_id, 'data': data}
json_string = json.dumps(message)
yield 'data: %s\n\n' % json_string
events = request.args.get('events', '').split(',')
if not events:
abort(404)
try:
listener = userevents.get_listener(current_user.db_user().username, events)
except CannotReadUserEventsException:
abort(504)
return Response(wrapper(listener), mimetype="text/event-stream")