Debian Codegraph @

docs/basic_usage.rst

raw
1 .. _basic_usage:
2
3 ===========
4 Basic Usage
5 ===========
6
7
8 Connection Handling
9 ===================
10
11 To begin using Kazoo, a :class:`~kazoo.client.KazooClient` object must be
12 created and a connection established:
13
14 .. code-block:: python
15
16 from kazoo.client import KazooClient
17
18 zk = KazooClient(hosts='127.0.0.1:2181')
19 zk.start()
20
21 By default, the client will connect to a local Zookeeper server on the default
22 port (2181). You should make sure Zookeeper is actually running there first,
23 or the ``start`` command will be waiting until its default timeout.
24
25 Once connected, the client will attempt to stay connected regardless of
26 intermittent connection loss or Zookeeper session expiration. The client can be
27 instructed to drop a connection by calling `stop`:
28
29 .. code-block:: python
30
31 zk.stop()
32
33
34 Logging Setup
35 -------------
36
37 If logging is not setup for your application, you can get following message:
38
39 .. code-block:: python
40
41 No handlers could be found for logger "kazoo.client"
42
43 To avoid this issue you can at the very minimum do the following:
44
45 .. code-block:: python
46
47 import logging
48 logging.basicConfig()
49
50 Read `Python's logging tutorial <https://docs.python.org/howto/logging.html>`_
51 for more details.
52
53
54 Listening for Connection Events
55 -------------------------------
56
57 It can be useful to know when the connection has been dropped, restored, or
58 when the Zookeeper session has expired. To simplify this process Kazoo uses a
59 state system and lets you register listener functions to be called when the
60 state changes.
61
62 .. code-block:: python
63
64 from kazoo.client import KazooState
65
66 def my_listener(state):
67 if state == KazooState.LOST:
68 # Register somewhere that the session was lost
69 elif state == KazooState.SUSPENDED:
70 # Handle being disconnected from Zookeeper
71 else:
72 # Handle being connected/reconnected to Zookeeper
73
74 zk.add_listener(my_listener)
75
76 When using the :class:`kazoo.recipe.lock.Lock` or creating ephemeral nodes, its
77 highly recommended to add a state listener so that your program can properly
78 deal with connection interruptions or a Zookeeper session loss.
79
80 Understanding Kazoo States
81 --------------------------
82
83 The :class:`~kazoo.protocol.states.KazooState` object represents several states
84 the client transitions through. The current state of the client can always be
85 determined by viewing the :attr:`~kazoo.client.KazooClient.state` property. The
86 possible states are:
87
88 - LOST
89 - CONNECTED
90 - SUSPENDED
91
92 When a :class:`~kazoo.client.KazooClient` instance is first created, it is in
93 the `LOST` state. After a connection is established it transitions to the
94 `CONNECTED` state. If any connection issues come up or if it needs to connect
95 to a different Zookeeper cluster node, it will transition to `SUSPENDED` to let
96 you know that commands cannot currently be run. The connection will also be
97 lost if the Zookeeper node is no longer part of the quorum, resulting in a
98 `SUSPENDED` state.
99
100 Upon re-establishing a connection the client could transition to `LOST` if the
101 session has expired, or `CONNECTED` if the session is still valid.
102
103 .. note::
104
105 These states should be monitored using a listener as described previously
106 so that the client behaves properly depending on the state of the
107 connection.
108
109 When a connection transitions to `SUSPENDED`, if the client is performing an
110 action that requires agreement with other systems (using the Lock recipe for
111 example), it should pause what it's doing. When the connection has been
112 re-established the client can continue depending on if the state is `LOST` or
113 transitions directly to `CONNECTED` again.
114
115 When a connection transitions to `LOST`, any ephemeral nodes that have been
116 created will be removed by Zookeeper. This affects all recipes that create
117 ephemeral nodes, such as the Lock recipe. Lock's will need to be re-acquired
118 after the state transitions to `CONNECTED` again. This transition occurs when
119 a session expires or when you stop the clients connection.
120
121 **Valid State Transitions**
122
123 - *LOST -> CONNECTED*
124
125 New connection, or previously lost one becoming connected.
126 - *CONNECTED -> SUSPENDED*
127
128 Connection loss to server occurred on a connection.
129 - *CONNECTED -> LOST*
130
131 Only occurs if invalid authentication credentials are provided after the
132 connection was established.
133 - *SUSPENDED -> LOST*
134
135 Connection resumed to server, but then lost as the session was expired.
136 - *SUSPENDED -> CONNECTED*
137
138 Connection that was lost has been restored.
139
140 Read-Only Connections
141 ---------------------
142
143 .. versionadded:: 0.6
144
145 Zookeeper 3.4 and above `supports a read-only mode
146 <http://wiki.apache.org/hadoop/ZooKeeper/GSoCReadOnlyMode>`_. This mode
147 must be turned on for the servers in the Zookeeper cluster for the
148 client to utilize it. To use this mode with Kazoo, the
149 :class:`~kazoo.client.KazooClient` should be called with the
150 `read_only` option set to `True`. This will let the client connect to
151 a Zookeeper node that has gone read-only, and the client will continue
152 to scan for other nodes that are read-write.
153
154 .. code-block:: python
155
156 from kazoo.client import KazooClient
157
158 zk = KazooClient(hosts='127.0.0.1:2181', read_only=True)
159 zk.start()
160
161 A new attribute on :class:`~kazoo.protocol.states.KeeperState` has been
162 added, `CONNECTED_RO`. The connection states above are still valid,
163 however upon `CONNECTED`, you will need to check the clients non-
164 simplified state to see if the connection is `CONNECTED_RO`. For
165 example:
166
167 .. code-block:: python
168
169 from kazoo.client import KazooState
170 from kazoo.client import KeeperState
171
172 @zk.add_listener
173 def watch_for_ro(state):
174 if state == KazooState.CONNECTED:
175 if zk.client_state == KeeperState.CONNECTED_RO:
176 print("Read only mode!")
177 else:
178 print("Read/Write mode!")
179
180 It's important to note that a `KazooState` is passed in to the listener
181 but the read-only information is only available by comparing the
182 non-simplified client state to the `KeeperState` object.
183
184 .. warning::
185
186 A client using read-only mode should not use any of the recipes.
187
188
189 Zookeeper CRUD
190 ==============
191
192 Zookeeper includes several functions for creating, reading, updating, and
193 deleting Zookeeper nodes (called znodes or nodes here). Kazoo adds several
194 convenience methods and a more Pythonic API.
195
196 Creating Nodes
197 --------------
198
199 Methods:
200
201 * :meth:`~kazoo.client.KazooClient.ensure_path`
202 * :meth:`~kazoo.client.KazooClient.create`
203
204 :meth:`~kazoo.client.KazooClient.ensure_path` will recursively create the node
205 and any nodes in the path necessary along the way, but can not set the data for
206 the node, only the ACL.
207
208 :meth:`~kazoo.client.KazooClient.create` creates a node and can set the data on
209 the node along with a watch function. It requires the path to it to exist
210 first, unless the `makepath` option is set to `True`.
211
212 .. code-block:: python
213
214 # Ensure a path, create if necessary
215 zk.ensure_path("/my/favorite")
216
217 # Create a node with data
218 zk.create("/my/favorite/node", b"a value")
219
220 Reading Data
221 ------------
222
223 Methods:
224
225 * :meth:`~kazoo.client.KazooClient.exists`
226 * :meth:`~kazoo.client.KazooClient.get`
227 * :meth:`~kazoo.client.KazooClient.get_children`
228
229 :meth:`~kazoo.client.KazooClient.exists` checks to see if a node exists.
230
231 :meth:`~kazoo.client.KazooClient.get` fetches the data of the node along with
232 detailed node information in a :class:`~kazoo.protocol.states.ZnodeStat`
233 structure.
234
235 :meth:`~kazoo.client.KazooClient.get_children` gets a list of the children of
236 a given node.
237
238 .. code-block:: python
239
240 # Determine if a node exists
241 if zk.exists("/my/favorite"):
242 # Do something
243
244 # Print the version of a node and its data
245 data, stat = zk.get("/my/favorite")
246 print("Version: %s, data: %s" % (stat.version, data.decode("utf-8")))
247
248 # List the children
249 children = zk.get_children("/my/favorite")
250 print("There are %s children with names %s" % (len(children), children))
251
252 Updating Data
253 -------------
254
255 Methods:
256
257 * :meth:`~kazoo.client.KazooClient.set`
258
259 :meth:`~kazoo.client.KazooClient.set` updates the data for a given node. A
260 version for the node can be supplied, which will be required to match before
261 updating the data, or a :exc:`~kazoo.exceptions.BadVersionError` will be
262 raised instead of updating.
263
264 .. code-block:: python
265
266 zk.set("/my/favorite", b"some data")
267
268 Deleting Nodes
269 --------------
270
271 Methods:
272
273 * :meth:`~kazoo.client.KazooClient.delete`
274
275 :meth:`~kazoo.client.KazooClient.delete` deletes a node, and can optionally
276 recursively delete all children of the node as well. A version can be
277 supplied when deleting a node which will be required to match the version of
278 the node before deleting it or a :exc:`~kazoo.exceptions.BadVersionError`
279 will be raised instead of deleting.
280
281 .. code-block:: python
282
283 zk.delete("/my/favorite/node", recursive=True)
284
285 .. _retrying_commands:
286
287 Retrying Commands
288 =================
289
290 Connections to Zookeeper may get interrupted if the Zookeeper server goes down
291 or becomes unreachable. By default, kazoo does not retry commands, so these
292 failures will result in an exception being raised. To assist with failures
293 kazoo comes with a :meth:`~kazoo.client.KazooClient.retry` helper that will
294 retry a function should one of the Zookeeper connection exceptions get raised.
295
296 Example:
297
298 .. code-block:: python
299
300 result = zk.retry(zk.get, "/path/to/node")
301
302 Some commands may have unique behavior that doesn't warrant automatic retries
303 on a per command basis. For example, if one creates a node a connection might
304 be lost before the command returns successfully but the node actually got
305 created. This results in a :exc:`kazoo.exceptions.NodeExistsError` being
306 raised when it runs again. A similar unique situation arises when a node is
307 created with ephemeral and sequence options set,
308 `documented here on the Zookeeper site
309 <http://zookeeper.apache.org/doc/trunk/recipes.html#sc_recipes_errorHandlingNote>`_.
310
311 Since the :meth:`~kazoo.client.KazooClient.retry` method takes a function to
312 call and its arguments, a function that runs multiple Zookeeper commands could
313 be passed to it so that the entire function will be retried if the connection
314 is lost.
315
316 This snippet from the lock implementation shows how it uses retry to re-run the
317 function acquiring a lock, and checks to see if it was already created to
318 handle this condition:
319
320 .. code-block:: python
321
322 # kazoo.recipe.lock snippet
323
324 def acquire(self):
325 """Acquire the mutex, blocking until it is obtained"""
326 try:
327 self.client.retry(self._inner_acquire)
328 self.is_acquired = True
329 except KazooException:
330 # if we did ultimately fail, attempt to clean up
331 self._best_effort_cleanup()
332 self.cancelled = False
333 raise
334
335 def _inner_acquire(self):
336 self.wake_event.clear()
337
338 # make sure our election parent node exists
339 if not self.assured_path:
340 self.client.ensure_path(self.path)
341
342 node = None
343 if self.create_tried:
344 node = self._find_node()
345 else:
346 self.create_tried = True
347
348 if not node:
349 node = self.client.create(self.create_path, self.data,
350 ephemeral=True, sequence=True)
351 # strip off path to node
352 node = node[len(self.path) + 1:]
353
354 `create_tried` records whether it has tried to create the node already in the
355 event the connection is lost before the node name is returned.
356
357 Custom Retries
358 --------------
359
360 Sometimes you may wish to have specific retry policies for a command or
361 set of commands that differs from the
362 :meth:`~kazoo.client.KazooClient.retry` method. You can manually create
363 a :class:`~kazoo.retry.KazooRetry` instance with the specific retry
364 policy you prefer:
365
366 .. code-block:: python
367
368 from kazoo.retry import KazooRetry
369
370 kr = KazooRetry(max_tries=3, ignore_expire=False)
371 result = kr(client.get, "/some/path")
372
373 This will retry the ``client.get`` command up to 3 times, and raise a
374 session expiration if it occurs. You can also make an instance with the
375 default behavior that ignores session expiration during a retry.
376
377 Watchers
378 ========
379
380 Kazoo can set watch functions on a node that can be triggered either when the
381 node has changed or when the children of the node change. This change to the
382 node or children can also be the node or its children being deleted.
383
384 Watchers can be set in two different ways, the first is the style that
385 Zookeeper supports by default for one-time watch events. These watch functions
386 will be called once by kazoo, and do *not* receive session events, unlike the
387 native Zookeeper watches. Using this style requires the watch function to be
388 passed to one of these methods:
389
390 * :meth:`~kazoo.client.KazooClient.get`
391 * :meth:`~kazoo.client.KazooClient.get_children`
392 * :meth:`~kazoo.client.KazooClient.exists`
393
394 A watch function passed to :meth:`~kazoo.client.KazooClient.get` or
395 :meth:`~kazoo.client.KazooClient.exists` will be called when the data on the
396 node changes or the node itself is deleted. It will be passed a
397 :class:`~kazoo.protocol.states.WatchedEvent` instance.
398
399 .. code-block:: python
400
401 def my_func(event):
402 # check to see what the children are now
403
404 # Call my_func when the children change
405 children = zk.get_children("/my/favorite/node", watch=my_func)
406
407 Kazoo includes a higher level API that watches for data and children
408 modifications that's easier to use as it doesn't require re-setting the watch
409 every time the event is triggered. It also passes in the data and
410 :class:`~kazoo.protocol.states.ZnodeStat` when watching a node or the list of
411 children when watching a nodes children. Watch functions registered with this
412 API will be called immediately and every time there's a change, or until the
413 function returns False. If `allow_session_lost` is set to `True`, then the
414 function will no longer be called if the session is lost.
415
416 The following methods provide this functionality:
417
418 * :class:`~kazoo.recipe.watchers.ChildrenWatch`
419 * :class:`~kazoo.recipe.watchers.DataWatch`
420
421 These classes are available directly on the :class:`~kazoo.client.KazooClient`
422 instance and don't require the client object to be passed in when used in this
423 manner. The instance returned by instantiating either of the classes can be
424 called directly allowing them to be used as decorators:
425
426 .. code-block:: python
427
428 @zk.ChildrenWatch("/my/favorite/node")
429 def watch_children(children):
430 print("Children are now: %s" % children)
431 # Above function called immediately, and from then on
432
433 @zk.DataWatch("/my/favorite")
434 def watch_node(data, stat):
435 print("Version: %s, data: %s" % (stat.version, data.decode("utf-8")))
436
437 Transactions
438 ============
439
440 .. versionadded:: 0.6
441
442 Zookeeper 3.4 and above supports the sending of multiple commands at
443 once that will be committed as a single atomic unit. Either they will
444 all succeed or they will all fail. The result of a transaction will be
445 a list of the success/failure results for each command in the
446 transaction.
447
448 .. code-block:: python
449
450 transaction = zk.transaction()
451 transaction.check('/node/a', version=3)
452 transaction.create('/node/b', b"a value")
453 results = transaction.commit()
454
455 The :meth:`~kazoo.client.KazooClient.transaction` method returns a
456 :class:`~kazoo.client.TransactionRequest` instance. It's methods may be
457 called to queue commands to be completed in the transaction. When the
458 transaction is ready to be sent, the
459 :meth:`~kazoo.client.TransactionRequest.commit` method on it is called.
460
461 In the example above, there's a command not available unless a
462 transaction is being used, `check`. This can check nodes for a specific
463 version, which could be used to make the transaction fail if a node
464 doesn't match a version that it should be at. In this case the node
465 `/node/a` must be at version 3 or `/node/b` will not be created.