1 """GNUmed configuration handling.
2
3 Two sources of configuration information are supported:
4
5 - database tables
6
7 Theory of operation:
8
9 It is helpful to have a solid log target set up before importing this
10 module in your code. This way you will be able to see even those log
11 messages generated during module import.
12
13 Once your software has established database connectivity you can
14 set up a config source from the database. You can limit the option
15 applicability by the constraints "workplace", "user", and "cookie".
16
17 The basic API for handling items is get()/set().
18 The database config objects auto-syncs with the backend.
19
20 @copyright: GPL
21 """
22
23
24
25
26 __version__ = "$Revision: 1.60 $"
27 __author__ = "Karsten Hilbert <Karsten.Hilbert@gmx.net>"
28
29
30 import sys, types, cPickle, decimal, logging, re as regex
31
32
33
34 if __name__ == '__main__':
35 sys.path.insert(0, '../../')
36 from Gnumed.pycommon import gmPG2, gmTools
37
38
39 _log = logging.getLogger('gm.cfg')
40 _log.info(__version__)
41
42
43
44 cfg_DEFAULT = "xxxDEFAULTxxx"
45
46
50
51
52
53 - def get2(self, option=None, workplace=None, cookie=None, bias=None, default=None, sql_return_type=None):
54 """Retrieve configuration option from backend.
55
56 @param bias: Determine the direction into which to look for config options.
57
58 'user': When no value is found for "current_user/workplace" look for a value
59 for "current_user" regardless of workspace. The corresponding concept is:
60
61 "Did *I* set this option anywhere on this site ? If so, reuse the value."
62
63 'workplace': When no value is found for "current_user/workplace" look for a value
64 for "workplace" regardless of user. The corresponding concept is:
65
66 "Did anyone set this option for *this workplace* ? If so, reuse that value."
67 @param default: if no value is found for the option this value is returned
68 instead, also the option is set to this value in the backend, if <None>
69 a missing option will NOT be created in the backend
70 @param sql_return_type: a PostgreSQL type the value of the option is to be
71 cast to before returning, if None no cast will be applied, you will
72 want to make sure that sql_return_type and type(default) are compatible
73 """
74
75
76
77 if None in [option, workplace]:
78 raise ValueError, 'neither <option> (%s) nor <workplace> (%s) may be [None]' % (option, workplace)
79 if bias not in ['user', 'workplace']:
80 raise ValueError, '<bias> must be "user" or "workplace"'
81
82
83 cmd = u"select type from cfg.cfg_template where name=%(opt)s"
84 rows, idx = gmPG2.run_ro_queries(link_obj=self.ro_conn, queries = [{'cmd': cmd, 'args': {'opt': option}}])
85 if len(rows) == 0:
86
87 if default is None:
88
89 return None
90 _log.info('creating option [%s] with default [%s]' % (option, default))
91 success = self.set(workplace = workplace, cookie = cookie, option = option, value = default)
92 if not success:
93
94 _log.error('creating option failed')
95 return default
96
97 cfg_table_type_suffix = rows[0][0]
98 args = {
99 'opt': option,
100 'wp': workplace,
101 'cookie': cookie,
102 'def': cfg_DEFAULT
103 }
104
105 if cfg_table_type_suffix == u'data':
106 sql_return_type = u''
107 else:
108 sql_return_type = gmTools.coalesce (
109 initial = sql_return_type,
110 instead = u'',
111 template_initial = u'::%s'
112 )
113
114
115 where_parts = [
116 u'vco.owner = CURRENT_USER',
117 u'vco.workplace = %(wp)s',
118 u'vco.option = %(opt)s'
119 ]
120 where_parts.append(gmTools.coalesce (
121 initial = cookie,
122 instead = u'vco.cookie is null',
123 template_initial = u'vco.cookie = %(cookie)s'
124 ))
125 cmd = u"select vco.value%s from cfg.v_cfg_opts_%s vco where %s limit 1" % (
126 sql_return_type,
127 cfg_table_type_suffix,
128 u' and '.join(where_parts)
129 )
130 rows, idx = gmPG2.run_ro_queries(link_obj=self.ro_conn, queries = [{'cmd': cmd, 'args': args}])
131 if len(rows) > 0:
132 if cfg_table_type_suffix == u'data':
133 return cPickle.loads(str(rows[0][0]))
134 return rows[0][0]
135
136 _log.warning('no user AND workplace specific value for option [%s] in config database' % option)
137
138
139 if bias == 'user':
140
141 where_parts = [
142 u'vco.option = %(opt)s',
143 u'vco.owner = CURRENT_USER',
144 ]
145 else:
146
147 where_parts = [
148 u'vco.option = %(opt)s',
149 u'vco.workplace = %(wp)s'
150 ]
151 where_parts.append(gmTools.coalesce (
152 initial = cookie,
153 instead = u'vco.cookie is null',
154 template_initial = u'vco.cookie = %(cookie)s'
155 ))
156 cmd = u"select vco.value%s from cfg.v_cfg_opts_%s vco where %s" % (
157 sql_return_type,
158 cfg_table_type_suffix,
159 u' and '.join(where_parts)
160 )
161 rows, idx = gmPG2.run_ro_queries(link_obj=self.ro_conn, queries = [{'cmd': cmd, 'args': args}])
162 if len(rows) > 0:
163
164 self.set (
165 workplace = workplace,
166 cookie = cookie,
167 option = option,
168 value = rows[0][0]
169 )
170 if cfg_table_type_suffix == u'data':
171 return cPickle.loads(str(rows[0][0]))
172 return rows[0][0]
173
174 _log.warning('no user OR workplace specific value for option [%s] in config database' % option)
175
176
177 where_parts = [
178 u'vco.owner = %(def)s',
179 u'vco.workplace = %(def)s',
180 u'vco.option = %(opt)s'
181 ]
182 cmd = u"select vco.value%s from cfg.v_cfg_opts_%s vco where %s" % (
183 sql_return_type,
184 cfg_table_type_suffix,
185 u' and '.join(where_parts)
186 )
187 rows, idx = gmPG2.run_ro_queries(link_obj=self.ro_conn, queries = [{'cmd': cmd, 'args': args}])
188 if len(rows) > 0:
189
190 self.set (
191 workplace = workplace,
192 cookie = cookie,
193 option = option,
194 value = rows[0]['value']
195 )
196 if cfg_table_type_suffix == u'data':
197 return cPickle.loads(str(rows[0]['value']))
198 return rows[0]['value']
199
200 _log.warning('no default site policy value for option [%s] in config database' % option)
201
202
203 if default is None:
204 _log.warning('no default value for option [%s] supplied by caller' % option)
205 return None
206 _log.info('setting option [%s] to default [%s]' % (option, default))
207 success = self.set (
208 workplace = workplace,
209 cookie = cookie,
210 option = option,
211 value = default
212 )
213 if not success:
214 return None
215
216 return default
217
218 - def getID(self, workplace = None, cookie = None, option = None):
219 """Get config value from database.
220
221 - unset arguments are assumed to mean database defaults except for <cookie>
222 """
223
224 if option is None:
225 _log.error("Need to know which option to retrieve.")
226 return None
227
228 alias = self.__make_alias(workplace, 'CURRENT_USER', cookie, option)
229
230
231 where_parts = [
232 'vco.option=%(opt)s',
233 'vco.workplace=%(wplace)s'
234 ]
235 where_args = {
236 'opt': option,
237 'wplace': workplace
238 }
239 if workplace is None:
240 where_args['wplace'] = cfg_DEFAULT
241
242 where_parts.append('vco.owner=CURRENT_USER')
243
244 if cookie is not None:
245 where_parts.append('vco.cookie=%(cookie)s')
246 where_args['cookie'] = cookie
247 where_clause = ' and '.join(where_parts)
248 cmd = u"""
249 select vco.pk_cfg_item
250 from cfg.v_cfg_options vco
251 where %s
252 limit 1""" % where_clause
253
254 rows, idx = gmPG2.run_ro_queries(link_obj=self.ro_conn, queries = [{'cmd': cmd, 'args': where_args}], return_data=True)
255 if len(rows) == 0:
256 _log.warning('option definition for [%s] not in config database' % alias)
257 return None
258 return rows[0][0]
259
260 - def set(self, workplace = None, cookie = None, option = None, value = None):
261 """Set (insert or update) option value in database.
262
263 Any parameter that is None will be set to the database default.
264
265 Note: you can't change the type of a parameter once it has been
266 created in the backend. If you want to change the type you will
267 have to delete the parameter and recreate it using the new type.
268 """
269
270 if None in [option, value]:
271 raise ValueError('invalid arguments (option=<%s>, value=<%s>)' % (option, value))
272
273 rw_conn = gmPG2.get_connection(readonly=False)
274
275 alias = self.__make_alias(workplace, 'CURRENT_USER', cookie, option)
276
277 opt_value = value
278 sql_type_cast = u''
279 if isinstance(value, basestring):
280 sql_type_cast = u'::text'
281 elif isinstance(value, types.BooleanType):
282 opt_value = int(opt_value)
283 elif isinstance(value, (types.FloatType, types.IntType, types.LongType, decimal.Decimal, types.BooleanType)):
284 sql_type_cast = u'::numeric'
285 elif isinstance(value, types.ListType):
286
287 pass
288 elif isinstance(value, types.BufferType):
289
290 pass
291 else:
292 try:
293 opt_value = gmPG2.dbapi.Binary(cPickle.dumps(value))
294 sql_type_cast = '::bytea'
295 except cPickle.PicklingError:
296 _log.error("cannot pickle option of type [%s] (key: %s, value: %s)", type(value), alias, str(value))
297 raise
298 except:
299 _log.error("don't know how to store option of type [%s] (key: %s, value: %s)", type(value), alias, str(value))
300 raise
301
302 cmd = u'select cfg.set_option(%%(opt)s, %%(val)s%s, %%(wp)s, %%(cookie)s, NULL)' % sql_type_cast
303 args = {
304 'opt': option,
305 'val': opt_value,
306 'wp': workplace,
307 'cookie': cookie
308 }
309 try:
310 rows, idx = gmPG2.run_rw_queries(link_obj=rw_conn, queries=[{'cmd': cmd, 'args': args}], return_data=True)
311 result = rows[0][0]
312 except:
313 _log.exception('cannot set option')
314 result = False
315
316 rw_conn.commit()
317 rw_conn.close()
318
319 return result
320
322 """Get names of all stored parameters for a given workplace/(user)/cookie-key.
323 This will be used by the ConfigEditor object to create a parameter tree.
324 """
325
326 where_snippets = [
327 u'cfg_template.pk=cfg_item.fk_template',
328 u'cfg_item.workplace=%(wplace)s'
329 ]
330 where_args = {'wplace': workplace}
331
332
333 if user is None:
334 where_snippets.append(u'cfg_item.owner=CURRENT_USER')
335 else:
336 where_snippets.append(u'cfg_item.owner=%(usr)s')
337 where_args['usr'] = user
338
339 where_clause = u' and '.join(where_snippets)
340
341 cmd = u"""
342 select name, cookie, owner, type, description
343 from cfg.cfg_template, cfg.cfg_item
344 where %s""" % where_clause
345
346
347 rows, idx = gmPG2.run_ro_queries(link_obj=self.ro_conn, queries = [{'cmd': cmd, 'args': where_args}], return_data=True)
348 return rows
349
350 - def delete(self, workplace = None, cookie = None, option = None):
351 """
352 Deletes an option or a whole group.
353 Note you have to call store() in order to save
354 the changes.
355 """
356 if option is None:
357 raise ValueError('<option> cannot be None')
358
359 if cookie is None:
360 cmd = u"""
361 delete from cfg.cfg_item where
362 fk_template=(select pk from cfg.cfg_template where name = %(opt)s) and
363 owner = CURRENT_USER and
364 workplace = %(wp)s and
365 cookie is Null
366 """
367 else:
368 cmd = u"""
369 delete from cfg.cfg_item where
370 fk_template=(select pk from cfg.cfg_template where name = %(opt)s) and
371 owner = CURRENT_USER and
372 workplace = %(wp)s and
373 cookie = %(cookie)s
374 """
375 args = {'opt': option, 'wp': workplace, 'cookie': cookie}
376 gmPG2.run_rw_queries(queries=[{'cmd': cmd, 'args': args}])
377 return True
378
380 return '%s-%s-%s-%s' % (workplace, user, cookie, option)
381
382 -def getDBParam(workplace = None, cookie = None, option = None):
383 """Convenience function to get config value from database.
384
385 will search for context dependant match in this order:
386 - CURRENT_USER_CURRENT_WORKPLACE
387 - CURRENT_USER_DEFAULT_WORKPLACE
388 - DEFAULT_USER_CURRENT_WORKPLACE
389 - DEFAULT_USER_DEFAULT_WORKPLACE
390
391 We assume that the config tables are found on service "default".
392 That way we can handle the db connection inside this function.
393
394 Returns (value, set) of first match.
395 """
396
397
398
399 if option is None:
400 return (None, None)
401
402
403 dbcfg = cCfgSQL()
404
405
406 sets2search = []
407 if workplace is not None:
408 sets2search.append(['CURRENT_USER_CURRENT_WORKPLACE', None, workplace])
409 sets2search.append(['CURRENT_USER_DEFAULT_WORKPLACE', None, None])
410 if workplace is not None:
411 sets2search.append(['DEFAULT_USER_CURRENT_WORKPLACE', cfg_DEFAULT, workplace])
412 sets2search.append(['DEFAULT_USER_DEFAULT_WORKPLACE', cfg_DEFAULT, None])
413
414 matchingSet = None
415 result = None
416 for set in sets2search:
417 result = dbcfg.get(
418 workplace = set[2],
419 user = set[1],
420 option = option,
421 cookie = cookie
422 )
423 if result is not None:
424 matchingSet = set[0]
425 break
426 _log.debug('[%s] not found for [%s@%s]' % (option, set[1], set[2]))
427
428
429 if matchingSet is None:
430 _log.warning('no config data for [%s]' % option)
431 return (result, matchingSet)
432
433 -def setDBParam(workplace = None, user = None, cookie = None, option = None, value = None):
434 """Convenience function to store config values in database.
435
436 We assume that the config tables are found on service "default".
437 That way we can handle the db connection inside this function.
438
439 Omitting any parameter (or setting to None) will store database defaults for it.
440
441 - returns True/False
442 """
443
444 dbcfg = cCfgSQL()
445
446 success = dbcfg.set(
447 workplace = workplace,
448 user = user,
449 option = option,
450 value = value
451 )
452
453 if not success:
454 return False
455 return True
456
457
458
459 if __name__ == "__main__":
460
461 root = logging.getLogger()
462 root.setLevel(logging.DEBUG)
463
464
466 print "testing database config"
467 print "======================="
468
469 myDBCfg = cCfgSQL()
470
471 print "delete() works:", myDBCfg.delete(option='font name', workplace = 'test workplace')
472 print "font is initially:", myDBCfg.get2(option = 'font name', workplace = 'test workplace', bias = 'user')
473 print "set() works:", myDBCfg.set(option='font name', value="Times New Roman", workplace = 'test workplace')
474 print "font after set():", myDBCfg.get2(option = 'font name', workplace = 'test workplace', bias = 'user')
475 print "delete() works:", myDBCfg.delete(option='font name', workplace = 'test workplace')
476 print "font after delete():", myDBCfg.get2(option = 'font name', workplace = 'test workplace', bias = 'user')
477 print "font after get() with default:", myDBCfg.get2(option = 'font name', workplace = 'test workplace', bias = 'user', default = 'WingDings')
478 print "font right after get() with another default:", myDBCfg.get2(option = 'font name', workplace = 'test workplace', bias = 'user', default = 'default: Courier')
479 print "set() works:", myDBCfg.set(option='font name', value="Times New Roman", workplace = 'test workplace')
480 print "font after set() on existing option:", myDBCfg.get2(option = 'font name', workplace = 'test workplace', bias = 'user')
481
482 print "setting array option"
483 print "array now:", myDBCfg.get2(option = 'test array', workplace = 'test workplace', bias = 'user')
484 aList = ['val 1', 'val 2']
485 print "set():", myDBCfg.set(option='test array', value = aList, workplace = 'test workplace')
486 print "array now:", myDBCfg.get2(option = 'test array', workplace = 'test workplace', bias = 'user')
487 aList = ['val 11', 'val 12']
488 print "set():", myDBCfg.set(option='test array', value = aList, workplace = 'test workplace')
489 print "array now:", myDBCfg.get2(option = 'test array', workplace = 'test workplace', bias = 'user')
490 print "delete() works:", myDBCfg.delete(option='test array', workplace='test workplace')
491 print "array now:", myDBCfg.get2(option = 'test array', workplace = 'test workplace', bias = 'user')
492
493 print "setting complex option"
494 data = {1: 'line 1', 2: 'line2', 3: {1: 'line3.1', 2: 'line3.2'}, 4: 1234}
495 print "set():", myDBCfg.set(option = "complex option test", value = data, workplace = 'test workplace')
496 print "complex option now:", myDBCfg.get2(workplace = 'test workplace', option = "complex option test", bias = 'user')
497 print "delete() works:", myDBCfg.delete(option = "complex option test", workplace = 'test workplace')
498 print "complex option now:", myDBCfg.get2(workplace = 'test workplace', option = "complex option test", bias = 'user')
499
500
501 if (len(sys.argv) > 1) and (sys.argv[1] == 'test'):
502 try:
503 test_db_cfg()
504 except:
505 _log.exception('test suite failed')
506 raise
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944