Skip to content

Instantly share code, notes, and snippets.

@HarlanH
Created November 30, 2017 18:41
Show Gist options
  • Save HarlanH/99b82a35d3190d879c0f6b9abeaf7032 to your computer and use it in GitHub Desktop.
Save HarlanH/99b82a35d3190d879c0f6b9abeaf7032 to your computer and use it in GitHub Desktop.
R Flexdashboard for dbt production metrics
---
title: "dbt Metrics"
output:
flexdashboard::flex_dashboard:
orientation: rows
---
<!--
If dbt is being run on an AWS server with logs being pulled into Cloudwatch,
this script generates a static dashboard of this history of your production dbt
runs.
Requirements:
* R with the packages in the `setup` block
* The AWS CLI installed and configured to access your systems
* Change the constants in `setup`
* Assumes you use model category prefixes of `stg`, `dim`, and `act` -- if you don't,
you'll probably need to change some code.
Author:
Harlan Harris, [email protected]
-->
<!--
MIT License
Copyright (c) 2017 Harlan D. Harris
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->
```{r setup, include=FALSE}
library(flexdashboard)
library(jsonlite)
library(magrittr)
library(tidyverse)
library(stringr)
library(forcats)
library(lubridate)
library(plotly)
library(glue)
usecache=FALSE # possibly set to TRUE for development
knitr::opts_chunk$set(fig.height=2.5, fig.width=5)
aws_path = "~/.local/bin/aws"
log_group_name = "/aws/batch/job"
log_stream_name_prefix = "run_dbt"
max_items = 10
contact = "[email protected]"
```
```{r get_files, cache=usecache}
base_get_files <- glue("{aws_path} logs describe-log-streams --log-group-name {log_group_name} --log-stream-name-prefix {log_stream_name_prefix} --max-items {max_items}")
get_files_next <- NA
get_files_df <- data_frame()
repeat {
get_files_cmd <- if (!is.na(get_files_next)) {
paste(base_get_files, glue("--starting-token {get_files_next}"))
} else base_get_files
ret <- system(get_files_cmd, intern=TRUE) %>% paste %>% fromJSON
get_files_df <- bind_rows(get_files_df, ret$logStreams)
if (!is.null(ret$NextToken)) {
#print(ret$NextToken)
get_files_next <- ret$NextToken
} else break
}
get_files_df %<>%
mutate(creationTime = as.POSIXct(creationTime/1000, origin = "1970-01-01")) %>% # ms since origin!
select(creationTime, logStreamName, storedBytes) %>%
arrange(creationTime)
```
```{r get_records, cache=usecache}
# now, for each of these streams, get the logs and parse
#' @param js one JSON object
parse_one_log <- function(df) {
found_row <- str_subset(df$message, "^Found")
start_rows <- str_subset(df$message, "START")
finish_row <- str_subset(df$message, "Finished")
done_row <- str_subset(df$message, "Done")
if (length(found_row) == 0 || length(start_rows) == 0 || length(finish_row) == 0 || length(done_row) == 0)
return(data_frame())
num_models <- str_match(found_row, "([0-9]+) models")[1,2]
num_tests <- str_match(found_row, "([0-9]+) tests")[1,2]
prefixes <- str_match(start_rows, "\\.([^_]+)_")[,2]
num_stg_models <- sum(prefixes == "stg")
num_dim_models <- sum(prefixes == "dim")
num_act_models <- sum(prefixes == "act")
run_time_sec <- str_match(finish_row, "in ([0-9.]+)s")[1,2]
num_view_models <- str_match(finish_row, "([0-9]+) view models")[1,2]
num_table_models <- str_match(finish_row, "([0-9]+) table models")[1,2]
num_incr_models <- str_match(finish_row, "([0-9]+) incremental models")[1,2]
num_pass_models <- str_match(done_row, "PASS=([0-9]+)")[1,2]
num_error_models <- str_match(done_row, "ERROR=([0-9]+)")[1,2]
num_skip_models <- str_match(done_row, "SKIP=([0-9]+)")[1,2]
data_frame(num_models, num_tests, num_stg_models, num_dim_models, num_act_models,
run_time_sec, num_view_models, num_table_models, num_incr_models,
num_pass_models, num_error_models, num_skip_models) %>% mutate_all(as.numeric)
}
get_stream_base <- "{aws_path} logs get-log-events --log-group-name {log_group_name} --log-stream-name"
logs <- get_files_df %>% # this takes a few minutes, mostly AWS query time
group_by(logStreamName) %>%
do({
get_stream_cmd <- paste(get_stream_base, .$logStreamName)
#print(get_stream_cmd)
ret <- system(get_stream_cmd, intern = TRUE) %>% paste %>% fromJSON
bind_cols(., parse_one_log(ret$events))
}) %>% ungroup
# NOTE! Gets test and product script output too!
```
# Metrics
Row {data-height=650}
-----------------------------------------------------------------------
### Outcome
```{r success}
filter(logs, !is.na(num_models)) %>%
select(creationTime, Pass=num_pass_models, Error=num_error_models, Skip=num_skip_models) %>%
gather(metric, value, -creationTime) %>%
ggplot(aes(creationTime, value, fill=metric)) +
geom_area() +
xlab("") +
ylab("") +
scale_fill_manual("", values = c("red", "grey50", "orange"))
```
### Time
```{r time}
filter(logs, !is.na(num_models)) %>%
select(creationTime, run_time_sec, num_error_models) %>%
mutate(any_errors=num_error_models > 0,
run_time_sec=pmin(run_time_sec, 9*60*60)) %>%
ggplot(aes(creationTime, run_time_sec/(60*60))) +
geom_line() +
geom_point(aes(color=any_errors), size=.5) +
xlab("") +
scale_y_continuous("Hours (truncated at 9)", breaks=0:12) +
scale_color_manual("Any Errors", values=c("grey30", "red"))
```
Row {data-height=650}
-----------------------------------------------------------------------
### Semantic Type
```{r Level}
filter(logs, !is.na(num_models), num_error_models==0) %>%
select(creationTime, Staging=num_stg_models, Dimension=num_dim_models, Activity=num_act_models, num_models) %>%
mutate(Other = num_models - (Staging + Dimension+Activity)) %>%
select(-num_models) %>%
gather(metric, value, -creationTime) %>%
ggplot(aes(creationTime, value, fill=metric)) +
geom_area() +
xlab("") +
ylab("") +
scale_fill_discrete("")
```
> Runs resulting in errors excluded. Level defined by table prefix.
### Logical Type
```{r type}
filter(logs, !is.na(num_models), num_error_models==0) %>%
select(creationTime, Views=num_view_models, Table=num_table_models, Incremental=num_incr_models) %>%
gather(metric, value, -creationTime) %>%
ggplot(aes(creationTime, value, fill=metric)) +
geom_area() +
xlab("") +
ylab("") +
scale_fill_discrete("")
```
> Runs resulting in errors excluded.
# About
* Generated `r now()`. Contact `r contact` with questions or suggestions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment