ATLAS Offline Software
Loading...
Searching...
No Matches
dmtest_condwriter.py
Go to the documentation of this file.
1#!/usr/bin/env python
2#
3# Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
4#
5# Script to create an AthenaAttributeList with a single attribute "xint".
6# Usage example: dmtest_condwriter.py --rs=1 --ls=1 'sqlite://;schema=test.db;dbname=OFLP200' AttrList_noTag 42
7# CREST file system: dmtest_condwriter.py --rs=1 --ls=1 --tag=Test_AttrList_noTag --xint=42 --gtag=TEST-HLT-CREST --label='/DMTest/TestAttrList' --host='/tmp/crest_dump'
8
9import sys,os
10import argparse
11import json
12import tempfile
13os.environ['CLING_STANDARD_PCH'] = 'none' #See bug ROOT-10789
14from PyCool import cool
15from CoolConvUtilities import AtlCoolLib, AtlCoolTool
16from pycrest.api.crest_api import CrestApi
17from pycrest.api.crest_fs_api import CrestApiFs
18from hep.crest.client.models import (
19 TagMetaSetDto, TagMetaDto, TagDto, GlobalTagDto,
20 GlobalTagMapDto, GlobalTagMapSetDto, StoreSetDto, StoreDto)
21
22import logging
23log = logging.getLogger('dmtest_condwriter')
24
25class createTestDB(AtlCoolLib.coolTool):
26
27 def setup(self,args):
28 # set values of non-optional parameters
29 self.tag=str(args[0])
30 self.xint=int(args[1])
31 self.folder=args[2] if len(args)>2 else '/DMTest/TestAttrList'
32
33 def usage(self):
34 """ Define the additional syntax for options """
35 self._usage1()
36 print ('TAG xint [Folder]')
37 self._usage2()
38
39 def execute(self):
40
41 # do update - setup folder specification and create if needed
42 spec = cool.RecordSpecification()
43 spec.extend("xint", cool.StorageType.Int32)
44 print (">== Store object in folder", self.folder)
45 cfolder = AtlCoolLib.ensureFolder(self.db, self.folder, spec,
46 AtlCoolLib.athenaDesc(self.runLumi, 'AthenaAttributeList'),
47 cool.FolderVersioning.MULTI_VERSION)
48 if (cfolder is None): sys.exit(1)
49 # now write data
50 payload = cool.Record(spec)
51 payload['xint'] = self.xint
52 print ('>== Store object with IOV [',self.since,',',self.until,'] and tag',self.tag,'xint',self.xint)
53 try:
54 if (self.tag=="HEAD"):
55 cfolder.storeObject(self.since,self.until,payload,0)
56 else:
57 cfolder.storeObject(self.since,self.until,payload,0,self.tag)
58 print (">== Storing COOL object succeeded. Current content:")
59 except Exception:
60 import traceback
61 traceback.print_exc()
62 print ('>== Storing COOL object FAILED')
63 sys.exit(1)
64
65 # print full content
66 act = AtlCoolTool.AtlCoolTool(self.db)
67 print (act.more(self.folder))
68
69
70def store_in_crest(parser):
71 """
72 Store xint into CREST
73 """
74 args, unknown = parser.parse_known_args()
75
76 def require_arg(arg_val, arg_name):
77 if arg_val is None:
78 parser.print_help()
79 sys.exit(1)
80 return arg_val
81
82 if not args.remove:
83 runNumber = require_arg(args.r, 'r')
84 lumiSince = require_arg(args.ls, 'ls')
85 xint = require_arg(args.xint, 'xint')
86
87 # Required in all cases
88 host = require_arg(args.host, 'host')
89 tag = require_arg(args.tag, 'tag')
90 gtag = require_arg(args.gtag, 'gtag')
91 label = require_arg(args.label, 'label')
92
93 # Optional with default
94 record = args.record if args.record is not None else 'test_record'
95
96 if args.remove and host.startswith(tempfile.gettempdir()):
97 print("Only remove tag from CREST server")
98 sys.exit(1)
99
100 # Instantiate the CREST API
101 if host.startswith(tempfile.gettempdir()):
102 api_instance = CrestApiFs(host)
103 log.debug('>== Using CREST file system')
104 else:
105 log.debug(f'>== Using CREST server: {host}')
106 api_instance = CrestApi(host=host)
107
108 # Create or find the global tag
109 gtag_dto=GlobalTagDto(
110 name=gtag,
111 description='Test global tag for hlt workflow',
112 release='2.0',
113 scenario='test',
114 workflow='T',
115 validity=0,
116 type='t'
117 )
118
119 log.debug(f'>== Looking for global tag {gtag} in CREST ...')
120 try:
121 existing_gtag = None
122 if host.startswith('http'):
123 existing_gtag = api_instance.find_global_tag(name=gtag)
124 elif os.path.exists(f'{host}/globaltags/{gtag}/globaltag.json'):
125 existing_gtag = api_instance.find_global_tag(name=gtag)
126 if existing_gtag is not None and isinstance(existing_gtag, GlobalTagDto):
127 log.debug(f'>== Found existing global tag {existing_gtag.name}. Will not recreate.')
128 else:
129 log.debug(f'>== Creating new global tag: {gtag}')
130 if host.startswith('http'):
131 api_response = api_instance.create_global_tag(gtag_dto,'false')
132 else:
133 api_response = api_instance.create_global_tag(gtag_dto)
134 if isinstance(api_response, GlobalTagDto):
135 log.debug(f'>== Created global tag: {api_response.name}')
136 else:
137 print(f'>== Error creating global tag {gtag}: {api_response}')
138 sys.exit(1)
139 except Exception as e:
140 print('Exception when calling CrestApi->create_global_tag:')
141 print(e)
142 sys.exit(1)
143
144 # If remove is specified, remove the tag
145 if args.remove:
146 log.debug(f'>== Removing global tag map for tag: {tag}')
147 try:
148 api_instance.delete_global_tag_map(gtag, tag, label)
149 except Exception as e:
150 print('Exception when calling CrestApi->delete_global_tag_map:')
151 print(e)
152 sys.exit(1)
153 log.debug(f'>== Removing tag with name: {tag}')
154 try:
155 api_instance.remove_tag(tag)
156 except Exception as e:
157 print('Exception when calling CrestApi->remove_tag:')
158 print(e)
159 sys.exit(1)
160 return
161
162 # Tag description
163 description = '<timeStamp>run-lumi</timeStamp><addrHeader><address_header service_type=\"71\" clid=\"40774348\" /></addrHeader><typeName>AthenaAttributeList</typeName>'
164
165 tag_info = {
166 'channel_list': [{'0': 'channel_0'}],
167 'node_description': description,
168 'payload_spec': [{'xint':'Int32'}]
169 }
170
171 # Create or find the tag
172 tag_dto = TagDto(
173 name=tag,
174 description=description,
175 time_type='run-lumi',
176 payload_spec='xint:Int32',
177 status='UNLOCKED',
178 synchronization='ALL',
179 last_validated_time=-1,
180 end_of_validity=-1
181 )
182
183 tag_meta_dto = TagMetaDto(
184 tag_name=tag,
185 description=description,
186 tag_info=json.dumps(tag_info),
187 chansize=1,
188 colsize=1
189 )
190
191 log.debug(f'>== Looking for tag {tag} in CREST ...')
192 try:
193 existing_tag = None
194 if host.startswith('http'):
195 existing_tag = api_instance.find_tag(name=tag)
196 elif os.path.exists(f'{host}/tags/{tag}/tag.json'):
197 existing_tag = api_instance.find_tag(name=tag)
198 if existing_tag and isinstance(existing_tag, TagDto):
199 log.debug(f'>== Found existing tag {existing_tag.name}. Will not recreate.')
200 else:
201 log.debug(f'>== Creating new tag: {tag}')
202 api_response = api_instance.create_tag(tag_dto)
203 if isinstance(api_response, TagDto):
204 log.debug(f'>== Created new tag with name: {api_response.name}')
205 else:
206 print(f'>== Error creating tag {tag}: {api_response}')
207 sys.exit(1)
208 except Exception as e:
209 print('Exception when calling CrestApi->create_tag:')
210 print(e)
211 sys.exit(1)
212
213 # Create or find tag metadata
214 log.debug(f'>== Looking for tag metadata for tag {tag} ...')
215 try:
216 tag_meta = None
217 if host.startswith('http'):
218 tag_meta = api_instance.find_tag_meta(name=tag)
219 elif os.path.exists(f'{host}/tags/{tag}/tagmetainfo.json'):
220 tag_meta = api_instance.find_tag_meta(name=tag)
221 if tag_meta and isinstance(tag_meta, TagMetaSetDto) and len(tag_meta.resources) > 0:
222 log.debug(f'>== Found existing metadata for tag {tag_meta.resources[0].tag_name}. Will not recreate.')
223 elif tag_meta and isinstance(tag_meta, TagMetaDto):
224 log.debug(f'>== Found existing metadata for tag {tag_meta.tag_name}. Will not recreate.')
225 else:
226 log.debug(f'>== Creating new tag metadata for tag: {tag}')
227 api_response = api_instance.create_tag_meta(tag_meta_dto)
228 if isinstance(api_response, TagMetaDto):
229 log.debug(f'>== Created tag meta for tag: {api_response.tag_name}')
230 else:
231 print(f'>== Error creating tag meta for tag {tag}: {api_response}')
232 sys.exit(1)
233 except Exception as e:
234 print('Exception when calling CrestApi->create_tag_meta:')
235 print(e)
236 sys.exit(1)
237
238 # Prepare the actual payload
239 # If runNumber and lumiSince are set, we store at that run-lumi
240 # We'll store the same integer in 'xint'
241 sinfo = {'run-lumi': f'{runNumber}-{lumiSince}'}
242 lumi_pyld = {'0': [int(xint)]}
243
244 # We will store at the 'since' = lumiSince
245 sdto = StoreDto(
246 since=int(lumiSince),
247 data=json.dumps(lumi_pyld),
248 streamer_info=json.dumps(sinfo)
249 )
250 ssdto = StoreSetDto(
251 size=1,
252 format="StoreSetDto",
253 datatype="data",
254 resources=[sdto]
255 )
256
257 log.debug(f'>== Storing data in CREST: tag={tag}, run={runNumber}, LB={lumiSince}, xint={xint}')
258 try:
259 api_response = api_instance.store_data(tag=tag, store_set=ssdto)
260 except Exception as e:
261 print('Exception when calling CrestApi->store_data:')
262 print(e)
263 sys.exit(1)
264
265 # Finally, create or find the global tag map
266 global_tag_map_dto = GlobalTagMapDto(
267 global_tag_name=gtag,
268 record=record,
269 label=label,
270 tag_name=tag
271 )
272 log.debug(f'>== Checking/Creating global tag map for tag={tag}, gtag={gtag}, label={label}')
273 try:
274 globalTagMap = None
275 if host.startswith('http'):
276 globalTagMap = api_instance.find_global_tag_map(name=tag, mode='BackTrace')
277 elif os.path.exists(f'{host}/globaltags/{gtag}/maps.json'):
278 globalTagMap = api_instance.find_global_tag_map(name=gtag)
279 if isinstance(globalTagMap, GlobalTagMapSetDto) and len(globalTagMap.resources) > 0:
280 log.debug(f'>== Found existing global tag map entries for tag {tag}. Will not recreate.')
281 else:
282 log.debug(f'>== Creating global tag map for tag: {tag}')
283 api_instance.create_global_tag_map(global_tag_map_dto)
284 except Exception as e:
285 print('Exception when calling CrestApi->create_global_tag_map:')
286 print(e)
287 sys.exit(1)
288
289
290def main():
291
292 parser = argparse.ArgumentParser(
293 description='CREST Commands',
294 formatter_class=argparse.RawDescriptionHelpFormatter,
295 epilog=(
296 "Required to create a tag:\n"
297 "--host=<host url or path> --tag=<tag> --gtag=<global tag> --label=<label> --r=<run number> --ls=<lumi since> --xint=<payload>\n\n"
298 "Required to remove a tag:\n"
299 "--remove --host=<host url> --tag=<tag> --gtag=<global tag> --label=<label>"
300 )
301 )
302
303 # CREST-related arguments
304 parser.add_argument('--host', default=None, help='Host URL of the CREST service')
305 parser.add_argument('--tag', default=None, help='CREST tag name')
306 parser.add_argument('--gtag', default=None, help='CREST global tag name')
307 parser.add_argument('--label', default=None, help='Label used in the global tag map')
308 parser.add_argument('--record', default=None, help='Record name for the global tag map')
309 parser.add_argument('--remove', action='store_true', help='Remove the specified CREST tag')
310 parser.add_argument('--r', type=int, default=int(0), help='Single run number (for CREST run-lumi info)')
311 parser.add_argument('--ls', type=int, default=None, help='Single lumi block (for CREST run-lumi info)')
312 parser.add_argument('--xint', type=int, default=None,
313 help='Integer payload value to store in COOL and/or CREST')
314 parser.add_argument('--debug', action='store_true', help='Enable debugging information')
315
316 args, unknown = parser.parse_known_args()
317
318 logging_level = logging.ERROR
319 if args.debug:
320 logging_level = logging.DEBUG
321 logging.basicConfig(level=logging_level, format = "%(name)s %(levelname)s: %(message)s")
322
323 # If host is not found, do COOL storage
324 if args.host is None:
325 createTestDB('dmtest_condwriter.py',False,3,4,[])
326 else:
327 store_in_crest(parser)
328
329if __name__ == "__main__":
330 main()
331
void print(char *figname, TCanvas *c1)
StatusCode usage()