1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
use std::str::FromStr;
use tracing_subscriber::EnvFilter;

use color_eyre::Help;
use rusoto_core::{Region, RusotoError};
use rusoto_s3::S3;
use rusoto_sqs::{ListQueuesRequest, Sqs};
use sqs_lambda::redis_cache::RedisCache;
use std::time::Duration;
use tracing::debug;

#[macro_export]
macro_rules! init_grapl_log {
    () => {
        $crate::_init_grapl_log(&module_path!().replace("-", "_"));
    };
    ($module_name: literal) => {
        $crate::_init_grapl_log($module_name);
    };
}

pub fn is_local() -> bool {
    std::env::var("IS_LOCAL")
        .map(|is_local| is_local.to_lowercase().parse().unwrap_or(false))
        .unwrap_or(false)
}

pub async fn event_cache() -> RedisCache {
    let cache_address = {
        let generic_event_cache_addr =
            std::env::var("EVENT_CACHE_ADDR").expect("GENERIC_EVENT_CACHE_ADDR");
        let generic_event_cache_port =
            std::env::var("EVENT_CACHE_PORT").expect("GENERIC_EVENT_CACHE_PORT");

        format!("{}:{}", generic_event_cache_addr, generic_event_cache_port,)
    };

    RedisCache::new(cache_address.to_owned())
        .await
        .expect("Could not create redis client")
}

pub fn region() -> Region {
    let region_override = std::env::var("AWS_REGION_OVERRIDE");

    match region_override {
        Ok(region) => Region::Custom {
            name: "override".to_string(),
            endpoint: region,
        },
        Err(_) => {
            let region_str = std::env::var("AWS_REGION").expect("AWS_REGION");
            Region::from_str(&region_str).expect("Region error")
        }
    }
}

pub fn grapl_log_level() -> log::Level {
    match std::env::var("GRAPL_LOG_LEVEL") {
        Ok(level) => {
            log::Level::from_str(&level).expect(&format!("Invalid logging level {}", level))
        }
        Err(_) => log::Level::Error,
    }
}

pub fn _init_grapl_log(service_name: &str) {
    let filter = EnvFilter::from_default_env().add_directive(
        format!("{}={}", service_name, grapl_log_level())
            .parse()
            .expect("Invalid directive"),
    );
    if is_local() {
        tracing_subscriber::fmt().with_env_filter(filter).init();
    } else {
        tracing_subscriber::fmt()
            .json()
            .with_env_filter(filter)
            .init();
    }
}

pub fn mg_alphas() -> Vec<String> {
    return std::env::var("MG_ALPHAS")
        .expect("MG_ALPHAS")
        .split(',')
        .map(str::to_string)
        .collect();
}

pub fn parse_host_port(mg_alpha: String) -> (String, u16) {
    let mut splat = mg_alpha.split(":");
    let host = splat.next().expect("missing host").to_owned();
    let port_str = splat.next();
    let port = port_str
        .expect("missing port")
        .parse()
        .expect(&format!("invalid port: \"{:?}\"", port_str));

    (host, port)
}

pub async fn wait_for_s3(s3_client: impl S3) -> color_eyre::Result<()> {
    wait_loop(150, || async {
        match s3_client.list_buckets().await {
            Err(RusotoError::HttpDispatch(e)) => {
                debug!("Waiting for S3 to become available: {:?}", e);
                Err(e)
            }
            _ => Ok(()),
        }
    })
    .await?;

    Ok(())
}

pub async fn wait_for_sqs(
    sqs_client: impl Sqs,
    queue_name_prefix: impl Into<String>,
) -> color_eyre::Result<()> {
    let queue_name_prefix = queue_name_prefix.into();
    wait_loop(150, || async {
        match sqs_client
            .list_queues(ListQueuesRequest {
                queue_name_prefix: Some(queue_name_prefix.clone()),
            })
            .await
        {
            Err(RusotoError::HttpDispatch(e)) => {
                debug!("Waiting for S3 to become available: {:?}", e);
                Err(e)
            }
            _ => Ok(()),
        }
    })
    .await?;

    Ok(())
}

async fn wait_loop<F, E>(max_tries: u32, f: impl Fn() -> F) -> color_eyre::Result<()>
where
    F: std::future::Future<Output = Result<(), E>>,
    E: std::error::Error + Send + Sync + 'static,
{
    let mut errs: Result<(), _> = Err(eyre::eyre!("wait_loop failed"));
    for _ in 0..max_tries {
        match (f)().await {
            Ok(()) => return Ok(()),
            Err(e) => {
                errs = errs.error(e);
            }
        };

        tokio::time::delay_for(Duration::from_secs(2)).await;
    }

    errs
}

pub fn static_mapping_table_name() -> String {
    return std::env::var("STATIC_MAPPING_TABLE").expect("STATIC_MAPPING_TABLE");
}

pub fn dynamic_session_table_name() -> String {
    return std::env::var("DYNAMIC_SESSION_TABLE").expect("DYNAMIC_SESSION_TABLE");
}

pub fn process_history_table_name() -> String {
    return std::env::var("PROCESS_HISTORY_TABLE").expect("PROCESS_HISTORY_TABLE");
}

pub fn file_history_table_name() -> String {
    return std::env::var("FILE_HISTORY_TABLE").expect("FILE_HISTORY_TABLE");
}

pub fn inbound_connection_history_table_name() -> String {
    return std::env::var("INBOUND_CONNECTION_HISTORY_TABLE")
        .expect("INBOUND_CONNECTION_HISTORY_TABLE");
}

pub fn outbound_connection_history_table_name() -> String {
    return std::env::var("OUTBOUND_CONNECTION_HISTORY_TABLE")
        .expect("OUTBOUND_CONNECTION_HISTORY_TABLE");
}

pub fn network_connection_history_table_name() -> String {
    return std::env::var("NETWORK_CONNECTION_HISTORY_TABLE")
        .expect("NETWORK_CONNECTION_HISTORY_TABLE");
}

pub fn ip_connection_history_table_name() -> String {
    return std::env::var("IP_CONNECTION_HISTORY_TABLE").expect("IP_CONNECTION_HISTORY_TABLE");
}

pub fn asset_id_mappings_table_name() -> String {
    return std::env::var("ASSET_ID_MAPPINGS").expect("ASSET_ID_MAPPINGS");
}