_parser.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # -*- test-case-name: twisted.protocols.haproxy.test.test_parser -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Parser for 'haproxy:' string endpoint.
  6. """
  7. from typing import Mapping, Tuple
  8. from zope.interface import implementer
  9. from twisted.internet import interfaces
  10. from twisted.internet.endpoints import (
  11. IStreamServerEndpointStringParser,
  12. _WrapperServerEndpoint,
  13. quoteStringArgument,
  14. serverFromString,
  15. )
  16. from twisted.plugin import IPlugin
  17. from . import proxyEndpoint
  18. def unparseEndpoint(args: Tuple[object, ...], kwargs: Mapping[str, object]) -> str:
  19. """
  20. Un-parse the already-parsed args and kwargs back into endpoint syntax.
  21. @param args: C{:}-separated arguments
  22. @param kwargs: C{:} and then C{=}-separated keyword arguments
  23. @return: a string equivalent to the original format which this was parsed
  24. as.
  25. """
  26. description = ":".join(
  27. [quoteStringArgument(str(arg)) for arg in args]
  28. + sorted(
  29. "{}={}".format(
  30. quoteStringArgument(str(key)), quoteStringArgument(str(value))
  31. )
  32. for key, value in kwargs.items()
  33. )
  34. )
  35. return description
  36. @implementer(IPlugin, IStreamServerEndpointStringParser)
  37. class HAProxyServerParser:
  38. """
  39. Stream server endpoint string parser for the HAProxyServerEndpoint type.
  40. @ivar prefix: See L{IStreamServerEndpointStringParser.prefix}.
  41. """
  42. prefix = "haproxy"
  43. def parseStreamServer(
  44. self, reactor: interfaces.IReactorCore, *args: object, **kwargs: object
  45. ) -> _WrapperServerEndpoint:
  46. """
  47. Parse a stream server endpoint from a reactor and string-only arguments
  48. and keyword arguments.
  49. @param reactor: The reactor.
  50. @param args: The parsed string arguments.
  51. @param kwargs: The parsed keyword arguments.
  52. @return: a stream server endpoint
  53. @rtype: L{IStreamServerEndpoint}
  54. """
  55. subdescription = unparseEndpoint(args, kwargs)
  56. wrappedEndpoint = serverFromString(reactor, subdescription)
  57. return proxyEndpoint(wrappedEndpoint)