|
| 1 | +import json |
| 2 | +import os |
| 3 | +import requests |
| 4 | +import subprocess |
| 5 | + |
| 6 | +import dataclasses # to define the MCProdInfo data layout and convert it to dict |
| 7 | +from dataclasses import dataclass, field, asdict, fields |
| 8 | +from typing import Optional |
| 9 | +import hashlib |
| 10 | + |
| 11 | +@dataclass(frozen=True) |
| 12 | +class MCProdInfo: |
| 13 | + """ |
| 14 | + struct for MonteCarlo production info |
| 15 | + """ |
| 16 | + LPMProductionTag: str |
| 17 | + Col: int |
| 18 | + IntRate: float # only indicative of some interaction rate (could vary within the run) |
| 19 | + RunNumber: int |
| 20 | + OrbitsPerTF: int |
| 21 | + # max_events_per_tf: Optional[int] = -1 |
| 22 | + Comment: Optional[str] = None |
| 23 | + Hash: Optional[str] = field(default=None) |
| 24 | + |
| 25 | + def __post_init__(self): |
| 26 | + if self.Hash == None: |
| 27 | + # Hash only the meaningful fields |
| 28 | + data_to_hash = { |
| 29 | + k: v for k, v in asdict(self).items() |
| 30 | + if k != 'hash' |
| 31 | + } |
| 32 | + hash_str = hashlib.sha256( |
| 33 | + json.dumps(data_to_hash, sort_keys=True).encode() |
| 34 | + ).hexdigest() |
| 35 | + object.__setattr__(self, 'hash', hash_str) |
| 36 | + |
| 37 | + |
| 38 | +import re |
| 39 | + |
| 40 | +def extract_metadata_blocks_from_CCDB(text: str): |
| 41 | + blocks = [] |
| 42 | + # Split on 'Metadata:\n' and iterate over each block |
| 43 | + sections = text.split('Metadata:\n') |
| 44 | + for section in sections[1:]: # skip the first chunk (before any Metadata:) |
| 45 | + metadata = {} |
| 46 | + for line in section.splitlines(): |
| 47 | + if not line.strip(): # stop at first blank line |
| 48 | + break |
| 49 | + match = re.match(r'\s*(\w+)\s*=\s*(.+)', line) |
| 50 | + if match: |
| 51 | + key, val = match.groups() |
| 52 | + # Type conversion |
| 53 | + if val == "None": |
| 54 | + val = None |
| 55 | + elif val.isdigit() or (val.startswith('-') and val[1:].isdigit()): |
| 56 | + val = int(val) |
| 57 | + else: |
| 58 | + try: |
| 59 | + val = float(val) |
| 60 | + except ValueError: |
| 61 | + val = val.strip() |
| 62 | + metadata[key] = val |
| 63 | + if metadata: |
| 64 | + blocks.append(metadata) |
| 65 | + return blocks |
| 66 | + |
| 67 | + |
| 68 | + |
| 69 | +def query_mcprodinfo(base_url, user, run_number, lpm_prod_tag, cert_dir="/tmp"): |
| 70 | + """ |
| 71 | + Queries MCProdInfo from CCDB. Returns object or None |
| 72 | + """ |
| 73 | + # check if the tokenfiles are there |
| 74 | + key_path = os.environ.get("JALIEN_TOKEN_KEY") |
| 75 | + cert_path = os.environ.get("JALIEN_TOKEN_CERT") |
| 76 | + if key_path == None and cert_path == None: |
| 77 | + uid = os.getuid() |
| 78 | + cert_path = os.path.join(cert_dir, f"tokencert_{uid}.pem") |
| 79 | + key_path = os.path.join(cert_dir, f"tokenkey_{uid}.pem") |
| 80 | + |
| 81 | + # Build full URL |
| 82 | + user_path = 'Users/' + user[0] + '/' + user |
| 83 | + start = run_number |
| 84 | + stop = run_number + 1 |
| 85 | + url = f"{base_url}/browse/{user_path}/MCProdInfo/{lpm_prod_tag}/{start}/{stop}" |
| 86 | + |
| 87 | + response = requests.get(url, cert=(cert_path, key_path), verify=False) |
| 88 | + if response.status_code != 404: |
| 89 | + meta = extract_metadata_blocks_from_CCDB(response.content.decode('utf-8')) |
| 90 | + if (len(meta) > 0): |
| 91 | + def filter_known_fields(cls, data: dict) -> dict: |
| 92 | + valid_keys = {f.name for f in fields(cls)} |
| 93 | + return {k: v for k, v in data.items() if k in valid_keys} |
| 94 | + |
| 95 | + clean_meta = filter_known_fields(MCProdInfo, meta[0]) |
| 96 | + return MCProdInfo(**clean_meta) |
| 97 | + |
| 98 | + return None |
| 99 | + |
| 100 | + |
| 101 | +def upload_mcprodinfo_meta(base_url, user, run_number, lpm_prod_tag, keys, cert_dir="/tmp"): |
| 102 | + """ |
| 103 | + Uploads an empty .dat file using client certificates. |
| 104 | +
|
| 105 | + Parameters: |
| 106 | + - base_url (str): The base HTTPS URL, e.g., "https://URL" |
| 107 | + - user (str): The uploader --> Determines location "Users/f/foo_bar/MCProdInfo/..." |
| 108 | + - keys (dict): Dictionary with meta information to upload, e.g., {"key1": "var1", "key2": "var2"} |
| 109 | + - cert_dir (str): Directory where the .pem files are located (default: /tmp) |
| 110 | +
|
| 111 | + Returns: |
| 112 | + - Response object from the POST request |
| 113 | + """ |
| 114 | + # Create an empty file |
| 115 | + empty_file = "empty.dat" |
| 116 | + with open(empty_file, "w") as f: |
| 117 | + f.write("0") |
| 118 | + |
| 119 | + # Construct user ID-specific cert and key paths |
| 120 | + key_path = os.environ.get("JALIEN_TOKEN_KEY") |
| 121 | + cert_path = os.environ.get("JALIEN_TOKEN_CERT") |
| 122 | + if key_path == None and cert_path == None: |
| 123 | + uid = os.getuid() |
| 124 | + cert_path = os.path.join(cert_dir, f"tokencert_{uid}.pem") |
| 125 | + key_path = os.path.join(cert_dir, f"tokenkey_{uid}.pem") |
| 126 | + |
| 127 | + # Build full URL |
| 128 | + query = "/".join(f"{k}={v}" for k, v in keys.items()) |
| 129 | + user_path = 'Users/' + user[0] + '/' + user |
| 130 | + start = run_number |
| 131 | + stop = run_number + 1 |
| 132 | + url = f"{base_url}/{user_path}/MCProdInfo/{lpm_prod_tag}/{start}/{stop}/{query}" |
| 133 | + |
| 134 | + print (f"Full {url}") |
| 135 | + |
| 136 | + # Prepare request |
| 137 | + with open(empty_file, 'rb') as f: |
| 138 | + files = {'blob': f} |
| 139 | + response = requests.post(url, files=files, cert=(cert_path, key_path), verify=False) |
| 140 | + |
| 141 | + # Optional: remove the temporary file |
| 142 | + os.remove(empty_file) |
| 143 | + |
| 144 | + return response |
0 commit comments