Package Ganga :: Package Lib :: Package MonitoringServices :: Package Dashboard :: Module FormatUtil
[hide private]
[frames] | no frames]

Source Code for Module Ganga.Lib.MonitoringServices.Dashboard.FormatUtil

 1  """Formatting utilities. 
 2   
 3  These utilities are not Ganga-specific and may be externalized. 
 4   
 5  N.B. This code is under development and should not generally be used or relied upon. 
 6   
 7  """ 
 8   
 9  DETAILS_DATA_KEY = 'detailsData' 
10 -def dictToWlcg(msg, include_microseconds=True):
11 """Converts the given dictionary to WLCG message format. 12 13 @param msg: A dictionary of key value pairs. 14 @param include_microseconds: If microseconds should be included in the date 15 format, default True. 16 17 The keys and values are converted to strings using str() with the following 18 exceptions: 19 - if key is 'detailsData' and the value is a list or tuple, then its value 20 is converted to a multi-line string using str() for each item and the 21 WLCG-specified line separator. 22 - if value is None, then it is converted to an empty string. 23 - if value is an instance of datetime.datetime, and it is naive (i.e. it 24 contains no timezone info), then it is assumed to be UTC and converted 25 to the WLCG date format. i.e. YYYY-MM-DDTHH:MM:SS.mmmmmmZ or 26 YYYY-MM-DDTHH:MM:SSZ if include_microseconds is False. 27 28 Apart from detailsData, which is by definition the final entry, the entries 29 are sorted according to natural ordering. 30 31 See also: 32 - WLCG message format. 33 https://twiki.cern.ch/twiki/bin/view/LCG/GridMonitoringProbeSpecification#Message_Formats 34 - WLCG date format. 35 https://twiki.cern.ch/twiki/bin/view/LCG/GridMonitoringProbeSpecification#Date_Formats 36 37 """ 38 import datetime 39 lines = [] 40 for k, v in msg.iteritems(): 41 if k != DETAILS_DATA_KEY: 42 # if v is UTC datetime then format in WLCG DateFormat 43 if isinstance(v, datetime.datetime) and v.tzinfo is None: 44 # remove microseconds 45 if not include_microseconds: 46 v = v.replace(microsecond=0) 47 v = '%sZ' % v.isoformat() 48 if v is None: 49 v = '' 50 lines.append('%s: %s' % (k, v)) 51 lines.sort() 52 if DETAILS_DATA_KEY in msg: 53 dd = msg[DETAILS_DATA_KEY] 54 if isinstance(dd, (list, tuple)): 55 dd = '\n'.join(dd) 56 lines.append('%s: %s' % (DETAILS_DATA_KEY, dd)) 57 lines.append('EOT\n') 58 wlcg = '\n'.join(lines) 59 return wlcg
60 61 62 if __name__ == '__main__': 63 # test code 64 import datetime 65 msg = { 66 'a':1, 67 'b':2, 68 'c':datetime.datetime.utcnow(), 69 'd':None, 70 'detailsData': ['line 1', 'line 2'] 71 } 72 wlcg = dictToWlcg(msg) 73 print wlcg 74 print 75 wlcg = dictToWlcg(msg, include_microseconds=False) 76 print wlcg 77