Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- # Used to capture data from TRN, and works around the severe rate limiting by using a key pool
- # and some clever timing to get a full sample in a two hour window, with 40 members being done
- # in < 20 minutes
- # This script is resumable, and doesn't wait when rate limited, instead just exiting.
- # When the sample is complete, a semaphore file is written out so the calling shell
- # script knows it can continue processing
- # This script should be called from cron with these timings:
- # cron *must* be configured to use UTC!
- # https://unix.stackexchange.com/questions/710815/how-do-i-make-cron-use-utc
- # (The above method works on the rPi/rasbian)
- # 00:05
- # 01:05 --delay
- # 02:05 --delay --complete
- # 03:50 (Sample Hour 03)
- # 04:05
- # 05:05 --delay
- # 06:05 --delay --complete
- # 07:50 (Sample Hour 07)
- # 08:05
- # 09:05 --delay
- # 10:05 --delay --complete
- # 11:50 (Sample Hour 11)
- # 12:05
- # 13:05 --delay
- # 14:05 --delay --complete
- # 15:50 (Sample Hour 15)
- # 16:05
- # 17:05 --delay
- # 18:05 --delay --complete
- # 19:50 (Sample Hour 19)
- # 20:05
- # 21:05 --delay
- # 22:05 --delay --complete
- # 23:50 (Sample Hour 23 (EOD))
- # Python 3
- import sys
- import os
- import json
- import requests
- from datetime import datetime, timedelta
- import pytz
- import argparse
- import random
- import time
- import logging
- # Configuration
- script_dir = os.path.dirname(os.path.abspath(__file__))
- data_dir = os.path.join(script_dir, "data")
- rejected_dir = os.path.join(script_dir, "rejected")
- inactive_src = os.path.join(script_dir, "inactive.txt")
- players_src = os.path.join(script_dir, "players.json")
- complete_flag = os.path.join(data_dir,"capture.complete")
- api_keys = [
- { 'secret': os.environ['TRN_SECRET'], 'name': 'Primary' },
- { 'secret': os.environ['TRN_SECRET_LEGACY'], 'name': 'Legacy' }
- ]
- trn_api_url = "https://public-api.tracker.gg/v2/division-2/standard/profile/psn/"
- local_timezone = 'Europe/Berlin'
- # Parameter parsing
- parser = argparse.ArgumentParser(
- prog="TRN Fetch",
- description="Captures JSON files of player stats from TRN.",
- epilog="Requires the TRN_SECRET environment variable to be defined."
- )
- parser.add_argument('-v', '--verbose', help="Show detailed messages.", action="store_true")
- parser.add_argument('-u', '--complete', help="Force complete flag.", action="store_true")
- parser.add_argument('-q', '--quiet', help="Only log warnings and errors.", action="store_true")
- parser.add_argument('-d', '--delay', help="Start capture with a random delay of 1-3 minutes.", action='store_true')
- options = parser.parse_args()
- # Verbose mode overrides quiet
- if options.verbose:
- options.quiet = False
- logging.basicConfig(level=logging.DEBUG)
- else:
- if options.quiet:
- logging.basicConfig(level=logging.WARNING)
- else:
- logging.basicConfig(level=logging.INFO)
- if options.delay:
- options.pause_seconds = 160
- else:
- options.pause_seconds = 15
- # Define classes
- # Class to manage keys and rate limiting
- class KeyPool:
- def __init__(self, use_cap: 10):
- self.keys = []
- self.key_count = 0
- self.limited_keys = 0
- self.next_key = 0
- self.last_key = 0
- self.use_cap = use_cap
- self.available_calls = 0
- def add_key(self, name, secret):
- self.keys.append({ 'name': name, 'secret': secret, 'hour_used' : None, 'available' : self.use_cap, 'uses' : 0, 'errors' : 0 })
- self.key_count = self.key_count+1
- self.available_calls = self.available_calls + self.use_cap
- logging.debug(f"Added key #{self.key_count-1}, available calls: {self.available_calls}")
- def key_available(self):
- return self.available_calls > 0
- def key_limited(self):
- logging.debug(f"Key {self.last_key} was limited. Reducing available calls.")
- logging.debug(f"Calls available was: {self.available_calls}")
- logging.debug(f"Calls attached to limited key is: {self.keys[self.last_key]['available']}")
- self.available_calls = self.available_calls - self.keys[self.last_key]['available']
- self.keys[self.last_key]['available']=0
- logging.debug(f"Calls available now: {self.available_calls}")
- if self.last_key == self.key_count - 1:
- self.next_key = None
- else:
- self.next_key = self.last_key + 1
- logging.debug(f"Next key to use is {self.next_key}")
- def get_secret(self):
- this_hour = datetime.utcnow().hour
- if self.keys[self.next_key]['hour_used']!=this_hour:
- self.keys[self.next_key]['hour_used']=this_hour
- # remove any unused calls from the previous hour from the total available
- self.available_calls = self.available_calls - self.keys[self.next_key]['available']
- # reset the available uses on the key
- self.keys[self.next_key]['available']=self.use_cap
- # add the number of calls to the total available
- self.available_calls = self.available_calls + self.keys[self.next_key]['available']
- # this key will now be used, so reduce the count of available remaining calls
- self.available_calls = self.available_calls - 1
- self.keys[self.next_key]['available'] = self.keys[self.next_key]['available'] - 1
- # increment how many times it was used in total
- self.keys[self.next_key]['uses'] = self.keys[self.next_key]['uses'] + 1
- self.last_key = self.next_key
- if self.keys[self.next_key]['available'] == 0:
- self.next_key = self.next_key + 1
- if self.next_key > self.key_count - 1:
- self.available_calls = 0
- self.next_key = None
- logging.debug(f"Using key #{self.last_key}, calls remaining: {self.available_calls}, next key is #{self.next_key}")
- return self.keys[self.last_key]['secret']
- # Class used to ensure we don't go over the rate limit with TRN
- class Throttle:
- def __init__(self, transactions, secs=1.0):
- self.max_transactions = transactions
- self.duration = secs
- self.queue = []
- self.tolerance = 1
- def next(self):
- waiting = True
- while waiting:
- self.queue = [recent for recent in self.queue if (recent+self.duration+self.tolerance) > time.monotonic()]
- if len(self.queue) < self.max_transactions:
- waiting = False
- self.queue.append(time.monotonic())
- else:
- oldest = self.queue[0]
- current = time.monotonic()
- elapsed = current - oldest
- pause = self.duration - elapsed + self.tolerance
- time.sleep(pause)
- # Define functions
- def player_list_load(player_file_path):
- players = []
- with open(player_file_path, 'r') as f:
- players = json.load(f)
- return players
- def fetch_from_api(url, id, keys: KeyPool, limiter):
- data = ""
- secret = keys.get_secret()
- trn_api_header = { 'TRN-Api-Key' : secret }
- limiter.next()
- fetch_url = f"{url}{id}"
- valid = False
- response = requests.get(
- fetch_url,
- headers = trn_api_header
- )
- try:
- data = response.json()
- except:
- data = {'message' : 'invalid non JSON response received.'}
- return data
- def touch(fname):
- if os.path.exists(fname):
- os.utime(fname, None)
- else:
- open(fname, 'a').close()
- ### Start main program
- keys = KeyPool(use_cap=10)
- for k in api_keys:
- keys.add_key(k['name'], k['secret'])
- start_utc = datetime.now(pytz.utc)
- start_local = start_utc.astimezone(pytz.timezone(local_timezone))
- if not options.quiet:
- print("\nTRN Fetch\n")
- print(f"Fetch run starting at {start_utc:%Y-%m-%d %H:%M:%S} UTC")
- print(f" {start_local:%Y-%m-%d %H:%M:%S} Local\n")
- logging.debug(f"Delayed start: {options.delay}")
- logging.debug(f"Complete mode: {options.complete}")
- logging.debug(f" Verbose mode: {options.verbose}\n")
- logging.debug(f"")
- # before starting
- # Determine our "run hour", which represents the UTC hour of the sample bucket.
- # We sample at 03, 07, 11, 15, 19, 23
- # (Every four hours, revised from the old script, which was almost every 4.
- # Put an hour into a bucket
- hour_buckets = ['23', '23', '23',
- '03', '03', '03', '03',
- '07', '07', '07', '07',
- '11', '11', '11', '11',
- '15', '15', '15', '15',
- '19', '19', '19', '19', '23']
- day_adjust = [-1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
- bucket_minute_cutoff = "44"
- run_hour = f"{start_utc:%H}"
- run_minute = f"{start_utc:%M}"
- hour_bucket = hour_buckets[int(run_hour)]
- logging.info(f"Run {run_hour}:{run_minute} for sample hour {hour_bucket}.")
- if run_hour == hour_bucket and run_minute < bucket_minute_cutoff:
- logging.warning(f"Exiting. Too early to start for initial sample hour {hour_bucket}")
- sys.exit()
- # Check if we need to run. If this is continuation run, we only want to do
- # the capture if we have files existing from a previous run
- skip_capture = False
- if run_hour != hour_bucket:
- # If there are no json files in the data directory, we don't need to run
- files=os.listdir(data_dir)
- existing = next((f for f in files if f[-5:] == ".json"), None)
- if existing is None:
- skip_capture = True
- if skip_capture:
- logging.info("Exiting. Previous run was completed.")
- sys.exit()
- # We need to adjust the time stamp for the 23 hour sample that spills over to tomorrow
- adjust = day_adjust[int(run_hour)]
- timestamp_date = start_utc + timedelta(days=adjust)
- timestamp = f"{timestamp_date:%Y%m%d}_{hour_bucket}-"
- logging.info(f"Timestamp tag is '{timestamp}'")
- logging.debug(f"Loading player info from {players_src}")
- players = player_list_load(players_src)
- to_do = players.copy()
- cycle = 0
- limiter = Throttle(1, 22.0) # TRN has a 20 second rate limit per call
- api_calls = 0
- complete = False
- delay = random.randint(0,options.pause_seconds)+20
- logging.debug(f"Holding for {delay} seconds to stagger start of API calls...")
- time.sleep(delay)
- while len(to_do)>0 and keys.key_available():
- successful = []
- failed = []
- incomplete = []
- cycle = cycle + 1
- if options.verbose:
- print(f"\n> Cycle {cycle} - players to do: {len(to_do)}.\n")
- random.shuffle(to_do)
- for p in to_do:
- player_name = p['name']
- player_id = p['id']
- player_data = f"{timestamp}{player_name}.json"
- data_path = os.path.join(data_dir, player_data)
- print(f"\n {p}")
- if os.path.isfile(data_path):
- if options.verbose:
- print(f" Data exists for {player_id}. Not fetching.")
- successful.append(p)
- continue
- if not keys.key_available():
- if options.verbose:
- print(f" No available key to fetch for {player_id}. Not fetching.")
- incomplete.append(p)
- continue
- api_calls = api_calls + 1
- if options.verbose:
- print(f" API call #{api_calls}:")
- data = fetch_from_api(trn_api_url, player_id, keys, limiter)
- if "data" in data:
- valid = True
- else:
- valid = False
- if "message" in data:
- message = data['message']
- if message=='API rate limit exceeded':
- keys.key_limited()
- if options.verbose:
- print(" Rate limit hit for key.")
- else:
- if options.verbose:
- print(f" Non valid message: {message}")
- print(f" data valid: {valid}")
- if valid:
- with open(data_path, 'w') as f:
- json.dump(data, f, indent = 4)
- successful.append(p)
- else:
- failed.append(p)
- if options.verbose:
- print(f"\n Successful data fetches: {len(successful)}")
- print(f"\n Failed data fetches: {len(failed)}")
- print(f"\n Incomplete data fetches: {len(incomplete)}")
- to_do = failed.copy() + incomplete.copy()
- # If there's no members left to process OR this is a forced "complete" run
- # (i.e. a run before the start of the next sample bucket) we write out the complete flag
- if len(to_do)==0 or options.complete:
- completed = True
- touch(complete_flag)
- if options.verbose:
- print("\nCompleted.")
- else:
- if options.verbose:
- print("\nDone for now, but more needs to done next hour.")
Advertisement
Add Comment
Please, Sign In to add comment