github.com/docker/app@v0.9.1-beta3.0.20210611140623-a48f773ab002/examples/dockercoins/worker/worker.py (about)

     1  import logging
     2  import os
     3  from redis import Redis
     4  import requests
     5  import time
     6  
     7  DEBUG = os.environ.get("DEBUG", "").lower().startswith("y")
     8  
     9  log = logging.getLogger(__name__)
    10  if DEBUG:
    11      logging.basicConfig(level=logging.DEBUG)
    12  else:
    13      logging.basicConfig(level=logging.INFO)
    14      logging.getLogger("requests").setLevel(logging.WARNING)
    15  
    16  
    17  redis = Redis("redis")
    18  
    19  
    20  def get_random_bytes():
    21      r = requests.get("http://rng/32")
    22      return r.content
    23  
    24  
    25  def hash_bytes(data):
    26      r = requests.post("http://hasher/",
    27                        data=data,
    28                        headers={"Content-Type": "application/octet-stream"})
    29      hex_hash = r.text
    30      return hex_hash
    31  
    32  
    33  def work_loop(interval=1):
    34      deadline = 0
    35      loops_done = 0
    36      while True:
    37          if time.time() > deadline:
    38              log.info("{} units of work done, updating hash counter"
    39                       .format(loops_done))
    40              redis.incrby("hashes", loops_done)
    41              loops_done = 0
    42              deadline = time.time() + interval
    43          work_once()
    44          loops_done += 1
    45  
    46  
    47  def work_once():
    48      log.debug("Doing one unit of work")
    49      time.sleep(0.1)
    50      random_bytes = get_random_bytes()
    51      hex_hash = hash_bytes(random_bytes)
    52      if not hex_hash.startswith('0'):
    53          log.debug("No coin found")
    54          return
    55      log.info("Coin found: {}...".format(hex_hash[:8]))
    56      created = redis.hset("wallet", hex_hash, random_bytes)
    57      if not created:
    58          log.info("We already had that coin")
    59  
    60  
    61  if __name__ == "__main__":
    62      while True:
    63          try:
    64              work_loop()
    65          except:
    66              log.exception("In work loop:")
    67              log.error("Waiting 10s and restarting.")
    68              time.sleep(10)
    69  
    70