<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Erkan Cetiner on Medium]]></title>
        <description><![CDATA[Stories by Erkan Cetiner on Medium]]></description>
        <link>https://medium.com/@ecetiner87?source=rss-6d9064cc812e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2KX7fJdgfFI4CthUWvdrUQ.jpeg</url>
            <title>Stories by Erkan Cetiner on Medium</title>
            <link>https://medium.com/@ecetiner87?source=rss-6d9064cc812e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 01:47:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ecetiner87/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[A Practical Grafana Dashboard for Watching Redis Keys at Scale]]></title>
            <link>https://medium.com/@ecetiner87/a-practical-grafana-dashboard-for-watching-redis-keys-at-scale-74d39af3dc6b?source=rss-6d9064cc812e------2</link>
            <guid isPermaLink="false">https://medium.com/p/74d39af3dc6b</guid>
            <dc:creator><![CDATA[Erkan Cetiner]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 00:06:15 GMT</pubDate>
            <atom:updated>2025-08-20T00:06:15.595Z</atom:updated>
            <content:encoded><![CDATA[<p>On <strong>high-traffic</strong> systems, <strong>Redis</strong> is often the <strong>first</strong> — and <strong>most fragile</strong> — line of defense for latency. <strong>Big</strong> or “<strong>hot</strong>” keys can quietly bother memory, skew shard balance, and throttle throughput. I built a Grafana dashboard that:</p><ul><li>Tracks key sizes,</li><li>Lists the top 50 keys by memory,</li><li>Charts the top 5 memory consumers over time,</li><li>Groups by key type,</li><li>And raises alerts when any key crosses a size threshold.</li></ul><p>Below I explain <em>why</em> this matters and <em>what</em> you gain from such a dashboard.</p><h3>Why Redis Matters for High-Traffic Systems</h3><p>Redis sits squarely in the critical path of modern services: caching database results, powering rate limits, session stores, leaderboards, message queues, and more. Its appeal is simple:</p><ul><li><strong>Consistently low latency</strong> (single-digit ms) under heavy concurrency.</li><li><strong>Rich data types</strong> (Strings, Hashes, Sets, Sorted Sets, Streams, Bitmaps) that map well to common patterns.</li><li><strong>Horizontal scaling via Redis Cluster</strong> to push read/write throughput beyond a single machine.</li></ul><p>When <strong>traffic spikes</strong>, Redis often becomes the <strong>performance floor </strong>of the entire application. If Redis is fast and stable, upstream and downstream components breathe easier. If it slows, <strong>p95/p99 latencies climb everywhere</strong>, and autoscaling in your app tier can’t hide it.</p><h3>Why Track Per-Key Memory in Redis Cluster</h3><p>Most teams track <strong>node-level metrics</strong> — <strong>CPU</strong>, <strong>RSS</strong>, <strong>used_memory</strong>, <strong>ops/sec</strong>. That’s <strong>necessary</strong> <strong>but</strong> <strong>not sufficient</strong>. Real incidents are often caused by <strong>key-level pathologies</strong> that node metrics can’t pinpoint:</p><ul><li>A key suddenly <strong>balloons</strong> from a few <strong>KB</strong> to <strong>hundreds of MB.</strong></li><li>A single Sorted Set or Stream becomes <strong>too “hot”</strong> and starts dominating a <strong>shard’s CPU.</strong></li><li>An application bug writes the <strong>same payload under many similar keys</strong> (exploding cardinality).</li><li>A Hash accumulates thousands of fields (<strong>accidental</strong> “<strong>document store</strong>”).</li></ul><p><strong>Per-key visibility</strong> connects application behavior to infrastructure reality. When you can see <strong>which keys are largest</strong> and <strong>how they evolve over time</strong>, you can answer:</p><ul><li>“What changed right before latency spiked?”</li><li>“Which shard is heavy because of <em>which</em> key?”</li><li>“Is this a legit workload shift or a bug?”</li></ul><h3>Implementation</h3><p><strong>At first</strong>; we implemented <strong>a bash script to analyze Redis Cluster keys’</strong> <strong>memory usage</strong> across <strong>all master nodes</strong> and <strong>outputs</strong> the data in <strong>JSON</strong> format suitable for Grafana consumption</p><pre>#!/bin/bash<br><br># ========================================<br># Redis Cluster Memory Analyzer for Grafana<br># ========================================<br><br><br># === CONFIGURATION ===<br>REDIS_NODES=(<br>    &quot;10.10.10.10:6379&quot;<br>    &quot;10.10.10.11:6379&quot;<br>    &quot;10.10.10.12:6379&quot;<br>    # Add your other master nodes here<br>)<br>REDIS_PASSWORD=&quot;${REDISCLI_AUTH:-mypassword!}&quot;<br>TOP_KEYS_LIMIT=50<br>OUTPUT_DIR=&quot;/var/lib/grafana-redis-data&quot;<br>TIMESTAMP=$(date +%s)<br><br>mkdir -p &quot;$OUTPUT_DIR&quot;<br><br># === OUTPUT FILES ===<br>JSON_OUTPUT=&quot;$OUTPUT_DIR/redis_memory_keys.json&quot;<br>CSV_OUTPUT=&quot;$OUTPUT_DIR/redis_memory_keys.csv&quot;<br>TEMP_FILE=&quot;$OUTPUT_DIR/temp_analysis.csv&quot;<br><br># === LOGGING ===<br>log() {<br>    echo &quot;[$(date &#39;+%Y-%m-%d %H:%M:%S&#39;)] $1&quot; &gt;&amp;2<br>}<br><br>get_cluster_info() {<br>    local host_port=$1<br>    local host=$(echo $host_port | cut -d&#39;:&#39; -f1)<br>    local port=$(echo $host_port | cut -d&#39;:&#39; -f2)<br><br>    redis-cli -h &quot;$host&quot; -p &quot;$port&quot; -a &quot;$REDIS_PASSWORD&quot; cluster nodes 2&gt;/dev/null | \<br>    grep master | grep -v fail | awk &#39;{print $2}&#39; | cut -d&#39;@&#39; -f1<br>}<br><br>analyze_node() {<br>    local host_port=$1<br>    local host=$(echo $host_port | cut -d&#39;:&#39; -f1)<br>    local port=$(echo $host_port | cut -d&#39;:&#39; -f2)<br>    local node_id=&quot;${host}:${port}&quot;<br><br>    log &quot;Analyzing node: $node_id&quot;<br><br>    # Check if node is accessible<br>    if ! redis-cli -h &quot;$host&quot; -p &quot;$port&quot; ping &gt;/dev/null 2&gt;&amp;1; then<br>        log &quot;ERROR: Cannot connect to $node_id&quot;<br>        return 1<br>    fi<br><br>    # Get node role<br>    local role=$(redis-cli -h &quot;$host&quot; -p &quot;$port&quot; info replication | grep &quot;role:master&quot; | wc -l)<br>    if [ &quot;$role&quot; -eq 0 ]; then<br>        log &quot;SKIP: $node_id is not a master node&quot;<br>        return 0<br>    fi<br><br>    # Scan keys and get memory usage<br>    redis-cli -h &quot;$host&quot; -p &quot;$port&quot; --scan | while read key; do<br>        if [ -n &quot;$key&quot; ]; then<br>            local usage=$(redis-cli -h &quot;$host&quot; -p &quot;$port&quot; MEMORY USAGE &quot;$key&quot; 2&gt;/dev/null)<br>            local type=$(redis-cli -h &quot;$host&quot; -p &quot;$port&quot; TYPE &quot;$key&quot; 2&gt;/dev/null)<br>            local ttl=$(redis-cli -h &quot;$host&quot; -p &quot;$port&quot; TTL &quot;$key&quot; 2&gt;/dev/null)<br><br>            if [ -n &quot;$usage&quot; ] &amp;&amp; [ &quot;$usage&quot; != &quot;(nil)&quot; ]; then<br>                echo &quot;$usage,$key,$type,$ttl,$node_id,$TIMESTAMP&quot; &gt;&gt; &quot;$TEMP_FILE&quot;<br>            fi<br>        fi<br>    done<br>}<br><br>log &quot;Starting Redis Cluster Memory Analysis&quot;<br>log &quot;Output directory: $OUTPUT_DIR&quot;<br><br>echo &quot;memory_bytes,key_name,key_type,ttl,node,timestamp&quot; &gt; &quot;$TEMP_FILE&quot;<br><br># Analyze each configured node<br>for node in &quot;${REDIS_NODES[@]}&quot;; do<br>    analyze_node &quot;$node&quot;<br>done<br><br># Check if we have any data<br>if [ ! -s &quot;$TEMP_FILE&quot; ] || [ $(wc -l &lt; &quot;$TEMP_FILE&quot;) -le 1 ]; then<br>    log &quot;ERROR: No data collected from any nodes&quot;<br>    exit 1<br>fi<br><br># Sort by memory usage (descending) and get top keys<br>log &quot;Processing results...&quot;<br>{<br>    head -n 1 &quot;$TEMP_FILE&quot;<br>    tail -n +2 &quot;$TEMP_FILE&quot; | sort -nr -t&#39;,&#39; -k1 | head -n &quot;$TOP_KEYS_LIMIT&quot;<br>} &gt; &quot;$CSV_OUTPUT&quot;<br><br># === GENERATE JSON OUTPUT FOR GRAFANA ===<br>log &quot;Generating JSON output for Grafana...&quot;<br><br>cat &gt; &quot;$JSON_OUTPUT&quot; &lt;&lt; &#39;EOF&#39;<br>{<br>  &quot;timestamp&quot;: TIMESTAMP_PLACEHOLDER,<br>  &quot;cluster_summary&quot;: {<br>    &quot;total_keys_analyzed&quot;: TOTAL_KEYS_PLACEHOLDER,<br>    &quot;top_keys_count&quot;: TOP_KEYS_PLACEHOLDER,<br>    &quot;analysis_time&quot;: &quot;ANALYSIS_TIME_PLACEHOLDER&quot;<br>  },<br>  &quot;top_memory_keys&quot;: [<br>EOF<br><br>tail -n +2 &quot;$CSV_OUTPUT&quot; | while IFS=&#39;,&#39; read -r memory key type ttl node timestamp; do<br>    escaped_key=$(echo &quot;$key&quot; | sed &#39;s/\\/\\\\/g&#39; | sed &#39;s/&quot;/\\&quot;/g&#39;)<br><br>    memory_kb=$(echo &quot;scale=2; $memory / 1024&quot; | bc 2&gt;/dev/null || echo &quot;0&quot;)<br>    memory_mb=$(echo &quot;scale=2; $memory / 1048576&quot; | bc 2&gt;/dev/null || echo &quot;0&quot;)<br><br>    if [ &quot;$ttl&quot; = &quot;-1&quot; ]; then<br>        ttl_status=&quot;persistent&quot;<br>    elif [ &quot;$ttl&quot; = &quot;-2&quot; ]; then<br>        ttl_status=&quot;expired&quot;<br>    else<br>        ttl_status=&quot;expires_in_${ttl}s&quot;<br>    fi<br><br>    cat &gt;&gt; &quot;$JSON_OUTPUT&quot; &lt;&lt; EOF<br>    {<br>      &quot;key_name&quot;: &quot;$escaped_key&quot;,<br>      &quot;memory_bytes&quot;: $memory,<br>      &quot;memory_kb&quot;: $memory_kb,<br>      &quot;memory_mb&quot;: $memory_mb,<br>      &quot;key_type&quot;: &quot;$type&quot;,<br>      &quot;ttl&quot;: $ttl,<br>      &quot;ttl_status&quot;: &quot;$ttl_status&quot;,<br>      &quot;node&quot;: &quot;$node&quot;,<br>      &quot;timestamp&quot;: $timestamp,<br>      &quot;human_readable_size&quot;: &quot;$(numfmt --to=iec-i --suffix=B $memory 2&gt;/dev/null || echo &quot;${memory}B&quot;)&quot;<br>    },<br>EOF<br>done<br><br>sed -i &#39;$ s/,$//&#39; &quot;$JSON_OUTPUT&quot; 2&gt;/dev/null || sed -i &#39;&#39; &#39;$ s/,$//&#39; &quot;$JSON_OUTPUT&quot;<br><br>cat &gt;&gt; &quot;$JSON_OUTPUT&quot; &lt;&lt; &#39;EOF&#39;<br>  ]<br>}<br>EOF<br><br>total_keys=$(tail -n +2 &quot;$TEMP_FILE&quot; | wc -l | tr -d &#39; &#39;)<br>top_keys=$(tail -n +2 &quot;$CSV_OUTPUT&quot; | wc -l | tr -d &#39; &#39;)<br>analysis_time=$(date &#39;+%Y-%m-%d %H:%M:%S&#39;)<br><br>sed -i &quot;s/TIMESTAMP_PLACEHOLDER/$TIMESTAMP/g&quot; &quot;$JSON_OUTPUT&quot; 2&gt;/dev/null || sed -i &#39;&#39; &quot;s/TIMESTAMP_PLACEHOLDER/$TIMESTAMP/g&quot; &quot;$JSON_OUTPUT&quot;<br>sed -i &quot;s/TOTAL_KEYS_PLACEHOLDER/$total_keys/g&quot; &quot;$JSON_OUTPUT&quot; 2&gt;/dev/null || sed -i &#39;&#39; &quot;s/TOTAL_KEYS_PLACEHOLDER/$total_keys/g&quot; &quot;$JSON_OUTPUT&quot;<br>sed -i &quot;s/TOP_KEYS_PLACEHOLDER/$top_keys/g&quot; &quot;$JSON_OUTPUT&quot; 2&gt;/dev/null || sed -i &#39;&#39; &quot;s/TOP_KEYS_PLACEHOLDER/$top_keys/g&quot; &quot;$JSON_OUTPUT&quot;<br>sed -i &quot;s/ANALYSIS_TIME_PLACEHOLDER/$analysis_time/g&quot; &quot;$JSON_OUTPUT&quot; 2&gt;/dev/null || sed -i &#39;&#39; &quot;s/ANALYSIS_TIME_PLACEHOLDER/$analysis_time/g&quot; &quot;$JSON_OUTPUT&quot;<br><br># === CLEANUP ===<br>rm -f &quot;$TEMP_FILE&quot;<br><br># === SUMMARY ===<br>log &quot; Analysis complete!&quot;<br>log &quot; Total keys analyzed: $total_keys&quot;<br>log &quot; Top keys tracked: $top_keys&quot;<br>log &quot; CSV output: $CSV_OUTPUT&quot;<br>log &quot; JSON output: $JSON_OUTPUT&quot;<br>log &quot; Analysis time: $analysis_time&quot;<br><br><br>exit 0<br><br></pre><p>Second phase; I just created a <strong>python program</strong> that provides <strong>HTTP API</strong> so Grafana can query to get Redis memory usage data. It reads the JSON files generated by the <strong>redis-cluster-memory-analyzer.sh</strong> script.</p><pre>#!/usr/bin/env python3<br>&quot;&quot;&quot;<br>Redis Memory Data Server for Grafana<br>=====================================<br>&quot;&quot;&quot;<br><br>import json<br>import os<br>import time<br>from datetime import datetime<br>from http.server import HTTPServer, BaseHTTPRequestHandler<br>from urllib.parse import urlparse, parse_qs<br>import csv<br><br># Configuration<br>DATA_DIR = &quot;/var/lib/grafana-redis-data&quot;<br>JSON_FILE = os.path.join(DATA_DIR, &quot;redis_memory_keys.json&quot;)<br>CSV_FILE = os.path.join(DATA_DIR, &quot;redis_memory_keys.csv&quot;)<br>PORT = 8080<br><br>class RedisDataHandler(BaseHTTPRequestHandler):<br>    def do_GET(self):<br>        parsed_path = urlparse(self.path)<br>        path = parsed_path.path<br>        params = parse_qs(parsed_path.query)<br><br>        try:<br>            if path == &#39;/&#39; or path == &#39;&#39;:<br>                self._handle_root()<br>            elif path == &#39;/health&#39;:<br>                self._handle_health()<br>            elif path == &#39;/api/keys&#39;:<br>                self._handle_keys_api(params)<br>            elif path == &#39;/api/summary&#39;:<br>                self._handle_summary_api()<br>            elif path == &#39;/api/table&#39;:<br>                self._handle_table_api(params)<br>            elif path == &#39;/api/timeseries&#39;:<br>                self._handle_timeseries_api(params)<br>            else:<br>                self._send_error(404, &quot;Endpoint not found&quot;)<br>        except Exception as e:<br>            self._send_error(500, f&quot;Internal server error: {str(e)}&quot;)<br><br>    def do_OPTIONS(self):<br>        &quot;&quot;&quot;Handle CORS preflight requests&quot;&quot;&quot;<br>        self.send_response(200)<br>        self.send_header(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;)<br>        self.send_header(&#39;Access-Control-Allow-Methods&#39;, &#39;GET, POST, OPTIONS&#39;)<br>        self.send_header(&#39;Access-Control-Allow-Headers&#39;, &#39;Content-Type&#39;)<br>        self.end_headers()<br><br>    def _send_json_response(self, data, status=200):<br>        &quot;&quot;&quot;Send JSON response with proper headers&quot;&quot;&quot;<br>        self.send_response(status)<br>        self.send_header(&#39;Content-type&#39;, &#39;application/json&#39;)<br>        self.send_header(&#39;Access-Control-Allow-Origin&#39;, &#39;*&#39;)<br>        self.end_headers()<br>        self.wfile.write(json.dumps(data, indent=2).encode(&#39;utf-8&#39;))<br><br>    def _send_error(self, status, message):<br>        &quot;&quot;&quot;Send error response&quot;&quot;&quot;<br>        self._send_json_response({&quot;error&quot;: message, &quot;status&quot;: status}, status)<br><br>    def _load_data(self):<br>        &quot;&quot;&quot;Load the latest Redis memory data&quot;&quot;&quot;<br>        if not os.path.exists(JSON_FILE):<br>            raise FileNotFoundError(&quot;Redis memory data file not found&quot;)<br><br>        with open(JSON_FILE, &#39;r&#39;) as f:<br>            return json.load(f)<br><br>    def _handle_root(self):<br>        &quot;&quot;&quot;Root endpoint with API information&quot;&quot;&quot;<br>        api_info = {<br>            &quot;service&quot;: &quot;Redis Memory Data API&quot;,<br>            &quot;version&quot;: &quot;1.0&quot;,<br>            &quot;endpoints&quot;: {<br>                &quot;/health&quot;: &quot;Health check and status&quot;,<br>                &quot;/api/keys&quot;: &quot;Memory keys data (supports ?limit=N, ?node=X, ?type=Y)&quot;,<br>                &quot;/api/summary&quot;: &quot;Cluster summary statistics&quot;,<br>                &quot;/api/table&quot;: &quot;Table format for Grafana&quot;,<br>                &quot;/api/timeseries&quot;: &quot;Time series format (supports ?limit=N)&quot;<br>            },<br>            &quot;status&quot;: &quot;running&quot;<br>        }<br>        self._send_json_response(api_info)<br><br>    def _handle_health(self):<br>        &quot;&quot;&quot;Health check endpoint&quot;&quot;&quot;<br>        data_exists = os.path.exists(JSON_FILE)<br>        data_age = 0<br>        if data_exists:<br>            data_age = time.time() - os.path.getmtime(JSON_FILE)<br><br>        health_data = {<br>            &quot;status&quot;: &quot;healthy&quot; if data_exists and data_age &lt; 600 else &quot;unhealthy&quot;,<br>            &quot;data_file_exists&quot;: data_exists,<br>            &quot;data_age_seconds&quot;: int(data_age),<br>            &quot;last_update&quot;: datetime.fromtimestamp(os.path.getmtime(JSON_FILE)).isoformat() if data_exists else None<br>        }<br>        self._send_json_response(health_data)<br><br>    def _handle_keys_api(self, params):<br>        &quot;&quot;&quot;API endpoint for key data (compatible with Grafana table panel)&quot;&quot;&quot;<br>        data = self._load_data()<br><br>        # Get parameters<br>        limit = int(params.get(&#39;limit&#39;, [50])[0])<br>        node_filter = params.get(&#39;node&#39;, [None])[0]<br>        type_filter = params.get(&#39;type&#39;, [None])[0]<br><br>        keys = data[&#39;top_memory_keys&#39;]<br><br>        # Apply filters<br>        if node_filter:<br>            keys = [k for k in keys if k[&#39;node&#39;] == node_filter]<br>        if type_filter:<br>            keys = [k for k in keys if k[&#39;key_type&#39;] == type_filter]<br><br>        # Limit results<br>        keys = keys[:limit]<br><br>        # Format for Grafana table<br>        response = {<br>            &quot;data&quot;: keys,<br>            &quot;meta&quot;: {<br>                &quot;total&quot;: len(keys),<br>                &quot;limit&quot;: limit,<br>                &quot;timestamp&quot;: data[&#39;timestamp&#39;],<br>                &quot;cluster_summary&quot;: data[&#39;cluster_summary&#39;]<br>            }<br>        }<br><br>        self._send_json_response(response)<br><br>    def _handle_summary_api(self):<br>        &quot;&quot;&quot;API endpoint for cluster summary data&quot;&quot;&quot;<br>        data = self._load_data()<br>        self._send_json_response(data[&#39;cluster_summary&#39;])<br><br>    def _handle_table_api(self, params):<br>        &quot;&quot;&quot;API endpoint formatted specifically for Grafana table panel&quot;&quot;&quot;<br>        data = self._load_data()<br><br>        # Get parameters<br>        limit = int(params.get(&#39;limit&#39;, [50])[0])<br><br>        # Format data as columns for Grafana table<br>        columns = [<br>            {&quot;text&quot;: &quot;Key Name&quot;, &quot;type&quot;: &quot;string&quot;},<br>            {&quot;text&quot;: &quot;Memory (MB)&quot;, &quot;type&quot;: &quot;number&quot;},<br>            {&quot;text&quot;: &quot;Memory (Bytes)&quot;, &quot;type&quot;: &quot;number&quot;},<br>            {&quot;text&quot;: &quot;Type&quot;, &quot;type&quot;: &quot;string&quot;},<br>            {&quot;text&quot;: &quot;TTL&quot;, &quot;type&quot;: &quot;number&quot;},<br>            {&quot;text&quot;: &quot;Node&quot;, &quot;type&quot;: &quot;string&quot;},<br>            {&quot;text&quot;: &quot;Human Size&quot;, &quot;type&quot;: &quot;string&quot;}<br>        ]<br><br>        rows = []<br>        for key_data in data[&#39;top_memory_keys&#39;][:limit]:<br>            rows.append([<br>                key_data[&#39;key_name&#39;],<br>                float(key_data[&#39;memory_mb&#39;]),<br>                int(key_data[&#39;memory_bytes&#39;]),<br>                key_data[&#39;key_type&#39;],<br>                int(key_data[&#39;ttl&#39;]),<br>                key_data[&#39;node&#39;],<br>                key_data[&#39;human_readable_size&#39;]<br>            ])<br><br>        response = {<br>            &quot;columns&quot;: columns,<br>            &quot;rows&quot;: rows,<br>            &quot;type&quot;: &quot;table&quot;<br>        }<br><br>        self._send_json_response(response)<br><br>    def _handle_timeseries_api(self, params):<br>        &quot;&quot;&quot;API endpoint for time series data (for trending)&quot;&quot;&quot;<br>        <br>        data = self._load_data()<br><br>        # Get top N keys for trending<br>        limit = int(params.get(&#39;limit&#39;, [10])[0])<br>        top_keys = data[&#39;top_memory_keys&#39;][:limit]<br><br>        timestamp_ms = data[&#39;timestamp&#39;] * 1000  # Convert to milliseconds<br><br>        series = []<br>        for key_data in top_keys:<br>            series.append({<br>                &quot;target&quot;: f&quot;{key_data[&#39;key_name&#39;]} ({key_data[&#39;node&#39;]})&quot;,<br>                &quot;datapoints&quot;: [[float(key_data[&#39;memory_mb&#39;]), timestamp_ms]]<br>            })<br><br>        self._send_json_response(series)<br><br>def main():<br>    &quot;&quot;&quot;Start the HTTP server&quot;&quot;&quot;<br>    os.makedirs(DATA_DIR, exist_ok=True)<br><br>    server = HTTPServer((&#39;0.0.0.0&#39;, PORT), RedisDataHandler)<br>    print(f&quot; Redis Data Server starting on port {PORT}&quot;)<br>    print(f&quot; Data directory: {DATA_DIR}&quot;)<br>    print(f&quot; Health check: http://localhost:{PORT}/health&quot;)<br>    print(f&quot; API endpoints:&quot;)<br>    print(f&quot;   - /api/keys - Key data with filtering&quot;)<br>    print(f&quot;   - /api/summary - Cluster summary&quot;)<br>    print(f&quot;   - /api/table - Table format for Grafana&quot;)<br>    print(f&quot;   - /api/timeseries - Time series format&quot;)<br><br>    try:<br>        server.serve_forever()<br>    except KeyboardInterrupt:<br>        print(&quot;\n Server shutting down...&quot;)<br>        server.shutdown()<br><br>if __name__ == &#39;__main__&#39;:<br>    main()</pre><p>Now <strong>redis-cluster-memory-analyzer.sh</strong> can <strong>collect</strong> the data and <strong>redis-data-server.py </strong>interprets it for Grafana. Since we don’t want redis cluster to be disturbed all the time, we can arrange a <strong>linux service working with timer</strong> so that it collects the data from Redis Cluster with <strong>periods</strong>.</p><p><strong>redis-memory-collector.service</strong></p><pre>[Unit]<br>Description=Redis Cluster Memory Analyzer<br>After=network.target network-online.target<br>Wants=network-online.target<br><br>[Service]<br>Type=oneshot<br>User=grafana<br>Group=grafana<br>ExecStart=/opt/redis-monitoring/redis-cluster-memory-analyzer.sh<br>WorkingDirectory=/opt/redis-monitoring<br>StandardOutput=journal<br>StandardError=journal<br>TimeoutStartSec=1800<br><br># Environment<br>Environment=PATH=/usr/local/bin:/usr/bin:/bin<br>Environment=HOME=/var/lib/grafana<br>Environment=REDISCLI_AUTH=mypassword!<br><br># Security settings<br>NoNewPrivileges=true<br>ProtectSystem=strict<br>ProtectHome=true<br>ReadWritePaths=/var/lib/grafana-redis-data /var/log<br>PrivateTmp=true<br>ProtectKernelTunables=true<br>ProtectKernelModules=true<br>ProtectControlGroups=true<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>And <strong>another service</strong> to <strong>process</strong> this data:</p><pre>[Unit]<br>Description=Redis Memory Data API Server<br>After=network.target network-online.target<br>Wants=network-online.target<br><br>[Service]<br>Type=simple<br>User=grafana<br>Group=grafana<br>ExecStart=/usr/bin/python3 /opt/redis-monitoring/redis-data-server.py<br>WorkingDirectory=/opt/redis-monitoring<br>Restart=always<br>RestartSec=10<br>TimeoutStartSec=30<br>TimeoutStopSec=30<br><br># Environment<br>Environment=PATH=/usr/local/bin:/usr/bin:/bin<br>Environment=HOME=/var/lib/grafana<br>Environment=PYTHONPATH=/opt/redis-monitoring<br><br># Logging<br>StandardOutput=journal<br>StandardError=journal<br>SyslogIdentifier=redis-data-server<br><br># Security settings<br>NoNewPrivileges=true<br>ProtectSystem=strict<br>ProtectHome=true<br>ReadWritePaths=/var/lib/grafana-redis-data<br>PrivateTmp=true<br>ProtectKernelTunables=true<br>ProtectKernelModules=true<br>ProtectControlGroups=true<br>RestrictNamespaces=true<br>LockPersonality=true<br>MemoryDenyWriteExecute=true<br>RestrictRealtime=true<br>RestrictSUIDSGID=true<br>RemoveIPC=true<br>PrivateMounts=true<br><br>[Install]<br>WantedBy=multi-user.target</pre><p>So now, we gather data from Redis Cluster, we process it as <strong>JSON</strong> and provide an <strong>HTTP API</strong> for Grafana. The only remaining part is Grafana Configuration to visualize these outputs.</p><ul><li>Add <strong>Infinity Type</strong> DataSource(<strong>Base URL</strong> is where API is working):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sb-YLCRqZn3WOgsRTyAcqQ.png" /><figcaption>DataSource — Infinity Type</figcaption></figure><ul><li><strong>Add New Dashboard</strong> → Import the <strong>following</strong> JSON Model (You can update <strong>HTTP_API:8080</strong> with the related <strong>API Endpoint IP</strong> -where your <strong>redis-collector</strong> and <strong>redis-data-server</strong> services are running- I prefered to execute them on <strong>GRAFANA</strong> <strong>Server</strong>)</li></ul><pre>{<br>  &quot;annotations&quot;: {<br>    &quot;list&quot;: [<br>      {<br>        &quot;builtIn&quot;: 1,<br>        &quot;datasource&quot;: {<br>          &quot;type&quot;: &quot;datasource&quot;,<br>          &quot;uid&quot;: &quot;grafana&quot;<br>        },<br>        &quot;enable&quot;: true,<br>        &quot;hide&quot;: true,<br>        &quot;iconColor&quot;: &quot;rgba(0, 211, 255, 1)&quot;,<br>        &quot;name&quot;: &quot;Annotations &amp; Alerts&quot;,<br>        &quot;target&quot;: {<br>          &quot;limit&quot;: 100,<br>          &quot;matchAny&quot;: false,<br>          &quot;tags&quot;: [],<br>          &quot;type&quot;: &quot;dashboard&quot;<br>        },<br>        &quot;type&quot;: &quot;dashboard&quot;<br>      }<br>    ]<br>  },<br>  &quot;description&quot;: &quot;Redis Cluster Memory Usage Analysis&quot;,<br>  &quot;editable&quot;: true,<br>  &quot;fiscalYearStartMonth&quot;: 0,<br>  &quot;graphTooltip&quot;: 0,<br>  &quot;id&quot;: 152,<br>  &quot;links&quot;: [],<br>  &quot;panels&quot;: [<br>    {<br>      &quot;collapsed&quot;: false,<br>      &quot;gridPos&quot;: {<br>        &quot;h&quot;: 1,<br>        &quot;w&quot;: 24,<br>        &quot;x&quot;: 0,<br>        &quot;y&quot;: 0<br>      },<br>      &quot;id&quot;: 100,<br>      &quot;panels&quot;: [],<br>      &quot;title&quot;: &quot;Redis Cluster Memory Analysis&quot;,<br>      &quot;type&quot;: &quot;row&quot;<br>    },<br>    {<br>      &quot;datasource&quot;: {<br>        &quot;type&quot;: &quot;infinity&quot;,<br>        &quot;uid&quot;: &quot;REDIS MEMORY&quot;<br>      },<br>      &quot;fieldConfig&quot;: {<br>        &quot;defaults&quot;: {<br>          &quot;color&quot;: {<br>            &quot;mode&quot;: &quot;thresholds&quot;<br>          },<br>          &quot;mappings&quot;: [],<br>          &quot;thresholds&quot;: {<br>            &quot;mode&quot;: &quot;absolute&quot;,<br>            &quot;steps&quot;: [<br>              {<br>                &quot;color&quot;: &quot;green&quot;,<br>                &quot;value&quot;: 0<br>              },<br>              {<br>                &quot;color&quot;: &quot;red&quot;,<br>                &quot;value&quot;: 1000000<br>              }<br>            ]<br>          },<br>          &quot;unit&quot;: &quot;short&quot;<br>        },<br>        &quot;overrides&quot;: []<br>      },<br>      &quot;gridPos&quot;: {<br>        &quot;h&quot;: 4,<br>        &quot;w&quot;: 8,<br>        &quot;x&quot;: 0,<br>        &quot;y&quot;: 1<br>      },<br>      &quot;id&quot;: 101,<br>      &quot;options&quot;: {<br>        &quot;colorMode&quot;: &quot;background&quot;,<br>        &quot;graphMode&quot;: &quot;area&quot;,<br>        &quot;justifyMode&quot;: &quot;center&quot;,<br>        &quot;orientation&quot;: &quot;auto&quot;,<br>        &quot;percentChangeColorMode&quot;: &quot;standard&quot;,<br>        &quot;reduceOptions&quot;: {<br>          &quot;calcs&quot;: [<br>            &quot;lastNotNull&quot;<br>          ],<br>          &quot;fields&quot;: &quot;&quot;,<br>          &quot;values&quot;: false<br>        },<br>        &quot;showPercentChange&quot;: false,<br>        &quot;text&quot;: {},<br>        &quot;textMode&quot;: &quot;auto&quot;,<br>        &quot;wideLayout&quot;: true<br>      },<br>      &quot;pluginVersion&quot;: &quot;12.1.0&quot;,<br>      &quot;targets&quot;: [<br>        {<br>          &quot;columns&quot;: [<br>            {<br>              &quot;selector&quot;: &quot;total_keys_analyzed&quot;,<br>              &quot;text&quot;: &quot;Total Keys&quot;,<br>              &quot;type&quot;: &quot;number&quot;<br>            }<br>          ],<br>          &quot;datasource&quot;: {<br>            &quot;type&quot;: &quot;infinity&quot;,<br>            &quot;uid&quot;: &quot;REDIS MEMORY&quot;<br>          },<br>          &quot;filters&quot;: [],<br>          &quot;format&quot;: &quot;table&quot;,<br>          &quot;global_query_id&quot;: &quot;&quot;,<br>          &quot;refId&quot;: &quot;A&quot;,<br>          &quot;source&quot;: &quot;url&quot;,<br>          &quot;type&quot;: &quot;json&quot;,<br>          &quot;url&quot;: &quot;http://HTTP_API:8080/api/summary&quot;,<br>          &quot;url_options&quot;: {<br>            &quot;data&quot;: &quot;&quot;,<br>            &quot;method&quot;: &quot;GET&quot;<br>          }<br>        }<br>      ],<br>      &quot;title&quot;: &quot;Total Keys Analyzed&quot;,<br>      &quot;type&quot;: &quot;stat&quot;<br>    },<br>    {<br>      &quot;datasource&quot;: {<br>        &quot;type&quot;: &quot;infinity&quot;,<br>        &quot;uid&quot;: &quot;REDIS MEMORY&quot;<br>      },<br>      &quot;fieldConfig&quot;: {<br>        &quot;defaults&quot;: {<br>          &quot;color&quot;: {<br>            &quot;mode&quot;: &quot;thresholds&quot;<br>          },<br>          &quot;mappings&quot;: [],<br>          &quot;thresholds&quot;: {<br>            &quot;mode&quot;: &quot;absolute&quot;,<br>            &quot;steps&quot;: [<br>              {<br>                &quot;color&quot;: &quot;green&quot;,<br>                &quot;value&quot;: 0<br>              },<br>              {<br>                &quot;color&quot;: &quot;yellow&quot;,<br>                &quot;value&quot;: 30<br>              },<br>              {<br>                &quot;color&quot;: &quot;red&quot;,<br>                &quot;value&quot;: 50<br>              }<br>            ]<br>          },<br>          &quot;unit&quot;: &quot;short&quot;<br>        },<br>        &quot;overrides&quot;: []<br>      },<br>      &quot;gridPos&quot;: {<br>        &quot;h&quot;: 4,<br>        &quot;w&quot;: 8,<br>        &quot;x&quot;: 8,<br>        &quot;y&quot;: 1<br>      },<br>      &quot;id&quot;: 102,<br>      &quot;options&quot;: {<br>        &quot;colorMode&quot;: &quot;background&quot;,<br>        &quot;graphMode&quot;: &quot;area&quot;,<br>        &quot;justifyMode&quot;: &quot;center&quot;,<br>        &quot;orientation&quot;: &quot;auto&quot;,<br>        &quot;percentChangeColorMode&quot;: &quot;standard&quot;,<br>        &quot;reduceOptions&quot;: {<br>          &quot;calcs&quot;: [<br>            &quot;lastNotNull&quot;<br>          ],<br>          &quot;fields&quot;: &quot;&quot;,<br>          &quot;values&quot;: false<br>        },<br>        &quot;showPercentChange&quot;: false,<br>        &quot;text&quot;: {},<br>        &quot;textMode&quot;: &quot;auto&quot;,<br>        &quot;wideLayout&quot;: true<br>      },<br>      &quot;pluginVersion&quot;: &quot;12.1.0&quot;,<br>      &quot;targets&quot;: [<br>        {<br>          &quot;columns&quot;: [<br>            {<br>              &quot;selector&quot;: &quot;top_keys_count&quot;,<br>              &quot;text&quot;: &quot;Top Keys&quot;,<br>              &quot;type&quot;: &quot;number&quot;<br>            }<br>          ],<br>          &quot;datasource&quot;: {<br>            &quot;type&quot;: &quot;infinity&quot;,<br>            &quot;uid&quot;: &quot;REDIS MEMORY&quot;<br>          },<br>          &quot;filters&quot;: [],<br>          &quot;format&quot;: &quot;table&quot;,<br>          &quot;global_query_id&quot;: &quot;&quot;,<br>          &quot;refId&quot;: &quot;A&quot;,<br>          &quot;source&quot;: &quot;url&quot;,<br>          &quot;type&quot;: &quot;json&quot;,<br>          &quot;url&quot;: &quot;http://HTTP_API:8080/api/summary&quot;,<br>          &quot;url_options&quot;: {<br>            &quot;data&quot;: &quot;&quot;,<br>            &quot;method&quot;: &quot;GET&quot;<br>          }<br>        }<br>      ],<br>      &quot;title&quot;: &quot;Top Keys Tracked&quot;,<br>      &quot;type&quot;: &quot;stat&quot;<br>    },<br>    {<br>      &quot;datasource&quot;: {<br>        &quot;type&quot;: &quot;infinity&quot;,<br>        &quot;uid&quot;: &quot;REDIS MEMORY&quot;<br>      },<br>      &quot;fieldConfig&quot;: {<br>        &quot;defaults&quot;: {<br>          &quot;color&quot;: {<br>            &quot;mode&quot;: &quot;thresholds&quot;<br>          },<br>          &quot;mappings&quot;: [],<br>          &quot;thresholds&quot;: {<br>            &quot;mode&quot;: &quot;absolute&quot;,<br>            &quot;steps&quot;: [<br>              {<br>                &quot;color&quot;: &quot;green&quot;,<br>                &quot;value&quot;: 0<br>              }<br>            ]<br>          },<br>          &quot;unit&quot;: &quot;string&quot;<br>        },<br>        &quot;overrides&quot;: []<br>      },<br>      &quot;gridPos&quot;: {<br>        &quot;h&quot;: 4,<br>        &quot;w&quot;: 8,<br>        &quot;x&quot;: 16,<br>        &quot;y&quot;: 1<br>      },<br>      &quot;id&quot;: 103,<br>      &quot;options&quot;: {<br>        &quot;colorMode&quot;: &quot;background_solid&quot;,<br>        &quot;graphMode&quot;: &quot;none&quot;,<br>        &quot;justifyMode&quot;: &quot;center&quot;,<br>        &quot;orientation&quot;: &quot;auto&quot;,<br>        &quot;percentChangeColorMode&quot;: &quot;standard&quot;,<br>        &quot;reduceOptions&quot;: {<br>          &quot;calcs&quot;: [<br>            &quot;lastNotNull&quot;<br>          ],<br>          &quot;fields&quot;: &quot;/.*/&quot;,<br>          &quot;values&quot;: false<br>        },<br>        &quot;showPercentChange&quot;: false,<br>        &quot;text&quot;: {},<br>        &quot;textMode&quot;: &quot;value_and_name&quot;,<br>        &quot;wideLayout&quot;: true<br>      },<br>      &quot;pluginVersion&quot;: &quot;12.1.0&quot;,<br>      &quot;targets&quot;: [<br>        {<br>          &quot;columns&quot;: [<br>            {<br>              &quot;selector&quot;: &quot;analysis_time&quot;,<br>              &quot;text&quot;: &quot;Time&quot;,<br>              &quot;type&quot;: &quot;string&quot;<br>            }<br>          ],<br>          &quot;datasource&quot;: {<br>            &quot;type&quot;: &quot;infinity&quot;,<br>            &quot;uid&quot;: &quot;REDIS MEMORY&quot;<br>          },<br>          &quot;filters&quot;: [],<br>          &quot;format&quot;: &quot;table&quot;,<br>          &quot;global_query_id&quot;: &quot;&quot;,<br>          &quot;refId&quot;: &quot;A&quot;,<br>          &quot;root_selector&quot;: &quot;&quot;,<br>          &quot;source&quot;: &quot;url&quot;,<br>          &quot;type&quot;: &quot;json&quot;,<br>          &quot;url&quot;: &quot;http://HTTP_API:8080/api/summary&quot;,<br>          &quot;url_options&quot;: {<br>            &quot;data&quot;: &quot;&quot;,<br>            &quot;method&quot;: &quot;GET&quot;<br>          }<br>        }<br>      ],<br>      &quot;title&quot;: &quot;Last Analysis Time&quot;,<br>      &quot;type&quot;: &quot;stat&quot;<br>    },<br>    {<br>      &quot;datasource&quot;: {<br>        &quot;type&quot;: &quot;infinity&quot;,<br>        &quot;uid&quot;: &quot;REDIS MEMORY&quot;<br>      },<br>      &quot;fieldConfig&quot;: {<br>        &quot;defaults&quot;: {<br>          &quot;custom&quot;: {<br>            &quot;align&quot;: &quot;auto&quot;,<br>            &quot;cellOptions&quot;: {<br>              &quot;type&quot;: &quot;auto&quot;<br>            },<br>            &quot;filterable&quot;: true,<br>            &quot;inspect&quot;: false<br>          },<br>          &quot;mappings&quot;: [],<br>          &quot;thresholds&quot;: {<br>            &quot;mode&quot;: &quot;absolute&quot;,<br>            &quot;steps&quot;: [<br>              {<br>                &quot;color&quot;: &quot;green&quot;,<br>                &quot;value&quot;: 0<br>              },<br>              {<br>                &quot;color&quot;: &quot;red&quot;,<br>                &quot;value&quot;: 80<br>              }<br>            ]<br>          },<br>          &quot;unit&quot;: &quot;decmbytes&quot;<br>        },<br>        &quot;overrides&quot;: [<br>          {<br>            &quot;matcher&quot;: {<br>              &quot;id&quot;: &quot;byName&quot;,<br>              &quot;options&quot;: &quot;key_name&quot;<br>            },<br>            &quot;properties&quot;: [<br>              {<br>                &quot;id&quot;: &quot;custom.width&quot;,<br>                &quot;value&quot;: 400<br>              },<br>              {<br>                &quot;id&quot;: &quot;displayName&quot;,<br>                &quot;value&quot;: &quot;Key Name&quot;<br>              },<br>              {<br>                &quot;id&quot;: &quot;unit&quot;,<br>                &quot;value&quot;: &quot;string&quot;<br>              }<br>            ]<br>          },<br>          {<br>            &quot;matcher&quot;: {<br>              &quot;id&quot;: &quot;byName&quot;,<br>              &quot;options&quot;: &quot;memory_bytes&quot;<br>            },<br>            &quot;properties&quot;: [<br>              {<br>                &quot;id&quot;: &quot;displayName&quot;,<br>                &quot;value&quot;: &quot;Memory (Bytes)&quot;<br>              },<br>              {<br>                &quot;id&quot;: &quot;unit&quot;,<br>                &quot;value&quot;: &quot;bytes&quot;<br>              },<br>              {<br>                &quot;id&quot;: &quot;custom.width&quot;,<br>                &quot;value&quot;: 120<br>              }<br>            ]<br>          },<br>          {<br>            &quot;matcher&quot;: {<br>              &quot;id&quot;: &quot;byName&quot;,<br>              &quot;options&quot;: &quot;memory_mb&quot;<br>            },<br>            &quot;properties&quot;: [<br>              {<br>                &quot;id&quot;: &quot;displayName&quot;,<br>                &quot;value&quot;: &quot;Memory (MB)&quot;<br>              },<br>              {<br>                &quot;id&quot;: &quot;unit&quot;,<br>                &quot;value&quot;: &quot;decbytes&quot;<br>              },<br>              {<br>                &quot;id&quot;: &quot;custom.width&quot;,<br>                &quot;value&quot;: 100<br>              }<br>            ]<br>          },<br>          {<br>            &quot;matcher&quot;: {<br>              &quot;id&quot;: &quot;byName&quot;,<br>              &quot;options&quot;: &quot;key_type&quot;<br>            },<br>            &quot;properties&quot;: [<br>              {<br>                &quot;id&quot;: &quot;displayName&quot;,<br>                &quot;value&quot;: &quot;Type&quot;<br>              },<br>              {<br>                &quot;id&quot;: &quot;unit&quot;,<br>                &quot;value&quot;: &quot;string&quot;<br>              },<br>              {<br>                &quot;id&quot;: &quot;custom.width&quot;,<br>                &quot;value&quot;: 80<br>              }<br>            ]<br>          },<br>          {<br>            &quot;matcher&quot;: {<br>              &quot;id&quot;: &quot;byName&quot;,<br>              &quot;options&quot;: &quot;node&quot;<br>            },<br>            &quot;properties&quot;: [<br>              {<br>                &quot;id&quot;: &quot;displayName&quot;,<br>                &quot;value&quot;: &quot;Redis Node&quot;<br>              },<br>              {<br>                &quot;id&quot;: &quot;unit&quot;,<br>                &quot;value&quot;: &quot;string&quot;<br>              },<br>              {<br>                &quot;id&quot;: &quot;custom.width&quot;,<br>                &quot;value&quot;: 150<br>              }<br>            ]<br>          },<br>          {<br>            &quot;matcher&quot;: {<br>              &quot;id&quot;: &quot;byName&quot;,<br>              &quot;options&quot;: &quot;human_readable_size&quot;<br>            },<br>            &quot;properties&quot;: [<br>              {<br>                &quot;id&quot;: &quot;displayName&quot;,<br>                &quot;value&quot;: &quot;Human Size&quot;<br>              },<br>              {<br>                &quot;id&quot;: &quot;unit&quot;,<br>                &quot;value&quot;: &quot;string&quot;<br>              },<br>              {<br>                &quot;id&quot;: &quot;custom.width&quot;,<br>                &quot;value&quot;: 100<br>              }<br>            ]<br>          }<br>        ]<br>      },<br>      &quot;gridPos&quot;: {<br>        &quot;h&quot;: 12,<br>        &quot;w&quot;: 24,<br>        &quot;x&quot;: 0,<br>        &quot;y&quot;: 5<br>      },<br>      &quot;id&quot;: 104,<br>      &quot;options&quot;: {<br>        &quot;cellHeight&quot;: &quot;sm&quot;,<br>        &quot;footer&quot;: {<br>          &quot;countRows&quot;: false,<br>          &quot;fields&quot;: &quot;&quot;,<br>          &quot;reducer&quot;: [<br>            &quot;sum&quot;<br>          ],<br>          &quot;show&quot;: false<br>        },<br>        &quot;showHeader&quot;: true,<br>        &quot;sortBy&quot;: [<br>          {<br>            &quot;desc&quot;: true,<br>            &quot;displayName&quot;: &quot;Memory (Bytes)&quot;<br>          }<br>        ]<br>      },<br>      &quot;pluginVersion&quot;: &quot;12.1.0&quot;,<br>      &quot;targets&quot;: [<br>        {<br>          &quot;columns&quot;: [<br>            {<br>              &quot;selector&quot;: &quot;key_name&quot;,<br>              &quot;text&quot;: &quot;Key Name&quot;,<br>              &quot;type&quot;: &quot;string&quot;<br>            },<br>            {<br>              &quot;selector&quot;: &quot;memory_mb&quot;,<br>              &quot;text&quot;: &quot;Memory (MB)&quot;,<br>              &quot;type&quot;: &quot;number&quot;<br>            },<br>            {<br>              &quot;selector&quot;: &quot;key_type&quot;,<br>              &quot;text&quot;: &quot;Type&quot;,<br>              &quot;type&quot;: &quot;string&quot;<br>            },<br>            {<br>              &quot;selector&quot;: &quot;node&quot;,<br>              &quot;text&quot;: &quot;Redis Node&quot;,<br>              &quot;type&quot;: &quot;string&quot;<br>            },<br>            {<br>              &quot;selector&quot;: &quot;human_readable_size&quot;,<br>              &quot;text&quot;: &quot;Human Size&quot;,<br>              &quot;type&quot;: &quot;string&quot;<br>            }<br>          ],<br>          &quot;datasource&quot;: {<br>            &quot;type&quot;: &quot;infinity&quot;,<br>            &quot;uid&quot;: &quot;REDIS MEMORY&quot;<br>          },<br>          &quot;filters&quot;: [],<br>          &quot;format&quot;: &quot;table&quot;,<br>          &quot;global_query_id&quot;: &quot;&quot;,<br>          &quot;refId&quot;: &quot;A&quot;,<br>          &quot;root_selector&quot;: &quot;data&quot;,<br>          &quot;source&quot;: &quot;url&quot;,<br>          &quot;type&quot;: &quot;json&quot;,<br>          &quot;url&quot;: &quot;http://HTTP_API:8080/api/keys?limit=50&quot;,<br>          &quot;url_options&quot;: {<br>            &quot;data&quot;: &quot;&quot;,<br>            &quot;method&quot;: &quot;GET&quot;<br>          }<br>        }<br>      ],<br>      &quot;title&quot;: &quot;Top 50 Memory Consuming Keys Across Redis Cluster&quot;,<br>      &quot;type&quot;: &quot;table&quot;<br>    },<br>    {<br>      &quot;datasource&quot;: {<br>        &quot;type&quot;: &quot;infinity&quot;,<br>        &quot;uid&quot;: &quot;REDIS MEMORY&quot;<br>      },<br>      &quot;fieldConfig&quot;: {<br>        &quot;defaults&quot;: {<br>          &quot;color&quot;: {<br>            &quot;mode&quot;: &quot;thresholds&quot;<br>          },<br>          &quot;custom&quot;: {<br>            &quot;axisBorderShow&quot;: true,<br>            &quot;axisCenteredZero&quot;: false,<br>            &quot;axisColorMode&quot;: &quot;text&quot;,<br>            &quot;axisGridShow&quot;: true,<br>            &quot;axisLabel&quot;: &quot;&quot;,<br>            &quot;axisPlacement&quot;: &quot;left&quot;,<br>            &quot;fillOpacity&quot;: 80,<br>            &quot;gradientMode&quot;: &quot;none&quot;,<br>            &quot;hideFrom&quot;: {<br>              &quot;legend&quot;: false,<br>              &quot;tooltip&quot;: false,<br>              &quot;vis&quot;: false,<br>              &quot;viz&quot;: false<br>            },<br>            &quot;lineWidth&quot;: 1,<br>            &quot;scaleDistribution&quot;: {<br>              &quot;type&quot;: &quot;linear&quot;<br>            },<br>            &quot;thresholdsStyle&quot;: {<br>              &quot;mode&quot;: &quot;line&quot;<br>            }<br>          },<br>          &quot;mappings&quot;: [],<br>          &quot;thresholds&quot;: {<br>            &quot;mode&quot;: &quot;absolute&quot;,<br>            &quot;steps&quot;: [<br>              {<br>                &quot;color&quot;: &quot;green&quot;,<br>                &quot;value&quot;: 0<br>              },<br>              {<br>                &quot;color&quot;: &quot;red&quot;,<br>                &quot;value&quot;: 600<br>              }<br>            ]<br>          },<br>          &quot;unit&quot;: &quot;decmbytes&quot;<br>        },<br>        &quot;overrides&quot;: []<br>      },<br>      &quot;gridPos&quot;: {<br>        &quot;h&quot;: 8,<br>        &quot;w&quot;: 16,<br>        &quot;x&quot;: 0,<br>        &quot;y&quot;: 17<br>      },<br>      &quot;id&quot;: 105,<br>      &quot;options&quot;: {<br>        &quot;barRadius&quot;: 0.3,<br>        &quot;barWidth&quot;: 0.97,<br>        &quot;fullHighlight&quot;: true,<br>        &quot;groupWidth&quot;: 0.7,<br>        &quot;legend&quot;: {<br>          &quot;calcs&quot;: [],<br>          &quot;displayMode&quot;: &quot;list&quot;,<br>          &quot;placement&quot;: &quot;right&quot;,<br>          &quot;showLegend&quot;: true<br>        },<br>        &quot;orientation&quot;: &quot;horizontal&quot;,<br>        &quot;showValue&quot;: &quot;always&quot;,<br>        &quot;stacking&quot;: &quot;none&quot;,<br>        &quot;tooltip&quot;: {<br>          &quot;hideZeros&quot;: false,<br>          &quot;mode&quot;: &quot;single&quot;,<br>          &quot;sort&quot;: &quot;asc&quot;<br>        },<br>        &quot;xField&quot;: &quot;Key Name&quot;,<br>        &quot;xTickLabelRotation&quot;: 0,<br>        &quot;xTickLabelSpacing&quot;: 0<br>      },<br>      &quot;pluginVersion&quot;: &quot;12.1.0&quot;,<br>      &quot;targets&quot;: [<br>        {<br>          &quot;columns&quot;: [<br>            {<br>              &quot;selector&quot;: &quot;key_name&quot;,<br>              &quot;text&quot;: &quot;Key Name&quot;,<br>              &quot;type&quot;: &quot;string&quot;<br>            },<br>            {<br>              &quot;selector&quot;: &quot;memory_mb&quot;,<br>              &quot;text&quot;: &quot;Memory (MB)&quot;,<br>              &quot;type&quot;: &quot;number&quot;<br>            }<br>          ],<br>          &quot;datasource&quot;: {<br>            &quot;type&quot;: &quot;infinity&quot;,<br>            &quot;uid&quot;: &quot;REDIS MEMORY&quot;<br>          },<br>          &quot;filters&quot;: [],<br>          &quot;format&quot;: &quot;table&quot;,<br>          &quot;global_query_id&quot;: &quot;&quot;,<br>          &quot;refId&quot;: &quot;A&quot;,<br>          &quot;root_selector&quot;: &quot;data&quot;,<br>          &quot;source&quot;: &quot;url&quot;,<br>          &quot;type&quot;: &quot;json&quot;,<br>          &quot;url&quot;: &quot;http://HTTP_API:8080/api/keys?limit=5&quot;,<br>          &quot;url_options&quot;: {<br>            &quot;data&quot;: &quot;&quot;,<br>            &quot;method&quot;: &quot;GET&quot;<br>          }<br>        }<br>      ],<br>      &quot;title&quot;: &quot;Top 5 Keys Memory Usage (Bar Chart)&quot;,<br>      &quot;type&quot;: &quot;barchart&quot;<br>    },<br>    {<br>      &quot;datasource&quot;: {<br>        &quot;type&quot;: &quot;infinity&quot;,<br>        &quot;uid&quot;: &quot;REDIS MEMORY&quot;<br>      },<br>      &quot;fieldConfig&quot;: {<br>        &quot;defaults&quot;: {<br>          &quot;color&quot;: {<br>            &quot;mode&quot;: &quot;palette-classic&quot;<br>          },<br>          &quot;custom&quot;: {<br>            &quot;hideFrom&quot;: {<br>              &quot;legend&quot;: false,<br>              &quot;tooltip&quot;: false,<br>              &quot;vis&quot;: false,<br>              &quot;viz&quot;: false<br>            }<br>          },<br>          &quot;mappings&quot;: [],<br>          &quot;unit&quot;: &quot;bytes&quot;<br>        },<br>        &quot;overrides&quot;: []<br>      },<br>      &quot;gridPos&quot;: {<br>        &quot;h&quot;: 8,<br>        &quot;w&quot;: 8,<br>        &quot;x&quot;: 16,<br>        &quot;y&quot;: 17<br>      },<br>      &quot;id&quot;: 106,<br>      &quot;options&quot;: {<br>        &quot;legend&quot;: {<br>          &quot;calcs&quot;: [],<br>          &quot;displayMode&quot;: &quot;list&quot;,<br>          &quot;placement&quot;: &quot;right&quot;,<br>          &quot;showLegend&quot;: true,<br>          &quot;values&quot;: []<br>        },<br>        &quot;pieType&quot;: &quot;pie&quot;,<br>        &quot;reduceOptions&quot;: {<br>          &quot;calcs&quot;: [<br>            &quot;sum&quot;<br>          ],<br>          &quot;fields&quot;: &quot;&quot;,<br>          &quot;values&quot;: true<br>        },<br>        &quot;tooltip&quot;: {<br>          &quot;hideZeros&quot;: false,<br>          &quot;mode&quot;: &quot;single&quot;,<br>          &quot;sort&quot;: &quot;none&quot;<br>        }<br>      },<br>      &quot;pluginVersion&quot;: &quot;12.1.0&quot;,<br>      &quot;targets&quot;: [<br>        {<br>          &quot;columns&quot;: [<br>            {<br>              &quot;selector&quot;: &quot;key_type&quot;,<br>              &quot;text&quot;: &quot;Type&quot;,<br>              &quot;type&quot;: &quot;string&quot;<br>            },<br>            {<br>              &quot;selector&quot;: &quot;memory_bytes&quot;,<br>              &quot;text&quot;: &quot;Memory&quot;,<br>              &quot;type&quot;: &quot;number&quot;<br>            }<br>          ],<br>          &quot;datasource&quot;: {<br>            &quot;type&quot;: &quot;infinity&quot;,<br>            &quot;uid&quot;: &quot;REDIS MEMORY&quot;<br>          },<br>          &quot;filters&quot;: [],<br>          &quot;format&quot;: &quot;table&quot;,<br>          &quot;global_query_id&quot;: &quot;&quot;,<br>          &quot;refId&quot;: &quot;A&quot;,<br>          &quot;root_selector&quot;: &quot;data&quot;,<br>          &quot;source&quot;: &quot;url&quot;,<br>          &quot;type&quot;: &quot;json&quot;,<br>          &quot;url&quot;: &quot;http://HTTP_API:8080/api/keys?limit=50&quot;,<br>          &quot;url_options&quot;: {<br>            &quot;data&quot;: &quot;&quot;,<br>            &quot;method&quot;: &quot;GET&quot;<br>          }<br>        }<br>      ],<br>      &quot;title&quot;: &quot;Memory Usage by Key Type (Top 50 Keys)&quot;,<br>      &quot;transformations&quot;: [<br>        {<br>          &quot;id&quot;: &quot;groupBy&quot;,<br>          &quot;options&quot;: {<br>            &quot;fields&quot;: {<br>              &quot;Memory&quot;: {<br>                &quot;aggregations&quot;: [<br>                  &quot;sum&quot;<br>                ],<br>                &quot;operation&quot;: &quot;aggregate&quot;<br>              },<br>              &quot;Type&quot;: {<br>                &quot;aggregations&quot;: [],<br>                &quot;operation&quot;: &quot;groupby&quot;<br>              }<br>            }<br>          }<br>        }<br>      ],<br>      &quot;type&quot;: &quot;piechart&quot;<br>    }<br>  ],<br>  &quot;preload&quot;: false,<br>  &quot;refresh&quot;: &quot;1m&quot;,<br>  &quot;schemaVersion&quot;: 41,<br>  &quot;tags&quot;: [<br>    &quot;redis&quot;,<br>    &quot;memory&quot;,<br>    &quot;cluster&quot;,<br>    &quot;analysis&quot;<br>  ],<br>  &quot;templating&quot;: {<br>    &quot;list&quot;: []<br>  },<br>  &quot;time&quot;: {<br>    &quot;from&quot;: &quot;now-30m&quot;,<br>    &quot;to&quot;: &quot;now&quot;<br>  },<br>  &quot;timepicker&quot;: {},<br>  &quot;timezone&quot;: &quot;&quot;,<br>  &quot;title&quot;: &quot;Redis Cluster Memory Analysis&quot;,<br>  &quot;uid&quot;: &quot;redis-memory-complete&quot;,<br>  &quot;version&quot;: 16<br>}</pre><p>Now it’s time to see results :)</p><ul><li><strong>Total Keys Analyzed</strong></li><li><strong>Last Analysis Date</strong></li><li><strong>Top 50 Keys in Sorted Table</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OKNrDzGJD8qDXQZST0t1Q.png" /><figcaption>Table Format — Top 50 Memory Consuming Key in a Redis Cluster</figcaption></figure><ul><li><strong>Top 5 Keys in Bar Chart and Corresponding Threshold</strong></li><li><strong>Memory Usage Grouped By Key Type</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g4B8Zl0abynzxwA053ye3A.png" /><figcaption>Top 5 Keys on Bar Chart &amp; Memory Usage Grouped By Key Type</figcaption></figure><h3>Closing</h3><p>Redis is phenomenal under pressure — <strong>until a few keys grow fat and hot</strong>. With a <strong>focused Grafana dashboard</strong> that spotlights <strong>which keys</strong> are big, <strong>how they trend</strong>, <strong>what types they are</strong>, and <strong>when they cross thresholds</strong>, you turn opaque incidents into straightforward fixes.</p><p>If you already run Redis Cluster in production, this is one of those dashboards that pays for itself the first time it catches a runaway key.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74d39af3dc6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Endpoints Load Test with Locust Setup]]></title>
            <link>https://medium.com/@ecetiner87/api-endpoints-load-test-with-locust-setup-f62749348f49?source=rss-6d9064cc812e------2</link>
            <guid isPermaLink="false">https://medium.com/p/f62749348f49</guid>
            <category><![CDATA[locust]]></category>
            <category><![CDATA[traffic]]></category>
            <category><![CDATA[loadtest]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Erkan Cetiner]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 08:55:40 GMT</pubDate>
            <atom:updated>2024-09-13T08:55:40.888Z</atom:updated>
            <content:encoded><![CDATA[<p>Locust is an easy to use, scriptable and scalable performance testing tool. You define the behaviour of your users in regular Python code, instead of being stuck in a UI or restrictive domain specific language. This makes Locust infinitely expandable and very developer friendly.</p><h3>Locust Installation:</h3><p><strong>Pre-Requisites:</strong></p><ul><li>Docker should be installed on server.</li><li>Docker-compose should be installed on server.</li></ul><p><strong>Step-1:</strong> Create a <strong>locust</strong> directory at your <strong>/home/user</strong> directory</p><pre>cd /home/user<br>mkdir locust<br>chown -R user:user locust/</pre><p><strong>Step-2:</strong> Create a <strong>docker-compose.yml</strong> file with following content</p><pre>version: &#39;3&#39;<br><br>services:<br>  master:<br>    image: locustio/locust<br>    ports:<br>     - &quot;8089:8089&quot;<br>    volumes:<br>      - ./:/home/user/locust<br>    command: -f /home/user/locust/traffictest.py --master -H http://master:8089<br><br>  worker:<br>    image: locustio/locust<br>    volumes:<br>      - ./:/home/user/locust<br>    command: -f /home/user/locust/traffictest.py --worker --master-host master</pre><p><strong>Step-3:</strong> Create a <strong>traffictest.py </strong>file at <strong>/home/user/locust</strong> directory:</p><p>This is the crucial part; you need to modify your <strong>traffic setup</strong> in this file; you can arrange multiple tests with a single file. Let’s examine the following example:</p><pre>from locust import HttpUser, task<br>import random<br><br>class StartUser(HttpUser):<br>    @task(1)<br>    def homepage(self):<br>        self.client.get(&quot;/&quot;, name=&quot;Home&quot;)<br><br>    @task(112)<br>    def credit_homepage(self):<br>        self.client.get(&quot;/kredi&quot;, name=&quot;Credit&quot;)<br><br>    @task(148)<br>    def consumerloan_homepage(self):<br>        self.client.get(&quot;/kredi/ihtiyac-kredisi&quot;, name=&quot;ConsumerLoan&quot;)<br><br>    @task(3386)<br>    def consumerloansearch(self):<br>        maturity = random.randrange(3, 36, 3)<br>        amount = random.randrange(10000, 50000, 5000)<br>        self.client.get(&quot;/kredi/ihtiyac-kredisi/sorgulama?amount=&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;ConsumerLoan&quot;)<br><br>    @task(227)<br>    def consumerloan_detail(self):<br>        maturity = random.randrange(3, 36, 3)<br>        amount = random.randrange(10000, 50000, 5000)<br>        self.client.get(&quot;/kredi/ihtiyac-kredisi/ing-bank/yeni-musterilere-ozel?amount=&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;ConsumerLoan&quot;)<br><br>    @task(176)<br>    def consumerloan_recourse_forward(self):<br>        maturity = random.randrange(3, 36, 3)<br>        amount = random.randrange(10000, 50000, 5000)<br>        self.client.get(&quot;/basvuru/ihtiyac/yonlendirme?id=1323&amp;ct=Detail&amp;activityStatus=All&amp;amount=&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;ConsumerLoan&quot;)<br><br><br>    @task(10)<br>    def consumerloan_recourse_form(self):<br>        maturity = random.randrange(3, 36, 3)<br>        amount = random.randrange(10000, 50000, 5000)<br>        self.client.get(&quot;/basvuru/ihtiyac/form?id=713&amp;ct=List&amp;activityStatus=All&amp;amount=&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;ConsumerLoan&quot;)<br><br>    @task(280)<br>    def consumerloan_bank_list(self):<br>        maturity = random.randrange(3, 36, 3)<br>        amount = random.randrange(10000, 50000, 5000)<br>        self.client.get(&quot;/kredi/ihtiyac-kredisi/finansbank?amount&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;ConsumerLoan&quot;)<br><br>    @task(1)<br>    def consumerloan_shopping(self):<br>        self.client.get(&quot;/kredi/ihtiyac-kredisi/alisveris-kredisi&quot;, name=&quot;ConsumerLoanSubCategories&quot;)<br><br>    @task(1)<br>    def consumerloan_holiday(self):<br>        self.client.get(&quot;/kredi/ihtiyac-kredisi/tatil-kredisi&quot;, name=&quot;ConsumerLoanSubCategories&quot;)<br><br>    @task(1)<br>    def consumerloan_festal(self):<br>        self.client.get(&quot;/kredi/ihtiyac-kredisi/bayram-kredisi&quot;, name=&quot;ConsumerLoanSubCategories&quot;)<br><br>    @task(4)<br>    def consumerloan_marrige(self):<br>        self.client.get(&quot;/kredi/ihtiyac-kredisi/evlilik-kredisi&quot;, name=&quot;ConsumerLoanSubCategories&quot;)<br><br>    @task(1)<br>    def consumerloan_education(self):<br>        self.client.get(&quot;/kredi/ihtiyac-kredisi/egitim-kredisi&quot;, name=&quot;ConsumerLoanSubCategories&quot;)<br><br>    @task(1)<br>    def consumerloan_military(self):<br>        self.client.get(&quot;/kredi/ihtiyac-kredisi/abedelli-askerlik-kredisi&quot;, name=&quot;ConsumerLoanSubCategories&quot;)<br><br>    @task(1)<br>    def consumerloan_newyear(self):<br>        self.client.get(&quot;/kredi/ihtiyac-kredisi/yilbasi-kredisi&quot;, name=&quot;ConsumerLoanSubCategories&quot;)<br><br>    @task(6)<br>    def consumerloan_temel_ihtiyac(self):<br>        self.client.get(&quot;/kredi/ihtiyac-kredisi/temel-ihtiyac-kredisi&quot;, name=&quot;ConsumerLoanSubCategories&quot;)<br><br>    @task(151)<br>    def housingloan_homepage(self):<br>        self.client.get(&quot;/kredi/konut-kredisi&quot;, name=&quot;HousingLoan Homr&quot;)<br><br>    @task(292)<br>    def housingloan_search(self):<br>        maturity = random.randrange(12, 120, 12)<br>        amount = random.randrange(100000, 500000, 50000)<br>        self.client.get(&quot;/kredi/konut-kredisi/sorgulama?amount=&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;HousingLoan List&quot;)<br><br>    @task(20)<br>    def housingloan_detail(self):<br>        maturity = random.randrange(12, 120, 12)<br>        amount = random.randrange(100000, 500000, 50000)<br>        self.client.get(&quot;/kredi/konut-kredisi/akbank/konut-kredisi?amount=&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;HousingLoan Detail&quot;)<br><br>    @task(3)<br>    def housingloan_recourse_forward(self):<br>        maturity = random.randrange(12, 120, 12)<br>        amount = random.randrange(100000, 500000, 50000)<br>        self.client.get(&quot;/kredi/konut-kredisi/ing-bank/basvuru/yonlendirme?id=77&amp;ct=List&amp;amount=&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;HousingLoan Forward&quot;)<br><br>    @task(7)<br>    def housingloan_recourse_form(self):<br>        maturity = random.randrange(12, 120, 12)<br>        amount = random.randrange(100000, 500000, 50000)<br>        self.client.get(&quot;/kredi/konut-kredisi/akbank/basvuru/form?id=81&amp;ct=List&amp;activityStatus=All&amp;amount=&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;HousingLoan Form&quot;)<br><br>    @task(13)<br>    def housingloan_bank_list(self):<br>        maturity = random.randrange(12, 120, 12)<br>        amount = random.randrange(100000, 500000, 50000)<br>        self.client.get(&quot;/kredi/konut-kredisi/turkiye-is-bankasi?amount&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;HousingLoan Bank List&quot;)<br><br>    @task(117)<br>    def vehicleloanhomepage(self):<br>        self.client.get(&quot;/kredi/tasit-kredisi&quot;, name=&quot;VehicleLoan Home&quot;)<br><br>    @task(137)<br>    def vehicleloansearch(self):<br>        maturity = random.randrange(12, 36, 12)<br>        amount = random.randrange(100000, 400000, 25000)<br>        self.client.get(&quot;/kredi/tasit-kredisi/sorgulama?amount=200000&amp;maturity=42&amp;CarStatus=2&amp;VehicleExist=0?amount=&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;VehicleLoan List&quot;)<br><br>    @task(13)<br>    def vehicleloan_detail(self):<br>        maturity = random.randrange(12, 36, 12)<br>        amount = random.randrange(100000, 400000, 25000)<br>        self.client.get(&quot;/kredi/tasit-kredisi/garanti-bankasi/tasit-kredisi?amount=&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;VehicleLoan Detail&quot;)<br><br>    @task(13)<br>    def vehicleloan_recourse_forward(self):<br>        maturity = random.randrange(12, 36, 12)<br>        amount = random.randrange(100000, 400000, 25000)<br>        self.client.get(&quot;/kredi/tasit-kredisi/turkiye-is-bankasi/basvuru/yonlendirme?id=104&amp;ct=List&amp;amount=&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;VehicleLoan Forward&quot;)<br><br>    @task(6)<br>    def vehicleloan_recourse_form(self):<br>        maturity = random.randrange(12, 36, 12)<br>        amount = random.randrange(100000, 400000, 25000)<br>        self.client.get(&quot;/kredi/tasit-kredisi/akbank/basvuru/form?id=114&amp;ct=List&amp;activityStatus=All&amp;amount=&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;VehicleLoan Form&quot;)<br><br>    @task(13)<br>    def vehicleloan_bank_list(self):<br>        maturity = random.randrange(12, 36, 12)<br>        amount = random.randrange(100000, 400000, 25000)<br>        self.client.get(&quot;/kredi/tasit-kredisi/akbank?amount&quot;+ str(amount)  +&quot;&amp;maturity=&quot;+ str(maturity), name=&quot;VehicleLoan Bank List&quot;)<br><br><br>    @task(10)<br>    def creditcard_home(self):<br>        self.client.get(&quot;/kredi-karti&quot;, name=&quot;CreditCard&quot;)<br><br>    @task(82)<br>    def creditcard_search(self):<br>        self.client.get(&quot;/kredi-karti/sorgulama&quot;, name=&quot;CreditCard&quot;)<br><br>    @task(40)<br>    def creditcard_search_filter(self):<br>        earningType = [&quot;puan-1&quot;, &quot;mil-2&quot;, &quot;para-4&quot;]<br>        banks = [&quot;akbank-30&quot;, &quot;cepteteb-14&quot;, &quot;enpara-13&quot;]<br>        self.client.get(&quot;/kredi-karti/sorgulama?earningType=&quot; + str(earningType[random.randrange(1 , 3 , 1)]) + &quot;&amp;bank=&quot; + str(banks[random.randrange(1 , 3 , 1)]), name=&quot;CreditCard&quot;)<br><br>    @task(47)<br>    def creditcard_banklist(self):<br>        self.client.get(&quot;/kredi-karti/sorgulama/enpara&quot;, name=&quot;CreditCard&quot;)<br><br>    @task(70)<br>    def creditcard_detail(self):<br>        self.client.get(&quot;/kredi-karti/sorgulama/enpara&quot;, name=&quot;CreditCard&quot;)<br><br>    @task(81)<br>    def creditcard_forward(self):<br>        self.client.get(&quot;/basvuru/kredi-karti/yonlendirme?id=2&quot;, name=&quot;CreditCard&quot;)<br><br>    @task(4)<br>    def creditcard_product_campaign(self):<br>        self.client.get(&quot;/kredi-karti/akbank/axess&quot;, name=&quot;CreditCard&quot;)<br><br>    @task(20)<br>    def creditcard_all_campaign(self):<br>        self.client.get(&quot;/kredi-karti/kampanyalar&quot;, name=&quot;CreditCard&quot;)<br><br>    @task(352)<br>    def deposit_homepage(self):<br>        self.client.get(&quot;/yatirim-araclari/mevduat-faiz-oranlari&quot;, name=&quot;Deposit Home&quot;)<br><br>    @task(2619)<br>    def deposit_search(self):<br>        maturity = random.randrange(32, 108, 10)<br>        amount = random.randrange(10000, 50000, 5000)<br>        currencyType = random.randrange(1, 3, 1)<br>        self.client.get(&quot;/yatirim-araclari/mevduat-faiz-oranlari/hesaplama?amount=&quot;+ str(amount) + &quot;&amp;currencyType=1&amp;maturity=&quot; + str(maturity), name=&quot;Deposit List&quot;)<br><br>    @task(224)<br>    def deposit_detail(self):<br>        maturity = random.randrange(32, 108, 10)<br>        amount = random.randrange(10000, 50000, 5000)<br>        self.client.get(&quot;/yatirim-araclari/mevduat-faiz-oranlari/nkolay/n-kolay-bono?productId=93&amp;amount=&quot;+ str(amount) + &quot;&amp;maturityType=1&amp;currencyType=1&amp;maturity=&quot; + str(maturity), name=&quot;Deposit Detail&quot;)<br><br>    @task(58)<br>    def deposit_bank_list(self):<br>        maturity = random.randrange(32, 108, 10)<br>        amount = random.randrange(10000, 50000, 5000)<br>        self.client.get(&quot;/yatirim-araclari/mevduat-faiz-oranlari/ing-bank?&amp;amount=&quot;+ str(amount) + &quot;&amp;maturityType=1&amp;currencyType=1&amp;maturity=&quot; + str(maturity), name=&quot;Deposit Bank List&quot;)<br><br>    @task(54)<br>    def deposit_forward(self):<br>        maturity = random.randrange(32, 108, 10)<br>        amount = random.randrange(10000, 50000, 5000)<br>        self.client.get(&quot;/basvuru/mevduat/yonlendirme?productId=79&amp;amount=&quot;+ str(amount) + &quot;&amp;maturityType=1&amp;applicationType=1&amp;maturity=&quot; + str(maturity), name=&quot;Deposit Forward&quot;)<br><br>    @task(6)<br>    def investment_homepage(self):<br>        self.client.get(&quot;/yatirim-araclari&quot;, name=&quot;Investment Home&quot;)<br><br>    @task(17)<br>    def investment_gold_homepage(self):<br>        self.client.get(&quot;/yatirim-araclari/altin-fiyatlari&quot;, name=&quot;Investment Gold&quot;)<br><br>    @task(6)<br>    def investment_currency_homepage(self):<br>        self.client.get(&quot;/yatirim-araclari/doviz-kurlari&quot;, name=&quot;Investment Currency&quot;)<br><br>    @task(32)<br>    def financial_report(self):<br>        self.client.get(&quot;/kredi-notu&quot;, name=&quot;FinancialReport&quot;)<br><br>    @task(1)<br>    def financial_report_form(self):<br>        self.client.get(&quot;/kredi-notu/hesaplama/talep#1&quot;, name=&quot;FinancialReport&quot;)<br><br>    @task(130)<br>    def credit_calculationtools_homepage(self):<br>        self.client.get(&quot;/kredi/hesaplama-araclari&quot;, name=&quot;CalculationTools&quot;)<br><br></pre><p>The script defines a user class StartUser that inherits from HttpUser, and contains a variety of HTTP GET requests to simulate traffic to different endpoints of a web application.</p><h4>Key Elements:</h4><p><strong>HttpUser Class:</strong></p><p>HttpUser is a base class provided by Locust. It defines users that will generate HTTP traffic.</p><p><strong>Tasks</strong>:</p><p>Each method in the StartUser class is decorated with @task, which represents a simulated user action (HTTP request). The number in parentheses specifies <strong>the relative weight of each task </strong>(i.e., how often the task will be executed relative to others). If your web application has multiple endpoints and some of them have high traffic compared to others than you need to modify weights according to that.</p><p><strong>Task Methods</strong>:</p><p>Each method uses self.client.get() to send a GET request to a specific URL.</p><p>The name parameter inside the get() method is used to label the request in Locust&#39;s reporting.</p><h4>Task Breakdown:</h4><p><strong>Homepage Visits:</strong></p><ul><li>Simulates visits to different homepages like the main site, credit, consumer loan, housing loan, vehicle loan, and deposit homepages.</li></ul><p><strong>Searches:</strong></p><ul><li>Users search for consumer loans, housing loans, vehicle loans, credit cards, and deposits. Parameters like maturity, amount, and bank are randomized for each request.</li></ul><p><strong>Loan Details and Forwarding:</strong></p><ul><li>Users can view loan details and be forwarded to application forms for different types of loans (consumer, housing, vehicle).</li></ul><p><strong>Subcategories:</strong></p><ul><li>Users also visit subcategories for specific types of consumer loans (shopping, holiday, marriage, etc.).</li></ul><p><strong>Credit Card Actions:</strong></p><ul><li>Simulates searches and actions related to credit cards, including filtering based on earning types and bank preferences.</li></ul><p><strong>Investment and Financial Reports:</strong></p><ul><li>Users visit pages related to investment options, gold prices, currency exchange rates, and financial reports.</li></ul><p><strong>Calculation Tools:</strong></p><ul><li>Simulates users interacting with loan calculators, such as early loan repayment or VAT calculation tools.</li></ul><h4>Configuration Summary:</h4><ul><li>The script configures different weights for tasks to simulate more realistic traffic (e.g., get_deposit_list() runs more frequently).</li><li>Tasks are <strong>HTTP GET</strong> requests <strong>simulating user interaction</strong> with various parts of an application.</li><li>The script doesn’t define any additional behavior like wait times between tasks but <strong>can be extended</strong> for more <strong>complexity</strong>.</li></ul><p>This configuration allows you to load-test various endpoints and monitor how they handle traffic at different frequencies.</p><p><strong>Step-4:</strong> Create and deploy services with <strong>docker-compose</strong> command:</p><pre>cd /home/user/locust<br>docker-compose up -d<br>Building with native build. Learn about native build in Compose here: https://docs.docker.com/go/compose-native-build/<br>Creating network &quot;locust_default&quot; with the default driver<br>Creating locust_master_1 ... done<br>Creating locust_worker_1 ... done</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FnzzChoS8z7FlsbgKgkqCA.png" /><figcaption>Docker Container Status after Deployment</figcaption></figure><p><strong>Step-5</strong>: Open Locust tool from your web browser — default running port is <strong>8089: Example: </strong><a href="http://10.25.53.20:8089/">http://10.10.10.10:8089/</a></p><p>You will see number of locust workers at the right top of the screen. You can scale workers if you want to send high loads to your web application but of course your locust server should have enough resources (CPU/Memory) to support this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXIY-wYLncXUV5QR1ZvHyw.png" /><figcaption>Locust UI -Initate Traffic</figcaption></figure><p>To scale number of worker nodes run following command:</p><pre> docker-compose up --scale worker=10 -d<br> <br>Building with native build. Learn about native build in Compose here: https://docs.docker.com/go/compose-native-build/<br>locust_master_1 is up-to-date<br>Creating locust_worker_2  ... done<br>Creating locust_worker_3  ... done<br>Creating locust_worker_4  ... done<br>Creating locust_worker_5  ... done<br>Creating locust_worker_6  ... done<br>Creating locust_worker_7  ... done<br>Creating locust_worker_8  ... done<br>Creating locust_worker_9  ... done<br>Creating locust_worker_10 ... done</pre><p><strong>Step-6</strong>: <strong>Traffic Execution and Results</strong></p><p>Let’s enter traffic details:</p><ul><li><strong>Number of Users</strong>(Peak Number of Active Users): 1000</li><li><strong>Ramp Up</strong> (How many users will join each second)</li><li><strong>Host:</strong> Main Url of website (All endpoints will be tested according to main site)</li></ul><p>Following setup will create a load so that it adds 20 new users each second till 500 users. After reaching 500 users; it will balance # of active users in this level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N5AFMugRmZeq5NrDlYQmVA.png" /><figcaption>Initiate Traffic from Locust UI</figcaption></figure><h4><strong>Results</strong></h4><h4><strong>STATISTICS</strong></h4><p>On the STATISTICS tab; you can see details of each endpoint requests/fails and average response times’. Also at the top of the screen; you can check your current RPS (requests/second) and total Failure rate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4CFsmE1gjeiiQNp-1lQsbw.png" /><figcaption>Statistics</figcaption></figure><h4>FAILURES</h4><p>On the FAILURES tab; you can see details of each endpoint fails. Method, name of the endpoint and failure message from endpoint will be shown here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NcQLYCta0MR44LpIu_M0WA.png" /><figcaption>FAILURES</figcaption></figure><h4>CHARTS</h4><p>On Charts tab; you can graphically follow traffic execution details:</p><ul><li>Total Requests per Second</li><li>Response time Chart (ms)</li><li># of Users</li></ul><p>If you stop and start traffic tests; you can follow charts for each distinct run on the same page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKChvDdXgJqoqRFG2gtcEQ.png" /><figcaption>CHARTS</figcaption></figure><h4>WORKERS</h4><p>You can follow each locust worker detail on WORKERS tab. Their current status, # of users they send; cpu/memory usage details take place in this screen. As you remember; you can scale your workers and assign memory/cpu limits for them in <strong>docker-compose.yaml</strong> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DCSEeackXDHwT1h5A2O3Eg.png" /></figure><h3><strong>Summary</strong></h3><p><strong>Locust</strong> is an open-source load testing tool used to simulate traffic and measure the performance of web applications or systems. It allows users to define custom user behaviors and generate traffic to assess the system’s handling of multiple simultaneous users.</p><h3>Benefits:</h3><ol><li><strong>Scalability</strong>: Can simulate thousands of users by distributing tests across multiple machines.</li><li><strong>Custom user scenarios</strong>: Highly flexible, allowing users to define complex traffic patterns.</li><li><strong>Real-time metrics</strong>: Provides real-time data on response times, failures, and system capacity.</li><li><strong>Simple setup</strong>: Easy to write test scenarios in Python with minimal configuration.</li><li><strong>Open-source</strong>: Free and extensible, making it a cost-effective tool for performance testing.</li></ol><p>Locust is ideal for stress testing and identifying bottlenecks in systems before production deployment.</p><h3><strong>References:</strong></h3><ul><li><a href="https://docs.locust.io/en/stable/what-is-locust.html">What is Locust? — Locust 2.31.5 documentation</a></li><li><a href="https://locust.io/">https://locust.io/</a></li><li><a href="https://github.com/locustio/locust">https://github.com/locustio/locust</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f62749348f49" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streaming Performance Metrics from ZABBIX Server with Bash Scripting]]></title>
            <link>https://medium.com/hangikredi/streaming-performance-metrics-from-zabbix-server-with-bash-scripting-33979526fc47?source=rss-6d9064cc812e------2</link>
            <guid isPermaLink="false">https://medium.com/p/33979526fc47</guid>
            <category><![CDATA[bash]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[zabbix]]></category>
            <category><![CDATA[streaming]]></category>
            <dc:creator><![CDATA[Erkan Cetiner]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 14:04:53 GMT</pubDate>
            <atom:updated>2024-08-02T14:04:53.481Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rhW4XHVxhAzVhn_JbK9Sw.png" /></figure><p>Streaming <strong>ZABBIX</strong> performance metrics for physical servers, VMs, and Docker containers using <strong>bash scripting</strong> can be an effective solution for addressing <strong>disk storage limitations on the ZABBIX server</strong>. By redirecting the data collection process to external <strong>CSV</strong> or <strong>TXT</strong> files, you can alleviate the storage burden on the ZABBIX server, ensuring that it doesn’t run out of space due to the continuous accumulation of monitoring data.</p><p>This approach involves implementing simple bash scripts that regularly query ZABBIX metrics, extract relevant data, and append it to external files stored on alternative storage solutions or remote servers.</p><h3>Steps</h3><p><strong>Implementation of Bash Script</strong></p><pre>#!/bin/bash<br><br>ZABBIX_URL=&quot;http://10.10.10.10/zabbix/api_jsonrpc.php&quot;<br>USERNAME=&quot;zabbix&quot;<br>PASSWORD=&quot;zabbix1234!&quot;<br>HOSTGROUP_NAME=&quot;PRODUCTION_HOSTS&quot;<br><br># Predefined auth token<br>AUTH_TOKEN=&quot;1f123414e19fkl98e22b0asda23das32cd25ac4bc9976a271be6&quot;<br><br>if [ &quot;$AUTH_TOKEN&quot; == &quot;null&quot; ]; then<br>    echo &quot;Failed to get auth token. Response was: $AUTH_RESPONSE&quot;<br>    exit 1<br>fi<br><br># Get host group ID<br>HOSTGROUP_RESPONSE=$(curl -s -X POST -H &quot;Content-Type: application/json&quot; -d &quot;{<br>    \&quot;jsonrpc\&quot;: \&quot;2.0\&quot;,<br>    \&quot;method\&quot;: \&quot;hostgroup.get\&quot;,<br>    \&quot;params\&quot;: {<br>        \&quot;output\&quot;: \&quot;extend\&quot;,<br>        \&quot;filter\&quot;: {<br>            \&quot;name\&quot;: [\&quot;$HOSTGROUP_NAME\&quot;]<br>        }<br>    },<br>    \&quot;id\&quot;: 1,<br>    \&quot;auth\&quot;: \&quot;$AUTH_TOKEN\&quot;<br>}&quot; $ZABBIX_URL)<br><br>echo &quot;Host group response: $HOSTGROUP_RESPONSE&quot;<br><br>HOSTGROUP_ID=$(echo &quot;$HOSTGROUP_RESPONSE&quot; | jq -r &#39;.result[0].groupid&#39;)<br><br>if [ &quot;$HOSTGROUP_ID&quot; == &quot;null&quot; ]; then<br>    echo &quot;Failed to get host group ID for $HOSTGROUP_NAME. Response was: $HOSTGROUP_RESPONSE&quot;<br>    exit 1<br>fi<br><br>echo &quot;Host group ID: $HOSTGROUP_ID&quot;<br><br># Function to get item ID by item key<br>get_item_id() {<br>    local HOST_ID=$1<br>    local ITEM_KEY=$2<br>    ITEM_ID_RESPONSE=$(curl -s -X POST -H &quot;Content-Type: application/json&quot; -d &quot;{<br>        \&quot;jsonrpc\&quot;: \&quot;2.0\&quot;,<br>        \&quot;method\&quot;: \&quot;item.get\&quot;,<br>        \&quot;params\&quot;: {<br>            \&quot;output\&quot;: [\&quot;itemid\&quot;],<br>            \&quot;hostids\&quot;: \&quot;$HOST_ID\&quot;,<br>            \&quot;search\&quot;: {<br>                \&quot;key_\&quot;: \&quot;$ITEM_KEY\&quot;<br>            },<br>            \&quot;sortfield\&quot;: \&quot;name\&quot;<br>        },<br>        \&quot;id\&quot;: 1,<br>        \&quot;auth\&quot;: \&quot;$AUTH_TOKEN\&quot;<br>    }&quot; $ZABBIX_URL)<br>    echo &quot;Item ID response for key &#39;$ITEM_KEY&#39;: $ITEM_ID_RESPONSE&quot; &gt;&amp;2<br>    echo &quot;$ITEM_ID_RESPONSE&quot; | jq -r &#39;.result[0].itemid&#39;<br>}<br><br># Prepare the CSV file<br>FILENAME=&quot;ALL_SYSTEM_METRICS.csv&quot;<br>if [ ! -f &quot;$FILENAME&quot; ]; then<br>    echo &quot;Host,CPU Idle (%),Memory Available (%),Disk Usage (%),Time&quot; &gt; &quot;$FILENAME&quot;<br>fi<br><br>while true; do<br>    # Get all hosts in the specified host group<br>    HOSTS_RESPONSE=$(curl -s -X POST -H &quot;Content-Type: application/json&quot; -d &quot;{<br>        \&quot;jsonrpc\&quot;: \&quot;2.0\&quot;,<br>        \&quot;method\&quot;: \&quot;host.get\&quot;,<br>        \&quot;params\&quot;: {<br>            \&quot;output\&quot;: [\&quot;hostid\&quot;, \&quot;name\&quot;],<br>            \&quot;groupids\&quot;: \&quot;$HOSTGROUP_ID\&quot;<br>        },<br>        \&quot;id\&quot;: 1,<br>        \&quot;auth\&quot;: \&quot;$AUTH_TOKEN\&quot;<br>    }&quot; $ZABBIX_URL)<br><br>    echo &quot;Hosts response: $HOSTS_RESPONSE&quot;<br><br>    HOSTS=$(echo &quot;$HOSTS_RESPONSE&quot; | jq -c &#39;.result[]&#39;)<br><br>    # Iterate over each host<br>    for HOST in $HOSTS; do<br>        HOST_ID=$(echo &quot;$HOST&quot; | jq -r &#39;.hostid&#39;)<br>        HOST_NAME=$(echo &quot;$HOST&quot; | jq -r &#39;.name&#39;)<br><br>        echo &quot;Processing host: $HOST_NAME (ID: $HOST_ID)&quot;<br><br>        # Get item IDs for CPU idle, Memory, and Disk usage<br>        CPU_ITEM_ID=$(get_item_id &quot;$HOST_ID&quot; &quot;system.cpu.util[,idle]&quot;)<br>        MEM_TOTAL_ITEM_ID=$(get_item_id &quot;$HOST_ID&quot; &quot;vm.memory.size[total]&quot;)<br>        MEM_AVAILABLE_ITEM_ID=$(get_item_id &quot;$HOST_ID&quot; &quot;vm.memory.size[available]&quot;)<br>        DISK_ITEM_ID=$(get_item_id &quot;$HOST_ID&quot; &quot;vfs.fs.dependent.size[/,pused]&quot;)<br><br>        if [ &quot;$CPU_ITEM_ID&quot; == &quot;null&quot; ] || [ &quot;$MEM_TOTAL_ITEM_ID&quot; == &quot;null&quot; ] || [ &quot;$MEM_AVAILABLE_ITEM_ID&quot; == &quot;null&quot; ] || [ &quot;$DISK_ITEM_ID&quot; == &quot;null&quot; ]; then<br>            echo &quot;Failed to get item IDs for host $HOST_NAME&quot;<br>            continue<br>        fi<br><br>        echo &quot;  CPU Item ID: $CPU_ITEM_ID&quot;<br>        echo &quot;  Memory Total Item ID: $MEM_TOTAL_ITEM_ID&quot;<br>        echo &quot;  Memory Available Item ID: $MEM_AVAILABLE_ITEM_ID&quot;<br>        echo &quot;  Disk Item ID: $DISK_ITEM_ID&quot;<br><br>        # Fetch the latest data for each metric<br>        CPU_VALUE=$(curl -s -X POST -H &quot;Content-Type: application/json&quot; -d &quot;{<br>            \&quot;jsonrpc\&quot;: \&quot;2.0\&quot;,<br>            \&quot;method\&quot;: \&quot;history.get\&quot;,<br>            \&quot;params\&quot;: {<br>                \&quot;output\&quot;: \&quot;extend\&quot;,<br>                \&quot;history\&quot;: 0,<br>                \&quot;itemids\&quot;: \&quot;$CPU_ITEM_ID\&quot;,<br>                \&quot;sortfield\&quot;: \&quot;clock\&quot;,<br>                \&quot;sortorder\&quot;: \&quot;DESC\&quot;,<br>                \&quot;limit\&quot;: 1<br>            },<br>            \&quot;id\&quot;: 1,<br>            \&quot;auth\&quot;: \&quot;$AUTH_TOKEN\&quot;<br>        }&quot; $ZABBIX_URL | jq -r &#39;.result[0].value // &quot;N/A&quot;&#39;)<br><br>        MEM_TOTAL_VALUE=$(curl -s -X POST -H &quot;Content-Type: application/json&quot; -d &quot;{<br>            \&quot;jsonrpc\&quot;: \&quot;2.0\&quot;,<br>            \&quot;method\&quot;: \&quot;history.get\&quot;,<br>            \&quot;params\&quot;: {<br>                \&quot;output\&quot;: \&quot;extend\&quot;,<br>                \&quot;history\&quot;: 3,<br>                \&quot;itemids\&quot;: \&quot;$MEM_TOTAL_ITEM_ID\&quot;,<br>                \&quot;sortfield\&quot;: \&quot;clock\&quot;,<br>                \&quot;sortorder\&quot;: \&quot;DESC\&quot;,<br>                \&quot;limit\&quot;: 1<br>            },<br>            \&quot;id\&quot;: 1,<br>            \&quot;auth\&quot;: \&quot;$AUTH_TOKEN\&quot;<br>        }&quot; $ZABBIX_URL | jq -r &#39;.result[0].value // &quot;N/A&quot;&#39;)<br><br>        MEM_AVAILABLE_VALUE=$(curl -s -X POST -H &quot;Content-Type: application/json&quot; -d &quot;{<br>            \&quot;jsonrpc\&quot;: \&quot;2.0\&quot;,<br>            \&quot;method\&quot;: \&quot;history.get\&quot;,<br>            \&quot;params\&quot;: {<br>                \&quot;output\&quot;: \&quot;extend\&quot;,<br>                \&quot;history\&quot;: 3,<br>                \&quot;itemids\&quot;: \&quot;$MEM_AVAILABLE_ITEM_ID\&quot;,<br>                \&quot;sortfield\&quot;: \&quot;clock\&quot;,<br>                \&quot;sortorder\&quot;: \&quot;DESC\&quot;,<br>                \&quot;limit\&quot;: 1<br>            },<br>            \&quot;id\&quot;: 1,<br>            \&quot;auth\&quot;: \&quot;$AUTH_TOKEN\&quot;<br>        }&quot; $ZABBIX_URL | jq -r &#39;.result[0].value // &quot;N/A&quot;&#39;)<br><br>        DISK_VALUE=$(curl -s -X POST -H &quot;Content-Type: application/json&quot; -d &quot;{<br>            \&quot;jsonrpc\&quot;: \&quot;2.0\&quot;,<br>            \&quot;method\&quot;: \&quot;history.get\&quot;,<br>            \&quot;params\&quot;: {<br>                \&quot;output\&quot;: \&quot;extend\&quot;,<br>                \&quot;history\&quot;: 0,<br>                \&quot;itemids\&quot;: \&quot;$DISK_ITEM_ID\&quot;,<br>                \&quot;sortfield\&quot;: \&quot;clock\&quot;,<br>                \&quot;sortorder\&quot;: \&quot;DESC\&quot;,<br>                \&quot;limit\&quot;: 1<br>            },<br>            \&quot;id\&quot;: 1,<br>            \&quot;auth\&quot;: \&quot;$AUTH_TOKEN\&quot;<br>        }&quot; $ZABBIX_URL | jq -r &#39;.result[0].value // &quot;N/A&quot;&#39;)<br><br>        # Calculate memory available percentage<br>        if [ &quot;$MEM_TOTAL_VALUE&quot; != &quot;N/A&quot; ] &amp;&amp; [ &quot;$MEM_AVAILABLE_VALUE&quot; != &quot;N/A&quot; ]; then<br>            MEM_AVAILABLE_PERCENTAGE=$(echo &quot;scale=2; ($MEM_AVAILABLE_VALUE / $MEM_TOTAL_VALUE) * 100&quot; | bc)<br>        else<br>            MEM_AVAILABLE_PERCENTAGE=&quot;N/A&quot;<br>        fi<br><br>        # Get the current timestamp and convert it to GMT+3<br>        TIMESTAMP=$(date +%s)<br>        GMT_PLUS_3=$(date -d &quot;@$TIMESTAMP&quot; -u +&quot;%Y-%m-%d %H:%M:%S&quot; -d &#39;3 hours&#39;)<br><br>        # Append to the CSV file<br>        echo &quot;$HOST_NAME,$CPU_VALUE,$MEM_AVAILABLE_PERCENTAGE,$DISK_VALUE,$GMT_PLUS_3&quot; &gt;&gt; &quot;$FILENAME&quot;<br>    done<br><br>    # Sleep for 5 minutes before the next iteration<br>    sleep 300<br>done<br><br></pre><h4>Key Steps in the Script:</h4><ol><li><strong>Initialization</strong>:</li></ol><ul><li>The script sets variables for the <strong>ZABBIX</strong> <strong>server</strong> <strong>URL</strong>, <strong>credentials</strong>, and the <strong>host group name</strong> (“PRODUCTION_HOSTS”).</li><li>It uses a <strong>predefined authentication token </strong>(AUTH_TOKEN) for making API requests to the ZABBIX server. (Please check <a href="https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/users/api_tokens">Ref#1</a> for creation of API Token on ZABBIX)</li></ul><p><strong>2. Host Group ID Retrieval</strong>:</p><ul><li>The script makes an <strong>API call </strong>to get the <strong>ID of the specified host group</strong>.</li></ul><p><strong>3. Item ID Retrieval Function</strong>:</p><ul><li>A function named get_item_id is defined to get the item ID for a specific metric (e.g., CPU idle, memory usage) based on the host ID and item key.</li></ul><p><strong>4. CSV File Preparation</strong>:</p><ul><li>A <strong>CSV</strong> file named ALL_SYSTEM_METRICS.csv is created. If it doesn&#39;t already exist, a header line is added to define the columns (<strong>Host, CPU Idle, Memory Available, Disk Usage, Time</strong>).</li></ul><p><strong>5. Data Collection Loop</strong>:</p><ul><li>The script enters an infinite loop, where it retrieves a list of all hosts in the specified host group.</li><li>For each host, it retrieves the i<strong>tem IDs for CPU idle time</strong>, <strong>total memory</strong>, <strong>available memory</strong>, and <strong>disk usage</strong>.</li><li>The script then fetches the latest values for these metrics from ZABBIX using the <strong>history.get</strong> method.</li></ul><p><strong>6. Data Calculation and Formatting</strong>:</p><ul><li><strong>Memory availability</strong> is calculated <strong>as a percentage </strong>of total memory.</li><li>The current timestamp is converted to GMT+3 to ensure the data is time-stamped correctly. (You can update this to fit your purpose.)</li></ul><p><strong>7. Data Writing</strong>:</p><ul><li>The collected metrics, along with the host name and timestamp, are appended to the <strong>CSV file</strong>.</li></ul><p><strong>8. Repetition</strong>:</p><ul><li>The script sleeps for 5 minutes (sleep 300) before repeating the process, allowing it to continuously collect and log performance data.</li></ul><p><strong>Running Script as a Background Job</strong></p><p>The nohup command allows you to run the script in the background, even if you log out or close the terminal. Here&#39;s how you can use it:</p><pre>nohup ./collect_zabbix_metrics.sh &amp;</pre><p>Here is the snapshot of a CSV file from extracted metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kL_0awTvxuVc7x1_lPM0BA.png" /><figcaption>CSV file for Host Performance Metrics</figcaption></figure><p>The script is designed to offload performance metrics from the ZABBIX server to external storage, thereby reducing disk usage on the server and enabling longer retention of historical data. By saving this data externally, the metrics can be analyzed for trends, anomalies, and pattern recognition over time which are crucial for maintaining optimal system performance.</p><p><strong>References:</strong></p><ul><li><a href="https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/users/api_tokens">https://www.zabbix.com/documentation/current/en/manual/web_interface/frontend_sections/users/api_tokens</a></li><li><a href="https://www.zabbix.com/documentation/current/en/manual/api">https://www.zabbix.com/documentation/current/en/manual/api</a></li><li><a href="https://blog.zabbix.com/zabbix-api-scripting-via-curl-and-jq/12434/">https://blog.zabbix.com/zabbix-api-scripting-via-curl-and-jq/12434/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33979526fc47" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hangikredi/streaming-performance-metrics-from-zabbix-server-with-bash-scripting-33979526fc47">Streaming Performance Metrics from ZABBIX Server with Bash Scripting</a> was originally published in <a href="https://medium.com/hangikredi">HangiKredi</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[VMWare VSphere Center Monitoring with Telegraf/InfluxDB and Grafana Integration]]></title>
            <link>https://medium.com/@ecetiner87/vmware-vsphere-center-monitoring-with-telegraf-influxdb-and-grafana-integration-fe5138acb6c7?source=rss-6d9064cc812e------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe5138acb6c7</guid>
            <category><![CDATA[vmware-vsphere]]></category>
            <category><![CDATA[telegraf]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Erkan Cetiner]]></dc:creator>
            <pubDate>Fri, 07 Jun 2024 08:07:42 GMT</pubDate>
            <atom:updated>2024-06-07T08:07:42.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*f_H_kDWEUV9wwqisfkhr4w.png" /><figcaption>High Level Architecture</figcaption></figure><p>Nowadays, resource management is one of the most important topics that application managers need to pay attention to. No matter how well you develop a software, it requires a very detailed resource arrangement and real-time tracking to keep it running 24/7. Especially in the on-premises world, companies that fail to monitor how they use their resources can suffer both financial and reputational losses due to the impact on the accessibility of their developed applications/websites.</p><p>For this reason, in this article, I will discuss how detailed monitoring of a VMWare environment can be performed using the integration of open-source tools and how this can help in optimizing the distribution of the total resources (CPU/memory/storage) of VMs.</p><h3>Step-1 Install and Configure Telegraf on Vsphere</h3><p><strong>Telegraf</strong> is a server-based agent for collecting and sending all metrics and events from databases, systems, and IoT sensors. Telegraf is written in Go and compiles into a single binary with no external dependencies and requires a very minimal memory footprint.</p><p>VSphere uses its own Operating System based on Linux — Photon OS; and uses <strong>tdnf</strong> package manager similar to <strong>apt</strong>.</p><pre>sudo tdnf clean all<br>sudo tdnf makecache<br>tdnf install telegraf</pre><p>Configure <strong>/etc/telegraf/telegraf.conf</strong> file to direct metrics to the <strong>influxdb</strong>:</p><ul><li><strong>[[inputs.vsphere]]</strong> — <strong>Vcenter IP / Username / Password</strong></li><li><strong>[[outputs.influxdb_v2]] </strong>— <strong>InfluxDBv2 IP / Token / Organization and Bucket</strong></li></ul><pre>[global_tags]<br>  user = &quot;alice&quot;<br><br># Input Plugin Configuration<br>[[inputs.vsphere]]<br>  ## List of vCenter URLs to be monitored<br>  vcenters = [&quot;https://10.10.10.10/sdk&quot;]<br>  username = &quot;administrator@vsphere.local&quot;<br>  password = &quot;adminpassword&quot;<br><br>  ## VMs<br>  vm_metric_include = [<br>    &quot;cpu.demand.average&quot;,<br>    &quot;cpu.idle.summation&quot;,<br>    &quot;cpu.latency.average&quot;,<br>    &quot;cpu.readiness.average&quot;,<br>    &quot;cpu.ready.summation&quot;,<br>    &quot;cpu.run.summation&quot;,<br>    &quot;cpu.usagemhz.average&quot;,<br>    &quot;cpu.used.summation&quot;,<br>    &quot;cpu.wait.summation&quot;,<br>    &quot;mem.active.average&quot;,<br>    &quot;mem.granted.average&quot;,<br>    &quot;mem.latency.average&quot;,<br>    &quot;mem.swapin.average&quot;,<br>    &quot;mem.swapinRate.average&quot;,<br>    &quot;mem.swapout.average&quot;,<br>    &quot;mem.swapoutRate.average&quot;,<br>    &quot;mem.usage.average&quot;,<br>    &quot;mem.vmmemctl.average&quot;,<br>    &quot;net.bytesRx.average&quot;,<br>    &quot;net.bytesTx.average&quot;,<br>    &quot;net.droppedRx.summation&quot;,<br>    &quot;net.droppedTx.summation&quot;,<br>    &quot;net.usage.average&quot;,<br>    &quot;power.power.average&quot;,<br>    &quot;virtualDisk.numberReadAveraged.average&quot;,<br>    &quot;virtualDisk.numberWriteAveraged.average&quot;,<br>    &quot;virtualDisk.read.average&quot;,<br>    &quot;virtualDisk.readOIO.latest&quot;,<br>    &quot;virtualDisk.throughput.usage.average&quot;,<br>    &quot;virtualDisk.totalReadLatency.average&quot;,<br>    &quot;virtualDisk.totalWriteLatency.average&quot;,<br>    &quot;virtualDisk.write.average&quot;,<br>    &quot;virtualDisk.writeOIO.latest&quot;,<br>    &quot;sys.uptime.latest&quot;,<br>  ]<br>  # vm_metric_exclude = [] ## Nothing is excluded by default<br>  # vm_instances = true ## true by default<br><br>  ## Hosts<br>  host_metric_include = [<br>    &quot;cpu.coreUtilization.average&quot;,<br>    &quot;cpu.costop.summation&quot;,<br>    &quot;cpu.demand.average&quot;,<br>    &quot;cpu.idle.summation&quot;,<br>    &quot;cpu.latency.average&quot;,<br>    &quot;cpu.readiness.average&quot;,<br>    &quot;cpu.ready.summation&quot;,<br>    &quot;cpu.swapwait.summation&quot;,<br>    &quot;cpu.usage.average&quot;,<br>    &quot;cpu.usagemhz.average&quot;,<br>    &quot;cpu.used.summation&quot;,<br>    &quot;cpu.utilization.average&quot;,<br>    &quot;cpu.wait.summation&quot;,<br>    &quot;disk.deviceReadLatency.average&quot;,<br>    &quot;disk.deviceWriteLatency.average&quot;,<br>    &quot;disk.kernelReadLatency.average&quot;,<br>    &quot;disk.kernelWriteLatency.average&quot;,<br>    &quot;disk.numberReadAveraged.average&quot;,<br>    &quot;disk.numberWriteAveraged.average&quot;,<br>    &quot;disk.read.average&quot;,<br>    &quot;disk.totalReadLatency.average&quot;,<br>    &quot;disk.totalWriteLatency.average&quot;,<br>    &quot;disk.write.average&quot;,<br>    &quot;mem.active.average&quot;,<br>    &quot;mem.latency.average&quot;,<br>    &quot;mem.state.latest&quot;,<br>    &quot;mem.swapin.average&quot;,<br>    &quot;mem.swapinRate.average&quot;,<br>    &quot;mem.swapout.average&quot;,<br>    &quot;mem.swapoutRate.average&quot;,<br>    &quot;mem.totalCapacity.average&quot;,<br>    &quot;mem.usage.average&quot;,<br>    &quot;mem.vmmemctl.average&quot;,<br>    &quot;net.bytesRx.average&quot;,<br>    &quot;net.bytesTx.average&quot;,<br>    &quot;net.droppedRx.summation&quot;,<br>    &quot;net.droppedTx.summation&quot;,<br>    &quot;net.errorsRx.summation&quot;,<br>    &quot;net.errorsTx.summation&quot;,<br>    &quot;net.usage.average&quot;,<br>    &quot;power.power.average&quot;,<br>    &quot;storageAdapter.numberReadAveraged.average&quot;,<br>    &quot;storageAdapter.numberWriteAveraged.average&quot;,<br>    &quot;storageAdapter.read.average&quot;,<br>    &quot;storageAdapter.write.average&quot;,<br>    &quot;sys.uptime.latest&quot;,<br>  ]<br>  # host_metric_exclude = [] ## Nothing excluded by default<br>  # host_instances = true ## true by default<br><br>  ## Datacenters<br>  datacenter_metric_include = []<br>  datacenter_metric_exclude = [&quot;*&quot;] ## Datacenters are not collected by default.<br>  # datacenter_instances = false ## false by default<br><br>  ## Additional settings<br>  # separator = &quot;_&quot;<br>  # max_query_objects = 256<br>  # max_query_metrics = 256<br>  # collect_concurrency = 1<br>  # discover_concurrency = 1<br>  # object_discovery_interval = &quot;300s&quot;<br>  # timeout = &quot;60s&quot;<br>  # use_int_samples = true<br>  # custom_attribute_include = []<br>  # custom_attribute_exclude = [&quot;*&quot;]<br>  # metric_lookback = 3<br>  # ssl_ca = &quot;/path/to/cafile&quot;<br>  # ssl_cert = &quot;/path/to/certfile&quot;<br>  # ssl_key = &quot;/path/to/keyfile&quot;<br>  insecure_skip_verify = true<br>  # historical_interval = &quot;5m&quot;<br><br>[[outputs.influxdb_v2]]<br>  urls = [&quot;http://10.10.10.20:8086&quot;]<br>  token = &quot;lG3CSuXGD8klijqGTwqGG85QRNX_61JWx&quot;<br>  organization = &quot;MyOrganization&quot;<br>  bucket = &quot;telegraf&quot;</pre><p>After installation; we need to enable and start service:</p><pre>systemctl enable telegraf<br>systemctl start telegraf</pre><h3>Step-2 Grafana Configuration</h3><p>Now we are collecting vsphere metrics from telegraf and write them to our bucket on InfluxDB; to visualize them on Grafana; we need to <strong>add InfluxDB as a datasource (For Influx DB Installation; please refer to: </strong><a href="https://zeropage.io/how-to-install-influxdb-2-on-ubuntu-or-unix-in-general/">https://zeropage.io/how-to-install-influxdb-2-on-ubuntu-or-unix-in-general/</a><strong>)</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-T7azo0ySDkL_NUN39t9w.png" /><figcaption>Select Connections — Data Sources — Add New Data Source on GRAFANA</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITxFqo1juAQ241KI2WHysQ.png" /><figcaption>Select InfluxDB from List and Click</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_uqKTnVTrsc33rYs1_AjYA.png" /><figcaption>Enter Details of InfluxDB and Click Save</figcaption></figure><p>Now; we can create our dashboards for VMWare metrics; there are dozens of them on Grafana Library and you can select as many as you want which fit your purposes; in this article I want to show following dashboards:</p><ul><li>Grafana Dashboard ID: <strong>8168</strong> — VMWare <strong>Vsphere VMs</strong> Dashboard</li><li>Grafana Dashboard ID: <strong>8159</strong> — VMWare <strong>Vsphere Overall</strong> Dashboard</li><li>Grafana Dashboard ID: <strong>8165</strong> — VMWare <strong>Vsphere Hosts</strong> Dashboard</li><li>Grafana Dashboard ID: <strong>8162</strong> — VMWare <strong>Vsphere Datastores</strong> Dashboard</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WOZLSPu9TiLV0G8cqgvoPQ.png" /><figcaption>Select Dashboards on Grafana and Click on New Dashboard</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*W1tlsgN1VTZphzKf-17PWg.png" /><figcaption>Select Import Dashboard</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*4koHeRnkCEQD3bjMGNEPOA.png" /><figcaption>Enter Dashboard ID and Click on Load</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*Rd7nYXBguz_WXytp21CCVQ.png" /><figcaption>Give Name to Your Dashboard and Select InfluxDB as Datasources</figcaption></figure><p>After you create all your dashboards as in example; you can view them on Grafana:</p><p><strong>VMWare Vsphere VMs Dashboard:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PvXkQuRNZt9WkFCwOnACjA.png" /><figcaption>Detailed Metrics for Each VM on VMWare</figcaption></figure><p><strong>VMWare Vsphere Hosts Dashboard:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*juhBylP7WVcx9KrBFWWIqw.png" /><figcaption>Detailed Metrics for Each Physical Host on VMWare</figcaption></figure><p><strong>VMWare Vsphere DataStores Dashboard:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*13eDIOoszTp67HFINnrl9Q.png" /><figcaption>Detailed Metrics for Each Physical Storage on VMWare</figcaption></figure><p><strong>VMWare Vsphere Overview Dashboard:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NcoAWvtEt3O9eR_q3ix6yg.png" /><figcaption>Overview Summary of VSphere</figcaption></figure><p>With these simple and open-source integrations, you can monitor everything happening in your entire cluster, set thresholds and generate alarms, and track potential resource problems in real-time. This ensures that the applications running on your VMs are more robust and available. See you in another article :)</p><p><strong>References:</strong></p><ul><li><a href="https://github.com/influxdata/telegraf">GitHub - influxdata/telegraf: Agent for collecting, processing, aggregating, and writing metrics, logs, and other arbitrary data.</a></li><li><a href="https://docs.influxdata.com/telegraf/v1/install/">Install Telegraf</a></li><li><a href="https://grafana.com/grafana/dashboards/8159-vmware-vsphere-overview/">VMware vSphere - Overview | Grafana Labs</a></li><li><a href="https://grafana.com/grafana/dashboards/8168-vmware-vsphere-vms/">VMware vSphere - VMs | Grafana Labs</a></li><li><a href="https://grafana.com/grafana/dashboards/8165-vmware-vsphere-hosts/">VMware vSphere - Hosts | Grafana Labs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe5138acb6c7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Utilization of ElasticSearch Cluster Disk Capacity with Delete_by_Query API]]></title>
            <link>https://medium.com/@ecetiner87/utilization-of-elasticsearch-cluster-disk-capacity-with-delete-by-query-api-a43a78baf9e1?source=rss-6d9064cc812e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a43a78baf9e1</guid>
            <category><![CDATA[utilization]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[disk]]></category>
            <dc:creator><![CDATA[Erkan Cetiner]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 07:56:06 GMT</pubDate>
            <atom:updated>2024-01-11T07:56:06.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*vL9zGhnJXl3wuSReWbARYQ.png" /></figure><p>The <strong>ELK</strong> mechanism is significant and widespread in today’s application development and monitoring. Especially in analyzing application logs thoroughly, making them visible, and identifying patterns, it stands as a great ally for DEVOPS teams to derive meaningful insights from them. With the capability to generate real-time alarms from these logs, and send them to relevant channels, ELK significantly enhances the reliability and robustness of live systems.</p><p>However, effective management and handling according to needs are crucial. Considering the reality of not having unlimited disk and computation capacity in an ELK cluster, our utilization of these benefits might unexpectedly halt, potentially leading to the loss of the entire structure.</p><p>In Elasticsearch, we can control the <strong>lifecycles</strong> of the <strong>indexes</strong> where we send our logs using <strong>index lifecycle management</strong>. We can define phases like <strong>hot/warm/cold/delete </strong>based on our <strong>usage frequency</strong> and regulate the data we store on disk. This allows us to <strong>calculate</strong> and <strong>activate</strong> the <strong>index lifecycle</strong> according to how much historical log data we need to retain and the capacity available.</p><p>Yet, at times, we might not be able to increase our capacity but <strong>might want to keep certain pattern-based logs for longer periods</strong> in the past. Particularly, development teams, aside from their daily routines, might need to examine older dated <strong>exceptions and error logs</strong> to stabilize the system further. If we lose an entire index due to index lifecycle processing, the <strong>exception</strong> and <strong>error</strong> <strong>logs</strong> that are significant for us within that index are also lost.</p><p>Especially in an index where the majority of our logs consist of Info/Warning Level logs, what can we do? Can we retain specific pattern-based logs within an index while deleting others? <strong>The answer is yes!</strong></p><p><strong>Elasticsearch</strong> provides us with the <strong>DELETE_BY_QUERY API</strong>, granting us this opportunity. Let’s see how to use this API through the example below:</p><p>We want to delete <strong>WARNING</strong> and <strong>INFO</strong> <strong>level</strong> <strong>logs </strong>in <strong>indexes</strong> that are <strong>in the cold phase</strong> of our lifecycle management:</p><p><strong>Solution:</strong></p><ul><li><strong>Delete_by_Query API Usage on ElasticSeach Dev Tools</strong>:</li></ul><pre>POST /myindex/_delete_by_query<br>{<br>  &quot;query&quot;: {<br>   &quot;bool&quot;: {<br>    &quot;should&quot;: [<br>       { &quot;match&quot;: { &quot;Level&quot;: &quot;Information&quot; }},<br>       { &quot;match&quot;: { &quot;Level&quot;: &quot;Warning&quot; }}<br>      ]<br>  }<br>}</pre><p>This request will <strong>delete ALL documents </strong>on the index named “<strong>myindex</strong>” <strong>if</strong> the related document’s <strong>Level</strong> attribute is either <strong>Information</strong> or <strong>Warning.</strong></p><p>So all we have to do is implement a mechanism to fit our purpose so that we can do this operation continuously. A Simple bash script could help us to achieve this, let’s say the <strong>oldest 10 indexes </strong>of my<strong> Index Lifecycle</strong> correspond to <strong>COLD</strong> <strong>status</strong> and I want to keep <strong>ERROR/CRITICAL </strong>logs for those indexes:</p><pre>#!/bin/bash<br>PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/home<br><br># Elasticsearch endpoint<br>ELASTICSEARCH_HOST=&quot;http://10.10.10.10:9200&quot;<br>USERNAME=&quot;elastic&quot;<br>PASSWORD=&quot;elastic&quot;<br>LOG_FILE=&quot;/home/cleanUpIndexes.txt&quot;<br>exec &amp;&gt;&gt; &quot;$LOG_FILE&quot;<br><br># Function to get the list of indices<br>get_indices() {<br>    indices=$(curl -s -u &quot;$USERNAME:$PASSWORD&quot; -X GET &quot;$ELASTICSEARCH_HOST/_cat/indices&quot; | awk &#39;{print $3}&#39; | grep &#39;myindex-&#39; | sort)<br>    echo &quot;$indices&quot;<br>}<br><br># Function to delete documents matching the criteria<br>delete_docs_by_query() {<br>    index=$1<br>    query=&#39;{<br>      &quot;query&quot;: {<br>        &quot;bool&quot;: {<br>          &quot;should&quot;: [<br>            { &quot;match&quot;: { &quot;Level&quot;: &quot;Information&quot; }},<br>            { &quot;match&quot;: { &quot;Level&quot;: &quot;Warning&quot; }}<br>          ]<br>        }<br>      }<br>    }&#39;<br>    curl -s -u &quot;$USERNAME:$PASSWORD&quot; -X POST &quot;$ELASTICSEARCH_HOST/$index/_delete_by_query?refresh&quot; -H &#39;Content-Type: application/json&#39; -d &quot;$query&quot;<br>}<br><br># Function to find and delete documents from the oldest 10 indices<br>delete_from_oldest_indices() {<br>    start_time=$(date +%s)<br>    echo -e &quot;Script execution started on $(date)\n&quot;<br>    get_indices<br>    indices=$(get_indices)<br>    total_indices=$(echo &quot;$indices&quot; | wc -l)<br><br>    indices_to_delete=$(echo &quot;$indices&quot; | head -n 10)<br><br>    for index in $indices_to_delete; do<br>        delete_docs_by_query &quot;$index&quot;<br>        echo &quot;Deleted documents include INFO and WARN logs from index: $index&quot;<br>    done<br>    echo -e &quot;Script execution finished on $(date)\n&quot;<br>    end_time=$(date +%s)<br>    execution_time=$((end_time - start_time))<br>    echo -e &quot;Total execution time: $execution_time seconds\n&quot;<br>}<br><br><br># Main execution<br>delete_from_oldest_indices</pre><p>3 functions implemented:</p><ul><li><strong>get_indices():<br>- </strong>Get all indices from Elasticsearch and filter them with “<strong>myindex-</strong>“; also sort them from <strong>oldest</strong> to <strong>new</strong>.</li><li><strong>delete_docs_by_query():<br>- </strong>Delete <strong>WARN</strong> and <strong>INFORMATION</strong> Level Logs for the given index.</li><li><strong>delete_from_oldest_indices():<br>- </strong>Call<strong> the get_indices() </strong>function first; then <strong>parse the first 10 indexes</strong> out of the output and <strong>assign</strong> them to the <strong>indices_to_delete</strong> variable. Then, for each <strong>index</strong> in the <strong>indices_to_delete</strong> variable; it calls the <strong>delete_docs_by_query() </strong>function and iterates until the last index in the list.</li></ul><p>The <strong>oldest 10</strong> indexes will keep <strong>ERROR/CRITICAL</strong> level logs only for optimizing disk usage on <strong>Elasticsearch Cluster; </strong>as you can see, # of documents decreases significantly between indexes that are modified with related script.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8F5O70bb-LGN7W0-uvEECg.png" /></figure><p>Now you can put this bash script in a cron job on your cluster and <br>run it during the hours when the Elasticsearch is least busy, you can scan the cold index list daily for all your fallen indexes, freeing up more space in your cluster.</p><p>Hope you enjoy the article. Please follow for more!</p><p><strong>References:</strong></p><ul><li><a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html">https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-delete-by-query.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a43a78baf9e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>