Debian Codegraph @

hgext/fsmonitor/pywatchman/__init__.py

raw
1 # Copyright 2014-present Facebook, Inc.
2 # All rights reserved.
3 #
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are met:
6 #
7 # * Redistributions of source code must retain the above copyright notice,
8 # this list of conditions and the following disclaimer.
9 #
10 # * Redistributions in binary form must reproduce the above copyright notice,
11 # this list of conditions and the following disclaimer in the documentation
12 # and/or other materials provided with the distribution.
13 #
14 # * Neither the name Facebook nor the names of its contributors may be used to
15 # endorse or promote products derived from this software without specific
16 # prior written permission.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26 # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 from __future__ import annotations
30
31 import inspect
32 import math
33 import os
34 import socket
35 import subprocess
36 import time
37
38 from . import capabilities, compat, encoding, load
39
40
41 # Sometimes it's really hard to get Python extensions to compile,
42 # so fall back to a pure Python implementation.
43 try:
44 from . import bser
45
46 # Demandimport causes modules to be loaded lazily. Force the load now
47 # so that we can fall back on pybser if bser doesn't exist
48 bser.pdu_info
49 except ImportError:
50 from . import pybser as bser
51
52
53 if os.name == "nt":
54 import ctypes
55 import ctypes.wintypes
56
57 wintypes = ctypes.wintypes
58 GENERIC_READ = 0x80000000
59 GENERIC_WRITE = 0x40000000
60 FILE_FLAG_OVERLAPPED = 0x40000000
61 OPEN_EXISTING = 3
62 INVALID_HANDLE_VALUE = ctypes.c_void_p(-1).value
63 FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000
64 FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100
65 FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200
66 WAIT_FAILED = 0xFFFFFFFF
67 WAIT_TIMEOUT = 0x00000102
68 WAIT_OBJECT_0 = 0x00000000
69 WAIT_IO_COMPLETION = 0x000000C0
70 INFINITE = 0xFFFFFFFF
71
72 # Overlapped I/O operation is in progress. (997)
73 ERROR_IO_PENDING = 0x000003E5
74
75 # The pointer size follows the architecture
76 # We use WPARAM since this type is already conditionally defined
77 ULONG_PTR = ctypes.wintypes.WPARAM
78
79 class OVERLAPPED(ctypes.Structure):
80 _fields_ = [
81 ("Internal", ULONG_PTR),
82 ("InternalHigh", ULONG_PTR),
83 ("Offset", wintypes.DWORD),
84 ("OffsetHigh", wintypes.DWORD),
85 ("hEvent", wintypes.HANDLE),
86 ]
87
88 def __init__(self):
89 self.Internal = 0
90 self.InternalHigh = 0
91 self.Offset = 0
92 self.OffsetHigh = 0
93 self.hEvent = 0
94
95 LPDWORD = ctypes.POINTER(wintypes.DWORD)
96
97 _kernel32 = ctypes.windll.kernel32 # pytype: disable=module-attr
98
99 CreateFile = _kernel32.CreateFileA
100 CreateFile.argtypes = [
101 wintypes.LPSTR,
102 wintypes.DWORD,
103 wintypes.DWORD,
104 wintypes.LPVOID,
105 wintypes.DWORD,
106 wintypes.DWORD,
107 wintypes.HANDLE,
108 ]
109 CreateFile.restype = wintypes.HANDLE
110
111 CloseHandle = _kernel32.CloseHandle
112 CloseHandle.argtypes = [wintypes.HANDLE]
113 CloseHandle.restype = wintypes.BOOL
114
115 ReadFile = _kernel32.ReadFile
116 ReadFile.argtypes = [
117 wintypes.HANDLE,
118 wintypes.LPVOID,
119 wintypes.DWORD,
120 LPDWORD,
121 ctypes.POINTER(OVERLAPPED),
122 ]
123 ReadFile.restype = wintypes.BOOL
124
125 WriteFile = _kernel32.WriteFile
126 WriteFile.argtypes = [
127 wintypes.HANDLE,
128 wintypes.LPVOID,
129 wintypes.DWORD,
130 LPDWORD,
131 ctypes.POINTER(OVERLAPPED),
132 ]
133 WriteFile.restype = wintypes.BOOL
134
135 GetLastError = _kernel32.GetLastError
136 GetLastError.argtypes = []
137 GetLastError.restype = wintypes.DWORD
138
139 SetLastError = _kernel32.SetLastError
140 SetLastError.argtypes = [wintypes.DWORD]
141 SetLastError.restype = None
142
143 FormatMessage = _kernel32.FormatMessageA
144 FormatMessage.argtypes = [
145 wintypes.DWORD,
146 wintypes.LPVOID,
147 wintypes.DWORD,
148 wintypes.DWORD,
149 ctypes.POINTER(wintypes.LPSTR),
150 wintypes.DWORD,
151 wintypes.LPVOID,
152 ]
153 FormatMessage.restype = wintypes.DWORD
154
155 LocalFree = _kernel32.LocalFree
156
157 GetOverlappedResult = _kernel32.GetOverlappedResult
158 GetOverlappedResult.argtypes = [
159 wintypes.HANDLE,
160 ctypes.POINTER(OVERLAPPED),
161 LPDWORD,
162 wintypes.BOOL,
163 ]
164 GetOverlappedResult.restype = wintypes.BOOL
165
166 GetOverlappedResultEx = getattr(_kernel32, "GetOverlappedResultEx", None)
167 if GetOverlappedResultEx is not None:
168 GetOverlappedResultEx.argtypes = [
169 wintypes.HANDLE,
170 ctypes.POINTER(OVERLAPPED),
171 LPDWORD,
172 wintypes.DWORD,
173 wintypes.BOOL,
174 ]
175 GetOverlappedResultEx.restype = wintypes.BOOL
176
177 WaitForSingleObjectEx = _kernel32.WaitForSingleObjectEx
178 WaitForSingleObjectEx.argtypes = [
179 wintypes.HANDLE,
180 wintypes.DWORD,
181 wintypes.BOOL,
182 ]
183 WaitForSingleObjectEx.restype = wintypes.DWORD
184
185 CreateEvent = _kernel32.CreateEventA
186 CreateEvent.argtypes = [
187 LPDWORD,
188 wintypes.BOOL,
189 wintypes.BOOL,
190 wintypes.LPSTR,
191 ]
192 CreateEvent.restype = wintypes.HANDLE
193
194 # Windows Vista is the minimum supported client for CancelIoEx.
195 CancelIoEx = _kernel32.CancelIoEx
196 CancelIoEx.argtypes = [wintypes.HANDLE, ctypes.POINTER(OVERLAPPED)]
197 CancelIoEx.restype = wintypes.BOOL
198
199 # 2 bytes marker, 1 byte int size, 8 bytes int64 value
200 sniff_len = 13
201
202 # This is a helper for debugging the client.
203 _debugging = False
204 if _debugging:
205
206 def log(fmt, *args):
207 print(
208 "[%s] %s"
209 % (
210 time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime()),
211 fmt % args[:],
212 )
213 )
214
215 else:
216
217 def log(fmt, *args):
218 pass
219
220
221 def _win32_strerror(err):
222 """expand a win32 error code into a human readable message"""
223
224 # FormatMessage will allocate memory and assign it here
225 buf = ctypes.c_char_p()
226 FormatMessage(
227 FORMAT_MESSAGE_FROM_SYSTEM
228 | FORMAT_MESSAGE_ALLOCATE_BUFFER
229 | FORMAT_MESSAGE_IGNORE_INSERTS,
230 None,
231 err,
232 0,
233 buf,
234 0,
235 None,
236 )
237 try:
238 return buf.value
239 finally:
240 LocalFree(buf)
241
242
243 class WatchmanError(Exception):
244 def __init__(self, msg=None, cmd=None):
245 self.msg = msg
246 self.cmd = cmd
247
248 def setCommand(self, cmd):
249 self.cmd = cmd
250
251 def __str__(self):
252 if self.cmd:
253 return "%s, while executing %s" % (self.msg, self.cmd)
254 return self.msg
255
256
257 class BSERv1Unsupported(WatchmanError):
258 pass
259
260
261 class UseAfterFork(WatchmanError):
262 pass
263
264
265 class WatchmanEnvironmentError(WatchmanError):
266 def __init__(self, msg, errno, errmsg, cmd=None):
267 super().__init__(f"{msg}: errno={errno} errmsg={errmsg}", cmd)
268
269
270 class SocketConnectError(WatchmanError):
271 def __init__(self, sockpath, exc):
272 super().__init__("unable to connect to %s: %s" % (sockpath, exc))
273 self.sockpath = sockpath
274 self.exc = exc
275
276
277 class SocketTimeout(WatchmanError):
278 """A specialized exception raised for socket timeouts during communication to/from watchman.
279 This makes it easier to implement non-blocking loops as callers can easily distinguish
280 between a routine timeout and an actual error condition.
281
282 Note that catching WatchmanError will also catch this as it is a super-class, so backwards
283 compatibility in exception handling is preserved.
284 """
285
286
287 class CommandError(WatchmanError):
288 """error returned by watchman
289
290 self.msg is the message returned by watchman.
291 """
292
293 def __init__(self, msg, cmd=None):
294 super().__init__("watchman command error: %s" % (msg,), cmd)
295
296
297 class Transport:
298 """communication transport to the watchman server"""
299
300 buf = None
301
302 def close(self):
303 """tear it down"""
304 raise NotImplementedError()
305
306 def readBytes(self, size):
307 """read size bytes"""
308 raise NotImplementedError()
309
310 def write(self, buf):
311 """write some data"""
312 raise NotImplementedError()
313
314 def setTimeout(self, value):
315 pass
316
317 def readLine(self):
318 """read a line
319 Maintains its own buffer, callers of the transport should not mix
320 calls to readBytes and readLine.
321 """
322 if self.buf is None:
323 self.buf = []
324
325 # Buffer may already have a line if we've received unilateral
326 # response(s) from the server
327 if len(self.buf) == 1 and b"\n" in self.buf[0]:
328 (line, b) = self.buf[0].split(b"\n", 1)
329 self.buf = [b]
330 return line
331
332 while True:
333 b = self.readBytes(4096)
334 if b"\n" in b:
335 result = b"".join(self.buf)
336 (line, b) = b.split(b"\n", 1)
337 self.buf = [b]
338 return result + line
339 self.buf.append(b)
340
341
342 class Codec:
343 """communication encoding for the watchman server"""
344
345 transport = None
346
347 def __init__(self, transport):
348 self.transport = transport
349
350 def receive(self):
351 raise NotImplementedError()
352
353 def send(self, *args):
354 raise NotImplementedError()
355
356 def setTimeout(self, value):
357 self.transport.setTimeout(value)
358
359
360 class UnixSocketTransport(Transport):
361 """local unix domain socket transport"""
362
363 sock = None
364
365 def __init__(self, sockpath, timeout):
366 self.sockpath = sockpath
367 self.timeout = timeout
368
369 sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
370 try:
371 sock.settimeout(self.timeout)
372 sock.connect(self.sockpath)
373 self.sock = sock
374 except OSError as e:
375 sock.close()
376 raise SocketConnectError(self.sockpath, e)
377
378 def close(self):
379 if self.sock:
380 self.sock.close()
381 self.sock = None
382
383 def setTimeout(self, value):
384 self.timeout = value
385 self.sock.settimeout(self.timeout)
386
387 def readBytes(self, size):
388 try:
389 buf = [self.sock.recv(size)]
390 if not buf[0]:
391 raise WatchmanError("empty watchman response")
392 return buf[0]
393 except socket.timeout:
394 raise SocketTimeout("timed out waiting for response")
395
396 def write(self, data):
397 try:
398 self.sock.sendall(data)
399 except socket.timeout:
400 raise SocketTimeout("timed out sending query command")
401
402
403 def _get_overlapped_result_ex_impl(pipe, olap, nbytes, millis, alertable):
404 """Windows 7 and earlier does not support GetOverlappedResultEx. The
405 alternative is to use GetOverlappedResult and wait for read or write
406 operation to complete. This is done be using CreateEvent and
407 WaitForSingleObjectEx. CreateEvent, WaitForSingleObjectEx
408 and GetOverlappedResult are all part of Windows API since WindowsXP.
409 This is the exact same implementation that can be found in the watchman
410 source code (see get_overlapped_result_ex_impl in stream_win.c). This
411 way, maintenance should be simplified.
412 """
413 log("Preparing to wait for maximum %dms", millis)
414 if millis != 0:
415 waitReturnCode = WaitForSingleObjectEx(olap.hEvent, millis, alertable)
416 if waitReturnCode == WAIT_OBJECT_0:
417 # Event is signaled, overlapped IO operation result should be available.
418 pass
419 elif waitReturnCode == WAIT_IO_COMPLETION:
420 # WaitForSingleObjectEx returnes because the system added an I/O completion
421 # routine or an asynchronous procedure call (APC) to the thread queue.
422 SetLastError(WAIT_IO_COMPLETION)
423 pass
424 elif waitReturnCode == WAIT_TIMEOUT:
425 # We reached the maximum allowed wait time, the IO operation failed
426 # to complete in timely fashion.
427 SetLastError(WAIT_TIMEOUT)
428 return False
429 elif waitReturnCode == WAIT_FAILED:
430 # something went wrong calling WaitForSingleObjectEx
431 err = GetLastError()
432 log("WaitForSingleObjectEx failed: %s", _win32_strerror(err))
433 return False
434 else:
435 # unexpected situation deserving investigation.
436 err = GetLastError()
437 log("Unexpected error: %s", _win32_strerror(err))
438 return False
439
440 return GetOverlappedResult(pipe, olap, nbytes, False)
441
442
443 class WindowsNamedPipeTransport(Transport):
444 """connect to a named pipe"""
445
446 def __init__(self, sockpath, timeout):
447 self.sockpath = sockpath
448 self.timeout = int(math.ceil(timeout * 1000))
449 self._iobuf = None
450
451 if compat.PYTHON3:
452 sockpath = os.fsencode(sockpath)
453 self.pipe = CreateFile(
454 sockpath,
455 GENERIC_READ | GENERIC_WRITE,
456 0,
457 None,
458 OPEN_EXISTING,
459 FILE_FLAG_OVERLAPPED,
460 None,
461 )
462
463 err = GetLastError()
464 if self.pipe == INVALID_HANDLE_VALUE or self.pipe == 0:
465 self.pipe = None
466 raise SocketConnectError(self.sockpath, self._make_win_err("", err))
467
468 # event for the overlapped I/O operations
469 self._waitable = CreateEvent(None, True, False, None)
470 err = GetLastError()
471 if self._waitable is None:
472 self._raise_win_err("CreateEvent failed", err)
473
474 self._get_overlapped_result_ex = GetOverlappedResultEx
475 if (
476 os.getenv("WATCHMAN_WIN7_COMPAT") == "1"
477 or self._get_overlapped_result_ex is None
478 ):
479 self._get_overlapped_result_ex = _get_overlapped_result_ex_impl
480
481 def _raise_win_err(self, msg, err):
482 raise self._make_win_err(msg, err)
483
484 def _make_win_err(self, msg, err):
485 return IOError(
486 "%s win32 error code: %d %s" % (msg, err, _win32_strerror(err))
487 )
488
489 def close(self):
490 if self.pipe:
491 log("Closing pipe")
492 CloseHandle(self.pipe)
493 self.pipe = None
494
495 if self._waitable is not None:
496 # We release the handle for the event
497 CloseHandle(self._waitable)
498 self._waitable = None
499
500 def setTimeout(self, value):
501 # convert to milliseconds
502 self.timeout = int(value * 1000)
503
504 def readBytes(self, size):
505 """A read can block for an unbounded amount of time, even if the
506 kernel reports that the pipe handle is signalled, so we need to
507 always perform our reads asynchronously
508 """
509
510 # try to satisfy the read from any buffered data
511 if self._iobuf:
512 if size >= len(self._iobuf):
513 res = self._iobuf
514 self.buf = None
515 return res
516 res = self._iobuf[:size]
517 self._iobuf = self._iobuf[size:]
518 return res
519
520 # We need to initiate a read
521 buf = ctypes.create_string_buffer(size)
522 olap = OVERLAPPED()
523 olap.hEvent = self._waitable
524
525 log("made read buff of size %d", size)
526
527 # ReadFile docs warn against sending in the nread parameter for async
528 # operations, so we always collect it via GetOverlappedResultEx
529 immediate = ReadFile(self.pipe, buf, size, None, olap)
530
531 if not immediate:
532 err = GetLastError()
533 if err != ERROR_IO_PENDING:
534 self._raise_win_err("failed to read %d bytes" % size, err)
535
536 nread = wintypes.DWORD()
537 if not self._get_overlapped_result_ex(
538 self.pipe, olap, nread, 0 if immediate else self.timeout, True
539 ):
540 err = GetLastError()
541 CancelIoEx(self.pipe, olap)
542
543 if err == WAIT_TIMEOUT:
544 log("GetOverlappedResultEx timedout")
545 raise SocketTimeout(
546 "timed out after waiting %dms for read" % self.timeout
547 )
548
549 log("GetOverlappedResultEx reports error %d", err)
550 self._raise_win_err("error while waiting for read", err)
551
552 nread = nread.value
553 if nread == 0:
554 # Docs say that named pipes return 0 byte when the other end did
555 # a zero byte write. Since we don't ever do that, the only
556 # other way this shows up is if the client has gotten in a weird
557 # state, so let's bail out
558 CancelIoEx(self.pipe, olap)
559 raise OSError("Async read yielded 0 bytes; unpossible!")
560
561 # Holds precisely the bytes that we read from the prior request
562 buf = buf[:nread]
563
564 returned_size = min(nread, size)
565 if returned_size == nread:
566 return buf
567
568 # keep any left-overs around for a later read to consume
569 self._iobuf = buf[returned_size:]
570 return buf[:returned_size]
571
572 def write(self, data):
573 olap = OVERLAPPED()
574 olap.hEvent = self._waitable
575
576 immediate = WriteFile(
577 self.pipe, ctypes.c_char_p(data), len(data), None, olap
578 )
579
580 if not immediate:
581 err = GetLastError()
582 if err != ERROR_IO_PENDING:
583 self._raise_win_err(
584 "failed to write %d bytes to handle %r"
585 % (len(data), self.pipe),
586 err,
587 )
588
589 # Obtain results, waiting if needed
590 nwrote = wintypes.DWORD()
591 if self._get_overlapped_result_ex(
592 self.pipe, olap, nwrote, 0 if immediate else self.timeout, True
593 ):
594 log("made write of %d bytes", nwrote.value)
595 return nwrote.value
596
597 err = GetLastError()
598
599 # It's potentially unsafe to allow the write to continue after
600 # we unwind, so let's make a best effort to avoid that happening
601 CancelIoEx(self.pipe, olap)
602
603 if err == WAIT_TIMEOUT:
604 raise SocketTimeout(
605 "timed out after waiting %dms for write" % self.timeout
606 )
607 self._raise_win_err(
608 "error while waiting for write of %d bytes" % len(data), err
609 )
610
611
612 def _default_binpath(binpath=None):
613 if binpath:
614 return binpath
615 # The test harness sets WATCHMAN_BINARY to the binary under test,
616 # so we use that by default, otherwise, allow resolving watchman
617 # from the users PATH.
618 return os.environ.get("WATCHMAN_BINARY", "watchman")
619
620
621 class CLIProcessTransport(Transport):
622 """open a pipe to the cli to talk to the service
623 This intended to be used only in the test harness!
624
625 The CLI is an oddball because we only support JSON input
626 and cannot send multiple commands through the same instance,
627 so we spawn a new process for each command.
628
629 We disable server spawning for this implementation, again, because
630 it is intended to be used only in our test harness. You really
631 should not need to use the CLI transport for anything real.
632
633 While the CLI can output in BSER, our Transport interface doesn't
634 support telling this instance that it should do so. That effectively
635 limits this implementation to JSON input and output only at this time.
636
637 It is the responsibility of the caller to set the send and
638 receive codecs appropriately.
639 """
640
641 proc = None
642 closed = True
643
644 def __init__(self, sockpath, timeout, binpath=None):
645 self.sockpath = sockpath
646 self.timeout = timeout
647 self.binpath = _default_binpath(binpath)
648
649 def close(self):
650 if self.proc:
651 if self.proc.pid is not None:
652 self.proc.kill()
653 self.proc.stdin.close()
654 self.proc.stdout.close()
655 self.proc.wait()
656 self.proc = None
657
658 def _connect(self):
659 if self.proc:
660 return self.proc
661 args = [
662 self.binpath,
663 f"--sockname={self.sockpath}",
664 "--logfile=/BOGUS",
665 "--statefile=/BOGUS",
666 "--no-spawn",
667 "--no-local",
668 "--no-pretty",
669 "-j",
670 ]
671 self.proc = subprocess.Popen(
672 args, stdin=subprocess.PIPE, stdout=subprocess.PIPE
673 )
674 return self.proc
675
676 def readBytes(self, size):
677 self._connect()
678 res = self.proc.stdout.read(size)
679 if not res:
680 raise WatchmanError("EOF on CLI process transport")
681 return res
682
683 def write(self, data):
684 if self.closed:
685 self.close()
686 self.closed = False
687 proc = self._connect()
688 res = proc.stdin.write(data)
689 proc.stdin.close()
690 self.closed = True
691 return res
692
693
694 class BserCodec(Codec):
695 """use the BSER encoding. This is the default, preferred codec"""
696
697 def __init__(self, transport, value_encoding, value_errors):
698 super().__init__(transport)
699 self._value_encoding = value_encoding
700 self._value_errors = value_errors
701
702 def _loads(self, response):
703 return bser.loads(
704 response,
705 value_encoding=self._value_encoding,
706 value_errors=self._value_errors,
707 )
708
709 def receive(self):
710 buf = [self.transport.readBytes(sniff_len)]
711 if not buf[0]:
712 raise WatchmanError("empty watchman response")
713
714 _1, _2, elen = bser.pdu_info(buf[0])
715
716 rlen = len(buf[0])
717 while elen > rlen:
718 buf.append(self.transport.readBytes(elen - rlen))
719 rlen += len(buf[-1])
720
721 response = b"".join(buf)
722 try:
723 res = self._loads(response)
724 return res
725 except ValueError as e:
726 raise WatchmanError("watchman response decode error: %s" % e)
727
728 def send(self, *args):
729 cmd = bser.dumps(*args) # Defaults to BSER v1
730 self.transport.write(cmd)
731
732
733 class ImmutableBserCodec(BserCodec):
734 """use the BSER encoding, decoding values using the newer
735 immutable object support"""
736
737 def _loads(self, response):
738 return bser.loads(
739 response,
740 False,
741 value_encoding=self._value_encoding,
742 value_errors=self._value_errors,
743 )
744
745
746 class Bser2WithFallbackCodec(BserCodec):
747 """use BSER v2 encoding"""
748
749 def __init__(self, transport, value_encoding, value_errors):
750 super().__init__(transport, value_encoding, value_errors)
751 if compat.PYTHON3:
752 bserv2_key = "required"
753 else:
754 bserv2_key = "optional"
755
756 self.send(["version", {bserv2_key: ["bser-v2"]}])
757
758 capabilities = self.receive()
759
760 if "error" in capabilities:
761 raise BSERv1Unsupported(
762 "The watchman server version does not support Python 3. Please "
763 "upgrade your watchman server."
764 )
765
766 if capabilities["capabilities"]["bser-v2"]:
767 self.bser_version = 2
768 self.bser_capabilities = 0
769 else:
770 self.bser_version = 1
771 self.bser_capabilities = 0
772
773 def receive(self):
774 buf = [self.transport.readBytes(sniff_len)]
775 if not buf[0]:
776 raise WatchmanError("empty watchman response")
777
778 recv_bser_version, recv_bser_capabilities, elen = bser.pdu_info(buf[0])
779
780 if hasattr(self, "bser_version"):
781 # Readjust BSER version and capabilities if necessary
782 self.bser_version = max(self.bser_version, recv_bser_version)
783 self.capabilities = self.bser_capabilities & recv_bser_capabilities
784
785 rlen = len(buf[0])
786 while elen > rlen:
787 buf.append(self.transport.readBytes(elen - rlen))
788 rlen += len(buf[-1])
789
790 response = b"".join(buf)
791 try:
792 res = self._loads(response)
793 return res
794 except ValueError as e:
795 raise WatchmanError("watchman response decode error: %s" % e)
796
797 def send(self, *args):
798 if hasattr(self, "bser_version"):
799 cmd = bser.dumps(
800 *args,
801 version=self.bser_version,
802 capabilities=self.bser_capabilities,
803 )
804 else:
805 cmd = bser.dumps(*args)
806 self.transport.write(cmd)
807
808
809 class ImmutableBser2Codec(Bser2WithFallbackCodec, ImmutableBserCodec):
810 """use the BSER encoding, decoding values using the newer
811 immutable object support"""
812
813 pass
814
815
816 class JsonCodec(Codec):
817 """Use json codec. This is here primarily for testing purposes"""
818
819 json = None
820
821 def __init__(self, transport):
822 super().__init__(transport)
823 # optional dep on json, only if JsonCodec is used
824 import json
825
826 self.json = json
827
828 def receive(self):
829 line = self.transport.readLine()
830 try:
831 # In Python 3, json.loads is a transformation from Unicode string to
832 # objects possibly containing Unicode strings. We typically expect
833 # the JSON blob to be ASCII-only with non-ASCII characters escaped,
834 # but it's possible we might get non-ASCII bytes that are valid
835 # UTF-8.
836 if compat.PYTHON3:
837 line = line.decode("utf-8")
838 return self.json.loads(line)
839 except Exception as e:
840 print(e, line)
841 raise
842
843 def send(self, *args):
844 cmd = self.json.dumps(*args)
845 # In Python 3, json.dumps is a transformation from objects possibly
846 # containing Unicode strings to Unicode string. Even with (the default)
847 # ensure_ascii=True, dumps returns a Unicode string.
848 if compat.PYTHON3:
849 cmd = cmd.encode("ascii")
850 self.transport.write(cmd + b"\n")
851
852
853 class client:
854 """Handles the communication with the watchman service"""
855
856 sockpath = None
857 transport = None
858 sendCodec = None
859 recvCodec = None
860 sendConn = None
861 recvConn = None
862 subs = {} # Keyed by subscription name
863 sub_by_root = {} # Keyed by root, then by subscription name
864 logs = [] # When log level is raised
865 unilateral = ["log", "subscription"]
866 tport = None
867 useImmutableBser = None
868 pid = None
869
870 def __init__(
871 self,
872 sockpath=None,
873 timeout=1.0,
874 transport=None,
875 sendEncoding=None,
876 recvEncoding=None,
877 useImmutableBser=False,
878 # use False for these two because None has a special
879 # meaning
880 valueEncoding=False,
881 valueErrors=False,
882 binpath=None,
883 ):
884 self.sockpath = sockpath
885 self.timeout = timeout
886 self.useImmutableBser = useImmutableBser
887 self.binpath = _default_binpath(binpath)
888
889 if inspect.isclass(transport) and issubclass(transport, Transport):
890 self.transport = transport
891 else:
892 transport = transport or os.getenv("WATCHMAN_TRANSPORT") or "local"
893 if transport == "local" and os.name == "nt":
894 self.transport = WindowsNamedPipeTransport
895 elif transport == "local":
896 self.transport = UnixSocketTransport
897 elif transport == "cli":
898 self.transport = CLIProcessTransport
899 if sendEncoding is None:
900 sendEncoding = "json"
901 if recvEncoding is None:
902 recvEncoding = sendEncoding
903 else:
904 raise WatchmanError("invalid transport %s" % transport)
905
906 sendEncoding = str(
907 sendEncoding or os.getenv("WATCHMAN_ENCODING") or "bser"
908 )
909 recvEncoding = str(
910 recvEncoding or os.getenv("WATCHMAN_ENCODING") or "bser"
911 )
912
913 self.recvCodec = self._parseEncoding(recvEncoding)
914 self.sendCodec = self._parseEncoding(sendEncoding)
915
916 # We want to act like the native OS methods as much as possible. This
917 # means returning bytestrings on Python 2 by default and Unicode
918 # strings on Python 3. However we take an optional argument that lets
919 # users override this.
920 if valueEncoding is False:
921 if compat.PYTHON3:
922 self.valueEncoding = encoding.get_local_encoding()
923 self.valueErrors = encoding.default_local_errors
924 else:
925 self.valueEncoding = None
926 self.valueErrors = None
927 else:
928 self.valueEncoding = valueEncoding
929 if valueErrors is False:
930 self.valueErrors = encoding.default_local_errors
931 else:
932 self.valueErrors = valueErrors
933
934 def _makeBSERCodec(self, codec):
935 def make_codec(transport):
936 return codec(transport, self.valueEncoding, self.valueErrors)
937
938 return make_codec
939
940 def _parseEncoding(self, enc):
941 if enc == "bser":
942 if self.useImmutableBser:
943 return self._makeBSERCodec(ImmutableBser2Codec)
944 return self._makeBSERCodec(Bser2WithFallbackCodec)
945 elif enc == "bser-v1":
946 if compat.PYTHON3:
947 raise BSERv1Unsupported(
948 "Python 3 does not support the BSER v1 encoding: specify "
949 '"bser" or omit the sendEncoding and recvEncoding '
950 "arguments"
951 )
952 if self.useImmutableBser:
953 return self._makeBSERCodec(ImmutableBserCodec)
954 return self._makeBSERCodec(BserCodec)
955 elif enc == "json":
956 return JsonCodec
957 else:
958 raise WatchmanError("invalid encoding %s" % enc)
959
960 def _hasprop(self, result, name):
961 if self.useImmutableBser:
962 return hasattr(result, name)
963 return name in result
964
965 def _resolvesockname(self):
966 # if invoked via a trigger, watchman will set this env var; we
967 # should use it unless explicitly set otherwise
968 path = os.getenv("WATCHMAN_SOCK")
969 if path:
970 return path
971
972 cmd = [self.binpath, "--output-encoding=bser", "get-sockname"]
973 try:
974 args = dict(
975 stdout=subprocess.PIPE, stderr=subprocess.PIPE
976 ) # noqa: C408
977
978 if os.name == "nt":
979 # if invoked via an application with graphical user interface,
980 # this call will cause a brief command window pop-up.
981 # Using the flag STARTF_USESHOWWINDOW to avoid this behavior.
982
983 # pytype: disable=module-attr
984 startupinfo = subprocess.STARTUPINFO()
985 startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
986 # pytype: enable=module-attr
987
988 args["startupinfo"] = startupinfo
989
990 p = subprocess.Popen(cmd, **args)
991
992 except OSError as e:
993 raise WatchmanError('"watchman" executable not in PATH (%s)' % e)
994
995 stdout, stderr = p.communicate()
996 exitcode = p.poll()
997
998 if exitcode:
999 raise WatchmanError("watchman exited with code %d" % exitcode)
1000
1001 result = bser.loads(stdout)
1002 if "error" in result:
1003 raise WatchmanError("get-sockname error: %s" % result["error"])
1004
1005 return result["sockname"]
1006
1007 def _connect(self):
1008 """establish transport connection"""
1009
1010 if self.recvConn:
1011 if self.pid != os.getpid():
1012 raise UseAfterFork(
1013 "do not re-use a connection after fork; open a new client instead"
1014 )
1015 return
1016
1017 if self.sockpath is None:
1018 self.sockpath = self._resolvesockname()
1019
1020 kwargs = {}
1021 if self.transport == CLIProcessTransport:
1022 kwargs["binpath"] = self.binpath
1023
1024 # Only CLIProcessTransport has the binpath kwarg
1025 # pytype: disable=wrong-keyword-args
1026 self.tport = self.transport(self.sockpath, self.timeout, **kwargs)
1027 # pytype: enable=wrong-keyword-args
1028
1029 self.sendConn = self.sendCodec(self.tport)
1030 self.recvConn = self.recvCodec(self.tport)
1031 self.pid = os.getpid()
1032
1033 def __del__(self):
1034 self.close()
1035
1036 def __enter__(self):
1037 self._connect()
1038 return self
1039
1040 def __exit__(self, exc_type, exc_value, exc_traceback):
1041 self.close()
1042
1043 def close(self):
1044 if self.tport:
1045 self.tport.close()
1046 self.tport = None
1047 self.recvConn = None
1048 self.sendConn = None
1049
1050 def receive(self):
1051 """receive the next PDU from the watchman service
1052
1053 If the client has activated subscriptions or logs then
1054 this PDU may be a unilateral PDU sent by the service to
1055 inform the client of a log event or subscription change.
1056
1057 It may also simply be the response portion of a request
1058 initiated by query.
1059
1060 There are clients in production that subscribe and call
1061 this in a loop to retrieve all subscription responses,
1062 so care should be taken when making changes here.
1063 """
1064
1065 self._connect()
1066 result = self.recvConn.receive()
1067 if self._hasprop(result, "error"):
1068 raise CommandError(result["error"])
1069
1070 if self._hasprop(result, "log"):
1071 self.logs.append(result["log"])
1072
1073 if self._hasprop(result, "subscription"):
1074 sub = result["subscription"]
1075 if not (sub in self.subs):
1076 self.subs[sub] = []
1077 self.subs[sub].append(result)
1078
1079 # also accumulate in {root,sub} keyed store
1080 root = os.path.normpath(os.path.normcase(result["root"]))
1081 if not root in self.sub_by_root:
1082 self.sub_by_root[root] = {}
1083 if not sub in self.sub_by_root[root]:
1084 self.sub_by_root[root][sub] = []
1085 self.sub_by_root[root][sub].append(result)
1086
1087 return result
1088
1089 def isUnilateralResponse(self, res):
1090 if "unilateral" in res and res["unilateral"]:
1091 return True
1092 # Fall back to checking for known unilateral responses
1093 for k in self.unilateral:
1094 if k in res:
1095 return True
1096 return False
1097
1098 def getLog(self, remove=True):
1099 """Retrieve buffered log data
1100
1101 If remove is true the data will be removed from the buffer.
1102 Otherwise it will be left in the buffer
1103 """
1104 res = self.logs
1105 if remove:
1106 self.logs = []
1107 return res
1108
1109 def getSubscription(self, name, remove=True, root=None):
1110 """Retrieve the data associated with a named subscription
1111
1112 If remove is True (the default), the subscription data is removed
1113 from the buffer. Otherwise the data is returned but left in
1114 the buffer.
1115
1116 Returns None if there is no data associated with `name`
1117
1118 If root is not None, then only return the subscription
1119 data that matches both root and name. When used in this way,
1120 remove processing impacts both the unscoped and scoped stores
1121 for the subscription data.
1122 """
1123 if root is not None:
1124 root = os.path.normpath(os.path.normcase(root))
1125 if root not in self.sub_by_root:
1126 return None
1127 if name not in self.sub_by_root[root]:
1128 return None
1129 sub = self.sub_by_root[root][name]
1130 if remove:
1131 del self.sub_by_root[root][name]
1132 # don't let this grow unbounded
1133 if name in self.subs:
1134 del self.subs[name]
1135 return sub
1136
1137 if name not in self.subs:
1138 return None
1139 sub = self.subs[name]
1140 if remove:
1141 del self.subs[name]
1142 return sub
1143
1144 def query(self, *args):
1145 """Send a query to the watchman service and return the response
1146
1147 This call will block until the response is returned.
1148 If any unilateral responses are sent by the service in between
1149 the request-response they will be buffered up in the client object
1150 and NOT returned via this method.
1151 """
1152
1153 log("calling client.query")
1154 self._connect()
1155 try:
1156 self.sendConn.send(args)
1157
1158 res = self.receive()
1159 while self.isUnilateralResponse(res):
1160 res = self.receive()
1161
1162 return res
1163 except OSError as ee:
1164 # When we can depend on Python 3, we can use PEP 3134
1165 # exception chaining here.
1166 raise WatchmanEnvironmentError(
1167 "I/O error communicating with watchman daemon",
1168 ee.errno,
1169 ee.strerror,
1170 args,
1171 )
1172 except WatchmanError as ex:
1173 ex.setCommand(args)
1174 raise
1175
1176 def capabilityCheck(self, optional=None, required=None):
1177 """Perform a server capability check"""
1178 res = self.query(
1179 "version", {"optional": optional or [], "required": required or []}
1180 )
1181
1182 if not self._hasprop(res, "capabilities"):
1183 # Server doesn't support capabilities, so we need to
1184 # synthesize the results based on the version
1185 capabilities.synthesize(res, optional)
1186 if "error" in res:
1187 raise CommandError(res["error"])
1188
1189 return res
1190
1191 def setTimeout(self, value):
1192 self.recvConn.setTimeout(value)
1193 self.sendConn.setTimeout(value)