port_alert.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. """
  3. Licensed to the Apache Software Foundation (ASF) under one
  4. or more contributor license agreements. See the NOTICE file
  5. distributed with this work for additional information
  6. regarding copyright ownership. The ASF licenses this file
  7. to you under the Apache License, Version 2.0 (the
  8. "License"); you may not use this file except in compliance
  9. with the License. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. """
  17. import logging
  18. import socket
  19. import time
  20. from alerts.base_alert import BaseAlert
  21. from resource_management.libraries.functions.get_port_from_url import get_port_from_url
  22. logger = logging.getLogger()
  23. class PortAlert(BaseAlert):
  24. def __init__(self, alert_meta, alert_source_meta):
  25. super(PortAlert, self).__init__(alert_meta, alert_source_meta)
  26. # can be parameterized
  27. self.uri = self._find_lookup_property(alert_source_meta['uri'])
  28. self.port = alert_source_meta['default_port']
  29. def _collect(self):
  30. urivalue = self._lookup_property_value(self.uri)
  31. port = self.port
  32. host = BaseAlert.get_host_from_url(urivalue)
  33. if host is None:
  34. host = self.host_name
  35. try:
  36. port = int(get_port_from_url(urivalue))
  37. except:
  38. # if port not found, default port already set to port
  39. pass
  40. if logger.isEnabledFor(logging.DEBUG):
  41. logger.debug("checking {0} listening on port {1}".format(host, str(port)))
  42. try:
  43. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  44. s.settimeout(1.5)
  45. t = time.time()
  46. s.connect((host, port))
  47. millis = time.time() - t
  48. return (self.RESULT_OK, [millis/1000, port])
  49. except Exception as e:
  50. return (self.RESULT_CRITICAL, [str(e), host, port])
  51. finally:
  52. if s is not None:
  53. try:
  54. s.close()
  55. except:
  56. pass