LogoLogo
  • Welcome
  • Explorers
    • Aptos Explorer
    • Cosmos Explorer
  • Blockchains
    • Aptos
      • Run a Validator and VFN
        • Operator
        • Node Requirements
        • Deploy Nodes
          • Using Source Code
        • Connect Nodes
          • Connect to a Network
          • Staking Pool Operations
          • Delegation Pool Operations
          • Staking Pool Voter
        • Verify Nodes
          • Node Health
          • Validator Leaderboard
        • Modify Nodes
          • Upgrade Nodes
          • Shutdown Nodes
      • Run a Public Fullnode
        • PFN Requirements
        • Deploy a PFN
          • Deploy a PFN using Source Code
        • Verify a PFN
        • Modify a PFN
          • Customize PFN Networks
          • Generate a PFN Identity
          • Upgrade your PFN
          • Run a PFN from Source Code
      • Bootstrap a Node with historical data
        • Bootstrap from a Backup
        • Bootstrap from a Snapshot
      • Configure a Node
        • State Synchronization
        • Data Pruning
        • Telemetry
        • Locating Node Files
          • Files For Mainnet
          • Files For Testnet
          • Files For Devnet
      • Monitor your Nodes
        • Important Node Metrics
        • Node Health Checker
        • Node Health Checker FAQ
        • Node Inspection Service
      • Building Aptos From Source
      • Aptos Networks
    • Berachain V2
      • Node Snapshot
      • Explorer
      • AddrBook File
      • Genesis File
      • API Endpoint
      • RPC Endpoint
      • gRPC Endpoint
      • Live Peers
      • Forest Staking Peer
      • Performance Optimizer Script
      • Discord & TG Alert System
      • RPC Load Balancer Setup
    • Casper
      • Explorer
    • Haqq
      • Node Snapshot
      • Explorer
      • AddrBook File
      • Genesis File
      • API Endpoint
      • RPC Endpoint
      • Live Peers
      • Forest Staking Peer
    • Mantra
      • Node Snapshot
      • Explorer
      • AddrBook File
      • Genesis File
      • API Endpoint
      • RPC Endpoint
      • Live Peers
      • Forest Staking Peer
    • Ika
    • Story Protocol
      • Node Snapshot
      • Explorer
      • AddrBook File
      • Genesis File
      • API Endpoint
      • RPC Endpoint
      • EVM Endpoint
      • Websocket
      • WSS
      • Discord & TG Alert System
      • RPC Load Balancer
      • Performance Optimizer Script
      • Live Peers
      • Forest Staking Peer
    • Supra
      • Explorer
      • Oracle data
    • Showdown
      • Node Snapshot
      • Explorer
      • AddrBook File
      • Genesis File
      • API Endpoint
      • RPC Endpoint
      • Live Peers
      • Forest Staking Peer
    • Soarchain
      • Node Snapshot
      • Explorer
      • AddrBook File
      • Genesis File
      • API Endpoint
      • RPC Endpoint
      • Live Peers
      • Forest Staking Peer
    • Zenrock
      • Node Snapshot
      • Explorer
      • AddrBook File
      • Genesis File
      • API Endpoint
      • RPC Endpoint
      • Live Peers
      • Forest Staking Peer
    • Zetachain
      • Node Snapshot
      • Explorer
      • AddrBook File
      • Genesis File
      • API Endpoint
      • RPC Endpoint
      • Live Peers
      • Forest Staking Peer
    • Airchains
      • Node Snapshot
      • Explorer
  • Gunzilla - Off The Grid
    • Vision and Foundation
    • Gunzilla Hacker Dashboard
      • Key Features of the Hackers Dashboard
        • Wallet Integration and Testnet Access
        • License System with Rarity Tiers
        • Decoding Stats and Hash Power Tracking
        • Marketplace for Trading Licenses and Assets
        • Scanner Tool for Blockchain Transparency
        • Social Media Integration and Community Engagement
      • Mastering the Hackers Dashboard
      • Benefits of the Hackers Dashboard
    • Gunzilla Token Page
  • Forest Esports Team
    • Forest Hexers
  • Crypto Tools & Analytics
    • Top 10 Crypto Exchanges
      • Binance
      • Coinbase
      • Kraken
      • Bybit
      • OKX
      • KuCoin
      • Bitfinex
      • Gemini
      • Crypto.com
      • Bitstamp
    • Top 10 Wallets
      • Ledger Nano X
      • Trezor Model T
      • Exodus
      • Coinbase Wallet
      • Trust Wallet
      • MetaMask
      • Crypto.com DeFi Wallet
      • ZenGo
      • Atomic Wallet
      • SafePal
  • Top 10 Crypto Data Platforms
    • CoinMarketCap
    • CoinGecko
    • CryptoCompare
    • CoinCodex
    • Live Coin Watch
    • CoinCheckup
    • Messari
    • CoinPaprika
    • Arkham Intelligence
  • DeFi Analytics and Tracking
    • DefiLlama
    • Dune Analytics
    • DeBank
    • Zapper
    • Token Terminal
    • DeepDAO
    • Revert Finance
    • L2BEAT
  • API's
    • What are APIs?
    • How APIs Work
    • Types of APIs
    • Real-World API Use Cases
    • Benefits of Using API's
    • Challenges and Considerations of using API's
  • Node Security
    • Physical Security
    • Network Security
    • System and Software Security
    • Access Control
    • Data Security
    • Monitoring and Logging
    • Backup and Disaster Recovery
    • Best Practices for Validator Nodes
    • Cloud Security
    • Incident Response and Recovery
  • Linux Bash
    • Bash 101
      • Getting Started with Bash
      • Navigating the File System
      • File Management Basics
      • Viewing and Editing Files
      • Managing Permissions
      • Working with Processes
      • Using Pipes and Redirection
      • Bash Scripting Basics
      • Essential Networking Commands
      • Installing Software with Package Managers
    • Advanced Linux for Validator Nodes
      • Advanced Bash Scripting for Node Automation and Maintenance
      • Monitoring and Logging Essentials
      • Networking and Security Best Practices
      • Backup and Disaster Recovery
  • Staking 101
    • Understand What Staking Is and How It Works
    • Choose a Blockchain Network to Stake On
    • Set Up a Compatible Wallet for Staking
    • Purchase or Transfer Funds for Staking
    • Choose a Staking Pool
    • Connect Your Wallet to a Staking Platform
    • Confirm and Stake Your Funds
    • Monitor Staking Rewards and Performance
    • Withdraw or Re-Stake Rewards
  • Optimizing Your Infrastructure Choices
    • Infrastructure Comparison: VPS vs. Bare Metal
