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
|
#!/usr/bin/env python3
from datetime import datetime
import configparser as ConfigParser
import json
import optparse
import os
import sqlalchemy
import string
import subprocess
import sys
import CondCore.Utilities.conddblib as conddb
##############################################
def getCommandOutput(command):
##############################################
"""This function executes `command` and returns it output.
Arguments:
- `command`: Shell command to be invoked by this function.
"""
child = os.popen(command)
data = child.read()
err = child.close()
if err:
print ('%s failed w/ exit code %d' % (command, err))
sys.exit(1) # This will stop the script immediately with the failure exit code
print(data)
return data
##############################################
def getCerts() -> str:
##############################################
cert_path = os.getenv('X509_USER_CERT', '')
key_path = os.getenv('X509_USER_KEY', '')
certs = ""
if cert_path:
certs += f' --cert {cert_path}'
else:
print("No certificate, nor proxy provided for Tier0 access")
if key_path:
certs += f' --key {key_path}'
return certs
##############################################
def build_curl_command(url, proxy="", certs="", timeout=30, retries=3, user_agent="MyUserAgent"):
##############################################
"""Builds the curl command with the appropriate proxy, certs, and options."""
cmd = f'/usr/bin/curl -k -L --user-agent "{user_agent}" '
if proxy:
cmd += f'--proxy {proxy} '
else:
cmd += f'{certs} '
cmd += f'--connect-timeout {timeout} --retry {retries} {url}'
return cmd
##############################################
def get_hlt_fcsr(session):
##############################################
RunInfo = session.get_dbtype(conddb.RunInfo)
lastRun = session.query(sqlalchemy.func.max(RunInfo.run_number)).scalar()
fcsr = lastRun+1
return int(fcsr)
##############################################
def fetch_data_from_url(url, proxy="", certs=""):
##############################################
cmd = build_curl_command(url, proxy=proxy, certs=certs)
try:
out = subprocess.check_output(cmd, shell=True)
except subprocess.CalledProcessError as e:
print(f"Error executing curl command: {e}")
return None
if not out.strip():
print("Received an empty response from the server.")
return None
try:
response = json.loads(out)
except json.JSONDecodeError as e:
print(f"Failed to decode JSON: {e}")
print(f"Raw output was: {out}")
return None
# Ensure the expected structure is there
if "result" not in response or len(response["result"]) == 0:
print("Unexpected response format or empty result.")
return None
return response["result"][0] # Return the first result entry (this is where individual functions can extract specific fields)
##############################################
def getFCSR(proxy="", certs=""):
##############################################
url = "https://cmsweb.cern.ch/t0wmadatasvc/prod/firstconditionsaferun"
response = fetch_data_from_url(url, proxy, certs)
if response is None:
return None
return int(response) # Assuming 'response' is already an integer value in this case
##############################################
def getPromptGT(proxy="", certs=""):
##############################################
url = "https://cmsweb.cern.ch/t0wmadatasvc/prod/reco_config"
response = fetch_data_from_url(url, proxy, certs)
if response is None:
return None
return response.get('global_tag')
##############################################
def getExpressGT(proxy="", certs=""):
##############################################
url = "https://cmsweb.cern.ch/t0wmadatasvc/prod/express_config"
response = fetch_data_from_url(url, proxy, certs)
if response is None:
return None
return response.get('global_tag')
##############################################
def _getFCSR(proxy="", certs=""):
##############################################
url = "https://cmsweb.cern.ch/t0wmadatasvc/prod/firstconditionsaferun"
cmd = build_curl_command(url, proxy=proxy, certs=certs)
out = subprocess.check_output(cmd, shell=True)
response = json.loads(out)["result"][0]
return int(response)
##############################################
def _getPromptGT(proxy="", certs=""):
##############################################
url = "https://cmsweb.cern.ch/t0wmadatasvc/prod/reco_config"
cmd = build_curl_command(url, proxy=proxy, certs=certs)
out = subprocess.check_output(cmd, shell=True)
response = json.loads(out)["result"][0]['global_tag']
return response
##############################################
def _getExpressGT(proxy="", certs=""):
##############################################
url = "https://cmsweb.cern.ch/t0wmadatasvc/prod/express_config"
cmd = build_curl_command(url, proxy=proxy, certs=certs)
out = subprocess.check_output(cmd, shell=True)
response = json.loads(out)["result"][0]['global_tag']
return response
##############################################
def resetSynchonization(db_name):
##############################################
import sqlite3
# Connect to the SQLite database
conn = sqlite3.connect(db_name)
# Create a cursor object to execute SQL commands
cursor = conn.cursor()
# Execute the SQL command to update the database
cursor.execute("UPDATE TAG SET SYNCHRONIZATION='any' WHERE SYNCHRONIZATION='express';")
# Commit the changes and close the connection
conn.commit()
conn.close()
##############################################
if __name__ == "__main__":
##############################################
parser = optparse.OptionParser(usage = 'Usage: %prog [options] <file> [<file> ...]\n')
parser.add_option('-t', '--validationTag',
dest = 'validationTag',
default = "SiStripApvGainAfterAbortGap_PCL_multirun_v0_prompt",
help = 'validation tag',
)
parser.add_option('-s', '--since',
dest = 'since',
default = -1,
help = 'sinces to copy from validation tag',
)
parser.add_option('-p', '--proxy',
dest = 'proxy',
default = "",
help = 'proxy to use for curl requests',
)
parser.add_option('-u', '--user-mode',
dest='user_mode',
action='store_true',
default=False,
help='Enable user mode with specific X509 user certificate and key')
(options, arguments) = parser.parse_args()
if options.user_mode:
os.environ['X509_USER_KEY'] = os.path.expanduser('~/.globus/userkey.pem')
os.environ['X509_USER_CERT'] = os.path.expanduser('~/.globus/usercert.pem')
print("User mode enabled. Using X509_USER_KEY and X509_USER_CERT from ~/.globus/")
certs = ""
if not options.proxy:
certs = getCerts()
FCSR = getFCSR(proxy=options.proxy, certs=certs)
promptGT = getPromptGT(proxy=options.proxy, certs=certs)
expressGT = getExpressGT(proxy=options.proxy, certs=certs)
con = conddb.connect(url = conddb.make_url("pro"))
session = con.session()
HLTFCSR = get_hlt_fcsr(session)
print ("Current next HLT run", HLTFCSR, "| curret FCSR:", FCSR ,"| Express Global Tag",expressGT,"| Prompt Global Tag",promptGT)
IOV = session.get_dbtype(conddb.IOV)
TAG = session.get_dbtype(conddb.Tag)
GT = session.get_dbtype(conddb.GlobalTag)
GTMAP = session.get_dbtype(conddb.GlobalTagMap)
RUNINFO = session.get_dbtype(conddb.RunInfo)
myGTMap = session.query(GTMAP.record, GTMAP.label, GTMAP.tag_name).\
filter(GTMAP.global_tag_name == str(expressGT)).\
order_by(GTMAP.record, GTMAP.label).\
all()
# Check if the query result is empty
if not myGTMap:
print("No records found in the GTMap.")
sys.exit(1)
## connect to prep DB and get the list of IOVs to look at
con2 = conddb.connect(url = conddb.make_url("dev"))
session2 = con2.session()
validationTagIOVs = session2.query(IOV.since,IOV.payload_hash,IOV.insertion_time).filter(IOV.tag_name == options.validationTag).all()
### fill the list of IOVs to be validated
IOVsToValidate=[]
if(options.since==-1):
IOVsToValidate.append(validationTagIOVs[-1][0])
print("Changing the default validation tag since to:",IOVsToValidate[0])
else:
for entry in validationTagIOVs:
if(options.since!=1 and int(entry[0])>=int(options.since)):
print("Appending to the validation list:",entry[0],entry[1],entry[2])
IOVsToValidate.append(entry[0])
for element in myGTMap:
#print element
Record = element[0]
Label = element[1]
Tag = element[2]
if(Record=="SiStripApvGain2Rcd"):
TagIOVs = session.query(IOV.since,IOV.payload_hash,IOV.insertion_time).filter(IOV.tag_name == Tag).all()
sorted_TagIOVs = sorted(TagIOVs, key=lambda x: x[0])
lastG2Payload = sorted_TagIOVs[-1]
print("Last G2 Prompt payload has IOV since:",lastG2Payload[0],"payload hash:",lastG2Payload[1],"insertion time:",lastG2Payload[2])
# Get and print the current working directory
current_directory = os.getcwd()
print("Current Working Directory:", current_directory)
# Construct the conddb_import command using f-strings for better readability
command = (
f'conddb_import -c sqlite_file:toCompare.db '
f'-f frontier://FrontierProd/CMS_CONDITIONS '
f'-i {Tag} -t {Tag} -b {lastG2Payload[0]}'
)
print(command)
getCommandOutput(command)
# set syncrhonization to any
resetSynchonization("toCompare.db")
for i,theValidationTagSince in enumerate(IOVsToValidate):
# Construct the conddb_import command, modifying the 'since' value if necessary
since_value = HLTFCSR + i if theValidationTagSince < lastG2Payload[0] else theValidationTagSince
command = (
f'conddb_import -c sqlite_file:toCompare.db '
f'-f frontier://FrontierPrep/CMS_CONDITIONS '
f'-i {options.validationTag} -t {Tag} -b {since_value}'
)
# Print and execute the conddb_import command
if theValidationTagSince < lastG2Payload[0]:
print("The last available IOV in the validation tag is older than the current last express IOV, taking Express FCSR (HLT) as a since!")
print(command)
getCommandOutput(command)
# Construct the testCompareSiStripG2Gains.sh command, adjusting the 'since' value similarly
since_value = HLTFCSR + i if theValidationTagSince < lastG2Payload[0] else theValidationTagSince
command = (
f'${{CMSSW_BASE}}/src/CondCore/SiStripPlugins/scripts/testCompareSiStripG2Gains.sh '
f'{Tag} {lastG2Payload[0]} {since_value} {current_directory}/toCompare.db'
)
# Print and execute the testCompareSiStripG2Gains.sh command
print(command)
getCommandOutput(command)
|