Exemplo n.º 1
0
def assert_instance_id(instance_id, config):
    actual_instance_id = get_instance_id(config)

    if instance_id != actual_instance_id:
        raise ControllerAssertionError(
            "The provided instance ID (%s) is not the same as the configured "
            "one (%s)." % (instance_id, actual_instance_id),
            reason="INSTANCE_OTHER")
Exemplo n.º 2
0
def notify(summary, message, urgency=None, ip_address=None, config=None):
    config = config or get_ngeo_config()

    urgency = urgency or "INFO"
    if urgency not in ("INFO", "CRITICAL", "BLOCK"):
        raise ValueError("Invalid urgency value '%s'." % urgency)

    try:
        if not ip_address:
            # get the value for "notification_url" and fall back to
            # "address"
            ip_address = safe_get(config, "control", "notification_url")

            if not ip_address:
                ctrl_config = get_controller_config(
                    get_controller_config_path(config))

                logger.debug(
                    "No 'notification_url' present. Trying to fall back to "
                    "registered IP address.")
                ip_address = safe_get(ctrl_config, CONTROLLER_SERVER_SECTION,
                                      "address")

    except (IOError, NoSectionError):
        # probably no config file present, so IP cannot be determined.
        pass

    if not ip_address:
        # cannot log this error as we would run into an endless loop
        logger.info("Cannot send notification to CTRL.")
        return

    tree = E(
        "notifyControllerServer",
        E("header", E("timestamp", isotime(now())),
          E("instance", get_instance_id(config)), E("subsystem", "BROW"),
          E("urgency", urgency)),
        E("body", E("summary", summary), E("message", message)))

    if ip_address.startswith("http://") or ip_address.startswith("https://"):
        pass
    else:
        ip_address = "http://%s" % ip_address

    if not ip_address.endswith("/notify"):
        ip_address += "/notify"

    logger.info("Sending notification to CTRL at IP '%s'." % ip_address)

    req = urllib2.Request(url=ip_address,
                          data=etree.tostring(tree, pretty_print=True),
                          headers={'Content-Type': 'application/xml'})
    try:
        urllib2.urlopen(req, timeout=1)
    except (urllib2.HTTPError, urllib2.URLError), e:
        logger.info("Error sending notification: %s" % e)
        logger.debug(traceback.format_exc() + "\n")
Exemplo n.º 3
0
def assert_instance_id(instance_id, config):
    actual_instance_id = get_instance_id(config)

    if instance_id != actual_instance_id:
        raise ControllerAssertionError(
            "The provided instance ID (%s) is not the same as the configured "
            "one (%s)." % (instance_id, actual_instance_id),
            reason="INSTANCE_OTHER"
        )
Exemplo n.º 4
0
def notify(summary, message, urgency=None, ip_address=None, config=None):
    config = config or get_ngeo_config()

    urgency = urgency or "INFO"
    if urgency not in ("INFO", "CRITICAL", "BLOCK"):
        raise ValueError("Invalid urgency value '%s'." % urgency)

    try:
        if not ip_address:
            ctrl_config = get_controller_config(get_controller_config_path(config))
            ip_address = safe_get(ctrl_config, CONTROLLER_SERVER_SECTION, "address")
    except IOError:
        # probably no config file present, so IP cannot be determined.
        pass

    if not ip_address:
        return

    tree = E("notifyControllerServer",
        E("header",
            E("timestamp", isotime(now())),
            E("instance", get_instance_id(config)),
            E("subsystem", "BROW"),
            E("urgency", urgency)
        ),
        E("body",
            E("summary", summary),
            E("message", message)
        )
    )

    req = urllib2.Request(
        url="http://%s/notify" % ip_address,
        data=etree.tostring(tree, pretty_print=True),
        headers={'Content-Type': 'text/xml'}
    )
    try:
        urllib2.urlopen(req, timeout=1)
    except (urllib2.HTTPError, urllib2.URLError):
        # could not send notification. Out of options
        pass
Exemplo n.º 5
0
def controller_server(request):
    config = get_ngeo_config()
    try:
        status = get_status()
        if not status.running:
            raise Exception("Server is currently not running.")

        if request.method not in ("POST", "DELETE"):
            raise Exception("Invalid request method '%s'." % request.method)

        values = json.load(request)

        # POST means "register"
        if request.method == "POST":
            register(values["instanceId"],
                     values["instanceType"], values["controllerServerId"],
                     get_client_ip(request), config)

        # DELETE means "unregister"
        elif request.method == "DELETE":
            unregister(values["instanceId"], values["controllerServerId"],
                       get_client_ip(request), config)

    except Exception as e:
        logger.debug(traceback.format_exc())
        logger.warning(str(e))
        instance_id = get_instance_id(config)
        values = {
            "faultString": str(e),
            "instanceId": instance_id,
            "reason": getattr(e, "reason", "NO_CODE")
        }
        if settings.DEBUG:
            values["traceback"] = traceback.format_exc()
        return JsonResponse(values, status=400)

    return JsonResponse({"result": "SUCCESS"})