Powered by GitBook
On this page
  • Validator Performance Optimizer Script
  • Prerequisites
  • Installation & Setup
  • Script: Validator Performance Optimizer
  • Running the Script
  • Future Enhancements

Was this helpful?

  1. Blockchains
  2. Story Protocol

Performance Optimizer Script

The Validator Performance Optimizer Script is a tool developed by Forest Staking to monitor your Story Protocol validator node's performance and ensure its efficiency.

Validator Performance Optimizer Script

Overview

The Validator Performance Optimizer Script helps monitor the key metrics of your Story Protocol validator, such as CPU usage, memory, and missed blocks. It provides recommendations or takes automatic actions to optimize performance.

Key Features

  • CPU & Memory Monitoring: Automatically tracks CPU and memory usage.

  • Missed Blocks Detection: Queries Prometheus for missed blocks.

  • Threshold-Based Alerts: Suggests optimizations when defined thresholds are exceeded.

  • Auto-Restart: Automatically restarts the validator if critical resource limits are reached.

  • Customizable: You can adjust thresholds to suit your requirements.


Prerequisites

Before running the script, ensure the following:

  • Prometheus is set up and monitoring your validator's metrics.

  • Your server can run Python 3.

  • Your validator node is managed by systemd (or adjust the restart command as needed).


Installation & Setup

Step 1: Install Dependencies

Ensure Python 3 is installed on your machine. Then, install the required Python package:

bashCopy codepip install requests

Step 2: Prometheus Setup

Ensure you have Prometheus installed and scraping the following metrics from your Story Protocol node:

  • CPU usage

  • Memory usage

  • Missed blocks (storyprotocol_missed_blocks)

Make sure Prometheus is set up as per Forest Staking's Prometheus Setup Guide, with an API endpoint to query metrics.


Script: Validator Performance Optimizer

Copy and paste the following Python script onto your server.

pythonCopy codeimport os
import subprocess
import requests

# Prometheus API endpoint for querying validator metrics
PROMETHEUS_URL = 'http://localhost:9090/api/v1/query'

