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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
use curl::easy::Easy2;

use rayon::prelude::*;
use regex::Regex;

use std::fs;
use std::io::{Error, ErrorKind};
use std::path::Path;


use crate::*;


/// Provide pongo page expectations:
pub fn pongo_page_expectations() -> PageExpectations {
    vec![
        PageExpectation::ValidCode(CHECK_DEFAULT_SUCCESSFUL_HTTP_CODE),
        // PageExpectation::ValidLength(CHECK_HTTP_MINIMUM_LENGHT),
        PageExpectation::ValidAddress("https://".to_string()),
        PageExpectation::ValidContent("SIGN IN".to_string()),
    ]
}


/// Provide pongo showroom page expectations:
pub fn showroom_page_expectations() -> PageExpectations {
    vec![
        PageExpectation::ValidCode(CHECK_DEFAULT_SUCCESSFUL_HTTP_CODE),
        // PageExpectation::ValidLength(CHECK_HTTP_MINIMUM_LENGHT),
        PageExpectation::ValidAddress("https://".to_string()),
        PageExpectation::ValidContent("API: 'https://".to_string()),
    ]
}


//
// Data structures based on private Centra API, called "Pongo":
//


#[derive(Debug, Clone, Serialize, Deserialize, Default)]
/// Remote structure that will be loaded as GenCheck:
pub struct PongoHost {
    /// Client data:
    pub data: PongoHostData,

    /// Client name:
    pub client: Option<String>,

    /// Client is active?:
    pub active: Option<bool>,

    /// Curl options:
    #[serde(skip_serializing_if = "Option::is_none")]
    pub options: Option<PageOptions>,

    /// Slack Webhook
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alert_webhook: Option<String>,

    /// Slack alert channel
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alert_channel: Option<String>,

    /// Domains to check
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domains: Option<Domains>,

    /// Pages to check
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pages: Option<Pages>,
}


#[derive(Debug, Clone, Serialize, Deserialize, Default)]
/// Remote structure that will be loaded as GenCheck:
pub struct PongoHostData {
    /// Host inner object:
    pub host: Option<PongoHostDetails>,

    /// Client env:
    #[serde(skip_serializing_if = "Option::is_none")]
    pub env: Option<String>,

    /// Client ams:
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ams: Option<String>,
}


#[derive(Debug, Clone, Serialize, Deserialize, Default)]
/// Remote structure that will be loaded as GenCheck:
pub struct PongoHostDetails {
    /// List of virtual hosts of client:
    pub vhosts: Option<Vec<String>>,

    /// Showroom urls of client:
    pub showroom_urls: Option<Vec<String>>,
}


/// PongoHosts collection type
pub type PongoHosts = Vec<PongoHost>;


#[derive(Debug, Clone, Serialize, Deserialize, Default)]
/// Map Remote fields/values mapper structure to GenCheck:
pub struct PongoRemoteMapper {
    /// Resource URL
    pub url: String,

    /// Check AMS only for specified subdomain
    #[serde(skip_serializing_if = "Option::is_none")]
    pub only_vhost_contains: Option<String>,

    /// Slack Webhook
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alert_webhook: Option<String>,

    /// Slack alert channel
    #[serde(skip_serializing_if = "Option::is_none")]
    pub alert_channel: Option<String>,
}


impl Checks<PongoHost> for PongoHost {
    fn load(remote_file_name: &str) -> Result<PongoHost, Error> {
        let mapper: PongoRemoteMapper = read_text_file(&remote_file_name)
            .and_then(|file_contents| {
                serde_json::from_str(&file_contents)
                    .map_err(|err| Error::new(ErrorKind::InvalidInput, err.to_string()))
            })
            .unwrap_or_default();

        let mut easy = Easy2::new(Collector(Vec::new()));
        easy.get(true).unwrap_or_default();
        easy.url(&mapper.url).unwrap_or_default();
        easy.perform().unwrap_or_default();
        let contents = easy.get_ref();
        let remote_raw = String::from_utf8_lossy(&contents.0);
        debug!(
            "PongoRemoteMapper::load REMOTE-JSON length: {}",
            &remote_raw.len().to_string().cyan()
        );

        // now use default Pongo structure defined as default for PongoRemoteMapper
        let pongo_hosts: PongoHosts = serde_json::from_str(&remote_raw)
            .map_err(|err| error!("Failed to parse Pongo input: {:#?}", err))
            .unwrap_or_default();

        debug!("Pongo hosts: {:#?}", &pongo_hosts);
        let pongo_checks = pongo_hosts
            .clone()
            .into_par_iter()
            .flat_map(|host| {
                let ams = host.clone().data.ams.unwrap_or_default();
                let active = host.active.unwrap_or_else(|| false);
                let client = host.clone().client.unwrap_or_default();
                let options = host.clone().options;

                let pongo_private_token = Regex::new(r"\?token=[A-Za-z0-9_-]*").unwrap();
                let safe_url = pongo_private_token.replace(&mapper.url, "[[token-masked]]");
                debug!(
                    "Pongo: URL: {}, CLIENT: {}, AMS: {}. ACTIVE: {}",
                    &safe_url.cyan(),
                    &client.cyan(),
                    &ams.cyan(),
                    format!("{}", active).cyan()
                );
                [
                    // merge two lists for URLs: "vhosts" and "showrooms":
                    host.clone()
                        .data
                        .host
                        .unwrap_or_default()
                        .vhosts
                        .and_then(|vhosts| {
                            vhosts
                                .par_iter()
                                .filter(|vhost| {
                                    !vhost.starts_with("*.")
                                        && vhost.contains(
                                            &mapper
                                                .only_vhost_contains
                                                .clone()
                                                .unwrap_or_default(),
                                        )
                                }) // filter out wildcard domains and pick only these matching value of only_vhost_contains field
                                .map(|vhost| {
                                    if active {
                                        Some(Page {
                                            url: format!(
                                                "{}{}/{}/",
                                                CHECK_DEFAULT_PROTOCOL, vhost, ams
                                            ),
                                            expects: pongo_page_expectations(),
                                            options: options.clone(),
                                        })
                                    } else {
                                        debug!("Skipping not active client: {}", &client);
                                        None
                                    }
                                })
                                .collect::<Option<Pages>>()
                        })
                        .unwrap_or_default(),
                    host.data
                        .host
                        .unwrap_or_default()
                        .showroom_urls
                        .and_then(|showrooms| {
                            showrooms
                                .par_iter()
                                .map(|vhost| {
                                    if active {
                                        Some(Page {
                                            url: vhost.to_string(),
                                            expects: showroom_page_expectations(),
                                            options: None,
                                        })
                                    } else {
                                        debug!("Skipping not active client: {}", &client);
                                        None
                                    }
                                })
                                .collect::<Option<Pages>>()
                        })
                        .unwrap_or_default(),
                ]
                .concat()
            })
            .collect();
        let domain_checks = pongo_hosts
            .into_par_iter()
            .flat_map(|host| {
                host.data
                    .host
                    .unwrap_or_default()
                    .vhosts
                    .and_then(|vhosts| {
                        vhosts
                            .par_iter()
                            .filter(|vhost| !vhost.starts_with("*.")) // filter out wildcard domains
                            .map(|vhost| {
                                Some(Domain {
                                    name: vhost.to_string(),
                                    expects: default_domain_expectations(),
                                })
                            })
                            .collect::<Option<Domains>>()
                    })
                    .unwrap_or_default()
            })
            .collect();
        Ok(PongoHost {
            pages: Some(pongo_checks),
            domains: Some(domain_checks),

            // pass alert webhook and channel from mapper to the checks
            alert_webhook: mapper.alert_webhook,
            alert_channel: mapper.alert_channel,
            ..PongoHost::default()
        })
    }


    fn execute(&self, execution_name: &str) -> History {
        let history = History::new_from(
            [
                Self::check_pages(self.pages.clone()).stories(),
                Self::check_domains(self.domains.clone()).stories(),
            ]
            .concat(),
        );
        match (&self.alert_webhook, &self.alert_channel) {
            (Some(webhook), Some(channel)) => {
                let failures = history
                    .stories()
                    .iter()
                    .filter_map(|story| {
                        if let Some(error) = &story.error {
                            Some(format!("{}\n", error))
                        } else {
                            None
                        }
                    })
                    .collect::<String>();

                let failures_state_file =
                    &format!("{}-{}", DEFAULT_FAILURES_STATE_FILE, execution_name);
                debug!("Failures state file: {}", failures_state_file);
                debug!("FAILURES: {:?}", failures);
                if failures.is_empty() {
                    if Path::new(failures_state_file).exists() {
                        debug!(
                            "No more failures! Removing failures log file and notifying that failures are gone"
                        );
                        fs::remove_file(failures_state_file).unwrap_or_default();
                        notify_success(
                            webhook,
                            channel,
                            &format!("All services are UP again ({}).\n", &execution_name),
                        );
                    } else {
                        debug!("All services are OK! No notification sent");
                    }
                } else {
                    // there are errors:
                    let file_entries = read_text_file(failures_state_file).unwrap_or_default();

                    let send_notification = failures.split('\n').find(|fail| {
                        if !file_entries.contains(fail) {
                            write_append(failures_state_file, &fail.to_string());
                            true
                        } else {
                            false
                        }
                    });
                    // send notification only for new error that's not present in failure state
                    let failures_to_notify = failures
                        .split('\n')
                        .filter(|fail| !file_entries.contains(fail))
                        .map(|fail| format!("{}\n", fail))
                        .collect::<String>();

                    if send_notification.is_some() {
                        notify_failure(webhook, channel, &failures_to_notify);
                    }
                }
            }
            (..) => {
                info!("Notifications not configured hence skipped…");
            }
        };
        history
    }
}


/// Implement JSON serialization on .to_string():
impl ToString for PongoRemoteMapper {
    fn to_string(&self) -> String {
        serde_json::to_string(&self).unwrap_or_else(|_| {
            String::from("{\"status\": \"PongoRemoteMapper serialization failure\"}")
        })
    }
}