Skip to content

Commit

Permalink
Merge branch 'main' of ../private
Browse files Browse the repository at this point in the history
  • Loading branch information
lunar-devops committed Feb 21, 2024
2 parents 47a6b67 + 5bfbe97 commit 77e0089
Show file tree
Hide file tree
Showing 18 changed files with 218 additions and 104 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
lines="31,"/>
<suppress checks="LineLengthCheck"
files="RoutingData.java"
lines="130,"/>
lines="137,"/>
<suppress checks="LineLengthCheck"
files="FailSafe.java"
lines="73,"/>
<suppress checks="LineLengthCheck"
files="InjectData.java"
lines="43-52"/>
Expand Down
2 changes: 1 addition & 1 deletion interceptors/lunar-java-interceptor/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
<modelVersion>4.0.0</modelVersion>
<groupId>dev.lunar.interceptor</groupId>
<artifactId>lunar-interceptor</artifactId>
<version>0.1.1</version>
<version>0.1.2</version>
<properties>
<junit.version>5.6.0</junit.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,7 @@ public boolean isCooldownEnded() {
return true;
}

boolean timerEnded = (clock.currentTimeMillis() - this.cooldownStartedAtMs)
>= this.cooldownTimeMs;
boolean timerEnded = (clock.currentTimeMillis() - this.cooldownStartedAtMs) >= this.cooldownTimeMs;
if (timerEnded) {
this.cooldownStartedAtMs = 0;
}
Expand Down Expand Up @@ -99,12 +98,12 @@ protected FailSafe(
this.cooldownControl = new CooldownControl(
cooldownTimeSec.orElse(
LunarHelpers.getIntFromEnv(FailSafe.exitAfterSecKey,
FailSafe.defaultExitAfterSec)),
FailSafe.defaultExitAfterSec)),
clock);
this.errorCounter = new ErrorCounter(
maxErrorsAllowed.orElse(
LunarHelpers.getIntFromEnv(FailSafe.enterAfterAttemptsKey,
FailSafe.defaultEnterAfter)));
FailSafe.defaultEnterAfter)));
}

/**
Expand Down Expand Up @@ -139,7 +138,7 @@ public boolean stateOk() {
*/
public void onError() {
this.lunarLogger.severe("Error communicating with LunarProxy, "
+ "will revert the request to the original Provider.");
+ "will revert the request to the original Provider.");
this.errorCounter.countError();
this.ensureEnterFailSafe();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ public static void premain(
}

