backing up
[vsorcdistro/.git] / ryu / build / lib.linux-armv7l-2.7 / ryu / services / protocols / zebra / db / base.py
1 # Copyright (C) 2017 Nippon Telegraph and Telephone Corporation.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #    http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 # implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 from __future__ import absolute_import
17
18 import functools
19 import logging
20
21 from sqlalchemy.ext.declarative import declarative_base
22
23
24 LOG = logging.getLogger(__name__)
25
26 Base = declarative_base()
27 """
28 Base class for Zebra protocol database tables.
29 """
30
31
32 def _repr(self):
33     m = ', '.join(
34         ['%s=%r' % (k, v)
35          for k, v in self.__dict__.items() if not k.startswith('_')])
36     return "%s(%s)" % (self.__class__.__name__, m)
37
38
39 Base.__repr__ = _repr
40
41
42 def sql_function(func):
43     """
44     Decorator for wrapping the given function in order to manipulate (CRUD)
45     the records safely.
46
47     For the adding/updating/deleting records function, this decorator
48     invokes "Session.commit()" after the given function.
49     If any exception while modifying records raised, this decorator invokes
50     "Session.rollbacks()".
51     """
52     @functools.wraps(func)
53     def _wrapper(session, *args, **kwargs):
54         ret = None
55         try:
56             ret = func(session, *args, **kwargs)
57             if session.dirty:
58                 # If the given function has any update to records,
59                 # commits them.
60                 session.commit()
61         except Exception as e:
62             # If any exception raised, rollbacks the transaction.
63             LOG.error('Error in %s: %s', func.__name__, e)
64             if session.dirty:
65                 LOG.error('Do rolling back %s table',
66                           session.dirty[0].__tablename__)
67                 session.rollback()
68
69         return ret
70
71     return _wrapper