This repository has been archived by the owner on Jul 23, 2024. It is now read-only.
forked from Joshi425/minecraft-exporter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminecraft_exporter.py
809 lines (763 loc) · 32 KB
/
minecraft_exporter.py
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
import json
import os
import re
import time
from os import listdir
from os.path import isfile, join
import nbt
import requests
import schedule
from mcrcon import MCRcon, MCRconException
from prometheus_client import Metric, REGISTRY, start_http_server
class MinecraftCollector(object):
def __init__(self):
self.world_dir = "/world"
if "WORLD_DIR" in os.environ:
self.world_dir = os.environ["WORLD_DIR"]
self.stats_directory = self.world_dir + "/stats"
self.player_directory = self.world_dir + "/playerdata"
self.advancements_directory = self.world_dir + "/advancements"
self.better_questing = self.world_dir + "/betterquesting"
self.player_map = dict()
self.quests_enabled = False
self.rcon = None
self.rcon_connected = False
if all(x in os.environ for x in ["RCON_HOST", "RCON_PASSWORD", "RCON_PORT"]):
self.rcon = MCRcon(
os.environ["RCON_HOST"],
os.environ["RCON_PASSWORD"],
port=int(os.environ["RCON_PORT"]),
)
print("RCON is enabled for " + os.environ["RCON_HOST"])
if os.path.isdir(self.better_questing):
self.quests_enabled = True
print("Found Better Questing folder, enabling metrics")
self.paper_server = False
if (
"PAPER_SERVER" in os.environ
and os.environ["PAPER_SERVER"].lower() == "true"
):
self.paper_server = True
print("Paper server is enabled, enabling metrics")
self.forge_server = False
if (
"FORGE_SERVER" in os.environ
and os.environ["FORGE_SERVER"].lower() == "true"
):
self.forge_server = True
print("Forge server is enabled, enabling metrics")
self.dynmap_enabled = False
if (
"DYNMAP_ENABLED" in os.environ
and os.environ["DYNMAP_ENABLED"].lower() == "true"
):
self.dynmap_enabled = True
print("Dynmap is enabled, enabling metrics")
self.reduce_metrics = False
if (
"REDUCE_METRICS" in os.environ
and os.environ["REDUCE_METRICS"].lower() == "true"
):
self.reduce_metrics = True
print("Reducing metrics for grafana cloud")
schedule.every().day.at("01:00").do(self.flush_playernamecache)
def get_players(self):
return [
f[:-5]
for f in listdir(self.stats_directory)
if isfile(join(self.stats_directory, f))
]
def flush_playernamecache(self):
print("flushing playername cache")
self.player_map = dict()
def uuid_to_player(self, uuid):
if uuid in self.player_map:
return self.player_map[uuid]
else:
try:
result = requests.get(
"https://sessionserver.mojang.com/session/minecraft/profile/" + uuid
)
self.player_map[uuid] = result.json()["name"]
return result.json()["name"]
except BaseException:
return
def rcon_connect(self):
try:
self.rcon.connect()
self.rcon_connected = True
print("Successfully connected to RCON")
return True
except Exception as e:
print("Failed to connect to RCON")
print(e)
return False
def rcon_disconnect(self):
self.rcon.disconnect()
self.rcon_connected = False
def rcon_command(self, command):
try:
response = self.rcon.command(command)
except MCRconException as e:
response = None
if e == "Connection timeout error":
print("Lost RCON Connection")
self.rcon_disconnect()
else:
print("RCON command failed")
except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError):
print("Lost RCON Connection")
self.rcon_disconnect()
response = None
return response
def get_server_stats(self):
if self.rcon is None or (not self.rcon_connected and not self.rcon_connect()):
return []
metrics = []
forge_dim_tps = Metric("forge_dim_tps", "TPS of a dimension", "counter")
forge_dim_ticktime = Metric(
"forge_dim_ticktime", "Time a Tick took in a Dimension", "counter"
)
forge_overall_tps = Metric("forge_overall_tps", "overall TPS", "counter")
forge_overall_ticktime = Metric(
"forge_overall_ticktime", "overall Ticktime", "counter"
)
minecraft_player_online = Metric(
"minecraft_player_online", "is 1 if player is online", "counter"
)
forge_entities = Metric(
"forge_entities", "type and count of active entites", "counter"
)
paper_tps_1m = Metric("paper_tps_1m", "1 Minute TPS", "counter")
paper_tps_5m = Metric("paper_tps_5m", "5 Minute TPS", "counter")
paper_tps_15m = Metric("paper_tps_15m", "15 Minute TPS", "counter")
metrics.extend(
[
forge_dim_tps,
forge_dim_ticktime,
forge_overall_tps,
forge_overall_ticktime,
minecraft_player_online,
forge_entities,
paper_tps_1m,
paper_tps_5m,
paper_tps_15m,
]
)
if self.paper_server:
resp = str(self.rcon_command("tps")).strip().replace("§a", "")
tpsregex = re.compile(
"§?.?TPS from last 1m, 5m, 15m: (\d*\.\d*)§?.?, (\d*\.\d*)§?.?, (\d*\.\d*)§?.?"
)
for m1, m5, m15 in tpsregex.findall(resp):
paper_tps_1m.add_sample("paper_tps_1m", value=m1, labels={"tps": "1m"})
paper_tps_5m.add_sample("paper_tps_5m", value=m5, labels={"tps": "5m"})
paper_tps_15m.add_sample(
"paper_tps_15m", value=m15, labels={"tps": "15m"}
)
if self.forge_server:
# dimensions
resp = self.rcon_command("forge tps")
dimtpsregex = re.compile(
"Dim\s*(-*\d*)\s\((.*?)\)\s:\sMean tick time:\s(.*?) ms\. Mean TPS: (\d*\.\d*)"
)
for dimid, dimname, meanticktime, meantps in dimtpsregex.findall(resp):
forge_dim_tps.add_sample(
"forge_dim_tps",
value=meantps,
labels={"dimension_id": dimid, "dimension_name": dimname},
)
forge_dim_ticktime.add_sample(
"forge_dim_ticktime",
value=meanticktime,
labels={"dimension_id": dimid, "dimension_name": dimname},
)
overallregex = re.compile(
"Overall\s?: Mean tick time: (.*) ms. Mean TPS: (.*)"
)
forge_overall_tps.add_sample(
"forge_overall_tps", value=overallregex.findall(resp)[0][1], labels={}
)
forge_overall_ticktime.add_sample(
"forge_overall_ticktime",
value=overallregex.findall(resp)[0][0],
labels={},
)
# entities
resp = self.rcon_command("forge entity list")
entityregex = re.compile("(\d+): (.*?:.*?)\s")
for entitycount, entityname in entityregex.findall(resp):
forge_entities.add_sample(
"forge_entities", value=entitycount, labels={"entity": entityname}
)
# dynmap
if self.dynmap_enabled:
dynmap_tile_render_statistics = Metric(
"dynmap_tile_render_statistics",
"Tile Render Statistics reported by Dynmap",
"counter",
)
dynmap_chunk_loading_statistics_count = Metric(
"dynmap_chunk_loading_statistics_count",
"Chunk Loading Statistics reported by Dynmap",
"counter",
)
dynmap_chunk_loading_statistics_duration = Metric(
"dynmap_chunk_loading_statistics_duration",
"Chunk Loading Statistics reported by Dynmap",
"counter",
)
metrics.extend(
[
dynmap_tile_render_statistics,
dynmap_chunk_loading_statistics_count,
dynmap_chunk_loading_statistics_duration,
]
)
resp = self.rcon_command("dynmap stats")
dynmaptilerenderregex = re.compile(
" (.*?): processed=(\d*), rendered=(\d*), updated=(\d*)"
)
for dim, processed, rendered, updated in dynmaptilerenderregex.findall(
resp
):
dynmap_tile_render_statistics.add_sample(
"dynmap_tile_render_statistics",
value=processed,
labels={"type": "processed", "file": dim},
)
dynmap_tile_render_statistics.add_sample(
"dynmap_tile_render_statistics",
value=rendered,
labels={"type": "rendered", "file": dim},
)
dynmap_tile_render_statistics.add_sample(
"dynmap_tile_render_statistics",
value=updated,
labels={"type": "updated", "file": dim},
)
dynmapchunkloadingregex = re.compile(
"Chunks processed: (.*?): count=(\d*), (\d*.\d*)"
)
for state, count, duration_per_chunk in dynmapchunkloadingregex.findall(
resp
):
dynmap_chunk_loading_statistics_count.add_sample(
"dynmap_chunk_loading_statistics",
value=count,
labels={"type": state},
)
dynmap_chunk_loading_statistics_duration.add_sample(
"dynmap_chunk_loading_duration",
value=duration_per_chunk,
labels={"type": state},
)
# player
resp = self.rcon_command("list")
playerregex = re.compile("players online:(.*)")
if playerregex.findall(resp):
for player in playerregex.findall(resp)[0].split(","):
if not player.isspace():
minecraft_player_online.add_sample(
"minecraft_player_online",
value=1,
labels={"player": player.lstrip()},
)
return metrics
def get_player_quests_finished(self, uuid):
with open(self.better_questing + "/QuestProgress.json") as json_file:
data = json.load(json_file)
json_file.close()
counter = 0
for _, value in data["questProgress:9"].items():
for _, u in value["tasks:9"]["0:10"]["completeUsers:9"].items():
if u == uuid:
counter += 1
return counter
def get_player_stats(self, uuid):
with open(self.stats_directory + "/" + uuid + ".json") as json_file:
data = json.load(json_file)
json_file.close()
nbtfile = nbt.nbt.NBTFile(self.player_directory + "/" + uuid + ".dat", "rb")
data["stat.XpTotal"] = nbtfile.get("XpTotal").value
data["stat.XpLevel"] = nbtfile.get("XpLevel").value
data["stat.Score"] = nbtfile.get("Score").value
data["stat.Health"] = nbtfile.get("Health").value
data["stat.foodLevel"] = nbtfile.get("foodLevel").value
with open(self.advancements_directory + "/" + uuid + ".json") as json_file:
count = 0
advancements = json.load(json_file)
for key, value in advancements.items():
if key in ("DataVersion"):
continue
if value["done"] is True:
count += 1
data["stat.advancements"] = count
if self.quests_enabled:
data["stat.questsFinished"] = self.get_player_quests_finished(uuid)
return data
def update_metrics_for_player(self, uuid):
name = self.uuid_to_player(uuid)
if not name:
return
data = self.get_player_stats(uuid)
blocks_mined_counter = int(0)
blocks_picked_up_counter = int(0)
blocks_crafted_counter = int(0)
minecraft_blocks_mined = Metric(
"minecraft_blocks_mined", "Blocks a Player mined", "counter"
)
minecraft_blocks_picked_up = Metric(
"minecraft_blocks_picked_up", "Blocks a Player picked up", "counter"
)
minecraft_player_deaths = Metric(
"minecraft_player_deaths", "How often a Player died", "counter"
)
minecraft_player_jumps = Metric(
"minecraft_player_jumps", "How often a Player has jumped", "counter"
)
minecraft_cm_traveled = Metric(
"minecraft_cm_traveled",
"How many cm a Player traveled, whatever that means",
"counter",
)
minecraft_player_xp_total = Metric(
"minecraft_player_xp_total", "How much total XP a player has", "counter"
)
minecraft_player_current_level = Metric(
"minecraft_player_current_level",
"How much current XP a player has",
"counter",
)
minecraft_player_food_level = Metric(
"minecraft_player_food_level",
"How much food the player currently has",
"counter",
)
minecraft_player_health = Metric(
"minecraft_player_health",
"How much Health the player currently has",
"counter",
)
minecraft_player_score = Metric(
"minecraft_player_score", "The Score of the player", "counter"
)
minecraft_entities_killed = Metric(
"minecraft_entities_killed", "Entities killed by player", "counter"
)
minecraft_damage_taken = Metric(
"minecraft_damage_taken", "Damage Taken by Player", "counter"
)
minecraft_damage_dealt = Metric(
"minecraft_damage_dealt", "Damage dealt by Player", "counter"
)
minecraft_blocks_crafted = Metric(
"minecraft_blocks_crafted", "Items a Player crafted", "counter"
)
minecraft_player_playtime = Metric(
"minecraft_player_playtime",
"Time in Minutes a Player was online",
"counter",
)
minecraft_player_advancements = Metric(
"minecraft_player_advancements",
"Number of completed advances of a player",
"counter",
)
minecraft_player_slept = Metric(
"minecraft_player_slept", "Times a Player slept in a bed", "counter"
)
minecraft_player_quests_finished = Metric(
"minecraft_player_quests_finished",
"Number of quests a Player has finished",
"counter",
)
minecraft_player_used_crafting_table = Metric(
"minecraft_player_used_crafting_table",
"Times a Player used a Crafting Table",
"counter",
)
minecraft_custom = Metric(
"minecraft_custom", "Custom Minecraft stat", "counter"
)
for key, value in data.items(): # pre 1.15
if key in ("stats", "DataVersion"):
continue
stat = key.split(".")[1] # entityKilledBy
if stat == "mineBlock":
if self.reduce_metrics:
blocks_mined_counter += value
else:
minecraft_blocks_mined.add_sample(
"minecraft_blocks_mined",
value=value,
labels={
"player": name,
"block": ".".join((key.split(".")[2], key.split(".")[3])),
},
)
elif stat == "pickup":
if self.reduce_metrics:
blocks_picked_up_counter += value
else:
minecraft_blocks_picked_up.add_sample(
"minecraft_blocks_picked_up",
value=value,
labels={
"player": name,
"block": ".".join((key.split(".")[2], key.split(".")[3])),
},
)
elif stat == "entityKilledBy":
if len(key.split(".")) == 4:
minecraft_player_deaths.add_sample(
"minecraft_player_deaths",
value=value,
labels={
"player": name,
"cause": ".".join((key.split(".")[2], key.split(".")[3])),
},
)
else:
minecraft_player_deaths.add_sample(
"minecraft_player_deaths",
value=value,
labels={"player": name, "cause": key.split(".")[2]},
)
elif stat == "jump":
minecraft_player_jumps.add_sample(
"minecraft_player_jumps", value=value, labels={"player": name}
)
elif stat == "walkOneCm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "walking"},
)
elif stat == "swimOneCm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "swimming"},
)
elif stat == "sprintOneCm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "sprinting"},
)
elif stat == "diveOneCm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "diving"},
)
elif stat == "fallOneCm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "falling"},
)
elif stat == "flyOneCm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "flying"},
)
elif stat == "boatOneCm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "boat"},
)
elif stat == "horseOneCm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "horse"},
)
elif stat == "climbOneCm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "climbing"},
)
elif stat == "XpTotal":
minecraft_player_xp_total.add_sample(
"minecraft_player_xp_total", value=value, labels={"player": name}
)
elif stat == "XpLevel":
minecraft_player_current_level.add_sample(
"minecraft_player_current_level",
value=value,
labels={"player": name},
)
elif stat == "foodLevel":
minecraft_player_food_level.add_sample(
"minecraft_player_food_level", value=value, labels={"player": name}
)
elif stat == "Health":
minecraft_player_health.add_sample(
"minecraft_player_health", value=value, labels={"player": name}
)
elif stat == "Score":
minecraft_player_score.add_sample(
"minecraft_player_score", value=value, labels={"player": name}
)
elif stat == "killEntity":
minecraft_entities_killed.add_sample(
"minecraft_entities_killed",
value=value,
labels={"player": name, "entity": key.split(".")[2]},
)
elif stat == "damageDealt":
minecraft_damage_dealt.add_sample(
"minecraft_damage_dealt", value=value, labels={"player": name}
)
elif stat == "damageTaken":
minecraft_damage_dealt.add_sample(
"minecraft_damage_taken", value=value, labels={"player": name}
)
elif stat == "craftItem":
if self.reduce_metrics:
blocks_crafted_counter += value
else:
minecraft_blocks_crafted.add_sample(
"minecraft_blocks_crafted",
value=value,
labels={
"player": name,
"block": ".".join((key.split(".")[2], key.split(".")[3])),
},
)
elif stat == "playOneMinute":
minecraft_player_playtime.add_sample(
"minecraft_player_playtime", value=value, labels={"player": name}
)
elif stat == "advancements":
minecraft_player_advancements.add_sample(
"minecraft_player_advancements",
value=value,
labels={"player": name},
)
elif stat == "sleepInBed":
minecraft_player_slept.add_sample(
"minecraft_player_slept", value=value, labels={"player": name}
)
elif stat == "craftingTableInteraction":
minecraft_player_used_crafting_table.add_sample(
"minecraft_player_used_crafting_table",
value=value,
labels={"player": name},
)
elif stat == "questsFinished":
minecraft_player_quests_finished.add_sample(
"minecraft_player_quests_finished",
value=value,
labels={"player": name},
)
if "stats" in data: # Minecraft > 1.15
if "minecraft:crafted" in data["stats"]:
for block, value in data["stats"]["minecraft:crafted"].items():
if self.reduce_metrics:
blocks_crafted_counter += value
else:
minecraft_blocks_crafted.add_sample(
"minecraft_blocks_crafted",
value=value,
labels={"player": name, "block": block},
)
if "minecraft:mined" in data["stats"]:
for block, value in data["stats"]["minecraft:mined"].items():
if self.reduce_metrics:
blocks_mined_counter += value
else:
minecraft_blocks_mined.add_sample(
"minecraft_blocks_mined",
value=value,
labels={"player": name, "block": block},
)
if "minecraft:picked_up" in data["stats"]:
for block, value in data["stats"]["minecraft:picked_up"].items():
if self.reduce_metrics:
blocks_picked_up_counter += value
else:
minecraft_blocks_picked_up.add_sample(
"minecraft_blocks_picked_up",
value=value,
labels={"player": name, "block": block},
)
if "minecraft:killed" in data["stats"]:
for entity, value in data["stats"]["minecraft:killed"].items():
minecraft_entities_killed.add_sample(
"minecraft_entities_killed",
value=value,
labels={"player": name, "entity": entity},
)
if "minecraft:killed_by" in data["stats"]:
for entity, value in data["stats"]["minecraft:killed_by"].items():
minecraft_player_deaths.add_sample(
"minecraft_player_deaths",
value=value,
labels={"player": name, "cause": entity},
)
for stat, value in data["stats"]["minecraft:custom"].items():
if stat == "minecraft:jump":
minecraft_player_jumps.add_sample(
"minecraft_player_jumps", value=value, labels={"player": name}
)
elif stat == "minecraft:deaths":
minecraft_player_deaths.add_sample(
"minecraft_player_deaths", value=value, labels={"player": name}
)
elif stat == "minecraft:minecraft_damage_taken":
minecraft_damage_taken.add_sample(
"minecraft_damage_taken", value=value, labels={"player": name}
)
elif stat == "minecraft:minecraft_damage_dealt":
minecraft_damage_dealt.add_sample(
"minecraft_damage_dealt", value=value, labels={"player": name}
)
elif stat == "minecraft:play_time":
minecraft_player_playtime.add_sample(
"minecraft_player_playtime",
value=value,
labels={"player": name},
)
elif stat == "minecraft:play_one_minute": # pre 1.17
minecraft_player_playtime.add_sample(
"minecraft_player_playtime",
value=value,
labels={"player": name},
)
elif stat == "minecraft:walk_one_cm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "walking"},
)
elif stat == "minecraft:walk_on_water_one_cm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "swimming"},
)
elif stat == "minecraft:sprint_one_cm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "sprinting"},
)
elif stat == "minecraft:walk_under_water_one_cm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "diving"},
)
elif stat == "minecraft:fall_one_cm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "falling"},
)
elif stat == "minecraft:fly_one_cm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "flying"},
)
elif stat == "minecraft:boat_one_cm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "boat"},
)
elif stat == "minecraft:horse_one_cm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "horse"},
)
elif stat == "minecraft:climb_one_cm":
minecraft_cm_traveled.add_sample(
"minecraft_cm_traveled",
value=value,
labels={"player": name, "method": "climbing"},
)
elif stat == "minecraft:sleep_in_bed":
minecraft_player_slept.add_sample(
"minecraft_player_slept", value=value, labels={"player": name}
)
elif stat == "minecraft:interact_with_crafting_table":
minecraft_player_used_crafting_table.add_sample(
"minecraft_player_used_crafting_table",
value=value,
labels={"player": name},
)
else:
minecraft_custom.add_sample(
"minecraft_custom", value=value, labels={"stat": stat}
)
if self.reduce_metrics:
minecraft_blocks_crafted.add_sample(
"minecraft_blocks_crafted",
value=blocks_crafted_counter,
labels={"player": name},
)
minecraft_blocks_mined.add_sample(
"minecraft_blocks_mined",
value=blocks_mined_counter,
labels={"player": name},
)
minecraft_blocks_picked_up.add_sample(
"minecraft_blocks_picked_up",
value=blocks_picked_up_counter,
labels={"player": name},
)
return [
minecraft_blocks_mined,
minecraft_blocks_picked_up,
minecraft_player_deaths,
minecraft_player_jumps,
minecraft_cm_traveled,
minecraft_player_xp_total,
minecraft_player_current_level,
minecraft_player_food_level,
minecraft_player_health,
minecraft_player_score,
minecraft_entities_killed,
minecraft_damage_taken,
minecraft_damage_dealt,
minecraft_blocks_crafted,
minecraft_player_playtime,
minecraft_player_advancements,
minecraft_player_slept,
minecraft_player_used_crafting_table,
minecraft_player_quests_finished,
minecraft_custom,
]
def collect(self):
for player in self.get_players():
metrics = self.update_metrics_for_player(player)
if not metrics:
continue
for metric in metrics:
yield metric
for metric in self.get_server_stats():
yield metric
if __name__ == "__main__":
try:
HTTP_PORT = int(os.environ.get("HTTP_PORT"))
except BaseException:
HTTP_PORT = 8000
collector = MinecraftCollector()
start_http_server(HTTP_PORT)
REGISTRY.register(collector)
print(f"Exporter started on Port {HTTP_PORT}")
while True:
try:
time.sleep(1)
schedule.run_pending()
except MCRconException:
# RCON timeout
collector.rcon_disconnect()