OpenStack Telemetry (Ceilometer)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

342 lines
11KB

  1. #
  2. # Copyright 2013 Intel Corp.
  3. # Copyright 2014 Red Hat, Inc
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. import abc
  17. from oslo_config import cfg
  18. from oslo_log import log
  19. import oslo_messaging
  20. import six
  21. from ceilometer import agent
  22. from ceilometer import publisher
  23. OPTS = [
  24. cfg.StrOpt('pipeline_cfg_file',
  25. default="pipeline.yaml",
  26. help="Configuration file for pipeline definition."
  27. ),
  28. cfg.StrOpt('event_pipeline_cfg_file',
  29. default="event_pipeline.yaml",
  30. help="Configuration file for event pipeline definition."
  31. ),
  32. ]
  33. LOG = log.getLogger(__name__)
  34. class PipelineException(agent.ConfigException):
  35. def __init__(self, message, cfg):
  36. super(PipelineException, self).__init__('Pipeline', message, cfg)
  37. class PublishContext(object):
  38. def __init__(self, pipelines):
  39. self.pipelines = pipelines or []
  40. def __enter__(self):
  41. def p(data):
  42. for p in self.pipelines:
  43. p.publish_data(data)
  44. return p
  45. def __exit__(self, exc_type, exc_value, traceback):
  46. for p in self.pipelines:
  47. p.flush()
  48. class PipelineSource(agent.Source):
  49. """Represents a source of samples or events."""
  50. def __init__(self, cfg):
  51. try:
  52. super(PipelineSource, self).__init__(cfg)
  53. except agent.SourceException as err:
  54. raise PipelineException(err.msg, cfg)
  55. try:
  56. self.sinks = cfg['sinks']
  57. except KeyError as err:
  58. raise PipelineException(
  59. "Required field %s not specified" % err.args[0], cfg)
  60. def check_sinks(self, sinks):
  61. if not self.sinks:
  62. raise PipelineException(
  63. "No sink defined in source %s" % self,
  64. self.cfg)
  65. for sink in self.sinks:
  66. if sink not in sinks:
  67. raise PipelineException(
  68. "Dangling sink %s from source %s" % (sink, self),
  69. self.cfg)
  70. class Sink(object):
  71. """Represents a sink for the transformation and publication of data.
  72. Each sink config is concerned *only* with the transformation rules
  73. and publication conduits for data.
  74. In effect, a sink describes a chain of handlers. The chain ends with one or
  75. more publishers.
  76. At the end of the chain, publishers publish the data. The exact
  77. publishing method depends on publisher type, for example, pushing
  78. into data storage via the message bus providing guaranteed delivery,
  79. or for loss-tolerant data UDP may be used.
  80. """
  81. def __init__(self, conf, cfg, publisher_manager):
  82. self.conf = conf
  83. self.cfg = cfg
  84. try:
  85. self.name = cfg['name']
  86. except KeyError as err:
  87. raise PipelineException(
  88. "Required field %s not specified" % err.args[0], cfg)
  89. if not cfg.get('publishers'):
  90. raise PipelineException("No publisher specified", cfg)
  91. self.publishers = []
  92. for p in cfg['publishers']:
  93. if '://' not in p:
  94. # Support old format without URL
  95. p = p + "://"
  96. try:
  97. self.publishers.append(publisher_manager.get(p))
  98. except Exception:
  99. LOG.error("Unable to load publisher %s", p,
  100. exc_info=True)
  101. self.multi_publish = True if len(self.publishers) > 1 else False
  102. def __str__(self):
  103. return self.name
  104. @staticmethod
  105. def flush():
  106. """Flush data after all events have been injected to pipeline."""
  107. @six.add_metaclass(abc.ABCMeta)
  108. class Pipeline(object):
  109. """Represents a coupling between a sink and a corresponding source."""
  110. def __init__(self, conf, source, sink):
  111. self.conf = conf
  112. self.source = source
  113. self.sink = sink
  114. self.name = str(self)
  115. def __str__(self):
  116. return (self.source.name if self.source.name == self.sink.name
  117. else '%s:%s' % (self.source.name, self.sink.name))
  118. def flush(self):
  119. self.sink.flush()
  120. @property
  121. def publishers(self):
  122. return self.sink.publishers
  123. @abc.abstractmethod
  124. def publish_data(self, data):
  125. """Publish data from pipeline."""
  126. @abc.abstractmethod
  127. def supported(self, data):
  128. """Attribute to filter on. Pass if no partitioning."""
  129. class PublisherManager(object):
  130. def __init__(self, conf, purpose):
  131. self._loaded_publishers = {}
  132. self._conf = conf
  133. self._purpose = purpose
  134. def get(self, url):
  135. if url not in self._loaded_publishers:
  136. p = publisher.get_publisher(
  137. self._conf, url,
  138. 'ceilometer.%s.publisher' % self._purpose)
  139. self._loaded_publishers[url] = p
  140. return self._loaded_publishers[url]
  141. class PipelineManager(agent.ConfigManagerBase):
  142. """Pipeline Manager
  143. Pipeline manager sets up pipelines according to config file
  144. """
  145. def __init__(self, conf, cfg_file):
  146. """Setup the pipelines according to config.
  147. The configuration is supported as follows:
  148. Decoupled: the source and sink configuration are separately
  149. specified before being linked together. This allows source-
  150. specific configuration, such as meter handling, to be
  151. kept focused only on the fine-grained source while avoiding
  152. the necessity for wide duplication of sink-related config.
  153. The configuration is provided in the form of separate lists
  154. of dictionaries defining sources and sinks, for example:
  155. {"sources": [{"name": source_1,
  156. "meters" : ["meter_1", "meter_2"],
  157. "sinks" : ["sink_1", "sink_2"]
  158. },
  159. {"name": source_2,
  160. "meters" : ["meter_3"],
  161. "sinks" : ["sink_2"]
  162. },
  163. ],
  164. "sinks": [{"name": sink_1,
  165. "publishers": ["publisher_1", "publisher_2"]
  166. },
  167. {"name": sink_2,
  168. "publishers": ["publisher_3"]
  169. },
  170. ]
  171. }
  172. Valid meter format is '*', '!meter_name', or 'meter_name'.
  173. '*' is wildcard symbol means any meters; '!meter_name' means
  174. "meter_name" will be excluded; 'meter_name' means 'meter_name'
  175. will be included.
  176. Valid meters definition is all "included meter names", all
  177. "excluded meter names", wildcard and "excluded meter names", or
  178. only wildcard.
  179. Publisher's name is plugin name in setup.cfg
  180. """
  181. super(PipelineManager, self).__init__(conf)
  182. cfg = self.load_config(cfg_file)
  183. self.pipelines = []
  184. if not ('sources' in cfg and 'sinks' in cfg):
  185. raise PipelineException("Both sources & sinks are required",
  186. cfg)
  187. publisher_manager = PublisherManager(self.conf, self.pm_type)
  188. unique_names = set()
  189. sources = []
  190. for s in cfg.get('sources'):
  191. name = s.get('name')
  192. if name in unique_names:
  193. raise PipelineException("Duplicated source names: %s" %
  194. name, self)
  195. else:
  196. unique_names.add(name)
  197. sources.append(self.pm_source(s))
  198. unique_names.clear()
  199. sinks = {}
  200. for s in cfg.get('sinks'):
  201. name = s.get('name')
  202. if name in unique_names:
  203. raise PipelineException("Duplicated sink names: %s" %
  204. name, self)
  205. else:
  206. unique_names.add(name)
  207. sinks[s['name']] = self.pm_sink(self.conf, s,
  208. publisher_manager)
  209. unique_names.clear()
  210. for source in sources:
  211. source.check_sinks(sinks)
  212. for target in source.sinks:
  213. pipe = self.pm_pipeline(self.conf, source, sinks[target])
  214. if pipe.name in unique_names:
  215. raise PipelineException(
  216. "Duplicate pipeline name: %s. Ensure pipeline"
  217. " names are unique. (name is the source and sink"
  218. " names combined)" % pipe.name, cfg)
  219. else:
  220. unique_names.add(pipe.name)
  221. self.pipelines.append(pipe)
  222. unique_names.clear()
  223. @abc.abstractproperty
  224. def pm_type(self):
  225. """Pipeline manager type."""
  226. @abc.abstractproperty
  227. def pm_pipeline(self):
  228. """Pipeline class"""
  229. @abc.abstractproperty
  230. def pm_source(self):
  231. """Pipeline source class"""
  232. @abc.abstractproperty
  233. def pm_sink(self):
  234. """Pipeline sink class"""
  235. def publisher(self):
  236. """Build publisher for pipeline publishing."""
  237. return PublishContext(self.pipelines)
  238. def get_main_endpoints(self):
  239. """Return endpoints for main queue."""
  240. pass
  241. class NotificationEndpoint(object):
  242. """Base Endpoint for plugins that support the notification API."""
  243. event_types = []
  244. """List of strings to filter messages on."""
  245. def __init__(self, conf, publisher):
  246. super(NotificationEndpoint, self).__init__()
  247. # NOTE(gordc): this is filter rule used by oslo.messaging to dispatch
  248. # messages to an endpoint.
  249. if self.event_types:
  250. self.filter_rule = oslo_messaging.NotificationFilter(
  251. event_type='|'.join(self.event_types))
  252. self.conf = conf
  253. self.publisher = publisher
  254. @abc.abstractmethod
  255. def process_notifications(self, priority, notifications):
  256. """Return a sequence of Counter instances for the given message.
  257. :param message: Message to process.
  258. """
  259. @classmethod
  260. def _consume_and_drop(cls, notifications):
  261. """RPC endpoint for useless notification level"""
  262. # NOTE(sileht): nothing special todo here, but because we listen
  263. # for the generic notification exchange we have to consume all its
  264. # queues
  265. audit = _consume_and_drop
  266. critical = _consume_and_drop
  267. debug = _consume_and_drop
  268. error = _consume_and_drop
  269. info = _consume_and_drop
  270. sample = _consume_and_drop
  271. warn = _consume_and_drop