error: error executing template “{{.data.token | base64decode}}“: template: output:1:16: executing “

用老的生成token方式
kubectl -n kubernetes-dashboard get secret $(kubectl -n kubernetes-dashboard get sa/admin-user -o jsonpath="{.secrets[0].name}") -o go-template="{{.data.token | base64decode}}"
报错
error: error executing template "{{.data.token | base64decode}}": template: output:1:16: executing "

解决方案:

kubectl -n kubernetes-dashboard create token admin-user

兜兜转转找了好久问题

参考:
https://github.com/kubernetes/dashboard/issues/7081

import yaml import os import threading import time import requests import hashlib import json import base64 from typing import Dict, Any, Callable class ConfigLoader: """Load and manage configuration from YAML file""" def __init__(self, config_path: str = "D:\\sogood\\test\\pyTools\\monitor\\monitor_config.yaml"): self.config_path = config_path self.config = self._load_config() def _load_config(self) -> Dict[str, Any]: """Load configuration from YAML file""" if not os.path.exists(self.config_path): raise FileNotFoundError(f"Config file not found: {self.config_path}") with open(self.config_path, 'r') as f: try: return yaml.safe_load(f) except yaml.YAMLError as e: raise ValueError(f"Invalid YAML in config file: {e}") def get_polling_interval(self) -> int: """Get timer polling interval in seconds""" return self.config.get('polling_interval', 60) def get_failure_threshold(self) -> int: """Get API failure threshold count""" return self.config.get('failure_threshold', 3) def get_api_endpoint(self) -> str: """Get API endpoint URL""" return self.config['api_endpoint'] # Required, no default def get_alert_endpoint(self) -> str: """Get alert notification URL""" return self.config['alert_endpoint'] # Required, no default def get_fund_codes(self) -> str: """Get fund codes for monitoring""" return self.config['fund_codes'] # Required, no default class MonitorThread(threading.Thread): """Thread that runs monitoring task at fixed intervals""" def __init__(self, task_id: int, config: ConfigLoader, callback: Callable[[int, 'MonitorThread'], None]): super().__init__() self.task_id = task_id self.config = config self.callback = callback self._stop_event = threading.Event() self.failure_count = 0 def run(self): """Main thread loop""" while not self._stop_event.is_set(): try: self.callback(self.task_id, self) except Exception as e: print(f"Task {self.task_id} error: {e}") self.failure_count += 1 if self.failure_count >= self.config.get_failure_threshold(): self.trigger_alert() time.sleep(10) # Fixed 10 second interval def trigger_alert(self): """Send alert notification via zabbix_sender""" try: # Format current date as YYYYMMDD date_str = time.strftime("%Y%m%d") # Execute zabbix_sender command and capture output cmd = f"zabbix_sender -p \"10051\" -z 220.112.1.147 -s \"SOGOOD360\" -k sg.wind.api.{self.task_id} -o {date_str}-error" print(f"Executing: {cmd}") result = os.popen(cmd).read() print(f"Command output:\n{result}") print(f"Sent zabbix alert for task {self.task_id}") except Exception as e: print(f"Failed to send zabbix alert: {e}") def stop(self): """Signal thread to stop""" self._stop_event.set() def generate_sign(params: dict, token: str = "AqsZ7aWd4vPas9bt") -> str: """Generate sign by: 1) sort params 2) base64 encode 3) MD5 with token""" sorted_params = sorted(params.items()) param_str = "&".join(f"{k}={v}" for k, v in sorted_params) base64_str = base64.b64encode(param_str.encode()).decode() sign_str = base64_str + token return hashlib.md5(sign_str.encode()).hexdigest() def task1_monitor(thread: MonitorThread): """Task 1: Node API monitoring""" try: # Prepare request params params = { "act": "60630980", "params": json.dumps({"type": 3}), "time": "", "token": "", "ip": "", "user_code": "", "m_id": "" } params["sign"] = generate_sign(params) # Make API call config = ConfigLoader() response = requests.post( config.get_api_endpoint(), json=params, timeout=10 ) # Check response status if response.status_code != 200: raise ValueError(f"API returned {response.status_code}") data = response.json() print(f"data: {data}") # Check response structure if not data or data.get("code") != "0" or not data.get("data"): raise ValueError("Invalid response data") # Get current date in YYYY-MM-DD format today = time.strftime("%Y-%m-%d") # Check update date update_date = data["data"].get("date", "") if update_date != today: raise ValueError(f"Data not updated today (last update: {update_date})") # Reset failure count on success thread.failure_count = 0 except Exception as e: raise # Let MonitorThread handle the failure counting def task2_monitor(thread: MonitorThread): """Task 2: Stock performance monitoring""" try: # Prepare request params params = { "act": "60630960", "params": json.dumps({"stock_code":"NDX.GI"}) } params["sign"] = generate_sign(params) # Make API call config = ConfigLoader() response = requests.post( config.get_api_endpoint(), json=params, timeout=10 ) # Check response status if response.status_code != 200: raise ValueError(f"API returned {response.status_code}") data = response.json() print(f"data: {data}") # Check response structure if not data or data.get("code") != "0" or not data.get("data"): raise ValueError("Invalid response data") # Get current date in YYYY-MM-DD format today = time.strftime("%Y-%m-%d") # Check update time update_time = data["data"].get("update_time", "") if not update_time.startswith(today): raise ValueError(f"Stock data not updated today (last update: {update_time})") # Reset failure count on success thread.failure_count = 0 except Exception as e: raise # Let MonitorThread handle the failure counting def task3_monitor(thread: MonitorThread): """Task 3: Fund quota monitoring""" try: # Make API call config = ConfigLoader() # Prepare request params params = { "act": "60630961", "params": json.dumps({"m_id":"1","fund_codes":config.get_fund_codes()}), "m_id": "1" } params["sign"] = generate_sign(params) response = requests.post( config.get_api_endpoint(), json=params, timeout=10 ) # Check response status if response.status_code != 200: raise ValueError(f"API returned {response.status_code}") data = response.json() print(f"data3: {data}") # Check response structure if not data or data.get("code") != 0 or not data.get("data_list"): raise ValueError("Invalid response data") # Get current date in YYYY-MM-DD format today = time.strftime("%Y-%m-%d") # Check each fund's update time for fund in data["data_list"]: update_time = fund.get("update_time", "") if not update_time.startswith(today): raise ValueError(f"Fund {fund.get('fund_code')} not updated today") # Reset failure count on success thread.failure_count = 0 except Exception as e: print(f"Configuration error: {e}") def task4_monitor(thread: MonitorThread): """Task 4: Placeholder for fourth monitoring task""" try: # Prepare request params params = { "act": "60630932", "params": json.dumps({"fund_code":"160140","date":"","type":1}) } params["sign"] = generate_sign(params) # Make API call config = ConfigLoader() response = requests.post( config.get_api_endpoint(), json=params, timeout=10 ) # Check response if response.status_code != 200: raise ValueError(f"API returned {response.status_code}") data = response.json() print(f"data4: {data}") if not data: raise ValueError("Empty response data") # Reset failure count on success thread.failure_count = 0 except Exception as e: raise # Let MonitorThread handle the failure counting def on_timer(task_id: int, thread: MonitorThread): """Called by each monitor thread on its interval""" print(f"Task {task_id} executing at {time.strftime('%X')}") if task_id == 1: task1_monitor(thread) elif task_id == 2: task2_monitor(thread) elif task_id == 3: task3_monitor(thread) elif task_id == 4: task4_monitor(thread) if __name__ == "__main__": try: config = ConfigLoader() print("Starting 4 monitor threads...") # Create and start threads threads = [ MonitorThread(i, config, on_timer) for i in range(1, 5) # Task IDs 1-4 ] for t in threads: t.start() # Wait for Ctrl+C try: while True: time.sleep(config.get_polling_interval()) except KeyboardInterrupt: print("\nStopping threads...") for t in threads: t.stop() t.join() except Exception as e: print(f"Configuration error: {e}") 给上面的代码,每行加上注释。
07-01
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值