added new gemini creations
This commit is contained in:
Binary file not shown.
@@ -0,0 +1,109 @@
|
||||
import os
|
||||
import requests
|
||||
import json
|
||||
import csv
|
||||
import sys
|
||||
import argparse
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
except ImportError:
|
||||
print("Warning: python-dotenv not installed. Environment variables from .env file will not be loaded.", file=sys.stderr)
|
||||
|
||||
def get_headers():
|
||||
TRUENAS_API_KEY = os.getenv("TRUENAS_API_KEY")
|
||||
if not TRUENAS_API_KEY:
|
||||
raise ValueError("TRUENAS_API_KEY not found in environment variables.")
|
||||
return {
|
||||
"Authorization": f"Bearer {TRUENAS_API_KEY}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def fetch_pool_data():
|
||||
TRUENAS_API_URL = os.getenv("TRUENAS_API_URL")
|
||||
if not TRUENAS_API_URL:
|
||||
raise ValueError("TRUENAS_API_URL not found in environment variables.")
|
||||
|
||||
url = f"{TRUENAS_API_URL}/pool"
|
||||
try:
|
||||
response = requests.get(url, headers=get_headers(), timeout=10)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except requests.exceptions.RequestException as e:
|
||||
print(f"Error connecting to TrueNAS API: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
def process_pool_data(raw_data):
|
||||
processed_data = []
|
||||
for pool in raw_data:
|
||||
# Extract relevant metrics.
|
||||
# Note: TrueNAS API structure varies slightly, but usually:
|
||||
# 'name' is the pool name.
|
||||
# 'size' is total size in bytes.
|
||||
# 'allocated' is used size in bytes.
|
||||
# 'free' is free size in bytes.
|
||||
# Values might be nested differently depending on version,
|
||||
# but typically top-level or under 'scan' or similar.
|
||||
# We will assume standard keys based on typical v2.0 response.
|
||||
|
||||
# Adjusting based on common TrueNAS Scale API response for /pool
|
||||
# It often returns a list where each item has 'name' and 'scan' or standard ZFS properties.
|
||||
# Let's try to find the size properties. often found in 'used', 'available', 'size' (top level for ZFS properties usually don't exist directly, usually inside 'properties' or computed).
|
||||
# Actually, /pool response usually has 'name' and 'size' (total), 'allocated' (used), 'free' (available).
|
||||
|
||||
# Fallback/Safe extraction
|
||||
name = pool.get('name', 'Unknown')
|
||||
|
||||
# Some versions use 'size', 'allocated', 'free' directly
|
||||
total_size = pool.get('size', 0)
|
||||
used_size = pool.get('allocated', 0)
|
||||
free_size = pool.get('free', 0)
|
||||
|
||||
# Calculate percentage if not present (sometimes it is not)
|
||||
if total_size > 0:
|
||||
percent_used = (used_size / total_size) * 100
|
||||
else:
|
||||
percent_used = 0.0
|
||||
|
||||
processed_data.append({
|
||||
"pool_name": name,
|
||||
"total_size_bytes": total_size,
|
||||
"used_size_bytes": used_size,
|
||||
"free_size_bytes": free_size,
|
||||
"percent_used": round(percent_used, 2)
|
||||
})
|
||||
return processed_data
|
||||
|
||||
def format_output(data, output_format):
|
||||
if output_format == 'json':
|
||||
print(json.dumps(data, indent=4))
|
||||
elif output_format == 'csv':
|
||||
writer = csv.DictWriter(sys.stdout, fieldnames=["pool_name", "total_size_bytes", "used_size_bytes", "free_size_bytes", "percent_used"])
|
||||
writer.writeheader()
|
||||
writer.writerows(data)
|
||||
else:
|
||||
# Default text/human-readable
|
||||
print(f"{'Pool Name':<20} {'Total Size':<15} {'Used Size':<15} {'Free Size':<15} {'% Used':<10}")
|
||||
print("-" * 75)
|
||||
for item in data:
|
||||
print(f"{item['pool_name']:<20} {item['total_size_bytes']:<15} {item['used_size_bytes']:<15} {item['free_size_bytes']:<15} {item['percent_used']:<10}%")
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="TrueNAS Scale Storage Tracker")
|
||||
parser.add_argument("--format", choices=['json', 'csv', 'text'], default='text', help="Output format (json, csv, text)")
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
raw_data = fetch_pool_data()
|
||||
processed_data = process_pool_data(raw_data)
|
||||
format_output(processed_data, args.format)
|
||||
except ValueError as e:
|
||||
print(f"Configuration Error: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
except Exception as e:
|
||||
print(f"An unexpected error occurred: {e}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user