-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlambda_function.py
More file actions
1752 lines (1644 loc) · 89.8 KB
/
Copy pathlambda_function.py
File metadata and controls
1752 lines (1644 loc) · 89.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Bedrock 用量/成本估算看板 — 单 Lambda(HTML + JSON + 趋势数据)
路由(GET):
/ -> HTML 看板
/?format=json®ion=&start=&end= -> 各模型汇总(估算)
/?format=series&model=®ion=&start=&end= -> 单模型按天趋势(估算)
区域可填具体区(us-west-2…)或 "global"(扫所有已启用区域聚合)。
单价来源:Secrets Manager 密钥 bedrock-dashboard/prices(读不到则用内置默认)。
"""
import os
import json
import time
import traceback
import datetime as dt
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
import boto3
from botocore.config import Config
# 快速失败:慢区/无用量区不拖累 global 扫描
FAST = Config(connect_timeout=3, read_timeout=12, retries={"max_attempts": 2},
max_pool_connections=50)
LAMBDA_REGION = os.environ.get("AWS_REGION", "us-west-2")
PRICE_SECRET = os.environ.get("PRICE_SECRET", "bedrock-dashboard/prices")
ACCOUNTS_SECRET = os.environ.get("ACCOUNTS_SECRET", "bedrock-dashboard/accounts")
ALERTS_SECRET = os.environ.get("ALERTS_SECRET", "bedrock-dashboard/alerts")
# 运维深水区面板(错误监控/运行时灰区)默认关闭,精简部署;要开在 CFN 参数 EnableOpsPanels=true
ENABLE_OPS_PANELS = os.environ.get("ENABLE_OPS_PANELS", "").lower() in ("1", "true", "yes")
CACHE_BUCKET = os.environ.get("CACHE_BUCKET", "")
CACHE_KEY = "cache/global-7d.json"
CACHE_MAX_AGE_SEC = 8 * 3600 # 定时任务每6h刷一次,超8h视为过期
try:
DASH_VERSION = (Path(__file__).parent / "VERSION").read_text().strip()
except Exception:
DASH_VERSION = "dev"
def write_snapshot_cache():
"""告警定时任务顺手刷新 7 天 global 快照,页面秒开。"""
if not CACHE_BUCKET:
return False
end = dt.datetime.now(dt.UTC)
start = end - dt.timedelta(days=7)
data = build_data("global", start, end)
data["cached_at"] = end.strftime("%Y-%m-%d %H:%M")
boto3.client("s3", region_name=LAMBDA_REGION).put_object(
Bucket=CACHE_BUCKET, Key=CACHE_KEY,
Body=json.dumps(data).encode(), ContentType="application/json")
return True
def read_snapshot_cache():
if not CACHE_BUCKET:
return None
try:
s3 = boto3.client("s3", region_name=LAMBDA_REGION)
obj = s3.get_object(Bucket=CACHE_BUCKET, Key=CACHE_KEY)
age = (dt.datetime.now(dt.UTC) - obj["LastModified"]).total_seconds()
if age > CACHE_MAX_AGE_SEC:
return None
return json.loads(obj["Body"].read())
except Exception:
return None
ALERT_STATE_KEY = "cache/alert-state.json"
def read_alert_state():
"""读推送节流状态(上次成功推送时间)。桶不可用时返回空=不节流,宁多勿漏。"""
if not CACHE_BUCKET:
return {}
try:
s3 = boto3.client("s3", region_name=LAMBDA_REGION)
return json.loads(s3.get_object(Bucket=CACHE_BUCKET, Key=ALERT_STATE_KEY)["Body"].read())
except Exception:
return {}
def write_alert_state(state):
if not CACHE_BUCKET:
return False
try:
boto3.client("s3", region_name=LAMBDA_REGION).put_object(
Bucket=CACHE_BUCKET, Key=ALERT_STATE_KEY,
Body=json.dumps(state).encode(), ContentType="application/json")
return True
except Exception as e:
print(f"alert state write failed: {e}")
return False
EDIT_KEY = os.environ.get("EDIT_KEY", "")
PRICE_TTL = 60 # 单价缓存秒数
DEFAULT_SESS = boto3.Session() # 中心账号默认会话
METRICS = {"InputTokenCount": "in", "OutputTokenCount": "out",
"CacheReadInputTokenCount": "cache_read", "CacheWriteInputTokenCount": "cache_write"}
DEFAULT_PRICES = { # 内置兜底 USD / 1M tokens
"opus": {"in": 5, "out": 25, "cache_read": 0.5, "cache_write": 7.0},
"sonnet": {"in": 3, "out": 15, "cache_read": 0.3, "cache_write": 3.75},
"haiku": {"in": 1, "out": 5, "cache_read": 0.1, "cache_write": 1.25},
"fable": {"in": 10, "out": 50, "cache_read": 1.0, "cache_write": 12.5},
"nova": {"in": 0.3, "out": 1.2, "cache_read": 0.03, "cache_write": 0.375},
}
_prices = None # (table, source)
_prices_ts = 0
_profile_cache = {}
def load_prices():
"""从 Secrets Manager 读单价(带 TTL 缓存);失败回退内置默认。返回 (table, source)。"""
global _prices, _prices_ts
if _prices is not None and time.time() - _prices_ts < PRICE_TTL:
return _prices
try:
sm = boto3.client("secretsmanager", region_name=LAMBDA_REGION)
table = json.loads(sm.get_secret_value(SecretId=PRICE_SECRET)["SecretString"])
_prices = (table, "secret")
except Exception:
_prices = (DEFAULT_PRICES, "default")
_prices_ts = time.time()
return _prices
def validate_prices(obj):
"""校验并归一化前端提交的单价表。"""
if not isinstance(obj, dict) or not obj:
raise ValueError("单价表必须为非空对象")
fields = ("in", "out", "cache_read", "cache_write")
clean = {}
for k, v in obj.items():
if not isinstance(k, str) or not k.strip():
raise ValueError("存在非法的模型键")
if not isinstance(v, dict):
raise ValueError(f"'{k}' 的值必须为对象")
row = {}
for f in fields:
row[f] = float(v.get(f, 0) or 0)
if row[f] < 0:
raise ValueError(f"'{k}.{f}' 不能为负")
clean[k.strip()] = row
return clean
def save_prices(obj):
"""校验后写入 Secrets Manager,并刷新缓存。"""
clean = validate_prices(obj)
sm = boto3.client("secretsmanager", region_name=LAMBDA_REGION)
sm.put_secret_value(SecretId=PRICE_SECRET, SecretString=json.dumps(clean))
global _prices, _prices_ts
_prices, _prices_ts = (clean, "secret"), time.time()
return clean
def load_accounts():
"""读账号注册表(JSON 列表)。读不到返回空。"""
try:
sm = DEFAULT_SESS.client("secretsmanager", region_name=LAMBDA_REGION)
return json.loads(sm.get_secret_value(SecretId=ACCOUNTS_SECRET)["SecretString"])
except Exception:
return []
def save_accounts(lst):
"""校验并写入账号注册表。"""
if not isinstance(lst, list):
raise ValueError("accounts 必须是列表")
clean = []
for a in lst:
if not a.get("accountId") or not a.get("roleArn"):
raise ValueError("每个账号需含 accountId 和 roleArn")
clean.append({"accountId": str(a["accountId"]).strip(),
"label": (a.get("label") or "")[:60],
"roleArn": a["roleArn"].strip(),
"externalId": (a.get("externalId") or "").strip(),
"regions": (a.get("regions") or "us-west-2").strip()})
sm = DEFAULT_SESS.client("secretsmanager", region_name=LAMBDA_REGION)
sm.put_secret_value(SecretId=ACCOUNTS_SECRET, SecretString=json.dumps(clean))
return clean
_central = None
def central_role_arn():
"""推导中心 Lambda 角色 ARN(用于生成各账号接入命令)。"""
global _central
if _central is not None:
return _central
try:
arn = DEFAULT_SESS.client("sts").get_caller_identity()["Arn"]
acct = arn.split(":")[4]
role = arn.split("assumed-role/")[1].split("/")[0]
_central = f"arn:aws:iam::{acct}:role/{role}"
except Exception:
_central = ""
return _central
def session_for(account):
"""空 account = 中心账号本地会话;否则 assume 该账号的 BedrockUsageReader。"""
if not account:
return DEFAULT_SESS
a = next((x for x in load_accounts() if x.get("accountId") == account), None)
if not a:
raise ValueError("账号未注册: " + account)
kw = {"RoleArn": a["roleArn"], "RoleSessionName": "bedrock-dashboard"}
if a.get("externalId"):
kw["ExternalId"] = a["externalId"]
cr = DEFAULT_SESS.client("sts").assume_role(**kw)["Credentials"]
return boto3.Session(aws_access_key_id=cr["AccessKeyId"],
aws_secret_access_key=cr["SecretAccessKey"],
aws_session_token=cr["SessionToken"])
def fetch_price_list(region):
"""调 AWS Price List API 拉取 Bedrock 各模型 on-demand 单价(USD/1M tokens)。"""
pricing = boto3.client("pricing", region_name="us-east-1") # Price List API 端点
filters = [{"Type": "TERM_MATCH", "Field": "servicecode", "Value": "AmazonBedrock"},
{"Type": "TERM_MATCH", "Field": "regionCode", "Value": region}]
out = {}
paginator = pricing.get_paginator("get_products")
for page in paginator.paginate(ServiceCode="AmazonBedrock", Filters=filters):
for item in page["PriceList"]:
p = json.loads(item)
attr = p.get("product", {}).get("attributes", {})
model = attr.get("model")
itype = (attr.get("inferenceType") or "").lower()
if not model or not itype:
continue
if "cache" in itype and "read" in itype:
field = "cache_read"
elif "cache" in itype and "write" in itype:
field = "cache_write"
elif "input" in itype:
field = "in"
elif "output" in itype:
field = "out"
else:
continue
# 取 OnDemand 第一个价格维度
for term in p.get("terms", {}).get("OnDemand", {}).values():
for dim in term.get("priceDimensions", {}).values():
usd = float(dim.get("pricePerUnit", {}).get("USD", 0) or 0)
unit = dim.get("unit", "")
per_m = usd * 1000 if "1K" in unit else usd # 1K tokens -> 1M
out.setdefault(model, {"in": 0, "out": 0, "cache_read": 0, "cache_write": 0})
out[model][field] = round(per_m, 4)
break
break
return out
def resolve_price(model_id, table):
"""完整ID精确 -> 关键字 匹配。返回 (price, matched_key) 或 (None, None)。"""
if model_id in table:
return table[model_id], model_id
mid = model_id.lower()
for kw, price in table.items():
if kw.lower() in mid:
return price, kw
return None, None
def profile_info(regions, model_id, sess=None):
"""反查 inference profile。返回 (profile名, 底层模型id, arn) 或 (None, None, None)。"""
sess = sess or DEFAULT_SESS
if model_id in _profile_cache:
return _profile_cache[model_id]
pid = model_id.split("/")[-1] if model_id.startswith("arn:") else model_id
# 优先试常用区,避免 global 视图按字母序把几十个区都试一遍拖死 Lambda
preferred = [r for r in ("us-west-2", "us-east-1", "us-east-2", "eu-west-1") if r in regions]
ordered = preferred + [r for r in regions if r not in preferred]
info = (None, None, None)
for r in ordered:
try:
resp = sess.client("bedrock", region_name=r, config=FAST).get_inference_profile(
inferenceProfileIdentifier=pid)
models = resp.get("models", [])
fm = models[0]["modelArn"].split("/")[-1] if models else None
info = (resp.get("inferenceProfileName"), fm, resp.get("inferenceProfileArn"))
break
except Exception:
continue
_profile_cache[model_id] = info
return info
def underlying_model(regions, model_id, sess=None):
return profile_info(regions, model_id, sess)[1]
PROFILE_ID_PREFIXES = ("us.", "eu.", "apac.", "jp.", "au.", "ca.", "sa.", "global.")
def short_model(mid):
return mid.split("anthropic.")[-1]
def display_model(mid, regions, sess=None):
"""直调模型显示模型名;系统跨区 profile 显示完整 id;
application inference profile(ARN 或裸 id, CloudWatch 记的是裸 id)反查出
profile 名和底层模型, 显示 '名字/id (底层模型名)'。"""
if not mid.startswith("arn:"):
if mid.startswith(PROFILE_ID_PREFIXES):
return mid # 系统跨区 profile:id 本身已含模型名,免 API 反查
if "." in mid:
return short_model(mid) # 直调 foundation model(vendor.model 必含点号)
# application inference profile:ARN 或无点号裸 id(如 ej8uoudeuci1)
pid = mid.split("/")[-1] if mid.startswith("arn:") else mid
name, fm, _ = profile_info(regions, mid, sess)
label = name or pid
if fm:
return f"{label} ({short_model(fm)})"
return label
def price_for(model_id, regions, sess=None):
"""返回 (price_dict_or_None, source_label)。含应用配置反查。"""
table, psource = load_prices()
price, key = resolve_price(model_id, table)
if price:
return price, f"{psource}:{key}"
fm = underlying_model(regions, model_id, sess)
if fm:
price, key = resolve_price(fm, table)
if price:
return price, f"{psource}:{key} (profile→{fm.split('.')[-1]})"
return None, "UNKNOWN"
def is_taggable_profile(mid):
"""只有 application inference profile 能打成本分配标签(可分账)。
CloudWatch ModelId 三形态: 直连fm id(含点号) / 系统跨区 profile(区域前缀,含点号) / app profile 裸id或ARN。"""
if mid.startswith("arn:"):
return ":application-inference-profile/" in mid
return "." not in mid # 裸 app profile id 无点号
def load_alerts():
sm = boto3.client("secretsmanager", region_name=LAMBDA_REGION)
try:
cfg = json.loads(sm.get_secret_value(SecretId=ALERTS_SECRET)["SecretString"])
except Exception as e:
# secret 读不到时告警配置整体为空(不发且此前无日志),这里必须留痕
print(f"[load_alerts] read secret FAILED: {e!r}")
cfg = {}
return {
"webhook": str(cfg.get("webhook", "") or ""),
"sign_secret": str(cfg.get("sign_secret", "") or ""),
"window_hours": int(cfg.get("window_hours", 6) or 6),
"region": str(cfg.get("region", "global") or "global"),
"enabled": bool(cfg.get("enabled", False)),
"ignore_list": [str(x).strip() for x in (cfg.get("ignore_list") or []) if str(x).strip()][:100],
}
def save_alerts(cfg):
clean = {
"webhook": str(cfg.get("webhook", "") or "").strip(),
"sign_secret": str(cfg.get("sign_secret", "") or "").strip(),
"window_hours": max(1, min(48, int(cfg.get("window_hours", 6) or 6))),
"region": str(cfg.get("region", "global") or "global").strip() or "global",
"enabled": bool(cfg.get("enabled", False)),
"ignore_list": [str(x).strip() for x in (cfg.get("ignore_list") or []) if str(x).strip()][:100],
}
if clean["webhook"] and not clean["webhook"].startswith("https://"):
raise ValueError("webhook 必须是 https URL")
sm = boto3.client("secretsmanager", region_name=LAMBDA_REGION)
sm.put_secret_value(SecretId=ALERTS_SECRET, SecretString=json.dumps(clean))
return clean
def dingtalk_send(webhook, sign_secret, title, text):
import base64
import hashlib
import hmac
import time as _t
import urllib.parse
import urllib.request
url = webhook
if sign_secret:
ts = str(round(_t.time() * 1000))
digest = hmac.new(sign_secret.encode(), f"{ts}\n{sign_secret}".encode(), hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(digest).decode())
url = f"{url}{'&' if '?' in url else '?'}timestamp={ts}&sign={sign}"
payload = {"msgtype": "markdown", "markdown": {"title": title, "text": text}}
req = urllib.request.Request(url, data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json"})
return json.loads(urllib.request.urlopen(req, timeout=10).read().decode())
def _is_ignored(model_id, patterns):
"""忽略清单匹配: 精确 id, 或前缀通配(条目以 * 结尾, 如 global.*)。"""
for p in patterns:
if p.endswith("*"):
if model_id.startswith(p[:-1]):
return True
elif model_id == p:
return True
return False
def run_alert_check(cfg=None, force_send=False):
"""扫描窗口内非 app-inference-profile 用量(不可分账),命中则推钉钉。"""
cfg = cfg or load_alerts()
hours = max(1, min(48, int(cfg.get("window_hours", 6))))
print(f"[alert_check] start: region={cfg.get('region', 'global')}, window={hours}h, "
f"enabled={bool(cfg.get('enabled'))}, has_webhook={bool(cfg.get('webhook'))}, "
f"has_secret={bool(cfg.get('sign_secret'))}, force_send={force_send}")
end = dt.datetime.now(dt.UTC)
start = end - dt.timedelta(hours=hours)
data = build_data(cfg.get("region", "global"), start, end)
raw_bad = [r for r in data["rows"] if not is_taggable_profile(r["id"])]
ignore = cfg.get("ignore_list") or []
bad = [r for r in raw_bad if not _is_ignored(r["id"], ignore)]
ignored_count = len(raw_bad) - len(bad)
total_bad = round(sum(r["cost"] for r in bad), 2)
# 推送节流: 同一窗口只推一次(按 window_hours 对齐)。EventBridge 扫描频率照旧
# (定时任务还负责刷快照), 只是重叠窗口不再重复推送。0.9 容差防触发时刻抖动错过整槽。
state = read_alert_state()
since_last = end.timestamp() - float(state.get("last_sent_epoch", 0) or 0)
throttled = (not force_send) and since_last < hours * 3600 * 0.9
result = {"checked": True, "window_hours": hours, "region": cfg.get("region", "global"),
"start": start.strftime("%Y-%m-%d %H:%M"), "end": end.strftime("%Y-%m-%d %H:%M"),
"violations": bad, "violation_cost": total_bad,
"ignored_count": ignored_count, "throttled": throttled,
"enabled": cfg.get("enabled", False), "sent": False, "send_error": ""}
# 无发现也推巡检报告(每窗口一条心跳,链路通断一目了然);节流对两种消息同样生效
should_send = bool(cfg.get("webhook")) and (cfg.get("enabled") or force_send) and not throttled
if force_send and cfg.get("webhook"):
should_send = True # 手动测试不受节流限制,便于验证 webhook 通不通
# 未发送时把原因打出来(否则"没报错日志"其实是静默跳过)
if not should_send:
reasons = []
if not cfg.get("webhook"):
reasons.append("webhook_empty")
if not (cfg.get("enabled") or force_send):
reasons.append("disabled(enabled=false)")
if throttled:
reasons.append(f"throttled(since_last={int(since_last)}s < {int(hours * 3600 * 0.9)}s)")
print(f"[dingtalk] SKIP send: {', '.join(reasons) or 'unknown'} "
f"(force_send={force_send}, has_secret={bool(cfg.get('sign_secret'))})")
if should_send:
def _tok(n):
if n >= 1_000_000:
return f"{n / 1e6:.1f}M"
if n >= 1_000:
return f"{n / 1e3:.1f}K"
return str(n)
def _label(name):
for p in ("global.", "us.", "eu.", "apac.", "jp.", "au.", "ca.", "sa."):
if name.startswith(p):
return name[len(p):].replace("anthropic.", ""), f"{p[:-1]} 跨区 profile"
return name.replace("anthropic.", ""), "直连模型 ID"
blocks = [f"## {'🚨 Bedrock 无标签用量告警' if bad else '✅ Bedrock 用量巡检'}",
f"**近 {hours} 小时**({result['start']} – {result['end']} UTC · {result['region']})"]
if bad:
blocks.append(f"共 **{len(bad)}** 个模型未走 app inference profile,"
f"**≈ ${total_bad}** 无法按标签归属:")
items = []
for i, r in enumerate(bad[:10], 1):
name, kind = _label(r["model"])
items.append(f"**{i}. {name}** — **${r['cost']}**\n"
f" {kind} · in {_tok(r['in'])} · out {_tok(r['out'])}")
if len(bad) > 10:
items.append(f"…等共 {len(bad)} 个模型")
blocks.append("\n\n".join(items))
blocks.append("> 💡 为每个应用创建 **application inference profile**,"
"调用时改用其 ARN,用量与费用即可按标签归属。")
else:
blocks.append("当前窗口内未发现无标签用量,全部调用均带标签可归属。"
if not force_send else "✅ 测试消息:当前窗口内未发现无标签用量。")
if ignored_count:
blocks.append(f"_已按忽略清单跳过 {ignored_count} 个模型_")
print(f"[dingtalk] sending: has_secret={bool(cfg.get('sign_secret'))}, "
f"violations={len(bad)}, force_send={force_send}")
try:
resp = dingtalk_send(cfg["webhook"], cfg.get("sign_secret", ""),
"Bedrock 无标签用量告警" if bad else "Bedrock 用量巡检",
"\n\n".join(blocks))
if resp.get("errcode") == 0:
result["sent"] = True
print("[dingtalk] OK errcode=0")
if not force_send:
# 心跳/告警都计入节流窗口;手动测试不占槽,避免测完把定时推送挤掉
write_alert_state({"last_sent_epoch": end.timestamp(),
"last_sent": end.strftime("%Y-%m-%d %H:%M")})
else:
result["send_error"] = f"dingtalk errcode={resp.get('errcode')} {resp.get('errmsg', '')}"
# 钉钉业务失败: HTTP 200 但 errcode!=0(如 310000 加签/关键词错配),强制落日志
print(f"[dingtalk] FAIL {result['send_error']} | resp={json.dumps(resp, ensure_ascii=False)}")
except Exception as e:
result["send_error"] = str(e)[:300]
# 网络/超时/URL/JSON 解析等异常,原本只塞进返回值不打日志
print(f"[dingtalk] EXCEPTION {type(e).__name__}: {e}")
traceback.print_exc()
return result
def regions_for(region):
if region in ("global", "all"):
ec2 = boto3.client("ec2", region_name=LAMBDA_REGION)
rs = ec2.describe_regions(Filters=[
{"Name": "opt-in-status", "Values": ["opt-in-not-required", "opted-in"]}])
return sorted(r["RegionName"] for r in rs["Regions"])
return [region]
def discover_models(cw):
models = set()
for page in cw.get_paginator("list_metrics").paginate(
Namespace="AWS/Bedrock", MetricName="InputTokenCount"):
for m in page["Metrics"]:
dims = {d["Name"]: d["Value"] for d in m["Dimensions"]}
if set(dims) == {"ModelId"}:
models.add(dims["ModelId"])
return sorted(models)
def _queries(model_id, period):
ids = {f"m{i}": key for i, key in enumerate(METRICS.values())}
q = [{"Id": f"m{i}", "MetricStat": {
"Metric": {"Namespace": "AWS/Bedrock", "MetricName": name,
"Dimensions": [{"Name": "ModelId", "Value": model_id}]},
"Period": period, "Stat": "Sum"}} for i, name in enumerate(METRICS)]
return q, ids
def get_tokens(cw, model_id, start, end):
q, ids = _queries(model_id, 3600) # 按小时分桶求和,稳健
tokens = dict.fromkeys(METRICS.values(), 0.0)
for page in cw.get_paginator("get_metric_data").paginate(
MetricDataQueries=q, StartTime=start, EndTime=end):
for r in page["MetricDataResults"]:
tokens[ids[r["Id"]]] += sum(r["Values"])
return tokens
def get_series(cw, model_id, start, end):
"""返回 {date(YYYY-MM-DD): {in,out,cache_read,cache_write}} 按天。"""
q, ids = _queries(model_id, 86400)
days = {}
for page in cw.get_paginator("get_metric_data").paginate(
MetricDataQueries=q, StartTime=start, EndTime=end):
for r in page["MetricDataResults"]:
key = ids[r["Id"]]
for ts, v in zip(r["Timestamps"], r["Values"]):
d = ts.strftime("%Y-%m-%d")
days.setdefault(d, dict.fromkeys(METRICS.values(), 0.0))[key] += v
return days
def region_tokens(region, start, end, sess=None):
"""单区域:发现所有模型 + 一次批量 get_metric_data 取齐所有指标。返回 {mid: tokens}。"""
sess = sess or DEFAULT_SESS
cw = sess.client("cloudwatch", region_name=region, config=FAST)
mids = discover_models(cw)
if not mids:
return {}
keys = list(METRICS.items()) # [(metricName, field), ...]
qlist, idmap = [], {}
for mi, mid in enumerate(mids):
for ki, (name, field) in enumerate(keys):
qid = f"q{mi}_{ki}"
idmap[qid] = (mid, field)
qlist.append({"Id": qid, "MetricStat": {
"Metric": {"Namespace": "AWS/Bedrock", "MetricName": name,
"Dimensions": [{"Name": "ModelId", "Value": mid}]},
"Period": 86400, "Stat": "Sum"}}) # 按 UTC 天分桶(对齐账单 + 数据量小)
agg = {mid: dict.fromkeys(METRICS.values(), 0.0) for mid in mids}
for i in range(0, len(qlist), 500): # GetMetricData 每次最多 500 个查询
chunk = qlist[i:i + 500]
for page in cw.get_paginator("get_metric_data").paginate(
MetricDataQueries=chunk, StartTime=start, EndTime=end):
for r in page["MetricDataResults"]:
mid, field = idmap[r["Id"]]
agg[mid][field] += sum(r["Values"])
return {mid: t for mid, t in agg.items() if sum(t.values())}
def build_data(region, start, end, sess=None):
t0 = time.monotonic()
regions = regions_for(region)
failed = []
agg = {}
with ThreadPoolExecutor(max_workers=min(18, len(regions))) as ex:
futs = {ex.submit(region_tokens, r, start, end, sess): r for r in regions}
for f in as_completed(futs):
try:
res = f.result()
except Exception as e:
# 单区失败原本静默跳过,导致数据缺块无迹可查
failed.append(futs[f])
print(f"[build_data] region {futs[f]} FAILED: {e!r}")
continue
for mid, t in res.items():
a = agg.setdefault(mid, dict.fromkeys(METRICS.values(), 0.0))
for k in METRICS.values():
a[k] += t[k]
rows, total = [], 0.0
for mid, t in agg.items():
price, src = price_for(mid, regions, sess)
cost = sum(t[k] / 1e6 * price[k] for k in METRICS.values()) if price else 0.0
total += cost
taggable = is_taggable_profile(mid)
arn = ""
kind = "模型 ID"
if taggable:
arn = profile_info(regions, mid, sess)[2] or (mid if mid.startswith("arn:") else "")
kind = "应用推理 profile"
elif mid.startswith(PROFILE_ID_PREFIXES):
kind = "系统跨区 profile"
rows.append({"id": mid, "model": display_model(mid, regions, sess),
"kind": kind, "arn": arn, "taggable": taggable,
"in": int(t["in"]), "out": int(t["out"]),
"cache_read": int(t["cache_read"]), "cache_write": int(t["cache_write"]),
"cost": round(cost, 2), "price": src})
rows.sort(key=lambda x: x["cost"], reverse=True)
print(f"[build_data] {region}: {len(regions)} regions in {time.monotonic() - t0:.1f}s, "
f"{len(rows)} models{', FAILED: ' + ','.join(failed) if failed else ''}")
_, psource = load_prices()
return {"region": region, "days": round((end - start).total_seconds() / 86400, 1),
"start": start.strftime("%Y-%m-%d %H:%M"), "end": end.strftime("%Y-%m-%d %H:%M"),
"rows": rows, "total": round(total, 2), "estimate": True, "price_source": psource}
def build_series(region, model_id, start, end, sess=None):
regions = regions_for(region)
sess = sess or DEFAULT_SESS
def one(r):
try:
return get_series(sess.client("cloudwatch", region_name=r, config=FAST), model_id, start, end)
except Exception:
return {}
merged = {}
with ThreadPoolExecutor(max_workers=min(18, len(regions))) as ex:
for s in ex.map(one, regions):
for d, t in s.items():
m = merged.setdefault(d, dict.fromkeys(METRICS.values(), 0.0))
for k in METRICS.values():
m[k] += t[k]
price, src = price_for(model_id, regions, sess)
points = []
for d in sorted(merged):
t = merged[d]
cost = sum(t[k] / 1e6 * price[k] for k in METRICS.values()) if price else 0.0
points.append({"date": d, "cost": round(cost, 4),
"in": int(t["in"]), "out": int(t["out"]),
"cache_read": int(t["cache_read"]), "cache_write": int(t["cache_write"])})
return {"region": region, "model": display_model(model_id, regions, sess), "id": model_id,
"price": src, "points": points, "total": round(sum(p["cost"] for p in points), 2),
"estimate": True}
ERROR_METRICS = {"Invocations": "calls", "InvocationClientErrors": "client",
"InvocationServerErrors": "server", "InvocationThrottles": "throttle"}
def _discover_ids(cw, metric):
ids = set()
for page in cw.get_paginator("list_metrics").paginate(Namespace="AWS/Bedrock", MetricName=metric):
for m in page["Metrics"]:
dims = {d["Name"]: d["Value"] for d in m["Dimensions"]}
if set(dims) == {"ModelId"}:
ids.add(dims["ModelId"])
return ids
def region_errors(region, start, end, sess):
cw = sess.client("cloudwatch", region_name=region, config=FAST)
mids = set()
for met in ("Invocations", "InvocationClientErrors", "InvocationServerErrors", "InvocationThrottles"):
try:
mids |= _discover_ids(cw, met)
except Exception:
pass
if not mids:
return {}
keys = list(ERROR_METRICS.items())
q, idmap = [], {}
for mi, mid in enumerate(sorted(mids)):
for ki, (name, field) in enumerate(keys):
qid = f"e{mi}_{ki}"
idmap[qid] = (mid, field)
q.append({"Id": qid, "MetricStat": {
"Metric": {"Namespace": "AWS/Bedrock", "MetricName": name,
"Dimensions": [{"Name": "ModelId", "Value": mid}]},
"Period": 86400, "Stat": "Sum"}})
agg = {mid: dict.fromkeys(ERROR_METRICS.values(), 0.0) for mid in mids}
for i in range(0, len(q), 500):
for page in cw.get_paginator("get_metric_data").paginate(
MetricDataQueries=q[i:i + 500], StartTime=start, EndTime=end):
for r in page["MetricDataResults"]:
mid, field = idmap[r["Id"]]
agg[mid][field] += sum(r["Values"])
return {mid: t for mid, t in agg.items() if any(t.values())}
def error_stats(region, start, end, sess=None):
regions = regions_for(region)
sess = sess or DEFAULT_SESS
agg = {}
with ThreadPoolExecutor(max_workers=min(18, len(regions))) as ex:
futs = {ex.submit(region_errors, r, start, end, sess): r for r in regions}
for f in as_completed(futs):
try:
res = f.result()
except Exception:
continue
for mid, t in res.items():
a = agg.setdefault(mid, dict.fromkeys(ERROR_METRICS.values(), 0.0))
for k in ERROR_METRICS.values():
a[k] += t[k]
rows = []
tc = ts = tt = tcalls = 0
for mid, t in agg.items():
calls, ce, se, th = int(t["calls"]), int(t["client"]), int(t["server"]), int(t["throttle"])
errs = ce + se + th
denom = calls + ce + se # throttles 不算入分母(未进入计费/调用)
rows.append({"model": mid.split("anthropic.")[-1], "calls": calls,
"client": ce, "server": se, "throttle": th,
"errorRate": round((ce + se) / denom * 100, 2) if denom else 0.0})
tc += ce; ts += se; tt += th; tcalls += calls
rows.sort(key=lambda x: -(x["server"] + x["client"] + x["throttle"]))
return {"region": region, "start": start.strftime("%Y-%m-%d %H:%M"),
"end": end.strftime("%Y-%m-%d %H:%M"), "rows": rows,
"totals": {"calls": tcalls, "client": tc, "server": ts, "throttle": tt}}
def logging_log_group(region, sess=None):
"""返回该区域已配置的调用日志 CloudWatch 日志组(用于前端自动选中)。"""
sess = sess or DEFAULT_SESS
try:
cfg = sess.client("bedrock", region_name=region, config=FAST) \
.get_model_invocation_logging_configuration().get("loggingConfig") or {}
cw = cfg.get("cloudWatchConfig") or {}
return {"region": region, "logGroup": cw.get("logGroupName"),
"text": cfg.get("textDataDeliveryEnabled")}
except Exception as e:
return {"region": region, "logGroup": None, "error": str(e)}
def gray_area(region, log_group, start, end, sess=None):
"""从 Model Invocation Logging 日志统计失败请求的计费 token(仅 bedrock-runtime)。
灰区: errorCode 存在;input 被处理即计费,output>0 为流式中途失败已产出部分。"""
sess = sess or DEFAULT_SESS
logs = sess.client("logs", region_name=region, config=FAST)
def runq(qs):
qid = logs.start_query(logGroupName=log_group,
startTime=int(start.timestamp()), endTime=int(end.timestamp()),
queryString=qs)["queryId"]
for _ in range(50):
r = logs.get_query_results(queryId=qid)
if r["status"] == "Complete":
return [{c["field"]: c["value"] for c in row} for row in r["results"]]
if r["status"] in ("Failed", "Cancelled", "Timeout"):
raise RuntimeError("Logs Insights " + r["status"])
time.sleep(0.8)
raise RuntimeError("Logs Insights 查询超时")
def i(x):
return int(float(x or 0))
overview = runq("stats count() as calls, sum(output.outputTokenCount) as outTok "
"by ispresent(errorCode) as isError")
detail = runq("filter ispresent(errorCode) | stats count() as calls, "
"sum(input.inputTokenCount) as inTok, sum(output.outputTokenCount) as outTok "
"by modelId, errorCode")
succ = next((r for r in overview if r.get("isError") == "0"), {})
fail = next((r for r in overview if r.get("isError") == "1"), {})
rows = [{"model": r.get("modelId", "").split("/")[-1], "errorCode": r.get("errorCode", ""),
"calls": i(r.get("calls")), "in": i(r.get("inTok")), "out": i(r.get("outTok"))}
for r in detail]
rows.sort(key=lambda x: -(x["in"] + x["out"]))
return {"region": region, "log_group": log_group,
"start": start.strftime("%Y-%m-%d %H:%M"), "end": end.strftime("%Y-%m-%d %H:%M"),
"success_calls": i(succ.get("calls")), "success_out": i(succ.get("outTok")),
"failed_calls": i(fail.get("calls")),
"billed_input_on_fail": sum(r["in"] for r in rows),
"gray_output_on_fail": sum(r["out"] for r in rows),
"rows": rows}
def ce_cost(start, end, sess=None):
ce = (sess or boto3).client("ce", region_name="us-east-1")
s = start.date().isoformat()
# end 来自 _range,已是"不含"上界(选中末日+1天的 00:00);若带时间(被 now 截断)则向上取整到次日。
# 注意:不能再 +1 天,否则会多算一整天(v1.3.4 修复)。
if (end.hour, end.minute, end.second, end.microsecond) == (0, 0, 0, 0):
e_excl = end.date()
else:
e_excl = end.date() + dt.timedelta(days=1)
today_next = dt.datetime.now(dt.UTC).date() + dt.timedelta(days=1)
e_excl = min(e_excl, today_next)
e = e_excl.isoformat()
e_incl = (e_excl - dt.timedelta(days=1)).isoformat() # 展示用:含的末日=用户选中的结束日
resp = ce.get_cost_and_usage(
TimePeriod={"Start": s, "End": e}, Granularity="MONTHLY",
Metrics=["UnblendedCost"],
GroupBy=[{"Type": "DIMENSION", "Key": "SERVICE"}])
all_services = []
by_service = {}
for period in resp.get("ResultsByTime", []):
for g in period.get("Groups", []):
name = g["Keys"][0]
amt = float(g["Metrics"]["UnblendedCost"]["Amount"])
all_services.append((name, amt))
if "amazon bedrock" not in name.lower():
continue
by_service[name] = by_service.get(name, 0.0) + amt
if not by_service and all_services:
print(f"[ce_cost] no bedrock match ({s}~{e}); services="
+ json.dumps(sorted(all_services, key=lambda x: -x[1])[:20], ensure_ascii=False))
total = sum(by_service.values())
tagged = untagged = 0.0
tag_values = {}
if by_service:
resp2 = ce.get_cost_and_usage(
TimePeriod={"Start": s, "End": e}, Granularity="MONTHLY",
Metrics=["UnblendedCost"],
Filter={"Dimensions": {"Key": "SERVICE", "Values": sorted(by_service)}},
GroupBy=[{"Type": "TAG", "Key": "map-migrated"}])
for period in resp2.get("ResultsByTime", []):
for g in period.get("Groups", []):
key = g["Keys"][0]
amt = float(g["Metrics"]["UnblendedCost"]["Amount"])
val = key.split("$", 1)[1] if "$" in key else ""
if val:
tagged += amt
tag_values[val] = tag_values.get(val, 0.0) + amt
else:
untagged += amt
note = ""
if total > 0 and tagged == 0:
note = ("map-migrated 打标金额为 0:资源可能未打标,或该 tag 未在 Billing 控制台"
"激活为成本分配标签(激活后仅对之后产生的账单生效,历史不回填)")
return {"start": s, "end": e_incl, "total": round(total, 2),
"tagged": round(tagged, 2), "untagged": round(untagged, 2),
"taggedPct": round(tagged / total * 100, 1) if total else 0.0,
"byService": [{"service": k, "cost": round(v, 2)}
for k, v in sorted(by_service.items(), key=lambda x: -x[1])],
"tagValues": [{"value": k, "cost": round(v, 2)}
for k, v in sorted(tag_values.items(), key=lambda x: -x[1])],
"note": note}
def ce_cost_all(start, end):
"""中心 + 全部注册账号逐账号查 CE, 一账号一行."""
rows = []
try:
central_id = central_role_arn().split(":")[4]
except Exception:
central_id = "中心账号"
targets = [{"accountId": None, "label": f"中心 {central_id}"}]
for a in load_accounts():
if a["accountId"] == central_id:
continue
targets.append({"accountId": a["accountId"],
"label": a.get("label") or a["accountId"]})
total = tagged = untagged = 0.0
meta = {}
for t in targets:
try:
d = ce_cost(start, end, session_for(t["accountId"]))
meta = d
rows.append({"account": t["accountId"] or central_id, "label": t["label"],
"total": d["total"], "tagged": d["tagged"],
"untagged": d["untagged"], "taggedPct": d["taggedPct"]})
total += d["total"]
tagged += d["tagged"]
untagged += d["untagged"]
except Exception as e:
print(f"[ce_cost_all] account={t['accountId'] or central_id} FAILED: {e!r}")
rows.append({"account": t["accountId"] or central_id, "label": t["label"],
"error": str(e)[:200]})
return {"start": meta.get("start", start.date().isoformat()),
"end": meta.get("end", (end - dt.timedelta(seconds=1)).date().isoformat()),
"total": round(total, 2), "tagged": round(tagged, 2),
"untagged": round(untagged, 2),
"taggedPct": round(tagged / total * 100, 1) if total else 0.0,
"rows": rows,
"note": ("map-migrated 拆分需要各账号已将该 tag 激活为成本分配标签"
"(激活后仅对新账单生效,历史不回填)" if total > 0 and tagged == 0 else "")}
def _range(q):
now = dt.datetime.now(dt.UTC)
try:
if q.get("start") and q.get("end"):
s = dt.datetime.fromisoformat(q["start"]).replace(tzinfo=dt.UTC)
e = min(dt.datetime.fromisoformat(q["end"]).replace(tzinfo=dt.UTC) + dt.timedelta(days=1), now)
if s < e:
return s, e
print(f"[_range] invalid range start={q.get('start')} end={q.get('end')}, falling back to default")
except (TypeError, ValueError):
print(f"[_range] unparsable dates start={q.get('start')!r} end={q.get('end')!r}, falling back to default")
try:
days = max(1, min(455, int(q.get("days", 30))))
except (TypeError, ValueError):
days = 30
return now - dt.timedelta(days=days), now
def _json(obj, code=200):
return {"statusCode": code,
"headers": {"content-type": "application/json", "cache-control": "no-store",
"access-control-allow-origin": "*"},
"body": json.dumps(obj)}
def lambda_handler(event, context):
if isinstance(event, dict) and not event.get("queryStringParameters") and event.get("action") == "refresh_cache":
return {"cache_refreshed": write_snapshot_cache()}
if isinstance(event, dict) and not event.get("queryStringParameters") and (
event.get("action") == "alert_check" or event.get("source") == "aws.events"):
t0 = time.monotonic()
result = run_alert_check(force_send=bool(event.get("force")))
print(json.dumps({"alert_check": {k: v for k, v in result.items() if k != "violations"},
"violation_count": len(result.get("violations", []))}, ensure_ascii=False))
# 超时排查: alert_check 与快照刷新各占多久,剩余多少毫秒
print(f"[alert_check] done in {time.monotonic() - t0:.1f}s, "
f"remaining={context.get_remaining_time_in_millis() if context else '?'}ms; snapshot refresh next")
t1 = time.monotonic()
try:
result["cache_refreshed"] = write_snapshot_cache()
print(f"[snapshot] refreshed in {time.monotonic() - t1:.1f}s")
except Exception as e:
print(f"cache refresh failed: {e!r}")
return result
q = (event.get("queryStringParameters") or {}) if isinstance(event, dict) else {}
q = q or {}
region = q.get("region", "us-west-2")
account = q.get("account") # 远程账号ID;空=中心本账号
start, end = _range(q)
fmt = q.get("format")
try:
if fmt == "prices":
table, src = load_prices()
return _json({"prices": table, "source": src, "editable": True})
if fmt == "accounts":
accts = [{"accountId": a["accountId"], "label": a.get("label", ""),
"regions": a.get("regions", "")} for a in load_accounts()]
return _json({"accounts": accts, "editable": True, "central": central_role_arn()})
if q.get("action") == "add_account":
if EDIT_KEY and q.get("key") != EDIT_KEY:
return _json({"error": "编辑密钥无效"}, 403)
try:
a = json.loads(q.get("account_json", "{}"))
except (TypeError, ValueError):
return _json({"error": "account_json 不是合法 JSON"}, 400)
lst = [x for x in load_accounts() if x.get("accountId") != str(a.get("accountId"))]
lst.append(a)
try:
save_accounts(lst)
except Exception as e:
return _json({"error": str(e)}, 400)
return _json({"ok": True})
if q.get("action") == "del_account":
if EDIT_KEY and q.get("key") != EDIT_KEY:
return _json({"error": "编辑密钥无效"}, 403)
lst = [x for x in load_accounts() if x.get("accountId") != q.get("accountId")]
save_accounts(lst)
return _json({"ok": True})
if fmt == "alerts":
return _json({"alerts": load_alerts(), "editable": True})
if q.get("action") == "save_alerts":
if EDIT_KEY and q.get("key") != EDIT_KEY:
return _json({"error": "编辑密钥无效"}, 403)
try:
cfg = save_alerts(json.loads(q.get("alerts_json", "{}")))
except Exception as e:
return _json({"error": str(e)}, 400)
return _json({"ok": True, "alerts": cfg})
if q.get("action") == "test_alert":
if EDIT_KEY and q.get("key") != EDIT_KEY:
return _json({"error": "编辑密钥无效"}, 403)
lam = boto3.client("lambda", region_name=LAMBDA_REGION)
lam.invoke(FunctionName=context.function_name, InvocationType="Event",
Payload=json.dumps({"action": "alert_check", "force": True}).encode())
return _json({"ok": True, "queued": True})
if fmt == "pricelist":
pr = fetch_price_list(region if region not in ("global", "all") else "us-east-1")
return _json({"prices": pr, "source": "AWS Price List API",
"region": region if region not in ("global", "all") else "us-east-1"})
if q.get("action") == "save":
if EDIT_KEY and q.get("key") != EDIT_KEY:
return _json({"error": "编辑密钥无效"}, 403)
try:
obj = json.loads(q.get("prices", "{}"))
except (TypeError, ValueError):
return _json({"error": "prices 不是合法 JSON"}, 400)