# Thresholds for optimizations
CPU_THRESHOLD = 80  # CPU usage percentage threshold
MEMORY_THRESHOLD = 70  # Memory usage percentage threshold
MISSED_BLOCKS_THRESHOLD = 10  # Missed blocks threshold

# Function to get metrics from Prometheus
def get_prometheus_metric(query):
    try:
        response = requests.get(f'{PROMETHEUS_URL}?query={query}')
        results = response.json()['data']['result']
        return float(results[0]['value'][1]) if results else None
    except Exception as e:
        print(f"Error fetching Prometheus metrics: {e}")
        return None

# Function to get CPU usage from system
def get_cpu_usage():
    try:
        cpu_usage = subprocess.check_output("top -bn1 | grep 'Cpu(s)' | awk '{print $2}'", shell=True)
        return float(cpu_usage)
    except Exception as e:
        print(f"Error fetching CPU usage: {e}")
        return None

# Function to get memory usage from system
def get_memory_usage():
    try:
        mem_info = subprocess.check_output("free -m", shell=True).decode('utf-8').splitlines()[1].split()
        total_mem = int(mem_info[1])
        used_mem = int(mem_info[2])
        return (used_mem / total_mem) * 100  # Return memory usage percentage
    except Exception as e:
        print(f"Error fetching memory usage: {e}")
        return None

# Function to check missed blocks from Prometheus
def check_missed_blocks():
    return get_prometheus_metric('storyprotocol_missed_blocks')

# Function to optimize validator performance
def optimize_performance():
    cpu_usage = get_cpu_usage()
    memory_usage = get_memory_usage()
    missed_blocks = check_missed_blocks()

    # Suggest optimizations or make adjustments based on thresholds
    if cpu_usage and cpu_usage > CPU_THRESHOLD:
        print(f"High CPU usage detected: {cpu_usage}%")
        print("Recommendation: Increase CPU resources or optimize node configuration.")
    
    if memory_usage and memory_usage > MEMORY_THRESHOLD:
        print(f"High memory usage detected: {memory_usage}%")
        print("Recommendation: Increase RAM or optimize node memory usage.")

    if missed_blocks and missed_blocks > MISSED_BLOCKS_THRESHOLD:
        print(f"Missed blocks detected: {missed_blocks} blocks missed.")
        print("Recommendation: Investigate node performance or network connection.")

# Optional: Function to automatically restart the validator node if critical thresholds are breached
def restart_validator():
    print("Restarting validator due to critical performance issues...")
    os.system("sudo systemctl restart storyprotocold")

# Run performance optimization and make adjustments if needed
def main():
    print("Starting validator performance optimizer...")
    
    cpu_usage = get_cpu_usage()
    memory_usage = get_memory_usage()
    missed_blocks = check_missed_blocks()

    print(f"Current CPU Usage: {cpu_usage}%")
    print(f"Current Memory Usage: {memory_usage}%")
    print(f"Missed Blocks: {missed_blocks}")

    optimize_performance()

    # Restart validator if CPU or memory usage is critically high
    if (cpu_usage and cpu_usage > 90) or (memory_usage and memory_usage > 90):
        restart_validator()

if __name__ == "__main__":
    main()

Step 3: Configure the Script

You can adjust the following parameters based on your preferences:

  • CPU_THRESHOLD: Maximum CPU usage percentage before triggering an alert.

  • MEMORY_THRESHOLD: Maximum memory usage percentage before triggering an alert.

  • MISSED_BLOCKS_THRESHOLD: Number of missed blocks that will trigger an alert.


Running the Script

To run the performance optimizer script:

  1. Ensure you are in the directory where the script is saved.

  2. Run the script using Python 3:

bashCopy codepython3 validator_optimizer.py

The script will monitor your validator’s performance, suggest optimizations, and restart the validator if needed.


Future Enhancements

  • Alerts & Notifications: Integrate with Telegram, Discord, or PagerDuty for real-time notifications.

  • Performance Dashboard: Combine with Prometheus and Grafana for a visual performance dashboard.

  • Expanded Metrics: Add monitoring for disk usage, network traffic, staking rewards, and more.


This script will be continuously improved by Forest Staking to ensure optimal performance for validators operating on Story Protocol and other networks.

PreviousRPC Load BalancerNextLive Peers

Last updated 6 months ago

Was this helpful?