upload_log.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/env python3
  2. """上传日志到自己S3空间(华为OBS官方SDK): user/<userid>/log/<YYYYMMDD>/<HHMM>.json"""
  3. import json, os, sys, datetime
  4. WORK = os.path.expanduser("~/.fmode-harness-agent")
  5. def upload():
  6. ident_path = "/opt/data/fmode-identity.json"
  7. if not os.path.exists(ident_path):
  8. ident_path = os.path.join(WORK, "fmode-identity.json")
  9. ident = json.load(open(ident_path))
  10. userid = ident["userid"]
  11. log_file = os.path.join(WORK, "tmp", "agent-log.json")
  12. if not os.path.exists(log_file):
  13. print("先跑 collect_metrics.py"); sys.exit(1)
  14. ak = os.environ.get("S3_AK") or os.environ.get("CLOUD_SDK_AK")
  15. sk = os.environ.get("S3_SK") or os.environ.get("CLOUD_SDK_SK")
  16. if not ak:
  17. print("缺少S3凭证"); sys.exit(1)
  18. from obs import ObsClient
  19. obs = ObsClient(access_key_id=ak, secret_access_key=sk,
  20. server="https://obs.cn-north-4.myhuaweicloud.com")
  21. now = datetime.datetime.now()
  22. key = f"user/{userid}/log/{now:%Y%m%d}/{now:%H%M}.json"
  23. r = obs.putObject("storage-s3-nkkj", key, content=open(log_file, "rb").read())
  24. if r.status < 300:
  25. print(f"uploaded: {key} (status {r.status})")
  26. else:
  27. print(f"upload FAILED: {r.status} {r.reason}"); sys.exit(1)
  28. # 清理30天前旧日志
  29. cutoff = (now - datetime.timedelta(days=30)).strftime("%Y%m%d")
  30. resp = obs.listObjects("storage-s3-nkkj", prefix=f"user/{userid}/log/")
  31. cleaned = 0
  32. if resp.status < 300 and resp.body.contents:
  33. for obj in resp.body.contents:
  34. day = obj.key.split("/")[3]
  35. if day < cutoff:
  36. obs.deleteObject("storage-s3-nkkj", obj.key)
  37. cleaned += 1
  38. if cleaned:
  39. print(f"cleaned {cleaned} old logs")
  40. if __name__ == "__main__":
  41. upload()