~sumner/nixos-configuration

ref: 77d5f4f4777b1b15d154dca95f1cbb2947c5d723 nixos-configuration/modules/services/goaccess.nix -rw-r--r-- 5.5 KiB
77d5f4f4Sumner Evans goaccess: delete stats from days older than a month 3 months ago
                                                                                
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
{ config, lib, options, pkgs, ... }: with lib; let
  cfg = config.services.metrics;
  hostnameDomain = "${config.networking.hostName}.${config.networking.domain}";
  goaccessDir = "/var/www/goaccess";
  excludeIPs = [
    "184.96.89.215"
    "184.96.97.165"
    "63.239.147.18"
  ];

  goaccessCmd = infile: outfile: ''
    ${pkgs.goaccess}/bin/goaccess ${infile} \
      -o ${outfile} \
      --ignore-crawlers \
      ${concatMapStringsSep " " (e: "-e \"${e}\"") excludeIPs} \
      --real-os \
      --log-format=COMBINED
  '';

  goaccessWebsiteMetricsForDayScriptPart = infile: hostname: n: ''
    # Output log for day $DATE - ${toString n}
    logdatefmt=$(${pkgs.coreutils}/bin/date +%d/%b/%Y -d "$DATE - ${toString n} day")
    outdatefmt=$(${pkgs.coreutils}/bin/date +%Y-%m-%d -d "$DATE - ${toString n} day")
    ${pkgs.coreutils}/bin/cat ${infile} |
      ${pkgs.gnugrep}/bin/grep "\[$logdatefmt" |
      ${goaccessCmd "-" "${goaccessDir}/${hostname}/days/$outdatefmt.html"}
  '';

  pipeIf = condition: cmd: if condition then "| ${cmd}" else "";

  goaccessWebsiteMetricsScript = { hostname, excludeTerms, ... }:
    pkgs.writeShellScript "goaccess-${hostname}" ''
      set -xef
      cd /var/log/nginx
      mkdir -p ${goaccessDir}/${hostname}/days

      logtmp=$(${pkgs.coreutils}/bin/mktemp)
      trap "rm -rfv $logtmp" EXIT

      # Combine the gzipped and non-gziped logs together
      ${pkgs.coreutils}/bin/cat \
        <(${pkgs.findutils}/bin/find . -regextype awk -regex "./${hostname}.access.log.[0-9]+.gz" |
            ${pkgs.findutils}/bin/xargs ${pkgs.gzip}/bin/zcat -fq) \
        <(${pkgs.findutils}/bin/find . -regextype awk -regex "./${hostname}.access.log(\.[0-9]+)?" |
            ${pkgs.findutils}/bin/xargs ${pkgs.coreutils}/bin/cat) \
            ${pipeIf (excludeTerms != [])
      "${pkgs.gnugrep}/bin/grep -v ${concatMapStringsSep " " (e: "-e \"${e}\"") excludeTerms}"} \
        > $logtmp

      # Run Goaccess for all of the logs that we have.
      ${goaccessCmd "$logtmp" "${goaccessDir}/${hostname}/index.html"}

      # Run Goaccess for the past week days as well.
      ${concatMapStringsSep "\n" (goaccessWebsiteMetricsForDayScriptPart "$logtmp" hostname) (range 0 7)}

      # Clean-up days older than a month.
      ${pkgs.findutils}/bin/find ${goaccessDir}/${hostname}/days -mtime +30 -delete
    '';

  hostListItem = { hostname, ... }: ''
    echo "
        <li>
          <a href=\"/metrics/${hostname}\">${hostname}</a>
          (<a href=\"/metrics/${hostname}/days\">Per Day</a>)
        </li>" >> ${goaccessDir}/index.html
  '';

  goaccessScript = websites: pkgs.writeShellScript "goaccess" ''
    set -xe
    cd /var/log/nginx
    ${pkgs.coreutils}/bin/mkdir -p ${goaccessDir}

    echo "<html>"                                > ${goaccessDir}/index.html
    echo "<head><title>Metrics</title></head>"  >> ${goaccessDir}/index.html
    echo "<body>"                               >> ${goaccessDir}/index.html
    echo "<h1>Metrics</h1>"                     >> ${goaccessDir}/index.html
    echo "<ul>"                                 >> ${goaccessDir}/index.html

    ${concatMapStringsSep "\n" hostListItem websites}

    echo "</ul>"                                >> ${goaccessDir}/index.html
    echo "</body>"                              >> ${goaccessDir}/index.html
  '';
in
{
  options =
    let
      websiteOpts = { ... }: {
        options = {
          hostname = mkOption {
            type = types.str;
            description = "Website name";
          };
          extraLocations = mkOption {
            type = types.attrsOf (types.submodule options.services.nginx.virtualHosts.locations.type);
            description = "Exclude patterns for metrics.";
            default = [];
          };
          excludeTerms = mkOption {
            type = types.listOf types.str;
            description = "Exclude patterns for metrics.";
            default = [];
          };
        };
      };
    in
      {
        services.metrics = {
          websites = mkOption {
            type = with types; listOf (submodule websiteOpts);
            description = ''
              A list of websites to create metrics for.
            '';
            default = [];
          };
        };
      };

  config = mkIf (cfg.websites != []) {
    systemd.services =
      let
        mkGoaccessService = website: {
          name = "goaccess-${website.hostname}";
          value = {
            description = "Goaccess web log report for ${website.hostname}.";
            serviceConfig = {
              User = "root";
              ExecStart = "${goaccessWebsiteMetricsScript website}";
            };
          };
        };
      in
        listToAttrs (map mkGoaccessService cfg.websites) // {
          goaccess-index = {
            description = "Generate Goaccess index.";
            serviceConfig = {
              User = "root";
              ExecStart = "${goaccessScript cfg.websites}";
              Type = "oneshot";
            };
          };
        };

    systemd.timers = let
      mkGoaccessTimer = website: {
        name = "goaccess-${website.hostname}";
        value = {
          description = "Goaccess timer for ${website.hostname}";
          wantedBy = [ "timers.target" ];
          timerConfig.OnCalendar = "*:0/15";
        };
      };
    in
      listToAttrs (map mkGoaccessTimer cfg.websites);

    # Set up nginx to forward requests properly.
    services.nginx.virtualHosts.${hostnameDomain} = {
      locations."/metrics/" = {
        alias = "${goaccessDir}/";
        extraConfig = ''
          autoindex on;
        '';
      };
    };
  };
}