55from wsdbtools import ConnectionWithTransactions
66import functools , traceback
77
8+
89def log_exceptions (f ):
9- ''' decorator logging exceptions and not letting them past '''
10+ """decorator logging exceptions and not letting them past"""
11+
1012 @functools .wraps (f )
11- def wrapper ( self , * args , ** kwargs ):
13+ def wrapper (self , * args , ** kwargs ):
1214 try :
13- return f ( self , * args , ** kwargs )
15+ return f (self , * args , ** kwargs )
1416 except Exception :
15- self .log (traceback .format_exc ())
16- return None
17+ self .log (traceback .format_exc ())
18+ return None
19+
1720 return wrapper
1821
22+
1923class MetaCatDaemon (Logged ):
20-
2124 def __init__ (self , config ):
2225 Logged .__init__ (self , "MetaCatDaemon" )
2326
2427 ssl_config = config .get ("ssl" , {})
25- self .CertFile = ssl_config .get ("cert" )
28+ self .CertFile = ssl_config .get ("cert" , None )
2629 self .KeyFile = ssl_config .get ("key" , self .CertFile )
27-
30+ self .TokenFile = ssl_config .get ("token" , None )
31+
2832 daemon_config = config ["daemon" ]
2933 self .FerryURL = daemon_config ["ferry_url" ]
30- if self .FerryURL .lower ().startswith ("https:" ) and not (self .CertFile and self .KeyFile ):
31- raise ValueError ("X.509 cert and key files are not in the conficuration" )
32-
33- self .FerryUpdateInterval = daemon_config .get ("ferry_update_interval" , 1 * 3600 )
34- self .CountsUpdateInterval = daemon_config .get ("counts_update_interval" , 1 * 3600 )
34+ if self .FerryURL .lower ().startswith ("https:" ) and not (
35+ (self .CertFile and self .KeyFile ) or self .TokenFile
36+ ):
37+ raise ValueError ("Token file, or X.509 cert and key files are not in the configuration" )
38+
39+ self .FerryUpdateInterval = daemon_config .get ("ferry_update_interval" , 1 * 3600 )
40+ self .CountsUpdateInterval = daemon_config .get ("counts_update_interval" , 1 * 3600 )
3541 self .VO = daemon_config ["vo" ]
3642
3743 db_config = config ["database" ]
@@ -42,16 +48,20 @@ def __init__(self, config):
4248
4349 self .Queue = TaskQueue (5 , delegate = self )
4450 self .Queue .append (self .ferry_update , interval = self .FerryUpdateInterval , after = time .time ())
45- self .Queue .append (self .update_dataset_file_counts , interval = self .CountsUpdateInterval , after = 0 ) #self.CountsUpdateInterval//3)
46- self .Queue .append (self .update_namespace_file_counts , interval = self .CountsUpdateInterval , after = 0 ) #2*self.CountsUpdateInterval//3)
51+ self .Queue .append (
52+ self .update_dataset_file_counts , interval = self .CountsUpdateInterval , after = 0
53+ ) # self.CountsUpdateInterval//3)
54+ self .Queue .append (
55+ self .update_namespace_file_counts , interval = self .CountsUpdateInterval , after = 0
56+ ) # 2*self.CountsUpdateInterval//3)
4757 self .debug ("tasks enqueued" )
48-
58+
4959 def db (self ):
5060 db = psycopg2 .connect (self .DBConnect )
5161 if self .Schema :
5262 db .cursor ().execute (f"set search_path to { self .Schema } " )
5363 return ConnectionWithTransactions (db )
54-
64+
5565 @log_exceptions
5666 def update_dataset_file_counts (self ):
5767 db = self .db ()
@@ -77,8 +87,21 @@ def ferry_update(self):
7787 self .debug ("ferry_update..." )
7888 url = f"{ self .FerryURL } /getAffiliationMembersRoles?unitname={ self .VO } "
7989
90+ # Authentication...
8091 self .debug ("ferry URL:" , url )
81- response = requests .get (url , verify = False , cert = (self .CertFile , self .KeyFile ))
92+ if self .CertFile :
93+ cert = (self .CertFile , self .KeyFile )
94+ else :
95+ cert = None
96+
97+ if self .TokenFile :
98+ with open (self .TokenFile , "r" ) as tf :
99+ token = tf .read ().strip ()
100+ headers = {"Authorization" : "Bearer " + token }
101+ else :
102+ headers = None
103+
104+ response = requests .get (url , verify = False , cert = cert , headers = headers )
82105 data = response .json ()
83106 self .debug ("data received" )
84107
@@ -94,14 +117,22 @@ def ferry_update(self):
94117
95118 db = self .db ()
96119 db_users = {u .Username : u for u in DBUser .list (db )}
97-
120+
98121 ncreated = nupdated = 0
99122 updated = []
100123 created = []
101124 for username , ferry_user in ferry_users .items ():
102125 db_user = db_users .get (username )
103126 if db_user is None :
104- new_user = DBUser (db , username , ferry_user .get ("fullname" , "" ), None , "" , None , ferry_user .get ("tokensubject" ))
127+ new_user = DBUser (
128+ db ,
129+ username ,
130+ ferry_user .get ("fullname" , "" ),
131+ None ,
132+ "" ,
133+ None ,
134+ ferry_user .get ("tokensubject" ),
135+ )
105136 new_user .save ()
106137 ncreated += ncreated
107138 created .append (username )
@@ -124,27 +155,30 @@ def ferry_update(self):
124155 self .log ("updated:" , len (updated ), "" if not updated else "," .join (updated ))
125156 db .close ()
126157
158+
127159Usage = """
128160daemon.py -c <config.yaml> [-d] [-l <log path>]
129161"""
130-
162+
163+
131164def main ():
132165 import sys , getopt , yaml , time
133166
134167 opts , args = getopt .getopt (sys .argv [1 :], "l:c:dh?" , ["help" ])
135168 opts = dict (opts )
136-
169+
137170 if "-c" not in opts or "-?" in opts or "-h" in opts or "--help" in opts :
138171 print (Usage )
139172 sys .exit (2 )
140-
173+
141174 config = yaml .load (open (opts ["-c" ], "r" ), Loader = yaml .SafeLoader )
142175 log_file = opts .get ("-l" , "-" )
143176 init_logs (log_file , error_out = log_file , debug_out = log_file , debug_enabled = "-d" in opts )
144-
177+
145178 daemon = MetaCatDaemon (config )
146179 while True :
147180 time .sleep (10 )
148-
181+
182+
149183if __name__ == "__main__" :
150184 main ()
0 commit comments