private static boolean validateConfigurations() {
if (logger.isDebugLevel()) {
logger.debug("Lunar Interceptor has loaded in debug mode."
+ "The current configuration are"
+ " * Interceptor Version: " + RoutingData.getInterceptorVersion() + " "
+ " * Lunar Proxy Host: " + RoutingData.getProxyHost() + " "
+ " * Lunar Proxy Handshake Port: " + RoutingData.getHandshakePort() + " "
+ ""
+ "Environment details:"
+ " * Java Engine Version: " + System.getProperty("java.version") + " ");
}
boolean shouldActivateInterceptor = RoutingData.getProxyHost().isPresent();
if (!shouldActivateInterceptor) {
logger.warning(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ private static class LunarFormatter extends Formatter {

private static final String LOG_DELIMITER = " - ";
private static final DateFormat DATE_FORMAT = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss,SSS");
"yyyy-MM-dd HH:mm:ss,SSS");

@Override
public String format(LogRecord record) {
Expand Down Expand Up @@ -86,23 +86,22 @@ public void debug(String msg) {
}

public void debug(String msg, Exception e) {
debug(msg + formatException(e) + "\ncaused by: " + formatException(e.getCause()));
debug(msg + formatException(e));
}

public void warning(String msg, Exception e) {
warning(msg + formatException(e) + "\ncaused by: " + formatException(e.getCause()));
warning(msg + formatException(e));
}

private String formatException(Throwable e) {
String error = "error: " + e.getMessage();

String formattedStackTrace = "trace:";

for (StackTraceElement traceElement : e.getStackTrace()) {
formattedStackTrace += "\n\tat " + traceElement;
private String formatException(Exception e) {
StringBuilder errorMessage = new StringBuilder();
errorMessage.append("Exception: ").append(e.getClass().getName()).append("\n");
errorMessage.append("Message: ").append(e.getMessage()).append("\n");
StackTraceElement[] stackTrace = e.getStackTrace();
for (StackTraceElement element : stackTrace) {
errorMessage.append("\tat ").append(element.toString()).append("\n");
}

return error + "\n" + formattedStackTrace;
return errorMessage.toString();
}

private Level getLogLevel() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ protected static Optional<String> getProxyHost() {
return Optional.ofNullable(System.getenv(PROXY_HOST_KEY));
}

/**
* @return Gets the LunarProxy handshake prot value configured in the
* environment,
* if nothing is set, then this will return an empty Optional object.
*/
protected static String getHandshakePort() {
return LunarHelpers.getStrFromEnv(HANDSHAKE_PORT_KEY, HANDSHAKE_PORT_DEFAULT);
}

/**
* @return Gets the tenant id value configured in the environment,
* if nothing is set, then will return unknown string.
Expand Down Expand Up @@ -78,7 +87,7 @@ private static String getProxyScheme() {
/**
* @return Gets the current interceptor version.
*/
private static String getInterceptorVersion() {
protected static String getInterceptorVersion() {
return Interceptor.class.getPackage().getImplementationVersion();
}

Expand All @@ -99,20 +108,18 @@ private static String ensureStringPrefix(String str, String prefix) {
}
}

private static Optional<String> getProxyHandshakeCheckURL(String handshakePort) {
private static Optional<String> getProxyHandshakeCheckURL() {
return getProxyHost()
.map(host -> RoutingData.getProxyScheme() + "://"
+ host.split(DELIMITER)[0] + ":" + handshakePort + "/handshake");
+ host.split(DELIMITER)[0] + ":" + getHandshakePort() + "/handshake");
}

/**
* Validate the connection status between the Interceptor and Lunar Proxy.
*/
public static void validateLunarProxyConnection() {
LunarLogger.getLogger().debug("Testing the communication with Lunar Proxy...");
String proxyHandshakeCheckPort = LunarHelpers.getStrFromEnv(HANDSHAKE_PORT_KEY,
HANDSHAKE_PORT_DEFAULT);
Optional<String> handshakeCheckURL = getProxyHandshakeCheckURL(proxyHandshakeCheckPort);
Optional<String> handshakeCheckURL = getProxyHandshakeCheckURL();

if (!handshakeCheckURL.isPresent()) {
LunarLogger.getLogger().debug("Lunar Proxy host was not configured!");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,18 @@ okhttp3.Response getResponseWithInterceptorChain() throws java.io.IOException {
}

isError = failSafe.isErrorHeader(headers);
if(isError){
lunarLogger.warning("An error occurs on the Proxy side");
}

} catch (java.io.IOException e) {
} catch (java.lang.Exception e) {
isError = true;
lunarLogger.severe("Error communicating with LunarProxy, "
+ "Error: " + e.getMessage() + ""
);
if (lunarLogger.isDebugLevel()) {
lunarLogger.debug("", e);
}
}

if (isError){
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[metadata]
name = lunar-interceptor
version = 0.3.1
version = 0.3.2
description = The Lunar interceptor used to manage the framwork traffic.
author = Lunar
author_email = [email protected]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,31 +1,26 @@
import logging
import platform

from lunar_interceptor.interceptor import Interceptor
from lunar_interceptor.interceptor.helpers import load_env_value
from lunar_interceptor.interceptor import (
Interceptor,
InterceptorConfig,
ENV_LUNAR_PROXY_HOST_KEY,
)
from lunar_interceptor.interceptor.traffic_filter import TrafficFilter
from lunar_interceptor.interceptor.fail_safe import (
FailSafe,
ProxyErrorException,
)

_ENV_LUNAR_PROXY_HOST_KEY = "LUNAR_PROXY_HOST"
_LUNAR_TENANT_ID = "LUNAR_TENANT_ID"
_ENV_LUNAR_HANDSHAKE_PORT_KEY = "LUNAR_HEALTHCHECK_PORT"
_ENV_PROXY_SUPPORT_TLS_KEY = "LUNAR_PROXY_SUPPORT_TLS"
_ENV_TRAFFIC_FILTER_ALLOW_LIST = "LUNAR_ALLOW_LIST"
_ENV_TRAFFIC_FILTER_BLOCK_LIST = "LUNAR_BLOCK_LIST"
_ENV_FAIL_SAFE_EXIT_COOLDOWN_SEC = "LUNAR_EXIT_COOLDOWN_AFTER_SEC"
_ENV_FAIL_SAFE_ENTER_AFTER = "LUNAR_ENTER_COOLDOWN_AFTER_ATTEMPTS"
_ENV_LUNAR_INTERCEPTOR_LOG_LEVEL = "LUNAR_INTERCEPTOR_LOG_LEVEL"

_INTERCEPTOR_NAME = "lunar-interceptor"
interceptor_config = InterceptorConfig()


def _initialize_lunar_logger() -> logging.Logger:
log_format = logging.Formatter(
f"%(asctime)s - {_INTERCEPTOR_NAME} - %(levelname)s: %(message)s"
)
log_level = load_env_value(_ENV_LUNAR_INTERCEPTOR_LOG_LEVEL, str, "INFO")
log_level = interceptor_config.log_level

logger = logging.getLogger(name=_INTERCEPTOR_NAME)
logger.setLevel(log_level)
Expand All @@ -41,42 +36,10 @@ def _initialize_lunar_logger() -> logging.Logger:
_LOGGER = _initialize_lunar_logger()


def _proxy_is_tls_supported() -> bool:
proxy_tls_supported = load_env_value(_ENV_PROXY_SUPPORT_TLS_KEY, int, 0)
if proxy_tls_supported == 0:
return False

elif proxy_tls_supported == 1:
return True

else:
_LOGGER.warning(
f"Environment variable {_ENV_PROXY_SUPPORT_TLS_KEY}"
"should be 0 or 1 , setting default to 0."
)
return False


def _get_proxy_host() -> str:
proxy_host = load_env_value(_ENV_LUNAR_PROXY_HOST_KEY, str, "")

if not proxy_host:
_LOGGER.warning(
f"Could not obtain the Host value of Lunar Proxy from environment variables,"
"please set {_ENV_LUNAR_PROXY_HOST_KEY} to the Lunar Proxy's host/IP and port in"
"order to allow the interceptor to be loaded."
)

return proxy_host


def _load_fail_safe() -> FailSafe:
cooldown_time = load_env_value(_ENV_FAIL_SAFE_ENTER_AFTER, int, None)
max_errors = load_env_value(_ENV_FAIL_SAFE_EXIT_COOLDOWN_SEC, int, None)

fail_safe = FailSafe(
cooldown_time=cooldown_time,
max_errors_allowed=max_errors,
cooldown_time=interceptor_config.fail_safe_config.cooldown_time,
max_errors_allowed=interceptor_config.fail_safe_config.max_errors,
logger=_LOGGER,
handle_on=(ProxyErrorException,),
)
Expand All @@ -85,17 +48,19 @@ def _load_fail_safe() -> FailSafe:


def _build_traffic_filter_from_env_vars() -> TrafficFilter:
raw_allow_list = load_env_value(_ENV_TRAFFIC_FILTER_ALLOW_LIST, str, None)
raw_block_list = load_env_value(_ENV_TRAFFIC_FILTER_BLOCK_LIST, str, None)
return TrafficFilter(raw_block_list, raw_allow_list, _LOGGER)
return TrafficFilter(
interceptor_config.traffic_filter.block_list,
interceptor_config.traffic_filter.allow_list,
_LOGGER,
)


def _initialize_hooks(proxy_host: str):
def _initialize_hooks():
lunar_interceptor = Interceptor(
lunar_proxy_host=proxy_host,
lunar_tenant_id=load_env_value(_LUNAR_TENANT_ID, str, "unknown"),
lunar_handshake_port=load_env_value(_ENV_LUNAR_HANDSHAKE_PORT_KEY, str, "8040"),
proxy_support_tls=_proxy_is_tls_supported(),
lunar_proxy_host=interceptor_config.connection_config.proxy_host,
lunar_tenant_id=interceptor_config.connection_config.tenant_id,
lunar_handshake_port=interceptor_config.connection_config.handshake_port,
proxy_support_tls=interceptor_config.connection_config.tls_supported == 1,
fail_safe=_load_fail_safe(),
traffic_filter=_build_traffic_filter_from_env_vars(),
logger=_LOGGER,
Expand All @@ -104,9 +69,27 @@ def _initialize_hooks(proxy_host: str):
_LOGGER.debug(f"Lunar Interceptor is ENABLED!")


_proxy_host = _get_proxy_host()
if _proxy_host: # Lunar Interceptor can be loaded.
_initialize_hooks(_proxy_host)
if _LOGGER.isEnabledFor(logging.DEBUG):
_LOGGER.debug(
"Lunar Interceptor has loaded in debug mode."
"The current configuration are"
f" * Interceptor Version: {interceptor_config.version}"
f" * Lunar Proxy Host: {interceptor_config.connection_config.proxy_host}"
f" * Lunar Proxy Handshake Port: {interceptor_config.connection_config.handshake_port}"
""
"Environment details:"
f" * Python Engine Version: {platform.python_version()}"
)

if (
interceptor_config.connection_config.proxy_host != ""
): # Lunar Interceptor can be loaded.
_initialize_hooks()

else: # Lunar Interceptor can׳t be loaded without the Lunar Proxy address.
_LOGGER.warning(f"Lunar Interceptor is DISABLED!")
_LOGGER.warning(
"Could not obtain the Host value of Lunar Proxy from environment variables,"
f"please set {ENV_LUNAR_PROXY_HOST_KEY} to the Lunar Proxy's host/IP and port in"
"order to allow the interceptor to be loaded."
"Lunar Interceptor is DISABLED!"
)
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
from lunar_interceptor.interceptor.interceptor import Interceptor
from lunar_interceptor.interceptor.configuration import (
InterceptorConfig,
ENV_LUNAR_PROXY_HOST_KEY,
)

__all__ = ["Interceptor"]
__all__ = ["Interceptor", "InterceptorConfig", "ENV_LUNAR_PROXY_HOST_KEY"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from typing import Optional
from dataclasses import dataclass, field

from lunar_interceptor.interceptor.hooks.const import VERSION
from lunar_interceptor.interceptor.helpers import load_env_value

ENV_LUNAR_PROXY_HOST_KEY = "LUNAR_PROXY_HOST"
_LUNAR_TENANT_ID = "LUNAR_TENANT_ID"
_ENV_LUNAR_HANDSHAKE_PORT_KEY = "LUNAR_HEALTHCHECK_PORT"
_ENV_PROXY_SUPPORT_TLS_KEY = "LUNAR_PROXY_SUPPORT_TLS"
_ENV_TRAFFIC_FILTER_ALLOW_LIST = "LUNAR_ALLOW_LIST"
_ENV_TRAFFIC_FILTER_BLOCK_LIST = "LUNAR_BLOCK_LIST"
_ENV_FAIL_SAFE_EXIT_COOLDOWN_SEC = "LUNAR_EXIT_COOLDOWN_AFTER_SEC"
_ENV_FAIL_SAFE_ENTER_AFTER = "LUNAR_ENTER_COOLDOWN_AFTER_ATTEMPTS"
_ENV_LUNAR_INTERCEPTOR_LOG_LEVEL = "LUNAR_INTERCEPTOR_LOG_LEVEL"


@dataclass
class TrafficFilterConfig:
allow_list: Optional[str] = load_env_value(
_ENV_TRAFFIC_FILTER_ALLOW_LIST, str, None
)
block_list: Optional[str] = load_env_value(
_ENV_TRAFFIC_FILTER_BLOCK_LIST, str, None
)


@dataclass
class FailSafeConfig:
cooldown_time: int = load_env_value(_ENV_FAIL_SAFE_ENTER_AFTER, int, 10)
max_errors: int = load_env_value(_ENV_FAIL_SAFE_EXIT_COOLDOWN_SEC, int, 5)


@dataclass
class ConnectionConfig:
proxy_host: str = load_env_value(ENV_LUNAR_PROXY_HOST_KEY, str, "")
tls_supported = load_env_value(_ENV_PROXY_SUPPORT_TLS_KEY, int, 0)
tenant_id: str = load_env_value(_LUNAR_TENANT_ID, str, "unknown")
handshake_port: str = load_env_value(_ENV_LUNAR_HANDSHAKE_PORT_KEY, str, "8040")


@dataclass
class InterceptorConfig:
version: str = VERSION
connection_config: ConnectionConfig = field(default_factory=ConnectionConfig)
traffic_filter: TrafficFilterConfig = field(default_factory=TrafficFilterConfig)
fail_safe_config: FailSafeConfig = field(default_factory=FailSafeConfig)
log_level: str = load_env_value(_ENV_LUNAR_INTERCEPTOR_LOG_LEVEL, str, "INFO")
Loading

0 comments on commit 77e0089

Please sign in to comment.