Exemplo n.º 6
0
def controller_server(request):
    config = get_ngeo_config()
    try:
        status = get_status()
        if not status.running:
            raise Exception("Server is currently not running.")

        values = json.load(request)

        # POST means "register"
        if request.method == "POST":
            register(
                values["instanceId"], values["instanceType"],
                values["controllerServerId"], get_client_ip(request), config
            )

        # DELETE means "unregister"
        elif request.method == "DELETE":
            unregister(
                values["instanceId"], values["controllerServerId"],
                get_client_ip(request), config
            )

    except Exception as e:
        logger.error(traceback.format_exc())
        instance_id = get_instance_id(config)
        values = {
            "faultString": str(e),
            "instanceId": instance_id, 
            "reason": getattr(e, "reason", "NO_CODE")
        }
        if settings.DEBUG:
            values["traceback"] = traceback.format_exc()
        return JsonResponse(values, status=400)

    return JsonResponse({"result": "SUCCESS"})
Exemplo n.º 7
0
            try:
                status.command(command)
                return JsonResponse({"result": "SUCCESS"})
            except AttributeError:
                fault_string = "Invalid command '%s'." % command
            except NotImplemented, e:
                fault_string = "Command '%s' is not supported." % command
            except Exception, e:
                fault_string = str(e)

            return JsonResponse({
                "faultString": fault_string,
                "detail": {
                    "currentState": str(status),
                    "failedState": command,
                    "instanceId": get_instance_id(get_ngeo_config())
                }
            }, status=400)
        else:
            raise Exception("Invalid method '%s'" % request.method)

    except Exception, e:
        print logger.handlers
        logger.warning(str(e))
        return JsonResponse({
            "faultString": str(e)
        }, status=400)


def log_file_list(request):
    status = get_status()
Exemplo n.º 8
0
def notify(summary, message, urgency=None, ip_address=None, config=None):
    config = config or get_ngeo_config()

    urgency = urgency or "INFO"
    if urgency not in ("INFO", "CRITICAL", "BLOCK"):
        raise ValueError("Invalid urgency value '%s'." % urgency)

    try:
        if not ip_address:
            # get the value for "notification_url" and fall back to
            # "address"
            ip_address = safe_get(
                config, "control", "notification_url"
            )

            if not ip_address:
                ctrl_config = get_controller_config(
                    get_controller_config_path(config)
                )

                logger.debug(
                    "No 'notification_url' present. Trying to fall back to "
                    "registered IP address."
                )
                ip_address = safe_get(
                    ctrl_config, CONTROLLER_SERVER_SECTION, "address"
                )

    except (IOError, NoSectionError):
        # probably no config file present, so IP cannot be determined.
        pass

    if not ip_address:
        # cannot log this error as we would run into an endless loop
        logger.info("Cannot send notification to CTRL.")
        return

    tree = E("notifyControllerServer",
        E("header",
            E("timestamp", isotime(now())),
            E("instance", get_instance_id(config)),
            E("subsystem", "BROW"),
            E("urgency", urgency)
        ),
        E("body",
            E("summary", summary),
            E("message", message)
        )
    )

    if ip_address.startswith("http://") or ip_address.startswith("https://"):
        pass
    else:
        ip_address = "http://%s" % ip_address

    if not ip_address.endswith("/notify"):
        ip_address += "/notify"

    logger.info("Sending notification to CTRL at IP '%s'." % ip_address)

    req = urllib2.Request(
        url=ip_address,
        data=etree.tostring(tree, pretty_print=True),
        headers={'Content-Type': 'application/xml'}
    )
    try:
        urllib2.urlopen(req, timeout=1)
    except (urllib2.HTTPError, urllib2.URLError), e:
        logger.info("Error sending notification: %s" % e)
        logger.debug(traceback.format_exc() + "\n")
Exemplo n.º 9
0
                status.command(command)
                return JsonResponse({"result": "SUCCESS"})
            except AttributeError:
                fault_string = "Invalid command '%s'." % command
            except NotImplemented, e:
                fault_string = "Command '%s' is not supported." % command
            except Exception, e:
                fault_string = str(e)

            return JsonResponse(
                {
                    "faultString": fault_string,
                    "detail": {
                        "currentState": str(status),
                        "failedState": command,
                        "instanceId": get_instance_id(get_ngeo_config())
                    }
                },
                status=400)
        else:
            raise Exception("Invalid method '%s'" % request.method)

    except Exception, e:
        print logger.handlers
        logger.warning(str(e))
        return JsonResponse({"faultString": str(e)}, status=400)


def log_file_list(request):
    status = get_status()
    if not status.running: