Implement XMPP health check
Anirudh Oppiliappan x@icyphox.sh
Fri, 24 Jul 2020 08:12:29 +0530
1 files changed,
43 insertions(+),
15 deletions(-)
jump to
M
src/wsabi.nim
→
src/wsabi.nim
@@ -54,34 +54,62 @@ except WebSocketError:
echo "client closed socket: ", getCurrentExceptionMsg() ## Health check endpoint + ## The 'uri' can be either 'ws' or 'http'. if req.url.path == "/check-health": if req.reqMethod == HttpPost: type HealthCheck = object - reqType: string + uri: string host: string port: int + try: + let + hcJson = parseJson(req.body) + hc = to(hcJson, HealthCheck) - let - hcJson = parseJson(req.body) - hc = to(hcJson, HealthCheck) + if hc.uri notin ["ws", "wss", "http", "https"]: + let r = %*{"status": "error", "msg": &"unknown URI {hc.uri}"} + await req.respond( + Http400, $r, + newHttpHeaders([("Content-Type", "application/json")]) + ) - try: - echo &"trying to reach {hc.host}:{hc.port}" - discard await asyncnet.dial(hc.host, Port(hc.port)) - let r = %*{"status": "OK"} - await req.respond( - Http200, $r, - newHttpHeaders([("Content-Type", "application/json")]) - ) - except OSError: + ## Check if host is a websocket, and try for the xmpp protocol + if hc.uri in ["ws", "wss"]: + let hostStr = &"{hc.uri}://{hc.host}:{hc.port}/ws/" + echo &"connecting to {hostStr}" + var ws = await newWebSocket(hostStr, protocol = "xmpp") + echo "sending test packet" + echo &"""<open xmlns="urn:ietf:params:xml:ns:xmpp-framing" to="{hc.host}" version="1.0" />""" + await ws.send(&"""<open xmlns="urn:ietf:params:xml:ns:xmpp-framing" to="{hc.host}" version="1.0" />""") + + echo await ws.receiveStrPacket() + ws.close() + let r = %*{"status": "OK"} + await req.respond( + Http200, $r, + newHttpHeaders([("Content-Type", "application/json")]) + ) + except OSError as e: echo "unable to reach specified host:port pair" let r = %*{ "status": "error", - "msg": "unable to reach specified host:port pair" + "msg": e.msg } await req.respond( - Http400, $r, + Http400, $r, + newHttpHeaders([("Content-Type", "application/json")]) + ) + except KeyError as e: + let r = %*{"status": "error", "msg": e.msg} + await req.respond( + Http400, $r, + newHttpHeaders([("Content-Type", "application/json")]) + ) + except WebSocketError as e: + let r = %*{"status": "error", "msg": e.msg} + await req.respond( + Http500, $r, newHttpHeaders([("Content-Type", "application/json")]) )