/freeipa-3.0.0.pre1/ipalib/base.py

# · Python · 486 lines · 451 code · 4 blank · 31 comment · 0 complexity · 11ca048783d16008c2ca9f6872b8c97f MD5 · raw file

  1. # Authors:
  2. # Jason Gerard DeRose <jderose@redhat.com>
  3. #
  4. # Copyright (C) 2008 Red Hat
  5. # see file 'COPYING' for use and warranty information
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. """
  20. Foundational classes and functions.
  21. """
  22. import re
  23. from constants import NAME_REGEX, NAME_ERROR
  24. from constants import TYPE_ERROR, SET_ERROR, DEL_ERROR, OVERRIDE_ERROR
  25. class ReadOnly(object):
  26. """
  27. Base class for classes that can be locked into a read-only state.
  28. Be forewarned that Python does not offer true read-only attributes for
  29. user-defined classes. Do *not* rely upon the read-only-ness of this
  30. class for security purposes!
  31. The point of this class is not to make it impossible to set or to delete
  32. attributes after an instance is locked, but to make it impossible to do so
  33. *accidentally*. Rather than constantly reminding our programmers of things
  34. like, for example, "Don't set any attributes on this ``FooBar`` instance
  35. because doing so wont be thread-safe", this class offers a real way to
  36. enforce read-only attribute usage.
  37. For example, before a `ReadOnly` instance is locked, you can set and delete
  38. its attributes as normal:
  39. >>> class Person(ReadOnly):
  40. ... pass
  41. ...
  42. >>> p = Person()
  43. >>> p.name = 'John Doe'
  44. >>> p.phone = '123-456-7890'
  45. >>> del p.phone
  46. But after an instance is locked, you cannot set its attributes:
  47. >>> p.__islocked__() # Is this instance locked?
  48. False
  49. >>> p.__lock__() # This will lock the instance
  50. >>> p.__islocked__()
  51. True
  52. >>> p.department = 'Engineering'
  53. Traceback (most recent call last):
  54. ...
  55. AttributeError: locked: cannot set Person.department to 'Engineering'
  56. Nor can you deleted its attributes:
  57. >>> del p.name
  58. Traceback (most recent call last):
  59. ...
  60. AttributeError: locked: cannot delete Person.name
  61. However, as noted at the start, there are still obscure ways in which
  62. attributes can be set or deleted on a locked `ReadOnly` instance. For
  63. example:
  64. >>> object.__setattr__(p, 'department', 'Engineering')
  65. >>> p.department
  66. 'Engineering'
  67. >>> object.__delattr__(p, 'name')
  68. >>> hasattr(p, 'name')
  69. False
  70. But again, the point is that a programmer would never employ the above
  71. techniques *accidentally*.
  72. Lastly, this example aside, you should use the `lock()` function rather
  73. than the `ReadOnly.__lock__()` method. And likewise, you should
  74. use the `islocked()` function rather than the `ReadOnly.__islocked__()`
  75. method. For example:
  76. >>> readonly = ReadOnly()
  77. >>> islocked(readonly)
  78. False
  79. >>> lock(readonly) is readonly # lock() returns the instance
  80. True
  81. >>> islocked(readonly)
  82. True
  83. """
  84. __locked = False
  85. def __lock__(self):
  86. """
  87. Put this instance into a read-only state.
  88. After the instance has been locked, attempting to set or delete an
  89. attribute will raise an AttributeError.
  90. """
  91. assert self.__locked is False, '__lock__() can only be called once'
  92. self.__locked = True
  93. def __islocked__(self):
  94. """
  95. Return True if instance is locked, otherwise False.
  96. """
  97. return self.__locked
  98. def __setattr__(self, name, value):
  99. """
  100. If unlocked, set attribute named ``name`` to ``value``.
  101. If this instance is locked, an AttributeError will be raised.
  102. :param name: Name of attribute to set.
  103. :param value: Value to assign to attribute.
  104. """
  105. if self.__locked:
  106. raise AttributeError(
  107. SET_ERROR % (self.__class__.__name__, name, value)
  108. )
  109. return object.__setattr__(self, name, value)
  110. def __delattr__(self, name):
  111. """
  112. If unlocked, delete attribute named ``name``.
  113. If this instance is locked, an AttributeError will be raised.
  114. :param name: Name of attribute to delete.
  115. """
  116. if self.__locked:
  117. raise AttributeError(
  118. DEL_ERROR % (self.__class__.__name__, name)
  119. )
  120. return object.__delattr__(self, name)
  121. def lock(instance):
  122. """
  123. Lock an instance of the `ReadOnly` class or similar.
  124. This function can be used to lock instances of any class that implements
  125. the same locking API as the `ReadOnly` class. For example, this function
  126. can lock instances of the `config.Env` class.
  127. So that this function can be easily used within an assignment, ``instance``
  128. is returned after it is locked. For example:
  129. >>> readonly = ReadOnly()
  130. >>> readonly is lock(readonly)
  131. True
  132. >>> readonly.attr = 'This wont work'
  133. Traceback (most recent call last):
  134. ...
  135. AttributeError: locked: cannot set ReadOnly.attr to 'This wont work'
  136. Also see the `islocked()` function.
  137. :param instance: The instance of `ReadOnly` (or similar) to lock.
  138. """
  139. assert instance.__islocked__() is False, 'already locked: %r' % instance
  140. instance.__lock__()
  141. assert instance.__islocked__() is True, 'failed to lock: %r' % instance
  142. return instance
  143. def islocked(instance):
  144. """
  145. Return ``True`` if ``instance`` is locked.
  146. This function can be used on an instance of the `ReadOnly` class or an
  147. instance of any other class implemented the same locking API.
  148. For example:
  149. >>> readonly = ReadOnly()
  150. >>> islocked(readonly)
  151. False
  152. >>> readonly.__lock__()
  153. >>> islocked(readonly)
  154. True
  155. Also see the `lock()` function.
  156. :param instance: The instance of `ReadOnly` (or similar) to interrogate.
  157. """
  158. assert (
  159. hasattr(instance, '__lock__') and callable(instance.__lock__)
  160. ), 'no __lock__() method: %r' % instance
  161. return instance.__islocked__()
  162. def check_name(name):
  163. """
  164. Verify that ``name`` is suitable for a `NameSpace` member name.
  165. In short, ``name`` must be a valid lower-case Python identifier that
  166. neither starts nor ends with an underscore. Otherwise an exception is
  167. raised.
  168. This function will raise a ``ValueError`` if ``name`` does not match the
  169. `constants.NAME_REGEX` regular expression. For example:
  170. >>> check_name('MyName')
  171. Traceback (most recent call last):
  172. ...
  173. ValueError: name must match '^[a-z][_a-z0-9]*[a-z0-9]$|^[a-z]$'; got 'MyName'
  174. Also, this function will raise a ``TypeError`` if ``name`` is not an
  175. ``str`` instance. For example:
  176. >>> check_name(u'my_name')
  177. Traceback (most recent call last):
  178. ...
  179. TypeError: name: need a <type 'str'>; got u'my_name' (a <type 'unicode'>)
  180. So that `check_name()` can be easily used within an assignment, ``name``
  181. is returned unchanged if it passes the check. For example:
  182. >>> n = check_name('my_name')
  183. >>> n
  184. 'my_name'
  185. :param name: Identifier to test.
  186. """
  187. if type(name) is not str:
  188. raise TypeError(
  189. TYPE_ERROR % ('name', str, name, type(name))
  190. )
  191. if re.match(NAME_REGEX, name) is None:
  192. raise ValueError(
  193. NAME_ERROR % (NAME_REGEX, name)
  194. )
  195. return name
  196. class NameSpace(ReadOnly):
  197. """
  198. A read-only name-space with handy container behaviours.
  199. A `NameSpace` instance is an ordered, immutable mapping object whose values
  200. can also be accessed as attributes. A `NameSpace` instance is constructed
  201. from an iterable providing its *members*, which are simply arbitrary objects
  202. with a ``name`` attribute whose value:
  203. 1. Is unique among the members
  204. 2. Passes the `check_name()` function
  205. Beyond that, no restrictions are placed on the members: they can be
  206. classes or instances, and of any type.
  207. The members can be accessed as attributes on the `NameSpace` instance or
  208. through a dictionary interface. For example, say we create a `NameSpace`
  209. instance from a list containing a single member, like this:
  210. >>> class my_member(object):
  211. ... name = 'my_name'
  212. ...
  213. >>> namespace = NameSpace([my_member])
  214. >>> namespace
  215. NameSpace(<1 member>, sort=True)
  216. We can then access ``my_member`` both as an attribute and as a dictionary
  217. item:
  218. >>> my_member is namespace.my_name # As an attribute
  219. True
  220. >>> my_member is namespace['my_name'] # As dictionary item
  221. True
  222. For a more detailed example, say we create a `NameSpace` instance from a
  223. generator like this:
  224. >>> class Member(object):
  225. ... def __init__(self, i):
  226. ... self.i = i
  227. ... self.name = 'member%d' % i
  228. ... def __repr__(self):
  229. ... return 'Member(%d)' % self.i
  230. ...
  231. >>> ns = NameSpace(Member(i) for i in xrange(3))
  232. >>> ns
  233. NameSpace(<3 members>, sort=True)
  234. As above, the members can be accessed as attributes and as dictionary items:
  235. >>> ns.member0 is ns['member0']
  236. True
  237. >>> ns.member1 is ns['member1']
  238. True
  239. >>> ns.member2 is ns['member2']
  240. True
  241. Members can also be accessed by index and by slice. For example:
  242. >>> ns[0]
  243. Member(0)
  244. >>> ns[-1]
  245. Member(2)
  246. >>> ns[1:]
  247. (Member(1), Member(2))
  248. (Note that slicing a `NameSpace` returns a ``tuple``.)
  249. `NameSpace` instances provide standard container emulation for membership
  250. testing, counting, and iteration. For example:
  251. >>> 'member3' in ns # Is there a member named 'member3'?
  252. False
  253. >>> 'member2' in ns # But there is a member named 'member2'
  254. True
  255. >>> len(ns) # The number of members
  256. 3
  257. >>> list(ns) # Iterate through the member names
  258. ['member0', 'member1', 'member2']
  259. Although not a standard container feature, the `NameSpace.__call__()` method
  260. provides a convenient (and efficient) way to iterate through the *members*
  261. (as opposed to the member names). Think of it like an ordered version of
  262. the ``dict.itervalues()`` method. For example:
  263. >>> list(ns[name] for name in ns) # One way to do it
  264. [Member(0), Member(1), Member(2)]
  265. >>> list(ns()) # A more efficient, simpler way to do it
  266. [Member(0), Member(1), Member(2)]
  267. Another convenience method is `NameSpace.__todict__()`, which will return
  268. a copy of the ``dict`` mapping the member names to the members.
  269. For example:
  270. >>> ns.__todict__()
  271. {'member1': Member(1), 'member0': Member(0), 'member2': Member(2)}
  272. As `NameSpace.__init__()` locks the instance, `NameSpace` instances are
  273. read-only from the get-go. An ``AttributeError`` is raised if you try to
  274. set *any* attribute on a `NameSpace` instance. For example:
  275. >>> ns.member3 = Member(3) # Lets add that missing 'member3'
  276. Traceback (most recent call last):
  277. ...
  278. AttributeError: locked: cannot set NameSpace.member3 to Member(3)
  279. (For information on the locking protocol, see the `ReadOnly` class, of which
  280. `NameSpace` is a subclass.)
  281. By default the members will be sorted alphabetically by the member name.
  282. For example:
  283. >>> sorted_ns = NameSpace([Member(7), Member(3), Member(5)])
  284. >>> sorted_ns
  285. NameSpace(<3 members>, sort=True)
  286. >>> list(sorted_ns)
  287. ['member3', 'member5', 'member7']
  288. >>> sorted_ns[0]
  289. Member(3)
  290. But if the instance is created with the ``sort=False`` keyword argument, the
  291. original order of the members is preserved. For example:
  292. >>> unsorted_ns = NameSpace([Member(7), Member(3), Member(5)], sort=False)
  293. >>> unsorted_ns
  294. NameSpace(<3 members>, sort=False)
  295. >>> list(unsorted_ns)
  296. ['member7', 'member3', 'member5']
  297. >>> unsorted_ns[0]
  298. Member(7)
  299. The `NameSpace` class is used in many places throughout freeIPA. For a few
  300. examples, see the `plugable.API` and the `frontend.Command` classes.
  301. """
  302. def __init__(self, members, sort=True, name_attr='name'):
  303. """
  304. :param members: An iterable providing the members.
  305. :param sort: Whether to sort the members by member name.
  306. """
  307. if type(sort) is not bool:
  308. raise TypeError(
  309. TYPE_ERROR % ('sort', bool, sort, type(sort))
  310. )
  311. self.__sort = sort
  312. if sort:
  313. self.__members = tuple(
  314. sorted(members, key=lambda m: getattr(m, name_attr))
  315. )
  316. else:
  317. self.__members = tuple(members)
  318. self.__names = tuple(getattr(m, name_attr) for m in self.__members)
  319. self.__map = dict()
  320. for member in self.__members:
  321. name = check_name(getattr(member, name_attr))
  322. if name in self.__map:
  323. raise AttributeError(OVERRIDE_ERROR %
  324. (self.__class__.__name__, name, self.__map[name], member)
  325. )
  326. assert not hasattr(self, name), 'Ouch! Has attribute %r' % name
  327. self.__map[name] = member
  328. setattr(self, name, member)
  329. lock(self)
  330. def __len__(self):
  331. """
  332. Return the number of members.
  333. """
  334. return len(self.__members)
  335. def __iter__(self):
  336. """
  337. Iterate through the member names.
  338. If this instance was created with ``sort=False``, the names will be in
  339. the same order as the members were passed to the constructor; otherwise
  340. the names will be in alphabetical order (which is the default).
  341. This method is like an ordered version of ``dict.iterkeys()``.
  342. """
  343. for name in self.__names:
  344. yield name
  345. def __call__(self):
  346. """
  347. Iterate through the members.
  348. If this instance was created with ``sort=False``, the members will be
  349. in the same order as they were passed to the constructor; otherwise the
  350. members will be in alphabetical order by name (which is the default).
  351. This method is like an ordered version of ``dict.itervalues()``.
  352. """
  353. for member in self.__members:
  354. yield member
  355. def __contains__(self, name):
  356. """
  357. Return ``True`` if namespace has a member named ``name``.
  358. """
  359. return name in self.__map
  360. def __getitem__(self, key):
  361. """
  362. Return a member by name or index, or return a slice of members.
  363. :param key: The name or index of a member, or a slice object.
  364. """
  365. if isinstance(key, basestring):
  366. return self.__map[key]
  367. if type(key) in (int, slice):
  368. return self.__members[key]
  369. raise TypeError(
  370. TYPE_ERROR % ('key', (str, int, slice), key, type(key))
  371. )
  372. def __repr__(self):
  373. """
  374. Return a pseudo-valid expression that could create this instance.
  375. """
  376. cnt = len(self)
  377. if cnt == 1:
  378. m = 'member'
  379. else:
  380. m = 'members'
  381. return '%s(<%d %s>, sort=%r)' % (
  382. self.__class__.__name__,
  383. cnt,
  384. m,
  385. self.__sort,
  386. )
  387. def __todict__(self):
  388. """
  389. Return a copy of the private dict mapping member name to member.
  390. """
  391. return dict(self.__map)