id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
236,100
kkroening/ffmpeg-python
ffmpeg/_filters.py
trim
def trim(stream, **kwargs): """Trim the input so that the output contains one continuous subpart of the input. Args: start: Specify the time of the start of the kept section, i.e. the frame with the timestamp start will be the first frame in the output. end: Specify the time of the first frame that will be dropped, i.e. the frame immediately preceding the one with the timestamp end will be the last frame in the output. start_pts: This is the same as start, except this option sets the start timestamp in timebase units instead of seconds. end_pts: This is the same as end, except this option sets the end timestamp in timebase units instead of seconds. duration: The maximum duration of the output in seconds. start_frame: The number of the first frame that should be passed to the output. end_frame: The number of the first frame that should be dropped. Official documentation: `trim <https://ffmpeg.org/ffmpeg-filters.html#trim>`__ """ return FilterNode(stream, trim.__name__, kwargs=kwargs).stream()
python
def trim(stream, **kwargs): return FilterNode(stream, trim.__name__, kwargs=kwargs).stream()
[ "def", "trim", "(", "stream", ",", "*", "*", "kwargs", ")", ":", "return", "FilterNode", "(", "stream", ",", "trim", ".", "__name__", ",", "kwargs", "=", "kwargs", ")", ".", "stream", "(", ")" ]
Trim the input so that the output contains one continuous subpart of the input. Args: start: Specify the time of the start of the kept section, i.e. the frame with the timestamp start will be the first frame in the output. end: Specify the time of the first frame that will be dropped, i.e. the frame immediately preceding the one with the timestamp end will be the last frame in the output. start_pts: This is the same as start, except this option sets the start timestamp in timebase units instead of seconds. end_pts: This is the same as end, except this option sets the end timestamp in timebase units instead of seconds. duration: The maximum duration of the output in seconds. start_frame: The number of the first frame that should be passed to the output. end_frame: The number of the first frame that should be dropped. Official documentation: `trim <https://ffmpeg.org/ffmpeg-filters.html#trim>`__
[ "Trim", "the", "input", "so", "that", "the", "output", "contains", "one", "continuous", "subpart", "of", "the", "input", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L81-L99
236,101
kkroening/ffmpeg-python
ffmpeg/_filters.py
overlay
def overlay(main_parent_node, overlay_parent_node, eof_action='repeat', **kwargs): """Overlay one video on top of another. Args: x: Set the expression for the x coordinates of the overlaid video on the main video. Default value is 0. In case the expression is invalid, it is set to a huge value (meaning that the overlay will not be displayed within the output visible area). y: Set the expression for the y coordinates of the overlaid video on the main video. Default value is 0. In case the expression is invalid, it is set to a huge value (meaning that the overlay will not be displayed within the output visible area). eof_action: The action to take when EOF is encountered on the secondary input; it accepts one of the following values: * ``repeat``: Repeat the last frame (the default). * ``endall``: End both streams. * ``pass``: Pass the main input through. eval: Set when the expressions for x, and y are evaluated. It accepts the following values: * ``init``: only evaluate expressions once during the filter initialization or when a command is processed * ``frame``: evaluate expressions for each incoming frame Default value is ``frame``. shortest: If set to 1, force the output to terminate when the shortest input terminates. Default value is 0. format: Set the format for the output video. It accepts the following values: * ``yuv420``: force YUV420 output * ``yuv422``: force YUV422 output * ``yuv444``: force YUV444 output * ``rgb``: force packed RGB output * ``gbrp``: force planar RGB output Default value is ``yuv420``. rgb (deprecated): If set to 1, force the filter to accept inputs in the RGB color space. Default value is 0. This option is deprecated, use format instead. repeatlast: If set to 1, force the filter to draw the last overlay frame over the main input until the end of the stream. A value of 0 disables this behavior. Default value is 1. Official documentation: `overlay <https://ffmpeg.org/ffmpeg-filters.html#overlay-1>`__ """ kwargs['eof_action'] = eof_action return FilterNode([main_parent_node, overlay_parent_node], overlay.__name__, kwargs=kwargs, max_inputs=2).stream()
python
def overlay(main_parent_node, overlay_parent_node, eof_action='repeat', **kwargs): kwargs['eof_action'] = eof_action return FilterNode([main_parent_node, overlay_parent_node], overlay.__name__, kwargs=kwargs, max_inputs=2).stream()
[ "def", "overlay", "(", "main_parent_node", ",", "overlay_parent_node", ",", "eof_action", "=", "'repeat'", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'eof_action'", "]", "=", "eof_action", "return", "FilterNode", "(", "[", "main_parent_node", ",", "ove...
Overlay one video on top of another. Args: x: Set the expression for the x coordinates of the overlaid video on the main video. Default value is 0. In case the expression is invalid, it is set to a huge value (meaning that the overlay will not be displayed within the output visible area). y: Set the expression for the y coordinates of the overlaid video on the main video. Default value is 0. In case the expression is invalid, it is set to a huge value (meaning that the overlay will not be displayed within the output visible area). eof_action: The action to take when EOF is encountered on the secondary input; it accepts one of the following values: * ``repeat``: Repeat the last frame (the default). * ``endall``: End both streams. * ``pass``: Pass the main input through. eval: Set when the expressions for x, and y are evaluated. It accepts the following values: * ``init``: only evaluate expressions once during the filter initialization or when a command is processed * ``frame``: evaluate expressions for each incoming frame Default value is ``frame``. shortest: If set to 1, force the output to terminate when the shortest input terminates. Default value is 0. format: Set the format for the output video. It accepts the following values: * ``yuv420``: force YUV420 output * ``yuv422``: force YUV422 output * ``yuv444``: force YUV444 output * ``rgb``: force packed RGB output * ``gbrp``: force planar RGB output Default value is ``yuv420``. rgb (deprecated): If set to 1, force the filter to accept inputs in the RGB color space. Default value is 0. This option is deprecated, use format instead. repeatlast: If set to 1, force the filter to draw the last overlay frame over the main input until the end of the stream. A value of 0 disables this behavior. Default value is 1. Official documentation: `overlay <https://ffmpeg.org/ffmpeg-filters.html#overlay-1>`__
[ "Overlay", "one", "video", "on", "top", "of", "another", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L103-L147
236,102
kkroening/ffmpeg-python
ffmpeg/_filters.py
crop
def crop(stream, x, y, width, height, **kwargs): """Crop the input video. Args: x: The horizontal position, in the input video, of the left edge of the output video. y: The vertical position, in the input video, of the top edge of the output video. width: The width of the output video. Must be greater than 0. heigth: The height of the output video. Must be greater than 0. Official documentation: `crop <https://ffmpeg.org/ffmpeg-filters.html#crop>`__ """ return FilterNode( stream, crop.__name__, args=[width, height, x, y], kwargs=kwargs ).stream()
python
def crop(stream, x, y, width, height, **kwargs): return FilterNode( stream, crop.__name__, args=[width, height, x, y], kwargs=kwargs ).stream()
[ "def", "crop", "(", "stream", ",", "x", ",", "y", ",", "width", ",", "height", ",", "*", "*", "kwargs", ")", ":", "return", "FilterNode", "(", "stream", ",", "crop", ".", "__name__", ",", "args", "=", "[", "width", ",", "height", ",", "x", ",", ...
Crop the input video. Args: x: The horizontal position, in the input video, of the left edge of the output video. y: The vertical position, in the input video, of the top edge of the output video. width: The width of the output video. Must be greater than 0. heigth: The height of the output video. Must be greater than 0. Official documentation: `crop <https://ffmpeg.org/ffmpeg-filters.html#crop>`__
[ "Crop", "the", "input", "video", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L169-L187
236,103
kkroening/ffmpeg-python
ffmpeg/_filters.py
drawbox
def drawbox(stream, x, y, width, height, color, thickness=None, **kwargs): """Draw a colored box on the input image. Args: x: The expression which specifies the top left corner x coordinate of the box. It defaults to 0. y: The expression which specifies the top left corner y coordinate of the box. It defaults to 0. width: Specify the width of the box; if 0 interpreted as the input width. It defaults to 0. heigth: Specify the height of the box; if 0 interpreted as the input height. It defaults to 0. color: Specify the color of the box to write. For the general syntax of this option, check the "Color" section in the ffmpeg-utils manual. If the special value invert is used, the box edge color is the same as the video with inverted luma. thickness: The expression which sets the thickness of the box edge. Default value is 3. w: Alias for ``width``. h: Alias for ``height``. c: Alias for ``color``. t: Alias for ``thickness``. Official documentation: `drawbox <https://ffmpeg.org/ffmpeg-filters.html#drawbox>`__ """ if thickness: kwargs['t'] = thickness return FilterNode(stream, drawbox.__name__, args=[x, y, width, height, color], kwargs=kwargs).stream()
python
def drawbox(stream, x, y, width, height, color, thickness=None, **kwargs): if thickness: kwargs['t'] = thickness return FilterNode(stream, drawbox.__name__, args=[x, y, width, height, color], kwargs=kwargs).stream()
[ "def", "drawbox", "(", "stream", ",", "x", ",", "y", ",", "width", ",", "height", ",", "color", ",", "thickness", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "thickness", ":", "kwargs", "[", "'t'", "]", "=", "thickness", "return", "Filter...
Draw a colored box on the input image. Args: x: The expression which specifies the top left corner x coordinate of the box. It defaults to 0. y: The expression which specifies the top left corner y coordinate of the box. It defaults to 0. width: Specify the width of the box; if 0 interpreted as the input width. It defaults to 0. heigth: Specify the height of the box; if 0 interpreted as the input height. It defaults to 0. color: Specify the color of the box to write. For the general syntax of this option, check the "Color" section in the ffmpeg-utils manual. If the special value invert is used, the box edge color is the same as the video with inverted luma. thickness: The expression which sets the thickness of the box edge. Default value is 3. w: Alias for ``width``. h: Alias for ``height``. c: Alias for ``color``. t: Alias for ``thickness``. Official documentation: `drawbox <https://ffmpeg.org/ffmpeg-filters.html#drawbox>`__
[ "Draw", "a", "colored", "box", "on", "the", "input", "image", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L191-L212
236,104
kkroening/ffmpeg-python
ffmpeg/_filters.py
drawtext
def drawtext(stream, text=None, x=0, y=0, escape_text=True, **kwargs): """Draw a text string or text from a specified file on top of a video, using the libfreetype library. To enable compilation of this filter, you need to configure FFmpeg with ``--enable-libfreetype``. To enable default font fallback and the font option you need to configure FFmpeg with ``--enable-libfontconfig``. To enable the text_shaping option, you need to configure FFmpeg with ``--enable-libfribidi``. Args: box: Used to draw a box around text using the background color. The value must be either 1 (enable) or 0 (disable). The default value of box is 0. boxborderw: Set the width of the border to be drawn around the box using boxcolor. The default value of boxborderw is 0. boxcolor: The color to be used for drawing box around text. For the syntax of this option, check the "Color" section in the ffmpeg-utils manual. The default value of boxcolor is "white". line_spacing: Set the line spacing in pixels of the border to be drawn around the box using box. The default value of line_spacing is 0. borderw: Set the width of the border to be drawn around the text using bordercolor. The default value of borderw is 0. bordercolor: Set the color to be used for drawing border around text. For the syntax of this option, check the "Color" section in the ffmpeg-utils manual. The default value of bordercolor is "black". expansion: Select how the text is expanded. Can be either none, strftime (deprecated) or normal (default). See the Text expansion section below for details. basetime: Set a start time for the count. Value is in microseconds. Only applied in the deprecated strftime expansion mode. To emulate in normal expansion mode use the pts function, supplying the start time (in seconds) as the second argument. fix_bounds: If true, check and fix text coords to avoid clipping. fontcolor: The color to be used for drawing fonts. For the syntax of this option, check the "Color" section in the ffmpeg-utils manual. The default value of fontcolor is "black". fontcolor_expr: String which is expanded the same way as text to obtain dynamic fontcolor value. By default this option has empty value and is not processed. When this option is set, it overrides fontcolor option. font: The font family to be used for drawing text. By default Sans. fontfile: The font file to be used for drawing text. The path must be included. This parameter is mandatory if the fontconfig support is disabled. alpha: Draw the text applying alpha blending. The value can be a number between 0.0 and 1.0. The expression accepts the same variables x, y as well. The default value is 1. Please see fontcolor_expr. fontsize: The font size to be used for drawing text. The default value of fontsize is 16. text_shaping: If set to 1, attempt to shape the text (for example, reverse the order of right-to-left text and join Arabic characters) before drawing it. Otherwise, just draw the text exactly as given. By default 1 (if supported). ft_load_flags: The flags to be used for loading the fonts. The flags map the corresponding flags supported by libfreetype, and are a combination of the following values: * ``default`` * ``no_scale`` * ``no_hinting`` * ``render`` * ``no_bitmap`` * ``vertical_layout`` * ``force_autohint`` * ``crop_bitmap`` * ``pedantic`` * ``ignore_global_advance_width`` * ``no_recurse`` * ``ignore_transform`` * ``monochrome`` * ``linear_design`` * ``no_autohint`` Default value is "default". For more information consult the documentation for the FT_LOAD_* libfreetype flags. shadowcolor: The color to be used for drawing a shadow behind the drawn text. For the syntax of this option, check the "Color" section in the ffmpeg-utils manual. The default value of shadowcolor is "black". shadowx: The x offset for the text shadow position with respect to the position of the text. It can be either positive or negative values. The default value is "0". shadowy: The y offset for the text shadow position with respect to the position of the text. It can be either positive or negative values. The default value is "0". start_number: The starting frame number for the n/frame_num variable. The default value is "0". tabsize: The size in number of spaces to use for rendering the tab. Default value is 4. timecode: Set the initial timecode representation in "hh:mm:ss[:;.]ff" format. It can be used with or without text parameter. timecode_rate option must be specified. rate: Set the timecode frame rate (timecode only). timecode_rate: Alias for ``rate``. r: Alias for ``rate``. tc24hmax: If set to 1, the output of the timecode option will wrap around at 24 hours. Default is 0 (disabled). text: The text string to be drawn. The text must be a sequence of UTF-8 encoded characters. This parameter is mandatory if no file is specified with the parameter textfile. textfile: A text file containing text to be drawn. The text must be a sequence of UTF-8 encoded characters. This parameter is mandatory if no text string is specified with the parameter text. If both text and textfile are specified, an error is thrown. reload: If set to 1, the textfile will be reloaded before each frame. Be sure to update it atomically, or it may be read partially, or even fail. x: The expression which specifies the offset where text will be drawn within the video frame. It is relative to the left border of the output image. The default value is "0". y: The expression which specifies the offset where text will be drawn within the video frame. It is relative to the top border of the output image. The default value is "0". See below for the list of accepted constants and functions. Expression constants: The parameters for x and y are expressions containing the following constants and functions: - dar: input display aspect ratio, it is the same as ``(w / h) * sar`` - hsub: horizontal chroma subsample values. For example for the pixel format "yuv422p" hsub is 2 and vsub is 1. - vsub: vertical chroma subsample values. For example for the pixel format "yuv422p" hsub is 2 and vsub is 1. - line_h: the height of each text line - lh: Alias for ``line_h``. - main_h: the input height - h: Alias for ``main_h``. - H: Alias for ``main_h``. - main_w: the input width - w: Alias for ``main_w``. - W: Alias for ``main_w``. - ascent: the maximum distance from the baseline to the highest/upper grid coordinate used to place a glyph outline point, for all the rendered glyphs. It is a positive value, due to the grid's orientation with the Y axis upwards. - max_glyph_a: Alias for ``ascent``. - descent: the maximum distance from the baseline to the lowest grid coordinate used to place a glyph outline point, for all the rendered glyphs. This is a negative value, due to the grid's orientation, with the Y axis upwards. - max_glyph_d: Alias for ``descent``. - max_glyph_h: maximum glyph height, that is the maximum height for all the glyphs contained in the rendered text, it is equivalent to ascent - descent. - max_glyph_w: maximum glyph width, that is the maximum width for all the glyphs contained in the rendered text. - n: the number of input frame, starting from 0 - rand(min, max): return a random number included between min and max - sar: The input sample aspect ratio. - t: timestamp expressed in seconds, NAN if the input timestamp is unknown - text_h: the height of the rendered text - th: Alias for ``text_h``. - text_w: the width of the rendered text - tw: Alias for ``text_w``. - x: the x offset coordinates where the text is drawn. - y: the y offset coordinates where the text is drawn. These parameters allow the x and y expressions to refer each other, so you can for example specify ``y=x/dar``. Official documentation: `drawtext <https://ffmpeg.org/ffmpeg-filters.html#drawtext>`__ """ if text is not None: if escape_text: text = escape_chars(text, '\\\'%') kwargs['text'] = text if x != 0: kwargs['x'] = x if y != 0: kwargs['y'] = y return filter(stream, drawtext.__name__, **kwargs)
python
def drawtext(stream, text=None, x=0, y=0, escape_text=True, **kwargs): if text is not None: if escape_text: text = escape_chars(text, '\\\'%') kwargs['text'] = text if x != 0: kwargs['x'] = x if y != 0: kwargs['y'] = y return filter(stream, drawtext.__name__, **kwargs)
[ "def", "drawtext", "(", "stream", ",", "text", "=", "None", ",", "x", "=", "0", ",", "y", "=", "0", ",", "escape_text", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "text", "is", "not", "None", ":", "if", "escape_text", ":", "text", "=...
Draw a text string or text from a specified file on top of a video, using the libfreetype library. To enable compilation of this filter, you need to configure FFmpeg with ``--enable-libfreetype``. To enable default font fallback and the font option you need to configure FFmpeg with ``--enable-libfontconfig``. To enable the text_shaping option, you need to configure FFmpeg with ``--enable-libfribidi``. Args: box: Used to draw a box around text using the background color. The value must be either 1 (enable) or 0 (disable). The default value of box is 0. boxborderw: Set the width of the border to be drawn around the box using boxcolor. The default value of boxborderw is 0. boxcolor: The color to be used for drawing box around text. For the syntax of this option, check the "Color" section in the ffmpeg-utils manual. The default value of boxcolor is "white". line_spacing: Set the line spacing in pixels of the border to be drawn around the box using box. The default value of line_spacing is 0. borderw: Set the width of the border to be drawn around the text using bordercolor. The default value of borderw is 0. bordercolor: Set the color to be used for drawing border around text. For the syntax of this option, check the "Color" section in the ffmpeg-utils manual. The default value of bordercolor is "black". expansion: Select how the text is expanded. Can be either none, strftime (deprecated) or normal (default). See the Text expansion section below for details. basetime: Set a start time for the count. Value is in microseconds. Only applied in the deprecated strftime expansion mode. To emulate in normal expansion mode use the pts function, supplying the start time (in seconds) as the second argument. fix_bounds: If true, check and fix text coords to avoid clipping. fontcolor: The color to be used for drawing fonts. For the syntax of this option, check the "Color" section in the ffmpeg-utils manual. The default value of fontcolor is "black". fontcolor_expr: String which is expanded the same way as text to obtain dynamic fontcolor value. By default this option has empty value and is not processed. When this option is set, it overrides fontcolor option. font: The font family to be used for drawing text. By default Sans. fontfile: The font file to be used for drawing text. The path must be included. This parameter is mandatory if the fontconfig support is disabled. alpha: Draw the text applying alpha blending. The value can be a number between 0.0 and 1.0. The expression accepts the same variables x, y as well. The default value is 1. Please see fontcolor_expr. fontsize: The font size to be used for drawing text. The default value of fontsize is 16. text_shaping: If set to 1, attempt to shape the text (for example, reverse the order of right-to-left text and join Arabic characters) before drawing it. Otherwise, just draw the text exactly as given. By default 1 (if supported). ft_load_flags: The flags to be used for loading the fonts. The flags map the corresponding flags supported by libfreetype, and are a combination of the following values: * ``default`` * ``no_scale`` * ``no_hinting`` * ``render`` * ``no_bitmap`` * ``vertical_layout`` * ``force_autohint`` * ``crop_bitmap`` * ``pedantic`` * ``ignore_global_advance_width`` * ``no_recurse`` * ``ignore_transform`` * ``monochrome`` * ``linear_design`` * ``no_autohint`` Default value is "default". For more information consult the documentation for the FT_LOAD_* libfreetype flags. shadowcolor: The color to be used for drawing a shadow behind the drawn text. For the syntax of this option, check the "Color" section in the ffmpeg-utils manual. The default value of shadowcolor is "black". shadowx: The x offset for the text shadow position with respect to the position of the text. It can be either positive or negative values. The default value is "0". shadowy: The y offset for the text shadow position with respect to the position of the text. It can be either positive or negative values. The default value is "0". start_number: The starting frame number for the n/frame_num variable. The default value is "0". tabsize: The size in number of spaces to use for rendering the tab. Default value is 4. timecode: Set the initial timecode representation in "hh:mm:ss[:;.]ff" format. It can be used with or without text parameter. timecode_rate option must be specified. rate: Set the timecode frame rate (timecode only). timecode_rate: Alias for ``rate``. r: Alias for ``rate``. tc24hmax: If set to 1, the output of the timecode option will wrap around at 24 hours. Default is 0 (disabled). text: The text string to be drawn. The text must be a sequence of UTF-8 encoded characters. This parameter is mandatory if no file is specified with the parameter textfile. textfile: A text file containing text to be drawn. The text must be a sequence of UTF-8 encoded characters. This parameter is mandatory if no text string is specified with the parameter text. If both text and textfile are specified, an error is thrown. reload: If set to 1, the textfile will be reloaded before each frame. Be sure to update it atomically, or it may be read partially, or even fail. x: The expression which specifies the offset where text will be drawn within the video frame. It is relative to the left border of the output image. The default value is "0". y: The expression which specifies the offset where text will be drawn within the video frame. It is relative to the top border of the output image. The default value is "0". See below for the list of accepted constants and functions. Expression constants: The parameters for x and y are expressions containing the following constants and functions: - dar: input display aspect ratio, it is the same as ``(w / h) * sar`` - hsub: horizontal chroma subsample values. For example for the pixel format "yuv422p" hsub is 2 and vsub is 1. - vsub: vertical chroma subsample values. For example for the pixel format "yuv422p" hsub is 2 and vsub is 1. - line_h: the height of each text line - lh: Alias for ``line_h``. - main_h: the input height - h: Alias for ``main_h``. - H: Alias for ``main_h``. - main_w: the input width - w: Alias for ``main_w``. - W: Alias for ``main_w``. - ascent: the maximum distance from the baseline to the highest/upper grid coordinate used to place a glyph outline point, for all the rendered glyphs. It is a positive value, due to the grid's orientation with the Y axis upwards. - max_glyph_a: Alias for ``ascent``. - descent: the maximum distance from the baseline to the lowest grid coordinate used to place a glyph outline point, for all the rendered glyphs. This is a negative value, due to the grid's orientation, with the Y axis upwards. - max_glyph_d: Alias for ``descent``. - max_glyph_h: maximum glyph height, that is the maximum height for all the glyphs contained in the rendered text, it is equivalent to ascent - descent. - max_glyph_w: maximum glyph width, that is the maximum width for all the glyphs contained in the rendered text. - n: the number of input frame, starting from 0 - rand(min, max): return a random number included between min and max - sar: The input sample aspect ratio. - t: timestamp expressed in seconds, NAN if the input timestamp is unknown - text_h: the height of the rendered text - th: Alias for ``text_h``. - text_w: the width of the rendered text - tw: Alias for ``text_w``. - x: the x offset coordinates where the text is drawn. - y: the y offset coordinates where the text is drawn. These parameters allow the x and y expressions to refer each other, so you can for example specify ``y=x/dar``. Official documentation: `drawtext <https://ffmpeg.org/ffmpeg-filters.html#drawtext>`__
[ "Draw", "a", "text", "string", "or", "text", "from", "a", "specified", "file", "on", "top", "of", "a", "video", "using", "the", "libfreetype", "library", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L216-L354
236,105
kkroening/ffmpeg-python
ffmpeg/_filters.py
concat
def concat(*streams, **kwargs): """Concatenate audio and video streams, joining them together one after the other. The filter works on segments of synchronized video and audio streams. All segments must have the same number of streams of each type, and that will also be the number of streams at output. Args: unsafe: Activate unsafe mode: do not fail if segments have a different format. Related streams do not always have exactly the same duration, for various reasons including codec frame size or sloppy authoring. For that reason, related synchronized streams (e.g. a video and its audio track) should be concatenated at once. The concat filter will use the duration of the longest stream in each segment (except the last one), and if necessary pad shorter audio streams with silence. For this filter to work correctly, all segments must start at timestamp 0. All corresponding streams must have the same parameters in all segments; the filtering system will automatically select a common pixel format for video streams, and a common sample format, sample rate and channel layout for audio streams, but other settings, such as resolution, must be converted explicitly by the user. Different frame rates are acceptable but will result in variable frame rate at output; be sure to configure the output file to handle it. Official documentation: `concat <https://ffmpeg.org/ffmpeg-filters.html#concat>`__ """ video_stream_count = kwargs.get('v', 1) audio_stream_count = kwargs.get('a', 0) stream_count = video_stream_count + audio_stream_count if len(streams) % stream_count != 0: raise ValueError( 'Expected concat input streams to have length multiple of {} (v={}, a={}); got {}' .format(stream_count, video_stream_count, audio_stream_count, len(streams))) kwargs['n'] = int(len(streams) / stream_count) return FilterNode(streams, concat.__name__, kwargs=kwargs, max_inputs=None).stream()
python
def concat(*streams, **kwargs): video_stream_count = kwargs.get('v', 1) audio_stream_count = kwargs.get('a', 0) stream_count = video_stream_count + audio_stream_count if len(streams) % stream_count != 0: raise ValueError( 'Expected concat input streams to have length multiple of {} (v={}, a={}); got {}' .format(stream_count, video_stream_count, audio_stream_count, len(streams))) kwargs['n'] = int(len(streams) / stream_count) return FilterNode(streams, concat.__name__, kwargs=kwargs, max_inputs=None).stream()
[ "def", "concat", "(", "*", "streams", ",", "*", "*", "kwargs", ")", ":", "video_stream_count", "=", "kwargs", ".", "get", "(", "'v'", ",", "1", ")", "audio_stream_count", "=", "kwargs", ".", "get", "(", "'a'", ",", "0", ")", "stream_count", "=", "vid...
Concatenate audio and video streams, joining them together one after the other. The filter works on segments of synchronized video and audio streams. All segments must have the same number of streams of each type, and that will also be the number of streams at output. Args: unsafe: Activate unsafe mode: do not fail if segments have a different format. Related streams do not always have exactly the same duration, for various reasons including codec frame size or sloppy authoring. For that reason, related synchronized streams (e.g. a video and its audio track) should be concatenated at once. The concat filter will use the duration of the longest stream in each segment (except the last one), and if necessary pad shorter audio streams with silence. For this filter to work correctly, all segments must start at timestamp 0. All corresponding streams must have the same parameters in all segments; the filtering system will automatically select a common pixel format for video streams, and a common sample format, sample rate and channel layout for audio streams, but other settings, such as resolution, must be converted explicitly by the user. Different frame rates are acceptable but will result in variable frame rate at output; be sure to configure the output file to handle it. Official documentation: `concat <https://ffmpeg.org/ffmpeg-filters.html#concat>`__
[ "Concatenate", "audio", "and", "video", "streams", "joining", "them", "together", "one", "after", "the", "other", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L358-L391
236,106
kkroening/ffmpeg-python
ffmpeg/_filters.py
zoompan
def zoompan(stream, **kwargs): """Apply Zoom & Pan effect. Args: zoom: Set the zoom expression. Default is 1. x: Set the x expression. Default is 0. y: Set the y expression. Default is 0. d: Set the duration expression in number of frames. This sets for how many number of frames effect will last for single input image. s: Set the output image size, default is ``hd720``. fps: Set the output frame rate, default is 25. z: Alias for ``zoom``. Official documentation: `zoompan <https://ffmpeg.org/ffmpeg-filters.html#zoompan>`__ """ return FilterNode(stream, zoompan.__name__, kwargs=kwargs).stream()
python
def zoompan(stream, **kwargs): return FilterNode(stream, zoompan.__name__, kwargs=kwargs).stream()
[ "def", "zoompan", "(", "stream", ",", "*", "*", "kwargs", ")", ":", "return", "FilterNode", "(", "stream", ",", "zoompan", ".", "__name__", ",", "kwargs", "=", "kwargs", ")", ".", "stream", "(", ")" ]
Apply Zoom & Pan effect. Args: zoom: Set the zoom expression. Default is 1. x: Set the x expression. Default is 0. y: Set the y expression. Default is 0. d: Set the duration expression in number of frames. This sets for how many number of frames effect will last for single input image. s: Set the output image size, default is ``hd720``. fps: Set the output frame rate, default is 25. z: Alias for ``zoom``. Official documentation: `zoompan <https://ffmpeg.org/ffmpeg-filters.html#zoompan>`__
[ "Apply", "Zoom", "&", "Pan", "effect", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L395-L410
236,107
kkroening/ffmpeg-python
ffmpeg/_filters.py
colorchannelmixer
def colorchannelmixer(stream, *args, **kwargs): """Adjust video input frames by re-mixing color channels. Official documentation: `colorchannelmixer <https://ffmpeg.org/ffmpeg-filters.html#colorchannelmixer>`__ """ return FilterNode(stream, colorchannelmixer.__name__, kwargs=kwargs).stream()
python
def colorchannelmixer(stream, *args, **kwargs): return FilterNode(stream, colorchannelmixer.__name__, kwargs=kwargs).stream()
[ "def", "colorchannelmixer", "(", "stream", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "FilterNode", "(", "stream", ",", "colorchannelmixer", ".", "__name__", ",", "kwargs", "=", "kwargs", ")", ".", "stream", "(", ")" ]
Adjust video input frames by re-mixing color channels. Official documentation: `colorchannelmixer <https://ffmpeg.org/ffmpeg-filters.html#colorchannelmixer>`__
[ "Adjust", "video", "input", "frames", "by", "re", "-", "mixing", "color", "channels", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_filters.py#L429-L434
236,108
kkroening/ffmpeg-python
ffmpeg/_utils.py
_recursive_repr
def _recursive_repr(item): """Hack around python `repr` to deterministically represent dictionaries. This is able to represent more things than json.dumps, since it does not require things to be JSON serializable (e.g. datetimes). """ if isinstance(item, basestring): result = str(item) elif isinstance(item, list): result = '[{}]'.format(', '.join([_recursive_repr(x) for x in item])) elif isinstance(item, dict): kv_pairs = ['{}: {}'.format(_recursive_repr(k), _recursive_repr(item[k])) for k in sorted(item)] result = '{' + ', '.join(kv_pairs) + '}' else: result = repr(item) return result
python
def _recursive_repr(item): if isinstance(item, basestring): result = str(item) elif isinstance(item, list): result = '[{}]'.format(', '.join([_recursive_repr(x) for x in item])) elif isinstance(item, dict): kv_pairs = ['{}: {}'.format(_recursive_repr(k), _recursive_repr(item[k])) for k in sorted(item)] result = '{' + ', '.join(kv_pairs) + '}' else: result = repr(item) return result
[ "def", "_recursive_repr", "(", "item", ")", ":", "if", "isinstance", "(", "item", ",", "basestring", ")", ":", "result", "=", "str", "(", "item", ")", "elif", "isinstance", "(", "item", ",", "list", ")", ":", "result", "=", "'[{}]'", ".", "format", "...
Hack around python `repr` to deterministically represent dictionaries. This is able to represent more things than json.dumps, since it does not require things to be JSON serializable (e.g. datetimes).
[ "Hack", "around", "python", "repr", "to", "deterministically", "represent", "dictionaries", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_utils.py#L44-L59
236,109
kkroening/ffmpeg-python
ffmpeg/_utils.py
escape_chars
def escape_chars(text, chars): """Helper function to escape uncomfortable characters.""" text = str(text) chars = list(set(chars)) if '\\' in chars: chars.remove('\\') chars.insert(0, '\\') for ch in chars: text = text.replace(ch, '\\' + ch) return text
python
def escape_chars(text, chars): text = str(text) chars = list(set(chars)) if '\\' in chars: chars.remove('\\') chars.insert(0, '\\') for ch in chars: text = text.replace(ch, '\\' + ch) return text
[ "def", "escape_chars", "(", "text", ",", "chars", ")", ":", "text", "=", "str", "(", "text", ")", "chars", "=", "list", "(", "set", "(", "chars", ")", ")", "if", "'\\\\'", "in", "chars", ":", "chars", ".", "remove", "(", "'\\\\'", ")", "chars", "...
Helper function to escape uncomfortable characters.
[ "Helper", "function", "to", "escape", "uncomfortable", "characters", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_utils.py#L71-L80
236,110
kkroening/ffmpeg-python
ffmpeg/_utils.py
convert_kwargs_to_cmd_line_args
def convert_kwargs_to_cmd_line_args(kwargs): """Helper function to build command line arguments out of dict.""" args = [] for k in sorted(kwargs.keys()): v = kwargs[k] args.append('-{}'.format(k)) if v is not None: args.append('{}'.format(v)) return args
python
def convert_kwargs_to_cmd_line_args(kwargs): args = [] for k in sorted(kwargs.keys()): v = kwargs[k] args.append('-{}'.format(k)) if v is not None: args.append('{}'.format(v)) return args
[ "def", "convert_kwargs_to_cmd_line_args", "(", "kwargs", ")", ":", "args", "=", "[", "]", "for", "k", "in", "sorted", "(", "kwargs", ".", "keys", "(", ")", ")", ":", "v", "=", "kwargs", "[", "k", "]", "args", ".", "append", "(", "'-{}'", ".", "form...
Helper function to build command line arguments out of dict.
[ "Helper", "function", "to", "build", "command", "line", "arguments", "out", "of", "dict", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_utils.py#L83-L91
236,111
kkroening/ffmpeg-python
ffmpeg/nodes.py
Node.stream
def stream(self, label=None, selector=None): """Create an outgoing stream originating from this node. More nodes may be attached onto the outgoing stream. """ return self.__outgoing_stream_type(self, label, upstream_selector=selector)
python
def stream(self, label=None, selector=None): return self.__outgoing_stream_type(self, label, upstream_selector=selector)
[ "def", "stream", "(", "self", ",", "label", "=", "None", ",", "selector", "=", "None", ")", ":", "return", "self", ".", "__outgoing_stream_type", "(", "self", ",", "label", ",", "upstream_selector", "=", "selector", ")" ]
Create an outgoing stream originating from this node. More nodes may be attached onto the outgoing stream.
[ "Create", "an", "outgoing", "stream", "originating", "from", "this", "node", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/nodes.py#L128-L133
236,112
kkroening/ffmpeg-python
examples/tensorflow_stream.py
DeepDream._tffunc
def _tffunc(*argtypes): '''Helper that transforms TF-graph generating function into a regular one. See `_resize` function below. ''' placeholders = list(map(tf.placeholder, argtypes)) def wrap(f): out = f(*placeholders) def wrapper(*args, **kw): return out.eval(dict(zip(placeholders, args)), session=kw.get('session')) return wrapper return wrap
python
def _tffunc(*argtypes): '''Helper that transforms TF-graph generating function into a regular one. See `_resize` function below. ''' placeholders = list(map(tf.placeholder, argtypes)) def wrap(f): out = f(*placeholders) def wrapper(*args, **kw): return out.eval(dict(zip(placeholders, args)), session=kw.get('session')) return wrapper return wrap
[ "def", "_tffunc", "(", "*", "argtypes", ")", ":", "placeholders", "=", "list", "(", "map", "(", "tf", ".", "placeholder", ",", "argtypes", ")", ")", "def", "wrap", "(", "f", ")", ":", "out", "=", "f", "(", "*", "placeholders", ")", "def", "wrapper"...
Helper that transforms TF-graph generating function into a regular one. See `_resize` function below.
[ "Helper", "that", "transforms", "TF", "-", "graph", "generating", "function", "into", "a", "regular", "one", ".", "See", "_resize", "function", "below", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/examples/tensorflow_stream.py#L159-L169
236,113
kkroening/ffmpeg-python
examples/tensorflow_stream.py
DeepDream._base_resize
def _base_resize(img, size): '''Helper function that uses TF to resize an image''' img = tf.expand_dims(img, 0) return tf.image.resize_bilinear(img, size)[0,:,:,:]
python
def _base_resize(img, size): '''Helper function that uses TF to resize an image''' img = tf.expand_dims(img, 0) return tf.image.resize_bilinear(img, size)[0,:,:,:]
[ "def", "_base_resize", "(", "img", ",", "size", ")", ":", "img", "=", "tf", ".", "expand_dims", "(", "img", ",", "0", ")", "return", "tf", ".", "image", ".", "resize_bilinear", "(", "img", ",", "size", ")", "[", "0", ",", ":", ",", ":", ",", ":...
Helper function that uses TF to resize an image
[ "Helper", "function", "that", "uses", "TF", "to", "resize", "an", "image" ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/examples/tensorflow_stream.py#L172-L175
236,114
kkroening/ffmpeg-python
examples/tensorflow_stream.py
DeepDream._calc_grad_tiled
def _calc_grad_tiled(self, img, t_grad, tile_size=512): '''Compute the value of tensor t_grad over the image in a tiled way. Random shifts are applied to the image to blur tile boundaries over multiple iterations.''' sz = tile_size h, w = img.shape[:2] sx, sy = np.random.randint(sz, size=2) img_shift = np.roll(np.roll(img, sx, 1), sy, 0) grad = np.zeros_like(img) for y in range(0, max(h-sz//2, sz),sz): for x in range(0, max(w-sz//2, sz),sz): sub = img_shift[y:y+sz,x:x+sz] g = self._session.run(t_grad, {self._t_input:sub}) grad[y:y+sz,x:x+sz] = g return np.roll(np.roll(grad, -sx, 1), -sy, 0)
python
def _calc_grad_tiled(self, img, t_grad, tile_size=512): '''Compute the value of tensor t_grad over the image in a tiled way. Random shifts are applied to the image to blur tile boundaries over multiple iterations.''' sz = tile_size h, w = img.shape[:2] sx, sy = np.random.randint(sz, size=2) img_shift = np.roll(np.roll(img, sx, 1), sy, 0) grad = np.zeros_like(img) for y in range(0, max(h-sz//2, sz),sz): for x in range(0, max(w-sz//2, sz),sz): sub = img_shift[y:y+sz,x:x+sz] g = self._session.run(t_grad, {self._t_input:sub}) grad[y:y+sz,x:x+sz] = g return np.roll(np.roll(grad, -sx, 1), -sy, 0)
[ "def", "_calc_grad_tiled", "(", "self", ",", "img", ",", "t_grad", ",", "tile_size", "=", "512", ")", ":", "sz", "=", "tile_size", "h", ",", "w", "=", "img", ".", "shape", "[", ":", "2", "]", "sx", ",", "sy", "=", "np", ".", "random", ".", "ran...
Compute the value of tensor t_grad over the image in a tiled way. Random shifts are applied to the image to blur tile boundaries over multiple iterations.
[ "Compute", "the", "value", "of", "tensor", "t_grad", "over", "the", "image", "in", "a", "tiled", "way", ".", "Random", "shifts", "are", "applied", "to", "the", "image", "to", "blur", "tile", "boundaries", "over", "multiple", "iterations", "." ]
ac111dc3a976ddbb872bc7d6d4fe24a267c1a956
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/examples/tensorflow_stream.py#L199-L213
236,115
python-diamond/Diamond
src/collectors/xen_collector/xen_collector.py
XENCollector.collect
def collect(self): """ Collect libvirt data """ if libvirt is None: self.log.error('Unable to import either libvirt') return {} # Open a restricted (non-root) connection to the hypervisor conn = libvirt.openReadOnly(None) # Get hardware info conninfo = conn.getInfo() # Initialize variables memallocated = 0 coresallocated = 0 totalcores = 0 results = {} domIds = conn.listDomainsID() if 0 in domIds: # Total cores domU = conn.lookupByID(0) totalcores = domU.info()[3] # Free Space s = os.statvfs('/') freeSpace = (s.f_bavail * s.f_frsize) / 1024 # Calculate allocated memory and cores for i in domIds: # Ignore 0 if i == 0: continue domU = conn.lookupByID(i) dominfo = domU.info() memallocated += dominfo[2] if i > 0: coresallocated += dominfo[3] results = { 'InstalledMem': conninfo[1], 'MemAllocated': memallocated / 1024, 'MemFree': conninfo[1] - (memallocated / 1024), 'AllocatedCores': coresallocated, 'DiskFree': freeSpace, 'TotalCores': totalcores, 'FreeCores': (totalcores - coresallocated) } for k in results.keys(): self.publish(k, results[k], 0)
python
def collect(self): if libvirt is None: self.log.error('Unable to import either libvirt') return {} # Open a restricted (non-root) connection to the hypervisor conn = libvirt.openReadOnly(None) # Get hardware info conninfo = conn.getInfo() # Initialize variables memallocated = 0 coresallocated = 0 totalcores = 0 results = {} domIds = conn.listDomainsID() if 0 in domIds: # Total cores domU = conn.lookupByID(0) totalcores = domU.info()[3] # Free Space s = os.statvfs('/') freeSpace = (s.f_bavail * s.f_frsize) / 1024 # Calculate allocated memory and cores for i in domIds: # Ignore 0 if i == 0: continue domU = conn.lookupByID(i) dominfo = domU.info() memallocated += dominfo[2] if i > 0: coresallocated += dominfo[3] results = { 'InstalledMem': conninfo[1], 'MemAllocated': memallocated / 1024, 'MemFree': conninfo[1] - (memallocated / 1024), 'AllocatedCores': coresallocated, 'DiskFree': freeSpace, 'TotalCores': totalcores, 'FreeCores': (totalcores - coresallocated) } for k in results.keys(): self.publish(k, results[k], 0)
[ "def", "collect", "(", "self", ")", ":", "if", "libvirt", "is", "None", ":", "self", ".", "log", ".", "error", "(", "'Unable to import either libvirt'", ")", "return", "{", "}", "# Open a restricted (non-root) connection to the hypervisor", "conn", "=", "libvirt", ...
Collect libvirt data
[ "Collect", "libvirt", "data" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/xen_collector/xen_collector.py#L38-L82
236,116
python-diamond/Diamond
src/collectors/elb/elb.py
ElbCollector.publish_delayed_metric
def publish_delayed_metric(self, name, value, timestamp, raw_value=None, precision=0, metric_type='GAUGE', instance=None): """ Metrics may not be immediately available when querying cloudwatch. Hence, allow the ability to publish a metric from some the past given its timestamp. """ # Get metric Path path = self.get_metric_path(name, instance) # Get metric TTL ttl = float(self.config['interval']) * float( self.config['ttl_multiplier']) # Create Metric metric = Metric(path, value, raw_value=raw_value, timestamp=timestamp, precision=precision, host=self.get_hostname(), metric_type=metric_type, ttl=ttl) # Publish Metric self.publish_metric(metric)
python
def publish_delayed_metric(self, name, value, timestamp, raw_value=None, precision=0, metric_type='GAUGE', instance=None): # Get metric Path path = self.get_metric_path(name, instance) # Get metric TTL ttl = float(self.config['interval']) * float( self.config['ttl_multiplier']) # Create Metric metric = Metric(path, value, raw_value=raw_value, timestamp=timestamp, precision=precision, host=self.get_hostname(), metric_type=metric_type, ttl=ttl) # Publish Metric self.publish_metric(metric)
[ "def", "publish_delayed_metric", "(", "self", ",", "name", ",", "value", ",", "timestamp", ",", "raw_value", "=", "None", ",", "precision", "=", "0", ",", "metric_type", "=", "'GAUGE'", ",", "instance", "=", "None", ")", ":", "# Get metric Path", "path", "...
Metrics may not be immediately available when querying cloudwatch. Hence, allow the ability to publish a metric from some the past given its timestamp.
[ "Metrics", "may", "not", "be", "immediately", "available", "when", "querying", "cloudwatch", ".", "Hence", "allow", "the", "ability", "to", "publish", "a", "metric", "from", "some", "the", "past", "given", "its", "timestamp", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/elb/elb.py#L184-L205
236,117
python-diamond/Diamond
src/collectors/netapp/netappDisk.py
netappDiskCol.agr_busy
def agr_busy(self): """ Collector for average disk busyness per aggregate As of Nov 22nd 2013 there is no API call for agr busyness. You have to collect all disk busyness and then compute agr busyness. #fml """ c1 = {} # Counters from time a c2 = {} # Counters from time b disk_results = {} # Disk busyness results % agr_results = {} # Aggregate busyness results $ names = ['disk_busy', 'base_for_disk_busy', 'raid_name', 'base_for_disk_busy', 'instance_uuid'] netapp_api = NaElement('perf-object-get-instances') netapp_api.child_add_string('objectname', 'disk') disk_1 = self.get_netapp_elem(netapp_api, 'instances') time.sleep(1) disk_2 = self.get_netapp_elem(netapp_api, 'instances') for instance_data in disk_1: temp = {} for element in instance_data.findall(".//counters/counter-data"): if element.find('name').text in names: temp[element.find('name').text] = element.find( 'value').text agr_name = temp['raid_name'] agr_name = agr_name[agr_name.find('/', 0):agr_name.find('/', 1)] temp['raid_name'] = agr_name.lstrip('/') c1[temp.pop('instance_uuid')] = temp for instance_data in disk_2: temp = {} for element in instance_data.findall(".//counters/counter-data"): if element.find('name').text in names: temp[element.find('name').text] = element.find( 'value').text agr_name = temp['raid_name'] agr_name = agr_name[agr_name.find('/', 0):agr_name.find('/', 1)] temp['raid_name'] = agr_name.lstrip('/') c2[temp.pop('instance_uuid')] = temp for item in c1: t_c1 = int(c1[item]['disk_busy']) # time_counter_1 t_b1 = int(c1[item]['base_for_disk_busy']) # time_base_1 t_c2 = int(c2[item]['disk_busy']) t_b2 = int(c2[item]['base_for_disk_busy']) disk_busy = 100 * (t_c2 - t_c1) / (t_b2 - t_b1) if c1[item]['raid_name'] in disk_results: disk_results[c1[item]['raid_name']].append(disk_busy) else: disk_results[c1[item]['raid_name']] = [disk_busy] for aggregate in disk_results: agr_results[aggregate] = \ sum(disk_results[aggregate]) / len(disk_results[aggregate]) for aggregate in agr_results: self.push('avg_busy', 'aggregate.' + aggregate, agr_results[aggregate])
python
def agr_busy(self): c1 = {} # Counters from time a c2 = {} # Counters from time b disk_results = {} # Disk busyness results % agr_results = {} # Aggregate busyness results $ names = ['disk_busy', 'base_for_disk_busy', 'raid_name', 'base_for_disk_busy', 'instance_uuid'] netapp_api = NaElement('perf-object-get-instances') netapp_api.child_add_string('objectname', 'disk') disk_1 = self.get_netapp_elem(netapp_api, 'instances') time.sleep(1) disk_2 = self.get_netapp_elem(netapp_api, 'instances') for instance_data in disk_1: temp = {} for element in instance_data.findall(".//counters/counter-data"): if element.find('name').text in names: temp[element.find('name').text] = element.find( 'value').text agr_name = temp['raid_name'] agr_name = agr_name[agr_name.find('/', 0):agr_name.find('/', 1)] temp['raid_name'] = agr_name.lstrip('/') c1[temp.pop('instance_uuid')] = temp for instance_data in disk_2: temp = {} for element in instance_data.findall(".//counters/counter-data"): if element.find('name').text in names: temp[element.find('name').text] = element.find( 'value').text agr_name = temp['raid_name'] agr_name = agr_name[agr_name.find('/', 0):agr_name.find('/', 1)] temp['raid_name'] = agr_name.lstrip('/') c2[temp.pop('instance_uuid')] = temp for item in c1: t_c1 = int(c1[item]['disk_busy']) # time_counter_1 t_b1 = int(c1[item]['base_for_disk_busy']) # time_base_1 t_c2 = int(c2[item]['disk_busy']) t_b2 = int(c2[item]['base_for_disk_busy']) disk_busy = 100 * (t_c2 - t_c1) / (t_b2 - t_b1) if c1[item]['raid_name'] in disk_results: disk_results[c1[item]['raid_name']].append(disk_busy) else: disk_results[c1[item]['raid_name']] = [disk_busy] for aggregate in disk_results: agr_results[aggregate] = \ sum(disk_results[aggregate]) / len(disk_results[aggregate]) for aggregate in agr_results: self.push('avg_busy', 'aggregate.' + aggregate, agr_results[aggregate])
[ "def", "agr_busy", "(", "self", ")", ":", "c1", "=", "{", "}", "# Counters from time a", "c2", "=", "{", "}", "# Counters from time b", "disk_results", "=", "{", "}", "# Disk busyness results %", "agr_results", "=", "{", "}", "# Aggregate busyness results $", "nam...
Collector for average disk busyness per aggregate As of Nov 22nd 2013 there is no API call for agr busyness. You have to collect all disk busyness and then compute agr busyness. #fml
[ "Collector", "for", "average", "disk", "busyness", "per", "aggregate" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netappDisk.py#L71-L135
236,118
python-diamond/Diamond
src/collectors/netapp/netappDisk.py
netappDiskCol.consistency_point
def consistency_point(self): """ Collector for getting count of consistancy points """ cp_delta = {} xml_path = 'instances/instance-data/counters' netapp_api = NaElement('perf-object-get-instances') netapp_api.child_add_string('objectname', 'wafl') instance = NaElement('instances') instance.child_add_string('instance', 'wafl') counter = NaElement('counters') counter.child_add_string('counter', 'cp_count') netapp_api.child_add(counter) netapp_api.child_add(instance) cp_1 = self.get_netapp_elem(netapp_api, xml_path) time.sleep(3) cp_2 = self.get_netapp_elem(netapp_api, xml_path) for element in cp_1: if element.find('name').text == 'cp_count': cp_1 = element.find('value').text.rsplit(',') break for element in cp_2: if element.find('name').text == 'cp_count': cp_2 = element.find('value').text.rsplit(',') break if not type(cp_2) is list or not type(cp_1) is list: log.error("consistency point data not available for filer: %s" % self.device) return cp_1 = { 'wafl_timer': cp_1[0], 'snapshot': cp_1[1], 'wafl_avail_bufs': cp_1[2], 'dirty_blk_cnt': cp_1[3], 'full_nv_log': cp_1[4], 'b2b': cp_1[5], 'flush_gen': cp_1[6], 'sync_gen': cp_1[7], 'def_b2b': cp_1[8], 'con_ind_pin': cp_1[9], 'low_mbuf_gen': cp_1[10], 'low_datavec_gen': cp_1[11] } cp_2 = { 'wafl_timer': cp_2[0], 'snapshot': cp_2[1], 'wafl_avail_bufs': cp_2[2], 'dirty_blk_cnt': cp_2[3], 'full_nv_log': cp_2[4], 'b2b': cp_2[5], 'flush_gen': cp_2[6], 'sync_gen': cp_2[7], 'def_b2b': cp_2[8], 'con_ind_pin': cp_2[9], 'low_mbuf_gen': cp_2[10], 'low_datavec_gen': cp_2[11] } for item in cp_1: c1 = int(cp_1[item]) c2 = int(cp_2[item]) cp_delta[item] = c2 - c1 for item in cp_delta: self.push(item + '_CP', 'system.system', cp_delta[item])
python
def consistency_point(self): cp_delta = {} xml_path = 'instances/instance-data/counters' netapp_api = NaElement('perf-object-get-instances') netapp_api.child_add_string('objectname', 'wafl') instance = NaElement('instances') instance.child_add_string('instance', 'wafl') counter = NaElement('counters') counter.child_add_string('counter', 'cp_count') netapp_api.child_add(counter) netapp_api.child_add(instance) cp_1 = self.get_netapp_elem(netapp_api, xml_path) time.sleep(3) cp_2 = self.get_netapp_elem(netapp_api, xml_path) for element in cp_1: if element.find('name').text == 'cp_count': cp_1 = element.find('value').text.rsplit(',') break for element in cp_2: if element.find('name').text == 'cp_count': cp_2 = element.find('value').text.rsplit(',') break if not type(cp_2) is list or not type(cp_1) is list: log.error("consistency point data not available for filer: %s" % self.device) return cp_1 = { 'wafl_timer': cp_1[0], 'snapshot': cp_1[1], 'wafl_avail_bufs': cp_1[2], 'dirty_blk_cnt': cp_1[3], 'full_nv_log': cp_1[4], 'b2b': cp_1[5], 'flush_gen': cp_1[6], 'sync_gen': cp_1[7], 'def_b2b': cp_1[8], 'con_ind_pin': cp_1[9], 'low_mbuf_gen': cp_1[10], 'low_datavec_gen': cp_1[11] } cp_2 = { 'wafl_timer': cp_2[0], 'snapshot': cp_2[1], 'wafl_avail_bufs': cp_2[2], 'dirty_blk_cnt': cp_2[3], 'full_nv_log': cp_2[4], 'b2b': cp_2[5], 'flush_gen': cp_2[6], 'sync_gen': cp_2[7], 'def_b2b': cp_2[8], 'con_ind_pin': cp_2[9], 'low_mbuf_gen': cp_2[10], 'low_datavec_gen': cp_2[11] } for item in cp_1: c1 = int(cp_1[item]) c2 = int(cp_2[item]) cp_delta[item] = c2 - c1 for item in cp_delta: self.push(item + '_CP', 'system.system', cp_delta[item])
[ "def", "consistency_point", "(", "self", ")", ":", "cp_delta", "=", "{", "}", "xml_path", "=", "'instances/instance-data/counters'", "netapp_api", "=", "NaElement", "(", "'perf-object-get-instances'", ")", "netapp_api", ".", "child_add_string", "(", "'objectname'", ",...
Collector for getting count of consistancy points
[ "Collector", "for", "getting", "count", "of", "consistancy", "points" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netappDisk.py#L137-L206
236,119
python-diamond/Diamond
src/collectors/netapp/netappDisk.py
netappDiskCol.zero_disk
def zero_disk(self, disk_xml=None): """ Collector and publish not zeroed disk metrics """ troubled_disks = 0 for filer_disk in disk_xml: raid_state = filer_disk.find('raid-state').text if not raid_state == 'spare': continue is_zeroed = filer_disk.find('is-zeroed').text if is_zeroed == 'false': troubled_disks += 1 self.push('not_zeroed', 'disk', troubled_disks)
python
def zero_disk(self, disk_xml=None): troubled_disks = 0 for filer_disk in disk_xml: raid_state = filer_disk.find('raid-state').text if not raid_state == 'spare': continue is_zeroed = filer_disk.find('is-zeroed').text if is_zeroed == 'false': troubled_disks += 1 self.push('not_zeroed', 'disk', troubled_disks)
[ "def", "zero_disk", "(", "self", ",", "disk_xml", "=", "None", ")", ":", "troubled_disks", "=", "0", "for", "filer_disk", "in", "disk_xml", ":", "raid_state", "=", "filer_disk", ".", "find", "(", "'raid-state'", ")", ".", "text", "if", "not", "raid_state",...
Collector and publish not zeroed disk metrics
[ "Collector", "and", "publish", "not", "zeroed", "disk", "metrics" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netappDisk.py#L225-L238
236,120
python-diamond/Diamond
src/collectors/netapp/netappDisk.py
netappDiskCol.spare_disk
def spare_disk(self, disk_xml=None): """ Number of spare disk per type. For example: storage.ontap.filer201.disk.SATA """ spare_disk = {} disk_types = set() for filer_disk in disk_xml: disk_types.add(filer_disk.find('effective-disk-type').text) if not filer_disk.find('raid-state').text == 'spare': continue disk_type = filer_disk.find('effective-disk-type').text if disk_type in spare_disk: spare_disk[disk_type] += 1 else: spare_disk[disk_type] = 1 for disk_type in disk_types: if disk_type in spare_disk: self.push('spare_' + disk_type, 'disk', spare_disk[disk_type]) else: self.push('spare_' + disk_type, 'disk', 0)
python
def spare_disk(self, disk_xml=None): spare_disk = {} disk_types = set() for filer_disk in disk_xml: disk_types.add(filer_disk.find('effective-disk-type').text) if not filer_disk.find('raid-state').text == 'spare': continue disk_type = filer_disk.find('effective-disk-type').text if disk_type in spare_disk: spare_disk[disk_type] += 1 else: spare_disk[disk_type] = 1 for disk_type in disk_types: if disk_type in spare_disk: self.push('spare_' + disk_type, 'disk', spare_disk[disk_type]) else: self.push('spare_' + disk_type, 'disk', 0)
[ "def", "spare_disk", "(", "self", ",", "disk_xml", "=", "None", ")", ":", "spare_disk", "=", "{", "}", "disk_types", "=", "set", "(", ")", "for", "filer_disk", "in", "disk_xml", ":", "disk_types", ".", "add", "(", "filer_disk", ".", "find", "(", "'effe...
Number of spare disk per type. For example: storage.ontap.filer201.disk.SATA
[ "Number", "of", "spare", "disk", "per", "type", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netappDisk.py#L240-L265
236,121
python-diamond/Diamond
src/collectors/netapp/netappDisk.py
netappDiskCol.get_netapp_elem
def get_netapp_elem(self, netapp_api=None, sub_element=None): """ Retrieve netapp elem """ netapp_data = self.server.invoke_elem(netapp_api) if netapp_data.results_status() == 'failed': self.log.error( 'While using netapp API failed to retrieve ' 'disk-list-info for netapp filer %s' % self.device) print(netapp_data.sprintf()) return netapp_xml = \ ET.fromstring(netapp_data.sprintf()).find(sub_element) return netapp_xml
python
def get_netapp_elem(self, netapp_api=None, sub_element=None): netapp_data = self.server.invoke_elem(netapp_api) if netapp_data.results_status() == 'failed': self.log.error( 'While using netapp API failed to retrieve ' 'disk-list-info for netapp filer %s' % self.device) print(netapp_data.sprintf()) return netapp_xml = \ ET.fromstring(netapp_data.sprintf()).find(sub_element) return netapp_xml
[ "def", "get_netapp_elem", "(", "self", ",", "netapp_api", "=", "None", ",", "sub_element", "=", "None", ")", ":", "netapp_data", "=", "self", ".", "server", ".", "invoke_elem", "(", "netapp_api", ")", "if", "netapp_data", ".", "results_status", "(", ")", "...
Retrieve netapp elem
[ "Retrieve", "netapp", "elem" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netappDisk.py#L267-L282
236,122
python-diamond/Diamond
src/collectors/netapp/netappDisk.py
netappDiskCol._netapp_login
def _netapp_login(self): """ Login to our netapp filer """ self.server = NaServer(self.ip, 1, 3) self.server.set_transport_type('HTTPS') self.server.set_style('LOGIN') self.server.set_admin_user(self.netapp_user, self.netapp_password)
python
def _netapp_login(self): self.server = NaServer(self.ip, 1, 3) self.server.set_transport_type('HTTPS') self.server.set_style('LOGIN') self.server.set_admin_user(self.netapp_user, self.netapp_password)
[ "def", "_netapp_login", "(", "self", ")", ":", "self", ".", "server", "=", "NaServer", "(", "self", ".", "ip", ",", "1", ",", "3", ")", "self", ".", "server", ".", "set_transport_type", "(", "'HTTPS'", ")", "self", ".", "server", ".", "set_style", "(...
Login to our netapp filer
[ "Login", "to", "our", "netapp", "filer" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netapp/netappDisk.py#L284-L291
236,123
python-diamond/Diamond
src/collectors/ceph/ceph.py
CephCollector._get_socket_paths
def _get_socket_paths(self): """Return a sequence of paths to sockets for communicating with ceph daemons. """ socket_pattern = os.path.join(self.config['socket_path'], (self.config['socket_prefix'] + '*.' + self.config['socket_ext'])) return glob.glob(socket_pattern)
python
def _get_socket_paths(self): socket_pattern = os.path.join(self.config['socket_path'], (self.config['socket_prefix'] + '*.' + self.config['socket_ext'])) return glob.glob(socket_pattern)
[ "def", "_get_socket_paths", "(", "self", ")", ":", "socket_pattern", "=", "os", ".", "path", ".", "join", "(", "self", ".", "config", "[", "'socket_path'", "]", ",", "(", "self", ".", "config", "[", "'socket_prefix'", "]", "+", "'*.'", "+", "self", "."...
Return a sequence of paths to sockets for communicating with ceph daemons.
[ "Return", "a", "sequence", "of", "paths", "to", "sockets", "for", "communicating", "with", "ceph", "daemons", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/ceph/ceph.py#L78-L85
236,124
python-diamond/Diamond
src/collectors/ceph/ceph.py
CephCollector._get_counter_prefix_from_socket_name
def _get_counter_prefix_from_socket_name(self, name): """Given the name of a UDS socket, return the prefix for counters coming from that source. """ base = os.path.splitext(os.path.basename(name))[0] if base.startswith(self.config['socket_prefix']): base = base[len(self.config['socket_prefix']):] return 'ceph.' + base
python
def _get_counter_prefix_from_socket_name(self, name): base = os.path.splitext(os.path.basename(name))[0] if base.startswith(self.config['socket_prefix']): base = base[len(self.config['socket_prefix']):] return 'ceph.' + base
[ "def", "_get_counter_prefix_from_socket_name", "(", "self", ",", "name", ")", ":", "base", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "name", ")", ")", "[", "0", "]", "if", "base", ".", "startswith", "(", "...
Given the name of a UDS socket, return the prefix for counters coming from that source.
[ "Given", "the", "name", "of", "a", "UDS", "socket", "return", "the", "prefix", "for", "counters", "coming", "from", "that", "source", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/ceph/ceph.py#L87-L94
236,125
python-diamond/Diamond
src/collectors/ceph/ceph.py
CephCollector._get_stats_from_socket
def _get_stats_from_socket(self, name): """Return the parsed JSON data returned when ceph is told to dump the stats from the named socket. In the event of an error error, the exception is logged, and an empty result set is returned. """ try: json_blob = subprocess.check_output( [self.config['ceph_binary'], '--admin-daemon', name, 'perf', 'dump', ]) except subprocess.CalledProcessError as err: self.log.info('Could not get stats from %s: %s', name, err) self.log.exception('Could not get stats from %s' % name) return {} try: json_data = json.loads(json_blob) except Exception as err: self.log.info('Could not parse stats from %s: %s', name, err) self.log.exception('Could not parse stats from %s' % name) return {} return json_data
python
def _get_stats_from_socket(self, name): try: json_blob = subprocess.check_output( [self.config['ceph_binary'], '--admin-daemon', name, 'perf', 'dump', ]) except subprocess.CalledProcessError as err: self.log.info('Could not get stats from %s: %s', name, err) self.log.exception('Could not get stats from %s' % name) return {} try: json_data = json.loads(json_blob) except Exception as err: self.log.info('Could not parse stats from %s: %s', name, err) self.log.exception('Could not parse stats from %s' % name) return {} return json_data
[ "def", "_get_stats_from_socket", "(", "self", ",", "name", ")", ":", "try", ":", "json_blob", "=", "subprocess", ".", "check_output", "(", "[", "self", ".", "config", "[", "'ceph_binary'", "]", ",", "'--admin-daemon'", ",", "name", ",", "'perf'", ",", "'du...
Return the parsed JSON data returned when ceph is told to dump the stats from the named socket. In the event of an error error, the exception is logged, and an empty result set is returned.
[ "Return", "the", "parsed", "JSON", "data", "returned", "when", "ceph", "is", "told", "to", "dump", "the", "stats", "from", "the", "named", "socket", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/ceph/ceph.py#L96-L125
236,126
python-diamond/Diamond
src/collectors/ceph/ceph.py
CephCollector._publish_stats
def _publish_stats(self, counter_prefix, stats): """Given a stats dictionary from _get_stats_from_socket, publish the individual values. """ for stat_name, stat_value in flatten_dictionary( stats, prefix=counter_prefix, ): self.publish_gauge(stat_name, stat_value)
python
def _publish_stats(self, counter_prefix, stats): for stat_name, stat_value in flatten_dictionary( stats, prefix=counter_prefix, ): self.publish_gauge(stat_name, stat_value)
[ "def", "_publish_stats", "(", "self", ",", "counter_prefix", ",", "stats", ")", ":", "for", "stat_name", ",", "stat_value", "in", "flatten_dictionary", "(", "stats", ",", "prefix", "=", "counter_prefix", ",", ")", ":", "self", ".", "publish_gauge", "(", "sta...
Given a stats dictionary from _get_stats_from_socket, publish the individual values.
[ "Given", "a", "stats", "dictionary", "from", "_get_stats_from_socket", "publish", "the", "individual", "values", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/ceph/ceph.py#L127-L135
236,127
python-diamond/Diamond
src/diamond/handler/graphitepickle.py
GraphitePickleHandler._pickle_batch
def _pickle_batch(self): """ Pickle the metrics into a form that can be understood by the graphite pickle connector. """ # Pickle payload = pickle.dumps(self.batch) # Pack Message header = struct.pack("!L", len(payload)) message = header + payload # Return Message return message
python
def _pickle_batch(self): # Pickle payload = pickle.dumps(self.batch) # Pack Message header = struct.pack("!L", len(payload)) message = header + payload # Return Message return message
[ "def", "_pickle_batch", "(", "self", ")", ":", "# Pickle", "payload", "=", "pickle", ".", "dumps", "(", "self", ".", "batch", ")", "# Pack Message", "header", "=", "struct", ".", "pack", "(", "\"!L\"", ",", "len", "(", "payload", ")", ")", "message", "...
Pickle the metrics into a form that can be understood by the graphite pickle connector.
[ "Pickle", "the", "metrics", "into", "a", "form", "that", "can", "be", "understood", "by", "the", "graphite", "pickle", "connector", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/graphitepickle.py#L88-L101
236,128
python-diamond/Diamond
src/diamond/handler/g_metric.py
GmetricHandler._send
def _send(self, metric): """ Send data to gmond. """ metric_name = self.get_name_from_path(metric.path) tmax = "60" dmax = "0" slope = "both" # FIXME: Badness, shouldn't *assume* double type metric_type = "double" units = "" group = "" self.gmetric.send(metric_name, metric.value, metric_type, units, slope, tmax, dmax, group)
python
def _send(self, metric): metric_name = self.get_name_from_path(metric.path) tmax = "60" dmax = "0" slope = "both" # FIXME: Badness, shouldn't *assume* double type metric_type = "double" units = "" group = "" self.gmetric.send(metric_name, metric.value, metric_type, units, slope, tmax, dmax, group)
[ "def", "_send", "(", "self", ",", "metric", ")", ":", "metric_name", "=", "self", ".", "get_name_from_path", "(", "metric", ".", "path", ")", "tmax", "=", "\"60\"", "dmax", "=", "\"0\"", "slope", "=", "\"both\"", "# FIXME: Badness, shouldn't *assume* double type...
Send data to gmond.
[ "Send", "data", "to", "gmond", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/g_metric.py#L87-L106
236,129
python-diamond/Diamond
src/diamond/handler/mqtt.py
MQTTHandler.process
def process(self, metric): """ Process a metric by converting metric name to MQTT topic name; the payload is metric and timestamp. """ if not mosquitto: return line = str(metric) topic, value, timestamp = line.split() if len(self.prefix): topic = "%s/%s" % (self.prefix, topic) topic = topic.replace('.', '/') topic = topic.replace('#', '&') # Topic must not contain wildcards if self.timestamp == 0: self.mqttc.publish(topic, "%s" % (value), self.qos) else: self.mqttc.publish(topic, "%s %s" % (value, timestamp), self.qos)
python
def process(self, metric): if not mosquitto: return line = str(metric) topic, value, timestamp = line.split() if len(self.prefix): topic = "%s/%s" % (self.prefix, topic) topic = topic.replace('.', '/') topic = topic.replace('#', '&') # Topic must not contain wildcards if self.timestamp == 0: self.mqttc.publish(topic, "%s" % (value), self.qos) else: self.mqttc.publish(topic, "%s %s" % (value, timestamp), self.qos)
[ "def", "process", "(", "self", ",", "metric", ")", ":", "if", "not", "mosquitto", ":", "return", "line", "=", "str", "(", "metric", ")", "topic", ",", "value", ",", "timestamp", "=", "line", ".", "split", "(", ")", "if", "len", "(", "self", ".", ...
Process a metric by converting metric name to MQTT topic name; the payload is metric and timestamp.
[ "Process", "a", "metric", "by", "converting", "metric", "name", "to", "MQTT", "topic", "name", ";", "the", "payload", "is", "metric", "and", "timestamp", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/mqtt.py#L175-L194
236,130
python-diamond/Diamond
src/diamond/handler/tsdb.py
TSDBHandler.process
def process(self, metric): """ Process a metric by sending it to TSDB """ entry = {'timestamp': metric.timestamp, 'value': metric.value, "tags": {}} entry["tags"]["hostname"] = metric.host if self.cleanMetrics: metric = MetricWrapper(metric, self.log) if self.skipAggregates and metric.isAggregate(): return for tagKey in metric.getTags(): entry["tags"][tagKey] = metric.getTags()[tagKey] entry['metric'] = (self.prefix + metric.getCollectorPath() + '.' + metric.getMetricPath()) for [key, value] in self.tags: entry["tags"][key] = value self.entrys.append(entry) # send data if list is long enough if (len(self.entrys) >= self.batch): # Compress data if self.compression >= 1: data = StringIO.StringIO() with contextlib.closing(gzip.GzipFile(fileobj=data, compresslevel=self.compression, mode="w")) as f: f.write(json.dumps(self.entrys)) self._send(data.getvalue()) else: # no compression data = json.dumps(self.entrys) self._send(data)
python
def process(self, metric): entry = {'timestamp': metric.timestamp, 'value': metric.value, "tags": {}} entry["tags"]["hostname"] = metric.host if self.cleanMetrics: metric = MetricWrapper(metric, self.log) if self.skipAggregates and metric.isAggregate(): return for tagKey in metric.getTags(): entry["tags"][tagKey] = metric.getTags()[tagKey] entry['metric'] = (self.prefix + metric.getCollectorPath() + '.' + metric.getMetricPath()) for [key, value] in self.tags: entry["tags"][key] = value self.entrys.append(entry) # send data if list is long enough if (len(self.entrys) >= self.batch): # Compress data if self.compression >= 1: data = StringIO.StringIO() with contextlib.closing(gzip.GzipFile(fileobj=data, compresslevel=self.compression, mode="w")) as f: f.write(json.dumps(self.entrys)) self._send(data.getvalue()) else: # no compression data = json.dumps(self.entrys) self._send(data)
[ "def", "process", "(", "self", ",", "metric", ")", ":", "entry", "=", "{", "'timestamp'", ":", "metric", ".", "timestamp", ",", "'value'", ":", "metric", ".", "value", ",", "\"tags\"", ":", "{", "}", "}", "entry", "[", "\"tags\"", "]", "[", "\"hostna...
Process a metric by sending it to TSDB
[ "Process", "a", "metric", "by", "sending", "it", "to", "TSDB" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/tsdb.py#L189-L225
236,131
python-diamond/Diamond
src/diamond/handler/tsdb.py
TSDBHandler._send
def _send(self, content): """ Send content to TSDB. """ retry = 0 success = False while retry < 3 and success is False: self.log.debug(content) try: request = urllib2.Request("http://"+self.host+":" + str(self.port)+"/api/put", content, self.httpheader) response = urllib2.urlopen(url=request, timeout=self.timeout) if response.getcode() < 301: self.log.debug(response.read()) # Transaction should be finished self.log.debug(response.getcode()) success = True except urllib2.HTTPError as e: self.log.error("HTTP Error Code: "+str(e.code)) self.log.error("Message : "+str(e.reason)) except urllib2.URLError as e: self.log.error("Connection Error: "+str(e.reason)) finally: retry += 1 self.entrys = []
python
def _send(self, content): retry = 0 success = False while retry < 3 and success is False: self.log.debug(content) try: request = urllib2.Request("http://"+self.host+":" + str(self.port)+"/api/put", content, self.httpheader) response = urllib2.urlopen(url=request, timeout=self.timeout) if response.getcode() < 301: self.log.debug(response.read()) # Transaction should be finished self.log.debug(response.getcode()) success = True except urllib2.HTTPError as e: self.log.error("HTTP Error Code: "+str(e.code)) self.log.error("Message : "+str(e.reason)) except urllib2.URLError as e: self.log.error("Connection Error: "+str(e.reason)) finally: retry += 1 self.entrys = []
[ "def", "_send", "(", "self", ",", "content", ")", ":", "retry", "=", "0", "success", "=", "False", "while", "retry", "<", "3", "and", "success", "is", "False", ":", "self", ".", "log", ".", "debug", "(", "content", ")", "try", ":", "request", "=", ...
Send content to TSDB.
[ "Send", "content", "to", "TSDB", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/tsdb.py#L227-L252
236,132
python-diamond/Diamond
src/collectors/snmp/snmp.py
SNMPCollector.get
def get(self, oid, host, port, community): """ Perform SNMP get for a given OID """ # Initialize return value ret = {} # Convert OID to tuple if necessary if not isinstance(oid, tuple): oid = self._convert_to_oid(oid) # Convert Host to IP if necessary host = socket.gethostbyname(host) # Assemble SNMP Auth Data snmpAuthData = cmdgen.CommunityData( 'agent-{}'.format(community), community) # Assemble SNMP Transport Data snmpTransportData = cmdgen.UdpTransportTarget( (host, port), int(self.config['timeout']), int(self.config['retries'])) # Assemble SNMP Next Command result = self.snmpCmdGen.getCmd(snmpAuthData, snmpTransportData, oid) varBind = result[3] # TODO: Error check for o, v in varBind: ret[str(o)] = v.prettyPrint() return ret
python
def get(self, oid, host, port, community): # Initialize return value ret = {} # Convert OID to tuple if necessary if not isinstance(oid, tuple): oid = self._convert_to_oid(oid) # Convert Host to IP if necessary host = socket.gethostbyname(host) # Assemble SNMP Auth Data snmpAuthData = cmdgen.CommunityData( 'agent-{}'.format(community), community) # Assemble SNMP Transport Data snmpTransportData = cmdgen.UdpTransportTarget( (host, port), int(self.config['timeout']), int(self.config['retries'])) # Assemble SNMP Next Command result = self.snmpCmdGen.getCmd(snmpAuthData, snmpTransportData, oid) varBind = result[3] # TODO: Error check for o, v in varBind: ret[str(o)] = v.prettyPrint() return ret
[ "def", "get", "(", "self", ",", "oid", ",", "host", ",", "port", ",", "community", ")", ":", "# Initialize return value", "ret", "=", "{", "}", "# Convert OID to tuple if necessary", "if", "not", "isinstance", "(", "oid", ",", "tuple", ")", ":", "oid", "="...
Perform SNMP get for a given OID
[ "Perform", "SNMP", "get", "for", "a", "given", "OID" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/snmp/snmp.py#L75-L109
236,133
python-diamond/Diamond
src/collectors/snmp/snmp.py
SNMPCollector.walk
def walk(self, oid, host, port, community): """ Perform an SNMP walk on a given OID """ # Initialize return value ret = {} # Convert OID to tuple if necessary if not isinstance(oid, tuple): oid = self._convert_to_oid(oid) # Convert Host to IP if necessary host = socket.gethostbyname(host) # Assemble SNMP Auth Data snmpAuthData = cmdgen.CommunityData( 'agent-{}'.format(community), community) # Assemble SNMP Transport Data snmpTransportData = cmdgen.UdpTransportTarget( (host, port), int(self.config['timeout']), int(self.config['retries'])) # Assemble SNMP Next Command resultTable = self.snmpCmdGen.nextCmd(snmpAuthData, snmpTransportData, oid) varBindTable = resultTable[3] # TODO: Error Check for varBindTableRow in varBindTable: for o, v in varBindTableRow: ret[str(o)] = v.prettyPrint() return ret
python
def walk(self, oid, host, port, community): # Initialize return value ret = {} # Convert OID to tuple if necessary if not isinstance(oid, tuple): oid = self._convert_to_oid(oid) # Convert Host to IP if necessary host = socket.gethostbyname(host) # Assemble SNMP Auth Data snmpAuthData = cmdgen.CommunityData( 'agent-{}'.format(community), community) # Assemble SNMP Transport Data snmpTransportData = cmdgen.UdpTransportTarget( (host, port), int(self.config['timeout']), int(self.config['retries'])) # Assemble SNMP Next Command resultTable = self.snmpCmdGen.nextCmd(snmpAuthData, snmpTransportData, oid) varBindTable = resultTable[3] # TODO: Error Check for varBindTableRow in varBindTable: for o, v in varBindTableRow: ret[str(o)] = v.prettyPrint() return ret
[ "def", "walk", "(", "self", ",", "oid", ",", "host", ",", "port", ",", "community", ")", ":", "# Initialize return value", "ret", "=", "{", "}", "# Convert OID to tuple if necessary", "if", "not", "isinstance", "(", "oid", ",", "tuple", ")", ":", "oid", "=...
Perform an SNMP walk on a given OID
[ "Perform", "an", "SNMP", "walk", "on", "a", "given", "OID" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/snmp/snmp.py#L111-L148
236,134
python-diamond/Diamond
src/collectors/diskusage/diskusage.py
DiskUsageCollector.get_disk_statistics
def get_disk_statistics(self): """ Create a map of disks in the machine. http://www.kernel.org/doc/Documentation/iostats.txt Returns: (major, minor) -> DiskStatistics(device, ...) """ result = {} if os.access('/proc/diskstats', os.R_OK): self.proc_diskstats = True fp = open('/proc/diskstats') try: for line in fp: try: columns = line.split() # On early linux v2.6 versions, partitions have only 4 # output fields not 11. From linux 2.6.25 partitions # have the full stats set. if len(columns) < 14: continue major = int(columns[0]) minor = int(columns[1]) device = columns[2] if ((device.startswith('ram') or device.startswith('loop'))): continue result[(major, minor)] = { 'device': device, 'reads': float(columns[3]), 'reads_merged': float(columns[4]), 'reads_sectors': float(columns[5]), 'reads_milliseconds': float(columns[6]), 'writes': float(columns[7]), 'writes_merged': float(columns[8]), 'writes_sectors': float(columns[9]), 'writes_milliseconds': float(columns[10]), 'io_in_progress': float(columns[11]), 'io_milliseconds': float(columns[12]), 'io_milliseconds_weighted': float(columns[13]) } except ValueError: continue finally: fp.close() else: self.proc_diskstats = False if not psutil: self.log.error('Unable to import psutil') return None disks = psutil.disk_io_counters(True) sector_size = int(self.config['sector_size']) for disk in disks: result[(0, len(result))] = { 'device': disk, 'reads': disks[disk].read_count, 'reads_sectors': disks[disk].read_bytes / sector_size, 'reads_milliseconds': disks[disk].read_time, 'writes': disks[disk].write_count, 'writes_sectors': disks[disk].write_bytes / sector_size, 'writes_milliseconds': disks[disk].write_time, 'io_milliseconds': disks[disk].read_time + disks[disk].write_time, 'io_milliseconds_weighted': disks[disk].read_time + disks[disk].write_time } return result
python
def get_disk_statistics(self): result = {} if os.access('/proc/diskstats', os.R_OK): self.proc_diskstats = True fp = open('/proc/diskstats') try: for line in fp: try: columns = line.split() # On early linux v2.6 versions, partitions have only 4 # output fields not 11. From linux 2.6.25 partitions # have the full stats set. if len(columns) < 14: continue major = int(columns[0]) minor = int(columns[1]) device = columns[2] if ((device.startswith('ram') or device.startswith('loop'))): continue result[(major, minor)] = { 'device': device, 'reads': float(columns[3]), 'reads_merged': float(columns[4]), 'reads_sectors': float(columns[5]), 'reads_milliseconds': float(columns[6]), 'writes': float(columns[7]), 'writes_merged': float(columns[8]), 'writes_sectors': float(columns[9]), 'writes_milliseconds': float(columns[10]), 'io_in_progress': float(columns[11]), 'io_milliseconds': float(columns[12]), 'io_milliseconds_weighted': float(columns[13]) } except ValueError: continue finally: fp.close() else: self.proc_diskstats = False if not psutil: self.log.error('Unable to import psutil') return None disks = psutil.disk_io_counters(True) sector_size = int(self.config['sector_size']) for disk in disks: result[(0, len(result))] = { 'device': disk, 'reads': disks[disk].read_count, 'reads_sectors': disks[disk].read_bytes / sector_size, 'reads_milliseconds': disks[disk].read_time, 'writes': disks[disk].write_count, 'writes_sectors': disks[disk].write_bytes / sector_size, 'writes_milliseconds': disks[disk].write_time, 'io_milliseconds': disks[disk].read_time + disks[disk].write_time, 'io_milliseconds_weighted': disks[disk].read_time + disks[disk].write_time } return result
[ "def", "get_disk_statistics", "(", "self", ")", ":", "result", "=", "{", "}", "if", "os", ".", "access", "(", "'/proc/diskstats'", ",", "os", ".", "R_OK", ")", ":", "self", ".", "proc_diskstats", "=", "True", "fp", "=", "open", "(", "'/proc/diskstats'", ...
Create a map of disks in the machine. http://www.kernel.org/doc/Documentation/iostats.txt Returns: (major, minor) -> DiskStatistics(device, ...)
[ "Create", "a", "map", "of", "disks", "in", "the", "machine", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/diskusage/diskusage.py#L72-L145
236,135
python-diamond/Diamond
src/diamond/handler/riemann.py
RiemannHandler.process
def process(self, metric): """ Send a metric to Riemann. """ event = self._metric_to_riemann_event(metric) try: self.client.send_event(event) except Exception as e: self.log.error( "RiemannHandler: Error sending event to Riemann: %s", e)
python
def process(self, metric): event = self._metric_to_riemann_event(metric) try: self.client.send_event(event) except Exception as e: self.log.error( "RiemannHandler: Error sending event to Riemann: %s", e)
[ "def", "process", "(", "self", ",", "metric", ")", ":", "event", "=", "self", ".", "_metric_to_riemann_event", "(", "metric", ")", "try", ":", "self", ".", "client", ".", "send_event", "(", "event", ")", "except", "Exception", "as", "e", ":", "self", "...
Send a metric to Riemann.
[ "Send", "a", "metric", "to", "Riemann", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/riemann.py#L83-L92
236,136
python-diamond/Diamond
src/diamond/handler/riemann.py
RiemannHandler._metric_to_riemann_event
def _metric_to_riemann_event(self, metric): """ Convert a metric to a dictionary representing a Riemann event. """ # Riemann has a separate "host" field, so remove from the path. path = '%s.%s.%s' % ( metric.getPathPrefix(), metric.getCollectorPath(), metric.getMetricPath() ) return self.client.create_event({ 'host': metric.host, 'service': path, 'time': metric.timestamp, 'metric_f': float(metric.value), 'ttl': metric.ttl, })
python
def _metric_to_riemann_event(self, metric): # Riemann has a separate "host" field, so remove from the path. path = '%s.%s.%s' % ( metric.getPathPrefix(), metric.getCollectorPath(), metric.getMetricPath() ) return self.client.create_event({ 'host': metric.host, 'service': path, 'time': metric.timestamp, 'metric_f': float(metric.value), 'ttl': metric.ttl, })
[ "def", "_metric_to_riemann_event", "(", "self", ",", "metric", ")", ":", "# Riemann has a separate \"host\" field, so remove from the path.", "path", "=", "'%s.%s.%s'", "%", "(", "metric", ".", "getPathPrefix", "(", ")", ",", "metric", ".", "getCollectorPath", "(", ")...
Convert a metric to a dictionary representing a Riemann event.
[ "Convert", "a", "metric", "to", "a", "dictionary", "representing", "a", "Riemann", "event", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/riemann.py#L94-L111
236,137
python-diamond/Diamond
src/collectors/s3/s3.py
S3BucketCollector.collect
def collect(self): """ Collect s3 bucket stats """ if boto is None: self.log.error("Unable to import boto python module") return {} for s3instance in self.config['s3']: self.log.info("S3: byte_unit: %s" % self.config['byte_unit']) aws_access = self.config['s3'][s3instance]['aws_access_key'] aws_secret = self.config['s3'][s3instance]['aws_secret_key'] for bucket_name in self.config['s3'][s3instance]['buckets']: bucket = self.getBucket(aws_access, aws_secret, bucket_name) # collect bucket size total_size = self.getBucketSize(bucket) for byte_unit in self.config['byte_unit']: new_size = diamond.convertor.binary.convert( value=total_size, oldUnit='byte', newUnit=byte_unit ) self.publish("%s.size.%s" % (bucket_name, byte_unit), new_size)
python
def collect(self): if boto is None: self.log.error("Unable to import boto python module") return {} for s3instance in self.config['s3']: self.log.info("S3: byte_unit: %s" % self.config['byte_unit']) aws_access = self.config['s3'][s3instance]['aws_access_key'] aws_secret = self.config['s3'][s3instance]['aws_secret_key'] for bucket_name in self.config['s3'][s3instance]['buckets']: bucket = self.getBucket(aws_access, aws_secret, bucket_name) # collect bucket size total_size = self.getBucketSize(bucket) for byte_unit in self.config['byte_unit']: new_size = diamond.convertor.binary.convert( value=total_size, oldUnit='byte', newUnit=byte_unit ) self.publish("%s.size.%s" % (bucket_name, byte_unit), new_size)
[ "def", "collect", "(", "self", ")", ":", "if", "boto", "is", "None", ":", "self", ".", "log", ".", "error", "(", "\"Unable to import boto python module\"", ")", "return", "{", "}", "for", "s3instance", "in", "self", ".", "config", "[", "'s3'", "]", ":", ...
Collect s3 bucket stats
[ "Collect", "s3", "bucket", "stats" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/s3/s3.py#L51-L74
236,138
python-diamond/Diamond
src/collectors/scribe/scribe.py
ScribeCollector.key_to_metric
def key_to_metric(self, key): """Replace all non-letter characters with underscores""" return ''.join(l if l in string.letters else '_' for l in key)
python
def key_to_metric(self, key): return ''.join(l if l in string.letters else '_' for l in key)
[ "def", "key_to_metric", "(", "self", ",", "key", ")", ":", "return", "''", ".", "join", "(", "l", "if", "l", "in", "string", ".", "letters", "else", "'_'", "for", "l", "in", "key", ")" ]
Replace all non-letter characters with underscores
[ "Replace", "all", "non", "-", "letter", "characters", "with", "underscores" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/scribe/scribe.py#L37-L39
236,139
python-diamond/Diamond
src/collectors/ipmisensor/ipmisensor.py
IPMISensorCollector.parse_value
def parse_value(self, value): """ Convert value string to float for reporting """ value = value.strip() # Skip missing sensors if value == 'na': return None # Try just getting the float value try: return float(value) except: pass # Next best guess is a hex value try: return float.fromhex(value) except: pass # No luck, bail return None
python
def parse_value(self, value): value = value.strip() # Skip missing sensors if value == 'na': return None # Try just getting the float value try: return float(value) except: pass # Next best guess is a hex value try: return float.fromhex(value) except: pass # No luck, bail return None
[ "def", "parse_value", "(", "self", ",", "value", ")", ":", "value", "=", "value", ".", "strip", "(", ")", "# Skip missing sensors", "if", "value", "==", "'na'", ":", "return", "None", "# Try just getting the float value", "try", ":", "return", "float", "(", ...
Convert value string to float for reporting
[ "Convert", "value", "string", "to", "float", "for", "reporting" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/ipmisensor/ipmisensor.py#L51-L74
236,140
python-diamond/Diamond
src/collectors/nagiosperfdata/nagiosperfdata.py
NagiosPerfdataCollector.collect
def collect(self): """Collect statistics from a Nagios perfdata directory. """ perfdata_dir = self.config['perfdata_dir'] try: filenames = os.listdir(perfdata_dir) except OSError: self.log.error("Cannot read directory `{dir}'".format( dir=perfdata_dir)) return for filename in filenames: self._process_file(os.path.join(perfdata_dir, filename))
python
def collect(self): perfdata_dir = self.config['perfdata_dir'] try: filenames = os.listdir(perfdata_dir) except OSError: self.log.error("Cannot read directory `{dir}'".format( dir=perfdata_dir)) return for filename in filenames: self._process_file(os.path.join(perfdata_dir, filename))
[ "def", "collect", "(", "self", ")", ":", "perfdata_dir", "=", "self", ".", "config", "[", "'perfdata_dir'", "]", "try", ":", "filenames", "=", "os", ".", "listdir", "(", "perfdata_dir", ")", "except", "OSError", ":", "self", ".", "log", ".", "error", "...
Collect statistics from a Nagios perfdata directory.
[ "Collect", "statistics", "from", "a", "Nagios", "perfdata", "directory", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nagiosperfdata/nagiosperfdata.py#L99-L112
236,141
python-diamond/Diamond
src/collectors/nagiosperfdata/nagiosperfdata.py
NagiosPerfdataCollector._fields_valid
def _fields_valid(self, d): """Verify that all necessary fields are present Determine whether the fields parsed represent a host or service perfdata. If the perfdata is unknown, return False. If the perfdata does not contain all fields required for that type, return False. Otherwise, return True. """ if 'DATATYPE' not in d: return False datatype = d['DATATYPE'] if datatype == 'HOSTPERFDATA': fields = self.GENERIC_FIELDS + self.HOST_FIELDS elif datatype == 'SERVICEPERFDATA': fields = self.GENERIC_FIELDS + self.SERVICE_FIELDS else: return False for field in fields: if field not in d: return False return True
python
def _fields_valid(self, d): if 'DATATYPE' not in d: return False datatype = d['DATATYPE'] if datatype == 'HOSTPERFDATA': fields = self.GENERIC_FIELDS + self.HOST_FIELDS elif datatype == 'SERVICEPERFDATA': fields = self.GENERIC_FIELDS + self.SERVICE_FIELDS else: return False for field in fields: if field not in d: return False return True
[ "def", "_fields_valid", "(", "self", ",", "d", ")", ":", "if", "'DATATYPE'", "not", "in", "d", ":", "return", "False", "datatype", "=", "d", "[", "'DATATYPE'", "]", "if", "datatype", "==", "'HOSTPERFDATA'", ":", "fields", "=", "self", ".", "GENERIC_FIELD...
Verify that all necessary fields are present Determine whether the fields parsed represent a host or service perfdata. If the perfdata is unknown, return False. If the perfdata does not contain all fields required for that type, return False. Otherwise, return True.
[ "Verify", "that", "all", "necessary", "fields", "are", "present" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nagiosperfdata/nagiosperfdata.py#L127-L150
236,142
python-diamond/Diamond
src/collectors/nagiosperfdata/nagiosperfdata.py
NagiosPerfdataCollector._normalize_to_unit
def _normalize_to_unit(self, value, unit): """Normalize the value to the unit returned. We use base-1000 for second-based units, and base-1024 for byte-based units. Sadly, the Nagios-Plugins specification doesn't disambiguate base-1000 (KB) and base-1024 (KiB). """ if unit == 'ms': return value / 1000.0 if unit == 'us': return value / 1000000.0 if unit == 'KB': return value * 1024 if unit == 'MB': return value * 1024 * 1024 if unit == 'GB': return value * 1024 * 1024 * 1024 if unit == 'TB': return value * 1024 * 1024 * 1024 * 1024 return value
python
def _normalize_to_unit(self, value, unit): if unit == 'ms': return value / 1000.0 if unit == 'us': return value / 1000000.0 if unit == 'KB': return value * 1024 if unit == 'MB': return value * 1024 * 1024 if unit == 'GB': return value * 1024 * 1024 * 1024 if unit == 'TB': return value * 1024 * 1024 * 1024 * 1024 return value
[ "def", "_normalize_to_unit", "(", "self", ",", "value", ",", "unit", ")", ":", "if", "unit", "==", "'ms'", ":", "return", "value", "/", "1000.0", "if", "unit", "==", "'us'", ":", "return", "value", "/", "1000000.0", "if", "unit", "==", "'KB'", ":", "...
Normalize the value to the unit returned. We use base-1000 for second-based units, and base-1024 for byte-based units. Sadly, the Nagios-Plugins specification doesn't disambiguate base-1000 (KB) and base-1024 (KiB).
[ "Normalize", "the", "value", "to", "the", "unit", "returned", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nagiosperfdata/nagiosperfdata.py#L152-L172
236,143
python-diamond/Diamond
src/collectors/nagiosperfdata/nagiosperfdata.py
NagiosPerfdataCollector._parse_perfdata
def _parse_perfdata(self, s): """Parse performance data from a perfdata string """ metrics = [] counters = re.findall(self.TOKENIZER_RE, s) if counters is None: self.log.warning("Failed to parse performance data: {s}".format( s=s)) return metrics for (key, value, uom, warn, crit, min, max) in counters: try: norm_value = self._normalize_to_unit(float(value), uom) metrics.append((key, norm_value)) except ValueError: self.log.warning( "Couldn't convert value '{value}' to float".format( value=value)) return metrics
python
def _parse_perfdata(self, s): metrics = [] counters = re.findall(self.TOKENIZER_RE, s) if counters is None: self.log.warning("Failed to parse performance data: {s}".format( s=s)) return metrics for (key, value, uom, warn, crit, min, max) in counters: try: norm_value = self._normalize_to_unit(float(value), uom) metrics.append((key, norm_value)) except ValueError: self.log.warning( "Couldn't convert value '{value}' to float".format( value=value)) return metrics
[ "def", "_parse_perfdata", "(", "self", ",", "s", ")", ":", "metrics", "=", "[", "]", "counters", "=", "re", ".", "findall", "(", "self", ".", "TOKENIZER_RE", ",", "s", ")", "if", "counters", "is", "None", ":", "self", ".", "log", ".", "warning", "(...
Parse performance data from a perfdata string
[ "Parse", "performance", "data", "from", "a", "perfdata", "string" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nagiosperfdata/nagiosperfdata.py#L174-L193
236,144
python-diamond/Diamond
src/collectors/nagiosperfdata/nagiosperfdata.py
NagiosPerfdataCollector._process_file
def _process_file(self, path): """Parse and submit the metrics from a file """ try: f = open(path) for line in f: self._process_line(line) os.remove(path) except IOError as ex: self.log.error("Could not open file `{path}': {error}".format( path=path, error=ex.strerror))
python
def _process_file(self, path): try: f = open(path) for line in f: self._process_line(line) os.remove(path) except IOError as ex: self.log.error("Could not open file `{path}': {error}".format( path=path, error=ex.strerror))
[ "def", "_process_file", "(", "self", ",", "path", ")", ":", "try", ":", "f", "=", "open", "(", "path", ")", "for", "line", "in", "f", ":", "self", ".", "_process_line", "(", "line", ")", "os", ".", "remove", "(", "path", ")", "except", "IOError", ...
Parse and submit the metrics from a file
[ "Parse", "and", "submit", "the", "metrics", "from", "a", "file" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nagiosperfdata/nagiosperfdata.py#L195-L206
236,145
python-diamond/Diamond
src/collectors/nagiosperfdata/nagiosperfdata.py
NagiosPerfdataCollector._process_line
def _process_line(self, line): """Parse and submit the metrics from a line of perfdata output """ fields = self._extract_fields(line) if not self._fields_valid(fields): self.log.warning("Missing required fields for line: {line}".format( line=line)) metric_path_base = [] graphite_prefix = fields.get('GRAPHITEPREFIX') graphite_postfix = fields.get('GRAPHITEPOSTFIX') if graphite_prefix: metric_path_base.append(graphite_prefix) hostname = fields['HOSTNAME'].lower() metric_path_base.append(hostname) datatype = fields['DATATYPE'] if datatype == 'HOSTPERFDATA': metric_path_base.append('host') elif datatype == 'SERVICEPERFDATA': service_desc = fields.get('SERVICEDESC') graphite_postfix = fields.get('GRAPHITEPOSTFIX') if graphite_postfix: metric_path_base.append(graphite_postfix) else: metric_path_base.append(service_desc) perfdata = fields[datatype] counters = self._parse_perfdata(perfdata) for (counter, value) in counters: metric_path = metric_path_base + [counter] metric_path = [self._sanitize(x) for x in metric_path] metric_name = '.'.join(metric_path) self.publish(metric_name, value)
python
def _process_line(self, line): fields = self._extract_fields(line) if not self._fields_valid(fields): self.log.warning("Missing required fields for line: {line}".format( line=line)) metric_path_base = [] graphite_prefix = fields.get('GRAPHITEPREFIX') graphite_postfix = fields.get('GRAPHITEPOSTFIX') if graphite_prefix: metric_path_base.append(graphite_prefix) hostname = fields['HOSTNAME'].lower() metric_path_base.append(hostname) datatype = fields['DATATYPE'] if datatype == 'HOSTPERFDATA': metric_path_base.append('host') elif datatype == 'SERVICEPERFDATA': service_desc = fields.get('SERVICEDESC') graphite_postfix = fields.get('GRAPHITEPOSTFIX') if graphite_postfix: metric_path_base.append(graphite_postfix) else: metric_path_base.append(service_desc) perfdata = fields[datatype] counters = self._parse_perfdata(perfdata) for (counter, value) in counters: metric_path = metric_path_base + [counter] metric_path = [self._sanitize(x) for x in metric_path] metric_name = '.'.join(metric_path) self.publish(metric_name, value)
[ "def", "_process_line", "(", "self", ",", "line", ")", ":", "fields", "=", "self", ".", "_extract_fields", "(", "line", ")", "if", "not", "self", ".", "_fields_valid", "(", "fields", ")", ":", "self", ".", "log", ".", "warning", "(", "\"Missing required ...
Parse and submit the metrics from a line of perfdata output
[ "Parse", "and", "submit", "the", "metrics", "from", "a", "line", "of", "perfdata", "output" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/nagiosperfdata/nagiosperfdata.py#L208-L244
236,146
python-diamond/Diamond
src/diamond/handler/rabbitmq_topic.py
rmqHandler._bind
def _bind(self): """ Create socket and bind """ credentials = pika.PlainCredentials(self.user, self.password) params = pika.ConnectionParameters(credentials=credentials, host=self.server, virtual_host=self.vhost, port=self.port) self.connection = pika.BlockingConnection(params) self.channel = self.connection.channel() # NOTE : PIKA version uses 'exchange_type' instead of 'type' self.channel.exchange_declare(exchange=self.topic_exchange, exchange_type="topic")
python
def _bind(self): credentials = pika.PlainCredentials(self.user, self.password) params = pika.ConnectionParameters(credentials=credentials, host=self.server, virtual_host=self.vhost, port=self.port) self.connection = pika.BlockingConnection(params) self.channel = self.connection.channel() # NOTE : PIKA version uses 'exchange_type' instead of 'type' self.channel.exchange_declare(exchange=self.topic_exchange, exchange_type="topic")
[ "def", "_bind", "(", "self", ")", ":", "credentials", "=", "pika", ".", "PlainCredentials", "(", "self", ".", "user", ",", "self", ".", "password", ")", "params", "=", "pika", ".", "ConnectionParameters", "(", "credentials", "=", "credentials", ",", "host"...
Create socket and bind
[ "Create", "socket", "and", "bind" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/rabbitmq_topic.py#L95-L112
236,147
python-diamond/Diamond
src/diamond/handler/rabbitmq_topic.py
rmqHandler.process
def process(self, metric): """ Process a metric and send it to RabbitMQ topic exchange """ # Send the data as ...... if not pika: return routingKeyDic = { 'metric': lambda: metric.path, 'custom': lambda: self.custom_routing_key, # These option and the below are really not needed because # with Rabbitmq you can use regular expressions to indicate # what routing_keys to subscribe to. But I figure this is # a good example of how to allow more routing keys 'host': lambda: metric.host, 'metric.path': metric.getMetricPath, 'path.prefix': metric.getPathPrefix, 'collector.path': metric.getCollectorPath, } try: self.channel.basic_publish( exchange=self.topic_exchange, routing_key=routingKeyDic[self.routing_key](), body="%s" % metric) except Exception: # Rough connection re-try logic. self.log.info( "Failed publishing to rabbitMQ. Attempting reconnect") self._bind()
python
def process(self, metric): # Send the data as ...... if not pika: return routingKeyDic = { 'metric': lambda: metric.path, 'custom': lambda: self.custom_routing_key, # These option and the below are really not needed because # with Rabbitmq you can use regular expressions to indicate # what routing_keys to subscribe to. But I figure this is # a good example of how to allow more routing keys 'host': lambda: metric.host, 'metric.path': metric.getMetricPath, 'path.prefix': metric.getPathPrefix, 'collector.path': metric.getCollectorPath, } try: self.channel.basic_publish( exchange=self.topic_exchange, routing_key=routingKeyDic[self.routing_key](), body="%s" % metric) except Exception: # Rough connection re-try logic. self.log.info( "Failed publishing to rabbitMQ. Attempting reconnect") self._bind()
[ "def", "process", "(", "self", ",", "metric", ")", ":", "# Send the data as ......", "if", "not", "pika", ":", "return", "routingKeyDic", "=", "{", "'metric'", ":", "lambda", ":", "metric", ".", "path", ",", "'custom'", ":", "lambda", ":", "self", ".", "...
Process a metric and send it to RabbitMQ topic exchange
[ "Process", "a", "metric", "and", "send", "it", "to", "RabbitMQ", "topic", "exchange" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/rabbitmq_topic.py#L123-L155
236,148
python-diamond/Diamond
src/collectors/pgq/pgq.py
PgQCollector._collect_for_instance
def _collect_for_instance(self, instance, connection): """Collects metrics for a named connection.""" with connection.cursor() as cursor: for queue, metrics in self.get_queue_info(instance, cursor): for name, metric in metrics.items(): self.publish('.'.join((instance, queue, name)), metric) with connection.cursor() as cursor: consumers = self.get_consumer_info(instance, cursor) for queue, consumer, metrics in consumers: for name, metric in metrics.items(): key_parts = (instance, queue, 'consumers', consumer, name) self.publish('.'.join(key_parts), metric)
python
def _collect_for_instance(self, instance, connection): with connection.cursor() as cursor: for queue, metrics in self.get_queue_info(instance, cursor): for name, metric in metrics.items(): self.publish('.'.join((instance, queue, name)), metric) with connection.cursor() as cursor: consumers = self.get_consumer_info(instance, cursor) for queue, consumer, metrics in consumers: for name, metric in metrics.items(): key_parts = (instance, queue, 'consumers', consumer, name) self.publish('.'.join(key_parts), metric)
[ "def", "_collect_for_instance", "(", "self", ",", "instance", ",", "connection", ")", ":", "with", "connection", ".", "cursor", "(", ")", "as", "cursor", ":", "for", "queue", ",", "metrics", "in", "self", ".", "get_queue_info", "(", "instance", ",", "curso...
Collects metrics for a named connection.
[ "Collects", "metrics", "for", "a", "named", "connection", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/pgq/pgq.py#L62-L74
236,149
python-diamond/Diamond
src/collectors/pgq/pgq.py
PgQCollector.get_queue_info
def get_queue_info(self, instance, cursor): """Collects metrics for all queues on the connected database.""" cursor.execute(self.QUEUE_INFO_STATEMENT) for queue_name, ticker_lag, ev_per_sec in cursor: yield queue_name, { 'ticker_lag': ticker_lag, 'ev_per_sec': ev_per_sec, }
python
def get_queue_info(self, instance, cursor): cursor.execute(self.QUEUE_INFO_STATEMENT) for queue_name, ticker_lag, ev_per_sec in cursor: yield queue_name, { 'ticker_lag': ticker_lag, 'ev_per_sec': ev_per_sec, }
[ "def", "get_queue_info", "(", "self", ",", "instance", ",", "cursor", ")", ":", "cursor", ".", "execute", "(", "self", ".", "QUEUE_INFO_STATEMENT", ")", "for", "queue_name", ",", "ticker_lag", ",", "ev_per_sec", "in", "cursor", ":", "yield", "queue_name", ",...
Collects metrics for all queues on the connected database.
[ "Collects", "metrics", "for", "all", "queues", "on", "the", "connected", "database", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/pgq/pgq.py#L84-L91
236,150
python-diamond/Diamond
src/collectors/pgq/pgq.py
PgQCollector.get_consumer_info
def get_consumer_info(self, instance, cursor): """Collects metrics for all consumers on the connected database.""" cursor.execute(self.CONSUMER_INFO_STATEMENT) for queue_name, consumer_name, lag, pending_events, last_seen in cursor: yield queue_name, consumer_name, { 'lag': lag, 'pending_events': pending_events, 'last_seen': last_seen, }
python
def get_consumer_info(self, instance, cursor): cursor.execute(self.CONSUMER_INFO_STATEMENT) for queue_name, consumer_name, lag, pending_events, last_seen in cursor: yield queue_name, consumer_name, { 'lag': lag, 'pending_events': pending_events, 'last_seen': last_seen, }
[ "def", "get_consumer_info", "(", "self", ",", "instance", ",", "cursor", ")", ":", "cursor", ".", "execute", "(", "self", ".", "CONSUMER_INFO_STATEMENT", ")", "for", "queue_name", ",", "consumer_name", ",", "lag", ",", "pending_events", ",", "last_seen", "in",...
Collects metrics for all consumers on the connected database.
[ "Collects", "metrics", "for", "all", "consumers", "on", "the", "connected", "database", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/pgq/pgq.py#L103-L111
236,151
python-diamond/Diamond
src/collectors/mdstat/mdstat.py
MdStatCollector.collect
def collect(self): """Publish all mdstat metrics.""" def traverse(d, metric_name=''): """ Traverse the given nested dict using depth-first search. If a value is reached it will be published with a metric name consisting of the hierarchically concatenated keys of its branch. """ for key, value in d.iteritems(): if isinstance(value, dict): if metric_name == '': metric_name_next = key else: metric_name_next = metric_name + '.' + key traverse(value, metric_name_next) else: metric_name_finished = metric_name + '.' + key self.publish_gauge( name=metric_name_finished, value=value, precision=1 ) md_state = self._parse_mdstat() traverse(md_state, '')
python
def collect(self): def traverse(d, metric_name=''): """ Traverse the given nested dict using depth-first search. If a value is reached it will be published with a metric name consisting of the hierarchically concatenated keys of its branch. """ for key, value in d.iteritems(): if isinstance(value, dict): if metric_name == '': metric_name_next = key else: metric_name_next = metric_name + '.' + key traverse(value, metric_name_next) else: metric_name_finished = metric_name + '.' + key self.publish_gauge( name=metric_name_finished, value=value, precision=1 ) md_state = self._parse_mdstat() traverse(md_state, '')
[ "def", "collect", "(", "self", ")", ":", "def", "traverse", "(", "d", ",", "metric_name", "=", "''", ")", ":", "\"\"\"\n Traverse the given nested dict using depth-first search.\n\n If a value is reached it will be published with a metric name\n consi...
Publish all mdstat metrics.
[ "Publish", "all", "mdstat", "metrics", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mdstat/mdstat.py#L70-L97
236,152
python-diamond/Diamond
src/collectors/mdstat/mdstat.py
MdStatCollector._parse_array_member_state
def _parse_array_member_state(self, block): """ Parse the state of the the md array members. >>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n' >>> ' 100171776 blocks super 1.2 [2/2] [UU]\n' >>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n' >>> print _parse_array_member_state(block) { 'active': 2, 'faulty': 0, 'spare': 1 } :return: dictionary of states with according count :rtype: dict """ members = block.split('\n')[0].split(' : ')[1].split(' ')[2:] device_regexp = re.compile( '^(?P<member_name>.*)' '\[(?P<member_role_number>\d*)\]' '\(?(?P<member_state>[FS])?\)?$' ) ret = { 'active': 0, 'faulty': 0, 'spare': 0 } for member in members: member_dict = device_regexp.match(member).groupdict() if member_dict['member_state'] == 'S': ret['spare'] += 1 elif member_dict['member_state'] == 'F': ret['faulty'] += 1 else: ret['active'] += 1 return ret
python
def _parse_array_member_state(self, block): members = block.split('\n')[0].split(' : ')[1].split(' ')[2:] device_regexp = re.compile( '^(?P<member_name>.*)' '\[(?P<member_role_number>\d*)\]' '\(?(?P<member_state>[FS])?\)?$' ) ret = { 'active': 0, 'faulty': 0, 'spare': 0 } for member in members: member_dict = device_regexp.match(member).groupdict() if member_dict['member_state'] == 'S': ret['spare'] += 1 elif member_dict['member_state'] == 'F': ret['faulty'] += 1 else: ret['active'] += 1 return ret
[ "def", "_parse_array_member_state", "(", "self", ",", "block", ")", ":", "members", "=", "block", ".", "split", "(", "'\\n'", ")", "[", "0", "]", ".", "split", "(", "' : '", ")", "[", "1", "]", ".", "split", "(", "' '", ")", "[", "2", ":", "]", ...
Parse the state of the the md array members. >>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n' >>> ' 100171776 blocks super 1.2 [2/2] [UU]\n' >>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n' >>> print _parse_array_member_state(block) { 'active': 2, 'faulty': 0, 'spare': 1 } :return: dictionary of states with according count :rtype: dict
[ "Parse", "the", "state", "of", "the", "the", "md", "array", "members", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mdstat/mdstat.py#L176-L216
236,153
python-diamond/Diamond
src/collectors/mdstat/mdstat.py
MdStatCollector._parse_array_status
def _parse_array_status(self, block): """ Parse the status of the md array. >>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n' >>> ' 100171776 blocks super 1.2 [2/2] [UU]\n' >>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n' >>> print _parse_array_status(block) { 'total_members': '2', 'actual_members': '2', 'superblock_version': '1.2', 'blocks': '100171776' } :return: dictionary of status information :rtype: dict """ array_status_regexp = re.compile( '^ *(?P<blocks>\d*) blocks ' '(?:super (?P<superblock_version>\d\.\d) )?' '(?:level (?P<raid_level>\d), ' '(?P<chunk_size>\d*)k chunk, ' 'algorithm (?P<algorithm>\d) )?' '(?:\[(?P<total_members>\d*)/(?P<actual_members>\d*)\])?' '(?:(?P<rounding_factor>\d*)k rounding)?.*$' ) array_status_dict = \ array_status_regexp.match(block.split('\n')[1]).groupdict() array_status_dict_sanitizied = {} # convert all non None values to float for key, value in array_status_dict.iteritems(): if not value: continue if key == 'superblock_version': array_status_dict_sanitizied[key] = float(value) else: array_status_dict_sanitizied[key] = int(value) if 'chunk_size' in array_status_dict_sanitizied: # convert chunk size from kBytes to Bytes array_status_dict_sanitizied['chunk_size'] *= 1024 if 'rounding_factor' in array_status_dict_sanitizied: # convert rounding_factor from kBytes to Bytes array_status_dict_sanitizied['rounding_factor'] *= 1024 return array_status_dict_sanitizied
python
def _parse_array_status(self, block): array_status_regexp = re.compile( '^ *(?P<blocks>\d*) blocks ' '(?:super (?P<superblock_version>\d\.\d) )?' '(?:level (?P<raid_level>\d), ' '(?P<chunk_size>\d*)k chunk, ' 'algorithm (?P<algorithm>\d) )?' '(?:\[(?P<total_members>\d*)/(?P<actual_members>\d*)\])?' '(?:(?P<rounding_factor>\d*)k rounding)?.*$' ) array_status_dict = \ array_status_regexp.match(block.split('\n')[1]).groupdict() array_status_dict_sanitizied = {} # convert all non None values to float for key, value in array_status_dict.iteritems(): if not value: continue if key == 'superblock_version': array_status_dict_sanitizied[key] = float(value) else: array_status_dict_sanitizied[key] = int(value) if 'chunk_size' in array_status_dict_sanitizied: # convert chunk size from kBytes to Bytes array_status_dict_sanitizied['chunk_size'] *= 1024 if 'rounding_factor' in array_status_dict_sanitizied: # convert rounding_factor from kBytes to Bytes array_status_dict_sanitizied['rounding_factor'] *= 1024 return array_status_dict_sanitizied
[ "def", "_parse_array_status", "(", "self", ",", "block", ")", ":", "array_status_regexp", "=", "re", ".", "compile", "(", "'^ *(?P<blocks>\\d*) blocks '", "'(?:super (?P<superblock_version>\\d\\.\\d) )?'", "'(?:level (?P<raid_level>\\d), '", "'(?P<chunk_size>\\d*)k chunk, '", "'a...
Parse the status of the md array. >>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n' >>> ' 100171776 blocks super 1.2 [2/2] [UU]\n' >>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n' >>> print _parse_array_status(block) { 'total_members': '2', 'actual_members': '2', 'superblock_version': '1.2', 'blocks': '100171776' } :return: dictionary of status information :rtype: dict
[ "Parse", "the", "status", "of", "the", "md", "array", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mdstat/mdstat.py#L218-L268
236,154
python-diamond/Diamond
src/collectors/mdstat/mdstat.py
MdStatCollector._parse_array_bitmap
def _parse_array_bitmap(self, block): """ Parse the bitmap status of the md array. >>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n' >>> ' 100171776 blocks super 1.2 [2/2] [UU]\n' >>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n' >>> print _parse_array_bitmap(block) { 'total_pages': '1', 'allocated_pages': '1', 'page_size': 4096, 'chunk_size': 67108864 } :return: dictionary of bitmap status information :rtype: dict """ array_bitmap_regexp = re.compile( '^ *bitmap: (?P<allocated_pages>[0-9]*)/' '(?P<total_pages>[0-9]*) pages ' '\[(?P<page_size>[0-9]*)KB\], ' '(?P<chunk_size>[0-9]*)KB chunk.*$', re.MULTILINE ) regexp_res = array_bitmap_regexp.search(block) # bitmap is optionally in mdstat if not regexp_res: return None array_bitmap_dict = regexp_res.groupdict() array_bitmap_dict_sanitizied = {} # convert all values to int for key, value in array_bitmap_dict.iteritems(): if not value: continue array_bitmap_dict_sanitizied[key] = int(value) # convert page_size to bytes array_bitmap_dict_sanitizied['page_size'] *= 1024 # convert chunk_size to bytes array_bitmap_dict_sanitizied['chunk_size'] *= 1024 return array_bitmap_dict
python
def _parse_array_bitmap(self, block): array_bitmap_regexp = re.compile( '^ *bitmap: (?P<allocated_pages>[0-9]*)/' '(?P<total_pages>[0-9]*) pages ' '\[(?P<page_size>[0-9]*)KB\], ' '(?P<chunk_size>[0-9]*)KB chunk.*$', re.MULTILINE ) regexp_res = array_bitmap_regexp.search(block) # bitmap is optionally in mdstat if not regexp_res: return None array_bitmap_dict = regexp_res.groupdict() array_bitmap_dict_sanitizied = {} # convert all values to int for key, value in array_bitmap_dict.iteritems(): if not value: continue array_bitmap_dict_sanitizied[key] = int(value) # convert page_size to bytes array_bitmap_dict_sanitizied['page_size'] *= 1024 # convert chunk_size to bytes array_bitmap_dict_sanitizied['chunk_size'] *= 1024 return array_bitmap_dict
[ "def", "_parse_array_bitmap", "(", "self", ",", "block", ")", ":", "array_bitmap_regexp", "=", "re", ".", "compile", "(", "'^ *bitmap: (?P<allocated_pages>[0-9]*)/'", "'(?P<total_pages>[0-9]*) pages '", "'\\[(?P<page_size>[0-9]*)KB\\], '", "'(?P<chunk_size>[0-9]*)KB chunk.*$'", "...
Parse the bitmap status of the md array. >>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n' >>> ' 100171776 blocks super 1.2 [2/2] [UU]\n' >>> ' bitmap: 1/1 pages [4KB], 65536KB chunk\n\n' >>> print _parse_array_bitmap(block) { 'total_pages': '1', 'allocated_pages': '1', 'page_size': 4096, 'chunk_size': 67108864 } :return: dictionary of bitmap status information :rtype: dict
[ "Parse", "the", "bitmap", "status", "of", "the", "md", "array", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mdstat/mdstat.py#L270-L317
236,155
python-diamond/Diamond
src/collectors/mdstat/mdstat.py
MdStatCollector._parse_array_recovery
def _parse_array_recovery(self, block): """ Parse the recovery progress of the md array. >>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n' >>> ' 100171776 blocks super 1.2 [2/2] [UU]\n' >>> ' [===================>.] recovery = 99.5% ' >>> '(102272/102272) finish=13.37min speed=102272K/sec\n' >>> '\n' >>> print _parse_array_recovery(block) { 'percent': '99.5', 'speed': 104726528, 'remaining_time': 802199 } :return: dictionary of recovery progress status information :rtype: dict """ array_recovery_regexp = re.compile( '^ *\[.*\] *recovery = (?P<percent>\d*\.?\d*)%' ' \(\d*/\d*\) finish=(?P<remaining_time>\d*\.?\d*)min ' 'speed=(?P<speed>\d*)K/sec$', re.MULTILINE ) regexp_res = array_recovery_regexp.search(block) # recovery is optionally in mdstat if not regexp_res: return None array_recovery_dict = regexp_res.groupdict() array_recovery_dict['percent'] = \ float(array_recovery_dict['percent']) # convert speed to bits array_recovery_dict['speed'] = \ int(array_recovery_dict['speed']) * 1024 # convert minutes to milliseconds array_recovery_dict['remaining_time'] = \ int(float(array_recovery_dict['remaining_time'])*60*1000) return array_recovery_dict
python
def _parse_array_recovery(self, block): array_recovery_regexp = re.compile( '^ *\[.*\] *recovery = (?P<percent>\d*\.?\d*)%' ' \(\d*/\d*\) finish=(?P<remaining_time>\d*\.?\d*)min ' 'speed=(?P<speed>\d*)K/sec$', re.MULTILINE ) regexp_res = array_recovery_regexp.search(block) # recovery is optionally in mdstat if not regexp_res: return None array_recovery_dict = regexp_res.groupdict() array_recovery_dict['percent'] = \ float(array_recovery_dict['percent']) # convert speed to bits array_recovery_dict['speed'] = \ int(array_recovery_dict['speed']) * 1024 # convert minutes to milliseconds array_recovery_dict['remaining_time'] = \ int(float(array_recovery_dict['remaining_time'])*60*1000) return array_recovery_dict
[ "def", "_parse_array_recovery", "(", "self", ",", "block", ")", ":", "array_recovery_regexp", "=", "re", ".", "compile", "(", "'^ *\\[.*\\] *recovery = (?P<percent>\\d*\\.?\\d*)%'", "' \\(\\d*/\\d*\\) finish=(?P<remaining_time>\\d*\\.?\\d*)min '", "'speed=(?P<speed>\\d*)K/sec$'", "...
Parse the recovery progress of the md array. >>> block = 'md0 : active raid1 sdd2[0] sdb2[2](S) sdc2[1]\n' >>> ' 100171776 blocks super 1.2 [2/2] [UU]\n' >>> ' [===================>.] recovery = 99.5% ' >>> '(102272/102272) finish=13.37min speed=102272K/sec\n' >>> '\n' >>> print _parse_array_recovery(block) { 'percent': '99.5', 'speed': 104726528, 'remaining_time': 802199 } :return: dictionary of recovery progress status information :rtype: dict
[ "Parse", "the", "recovery", "progress", "of", "the", "md", "array", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mdstat/mdstat.py#L319-L364
236,156
python-diamond/Diamond
src/collectors/passenger_stats/passenger_stats.py
PassengerCollector.get_passenger_memory_stats
def get_passenger_memory_stats(self): """ Execute passenger-memory-stats, parse its output, return dictionary with stats. """ command = [self.config["passenger_memory_stats_bin"]] if str_to_bool(self.config["use_sudo"]): command.insert(0, self.config["sudo_cmd"]) try: proc1 = subprocess.Popen(command, stdout=subprocess.PIPE) (std_out, std_err) = proc1.communicate() except OSError: return {} if std_out is None: return {} dict_stats = { "apache_procs": [], "nginx_procs": [], "passenger_procs": [], "apache_mem_total": 0.0, "nginx_mem_total": 0.0, "passenger_mem_total": 0.0, } # re_colour = re.compile("\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]") re_digit = re.compile("^\d") # apache_flag = 0 nginx_flag = 0 passenger_flag = 0 for raw_line in std_out.splitlines(): line = re_colour.sub("", raw_line) if "Apache processes" in line: apache_flag = 1 elif "Nginx processes" in line: nginx_flag = 1 elif "Passenger processes" in line: passenger_flag = 1 elif re_digit.match(line): # If line starts with digit, then store PID and memory consumed line_splitted = line.split() if apache_flag == 1: dict_stats["apache_procs"].append(line_splitted[0]) dict_stats["apache_mem_total"] += float(line_splitted[4]) elif nginx_flag == 1: dict_stats["nginx_procs"].append(line_splitted[0]) dict_stats["nginx_mem_total"] += float(line_splitted[4]) elif passenger_flag == 1: dict_stats["passenger_procs"].append(line_splitted[0]) dict_stats["passenger_mem_total"] += float(line_splitted[3]) elif "Processes:" in line: passenger_flag = 0 apache_flag = 0 nginx_flag = 0 return dict_stats
python
def get_passenger_memory_stats(self): command = [self.config["passenger_memory_stats_bin"]] if str_to_bool(self.config["use_sudo"]): command.insert(0, self.config["sudo_cmd"]) try: proc1 = subprocess.Popen(command, stdout=subprocess.PIPE) (std_out, std_err) = proc1.communicate() except OSError: return {} if std_out is None: return {} dict_stats = { "apache_procs": [], "nginx_procs": [], "passenger_procs": [], "apache_mem_total": 0.0, "nginx_mem_total": 0.0, "passenger_mem_total": 0.0, } # re_colour = re.compile("\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]") re_digit = re.compile("^\d") # apache_flag = 0 nginx_flag = 0 passenger_flag = 0 for raw_line in std_out.splitlines(): line = re_colour.sub("", raw_line) if "Apache processes" in line: apache_flag = 1 elif "Nginx processes" in line: nginx_flag = 1 elif "Passenger processes" in line: passenger_flag = 1 elif re_digit.match(line): # If line starts with digit, then store PID and memory consumed line_splitted = line.split() if apache_flag == 1: dict_stats["apache_procs"].append(line_splitted[0]) dict_stats["apache_mem_total"] += float(line_splitted[4]) elif nginx_flag == 1: dict_stats["nginx_procs"].append(line_splitted[0]) dict_stats["nginx_mem_total"] += float(line_splitted[4]) elif passenger_flag == 1: dict_stats["passenger_procs"].append(line_splitted[0]) dict_stats["passenger_mem_total"] += float(line_splitted[3]) elif "Processes:" in line: passenger_flag = 0 apache_flag = 0 nginx_flag = 0 return dict_stats
[ "def", "get_passenger_memory_stats", "(", "self", ")", ":", "command", "=", "[", "self", ".", "config", "[", "\"passenger_memory_stats_bin\"", "]", "]", "if", "str_to_bool", "(", "self", ".", "config", "[", "\"use_sudo\"", "]", ")", ":", "command", ".", "ins...
Execute passenger-memory-stats, parse its output, return dictionary with stats.
[ "Execute", "passenger", "-", "memory", "-", "stats", "parse", "its", "output", "return", "dictionary", "with", "stats", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/passenger_stats/passenger_stats.py#L69-L128
236,157
python-diamond/Diamond
src/collectors/passenger_stats/passenger_stats.py
PassengerCollector.get_passenger_cpu_usage
def get_passenger_cpu_usage(self, dict_stats): """ Execute % top; and return STDOUT. """ try: proc1 = subprocess.Popen( ["top", "-b", "-n", "2"], stdout=subprocess.PIPE) (std_out, std_err) = proc1.communicate() except OSError: return (-1) re_lspaces = re.compile("^\s*") re_digit = re.compile("^\d") overall_cpu = 0 for raw_line in std_out.splitlines(): line = re_lspaces.sub("", raw_line) if not re_digit.match(line): continue line_splitted = line.split() if line_splitted[0] in dict_stats["apache_procs"]: overall_cpu += float(line_splitted[8]) elif line_splitted[0] in dict_stats["nginx_procs"]: overall_cpu += float(line_splitted[8]) elif line_splitted[0] in dict_stats["passenger_procs"]: overall_cpu += float(line_splitted[8]) return overall_cpu
python
def get_passenger_cpu_usage(self, dict_stats): try: proc1 = subprocess.Popen( ["top", "-b", "-n", "2"], stdout=subprocess.PIPE) (std_out, std_err) = proc1.communicate() except OSError: return (-1) re_lspaces = re.compile("^\s*") re_digit = re.compile("^\d") overall_cpu = 0 for raw_line in std_out.splitlines(): line = re_lspaces.sub("", raw_line) if not re_digit.match(line): continue line_splitted = line.split() if line_splitted[0] in dict_stats["apache_procs"]: overall_cpu += float(line_splitted[8]) elif line_splitted[0] in dict_stats["nginx_procs"]: overall_cpu += float(line_splitted[8]) elif line_splitted[0] in dict_stats["passenger_procs"]: overall_cpu += float(line_splitted[8]) return overall_cpu
[ "def", "get_passenger_cpu_usage", "(", "self", ",", "dict_stats", ")", ":", "try", ":", "proc1", "=", "subprocess", ".", "Popen", "(", "[", "\"top\"", ",", "\"-b\"", ",", "\"-n\"", ",", "\"2\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ...
Execute % top; and return STDOUT.
[ "Execute", "%", "top", ";", "and", "return", "STDOUT", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/passenger_stats/passenger_stats.py#L130-L158
236,158
python-diamond/Diamond
src/collectors/passenger_stats/passenger_stats.py
PassengerCollector.get_passenger_queue_stats
def get_passenger_queue_stats(self): """ Execute passenger-stats, parse its output, returnand requests in queue """ queue_stats = { "top_level_queue_size": 0.0, "passenger_queue_size": 0.0, } command = [self.config["passenger_status_bin"]] if str_to_bool(self.config["use_sudo"]): command.insert(0, self.config["sudo_cmd"]) try: proc1 = subprocess.Popen(command, stdout=subprocess.PIPE) (std_out, std_err) = proc1.communicate() except OSError: return {} if std_out is None: return {} re_colour = re.compile("\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]") re_requests = re.compile(r"Requests") re_topqueue = re.compile(r"^top-level") gen_info_flag = 0 app_groups_flag = 0 for raw_line in std_out.splitlines(): line = re_colour.sub("", raw_line) if "General information" in line: gen_info_flag = 1 if "Application groups" in line: app_groups_flag = 1 elif re_requests.match(line) and re_topqueue.search(line): # If line starts with Requests and line has top-level queue then # store queue size line_splitted = line.split() if gen_info_flag == 1 and line_splitted: queue_stats["top_level_queue_size"] = float( line_splitted[5]) elif re_requests.search(line) and not re_topqueue.search(line): # If line has Requests and nothing else special line_splitted = line.split() if app_groups_flag == 1 and line_splitted: queue_stats["passenger_queue_size"] = float( line_splitted[3]) return queue_stats
python
def get_passenger_queue_stats(self): queue_stats = { "top_level_queue_size": 0.0, "passenger_queue_size": 0.0, } command = [self.config["passenger_status_bin"]] if str_to_bool(self.config["use_sudo"]): command.insert(0, self.config["sudo_cmd"]) try: proc1 = subprocess.Popen(command, stdout=subprocess.PIPE) (std_out, std_err) = proc1.communicate() except OSError: return {} if std_out is None: return {} re_colour = re.compile("\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]") re_requests = re.compile(r"Requests") re_topqueue = re.compile(r"^top-level") gen_info_flag = 0 app_groups_flag = 0 for raw_line in std_out.splitlines(): line = re_colour.sub("", raw_line) if "General information" in line: gen_info_flag = 1 if "Application groups" in line: app_groups_flag = 1 elif re_requests.match(line) and re_topqueue.search(line): # If line starts with Requests and line has top-level queue then # store queue size line_splitted = line.split() if gen_info_flag == 1 and line_splitted: queue_stats["top_level_queue_size"] = float( line_splitted[5]) elif re_requests.search(line) and not re_topqueue.search(line): # If line has Requests and nothing else special line_splitted = line.split() if app_groups_flag == 1 and line_splitted: queue_stats["passenger_queue_size"] = float( line_splitted[3]) return queue_stats
[ "def", "get_passenger_queue_stats", "(", "self", ")", ":", "queue_stats", "=", "{", "\"top_level_queue_size\"", ":", "0.0", ",", "\"passenger_queue_size\"", ":", "0.0", ",", "}", "command", "=", "[", "self", ".", "config", "[", "\"passenger_status_bin\"", "]", "...
Execute passenger-stats, parse its output, returnand requests in queue
[ "Execute", "passenger", "-", "stats", "parse", "its", "output", "returnand", "requests", "in", "queue" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/passenger_stats/passenger_stats.py#L160-L209
236,159
python-diamond/Diamond
src/collectors/passenger_stats/passenger_stats.py
PassengerCollector.collect
def collect(self): """ Collector Passenger stats """ if not os.access(self.config["bin"], os.X_OK): self.log.error("Path %s does not exist or is not executable", self.config["bin"]) return {} dict_stats = self.get_passenger_memory_stats() if len(dict_stats.keys()) == 0: return {} queue_stats = self.get_passenger_queue_stats() if len(queue_stats.keys()) == 0: return {} overall_cpu = self.get_passenger_cpu_usage(dict_stats) if overall_cpu >= 0: self.publish("phusion_passenger_cpu", overall_cpu) self.publish("total_passenger_procs", len( dict_stats["passenger_procs"])) self.publish("total_nginx_procs", len(dict_stats["nginx_procs"])) self.publish("total_apache_procs", len(dict_stats["apache_procs"])) self.publish("total_apache_memory", dict_stats["apache_mem_total"]) self.publish("total_nginx_memory", dict_stats["nginx_mem_total"]) self.publish("total_passenger_memory", dict_stats["passenger_mem_total"]) self.publish("top_level_queue_size", queue_stats[ "top_level_queue_size"]) self.publish("passenger_queue_size", queue_stats[ "passenger_queue_size"])
python
def collect(self): if not os.access(self.config["bin"], os.X_OK): self.log.error("Path %s does not exist or is not executable", self.config["bin"]) return {} dict_stats = self.get_passenger_memory_stats() if len(dict_stats.keys()) == 0: return {} queue_stats = self.get_passenger_queue_stats() if len(queue_stats.keys()) == 0: return {} overall_cpu = self.get_passenger_cpu_usage(dict_stats) if overall_cpu >= 0: self.publish("phusion_passenger_cpu", overall_cpu) self.publish("total_passenger_procs", len( dict_stats["passenger_procs"])) self.publish("total_nginx_procs", len(dict_stats["nginx_procs"])) self.publish("total_apache_procs", len(dict_stats["apache_procs"])) self.publish("total_apache_memory", dict_stats["apache_mem_total"]) self.publish("total_nginx_memory", dict_stats["nginx_mem_total"]) self.publish("total_passenger_memory", dict_stats["passenger_mem_total"]) self.publish("top_level_queue_size", queue_stats[ "top_level_queue_size"]) self.publish("passenger_queue_size", queue_stats[ "passenger_queue_size"])
[ "def", "collect", "(", "self", ")", ":", "if", "not", "os", ".", "access", "(", "self", ".", "config", "[", "\"bin\"", "]", ",", "os", ".", "X_OK", ")", ":", "self", ".", "log", ".", "error", "(", "\"Path %s does not exist or is not executable\"", ",", ...
Collector Passenger stats
[ "Collector", "Passenger", "stats" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/passenger_stats/passenger_stats.py#L211-L243
236,160
python-diamond/Diamond
src/collectors/haproxy/haproxy.py
HAProxyCollector._collect
def _collect(self, section=None): """ Collect HAProxy Stats """ if self.config['method'] == 'http': csv_data = self.http_get_csv_data(section) elif self.config['method'] == 'unix': csv_data = self.unix_get_csv_data() else: self.log.error("Unknown collection method: %s", self.config['method']) csv_data = [] data = list(csv.reader(csv_data)) headings = self._generate_headings(data[0]) section_name = section and self._sanitize(section.lower()) + '.' or '' for row in data: if ((self._get_config_value(section, 'ignore_servers') and row[1].lower() not in ['frontend', 'backend'])): continue part_one = self._sanitize(row[0].lower()) part_two = self._sanitize(row[1].lower()) metric_name = '%s%s.%s' % (section_name, part_one, part_two) for index, metric_string in enumerate(row): try: metric_value = float(metric_string) except ValueError: continue stat_name = '%s.%s' % (metric_name, headings[index]) self.publish(stat_name, metric_value, metric_type='GAUGE')
python
def _collect(self, section=None): if self.config['method'] == 'http': csv_data = self.http_get_csv_data(section) elif self.config['method'] == 'unix': csv_data = self.unix_get_csv_data() else: self.log.error("Unknown collection method: %s", self.config['method']) csv_data = [] data = list(csv.reader(csv_data)) headings = self._generate_headings(data[0]) section_name = section and self._sanitize(section.lower()) + '.' or '' for row in data: if ((self._get_config_value(section, 'ignore_servers') and row[1].lower() not in ['frontend', 'backend'])): continue part_one = self._sanitize(row[0].lower()) part_two = self._sanitize(row[1].lower()) metric_name = '%s%s.%s' % (section_name, part_one, part_two) for index, metric_string in enumerate(row): try: metric_value = float(metric_string) except ValueError: continue stat_name = '%s.%s' % (metric_name, headings[index]) self.publish(stat_name, metric_value, metric_type='GAUGE')
[ "def", "_collect", "(", "self", ",", "section", "=", "None", ")", ":", "if", "self", ".", "config", "[", "'method'", "]", "==", "'http'", ":", "csv_data", "=", "self", ".", "http_get_csv_data", "(", "section", ")", "elif", "self", ".", "config", "[", ...
Collect HAProxy Stats
[ "Collect", "HAProxy", "Stats" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/haproxy/haproxy.py#L137-L170
236,161
python-diamond/Diamond
src/collectors/processresources/processresources.py
match_process
def match_process(pid, name, cmdline, exe, cfg): """ Decides whether a process matches with a given process descriptor :param pid: process pid :param exe: process executable :param name: process name :param cmdline: process cmdline :param cfg: the dictionary from processes that describes with the process group we're testing for :return: True if it matches :rtype: bool """ if cfg['selfmon'] and pid == os.getpid(): return True for exe_re in cfg['exe']: if exe_re.search(exe): return True for name_re in cfg['name']: if name_re.search(name): return True for cmdline_re in cfg['cmdline']: if cmdline_re.search(' '.join(cmdline)): return True return False
python
def match_process(pid, name, cmdline, exe, cfg): if cfg['selfmon'] and pid == os.getpid(): return True for exe_re in cfg['exe']: if exe_re.search(exe): return True for name_re in cfg['name']: if name_re.search(name): return True for cmdline_re in cfg['cmdline']: if cmdline_re.search(' '.join(cmdline)): return True return False
[ "def", "match_process", "(", "pid", ",", "name", ",", "cmdline", ",", "exe", ",", "cfg", ")", ":", "if", "cfg", "[", "'selfmon'", "]", "and", "pid", "==", "os", ".", "getpid", "(", ")", ":", "return", "True", "for", "exe_re", "in", "cfg", "[", "'...
Decides whether a process matches with a given process descriptor :param pid: process pid :param exe: process executable :param name: process name :param cmdline: process cmdline :param cfg: the dictionary from processes that describes with the process group we're testing for :return: True if it matches :rtype: bool
[ "Decides", "whether", "a", "process", "matches", "with", "a", "given", "process", "descriptor" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/processresources/processresources.py#L49-L73
236,162
python-diamond/Diamond
src/collectors/processresources/processresources.py
ProcessResourcesCollector.collect
def collect(self): """ Collects resources usage of each process defined under the `process` subsection of the config file """ if not psutil: self.log.error('Unable to import psutil') self.log.error('No process resource metrics retrieved') return None for process in psutil.process_iter(): self.collect_process_info(process) # publish results for pg_name, counters in self.processes_info.iteritems(): if counters: metrics = ( ("%s.%s" % (pg_name, key), value) for key, value in counters.iteritems()) else: if self.processes[pg_name]['count_workers']: metrics = (('%s.workers_count' % pg_name, 0), ) else: metrics = () [self.publish(*metric) for metric in metrics] # reinitialize process info self.processes_info[pg_name] = {}
python
def collect(self): if not psutil: self.log.error('Unable to import psutil') self.log.error('No process resource metrics retrieved') return None for process in psutil.process_iter(): self.collect_process_info(process) # publish results for pg_name, counters in self.processes_info.iteritems(): if counters: metrics = ( ("%s.%s" % (pg_name, key), value) for key, value in counters.iteritems()) else: if self.processes[pg_name]['count_workers']: metrics = (('%s.workers_count' % pg_name, 0), ) else: metrics = () [self.publish(*metric) for metric in metrics] # reinitialize process info self.processes_info[pg_name] = {}
[ "def", "collect", "(", "self", ")", ":", "if", "not", "psutil", ":", "self", ".", "log", ".", "error", "(", "'Unable to import psutil'", ")", "self", ".", "log", ".", "error", "(", "'No process resource metrics retrieved'", ")", "return", "None", "for", "pro...
Collects resources usage of each process defined under the `process` subsection of the config file
[ "Collects", "resources", "usage", "of", "each", "process", "defined", "under", "the", "process", "subsection", "of", "the", "config", "file" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/processresources/processresources.py#L187-L214
236,163
python-diamond/Diamond
src/diamond/metric.py
Metric.parse
def parse(cls, string): """ Parse a string and create a metric """ match = re.match(r'^(?P<name>[A-Za-z0-9\.\-_]+)\s+' + '(?P<value>[0-9\.]+)\s+' + '(?P<timestamp>[0-9\.]+)(\n?)$', string) try: groups = match.groupdict() # TODO: get precision from value string return Metric(groups['name'], groups['value'], float(groups['timestamp'])) except: raise DiamondException( "Metric could not be parsed from string: %s." % string)
python
def parse(cls, string): match = re.match(r'^(?P<name>[A-Za-z0-9\.\-_]+)\s+' + '(?P<value>[0-9\.]+)\s+' + '(?P<timestamp>[0-9\.]+)(\n?)$', string) try: groups = match.groupdict() # TODO: get precision from value string return Metric(groups['name'], groups['value'], float(groups['timestamp'])) except: raise DiamondException( "Metric could not be parsed from string: %s." % string)
[ "def", "parse", "(", "cls", ",", "string", ")", ":", "match", "=", "re", ".", "match", "(", "r'^(?P<name>[A-Za-z0-9\\.\\-_]+)\\s+'", "+", "'(?P<value>[0-9\\.]+)\\s+'", "+", "'(?P<timestamp>[0-9\\.]+)(\\n?)$'", ",", "string", ")", "try", ":", "groups", "=", "match"...
Parse a string and create a metric
[ "Parse", "a", "string", "and", "create", "a", "metric" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/metric.py#L100-L116
236,164
python-diamond/Diamond
src/diamond/metric.py
Metric.getPathPrefix
def getPathPrefix(self): """ Returns the path prefix path servers.host.cpu.total.idle return "servers" """ # If we don't have a host name, assume it's just the first part of the # metric path if self.host is None: return self.path.split('.')[0] offset = self.path.index(self.host) - 1 return self.path[0:offset]
python
def getPathPrefix(self): # If we don't have a host name, assume it's just the first part of the # metric path if self.host is None: return self.path.split('.')[0] offset = self.path.index(self.host) - 1 return self.path[0:offset]
[ "def", "getPathPrefix", "(", "self", ")", ":", "# If we don't have a host name, assume it's just the first part of the", "# metric path", "if", "self", ".", "host", "is", "None", ":", "return", "self", ".", "path", ".", "split", "(", "'.'", ")", "[", "0", "]", "...
Returns the path prefix path servers.host.cpu.total.idle return "servers"
[ "Returns", "the", "path", "prefix", "path", "servers", ".", "host", ".", "cpu", ".", "total", ".", "idle", "return", "servers" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/metric.py#L118-L130
236,165
python-diamond/Diamond
src/diamond/metric.py
Metric.getCollectorPath
def getCollectorPath(self): """ Returns collector path servers.host.cpu.total.idle return "cpu" """ # If we don't have a host name, assume it's just the third part of the # metric path if self.host is None: return self.path.split('.')[2] offset = self.path.index(self.host) offset += len(self.host) + 1 endoffset = self.path.index('.', offset) return self.path[offset:endoffset]
python
def getCollectorPath(self): # If we don't have a host name, assume it's just the third part of the # metric path if self.host is None: return self.path.split('.')[2] offset = self.path.index(self.host) offset += len(self.host) + 1 endoffset = self.path.index('.', offset) return self.path[offset:endoffset]
[ "def", "getCollectorPath", "(", "self", ")", ":", "# If we don't have a host name, assume it's just the third part of the", "# metric path", "if", "self", ".", "host", "is", "None", ":", "return", "self", ".", "path", ".", "split", "(", "'.'", ")", "[", "2", "]", ...
Returns collector path servers.host.cpu.total.idle return "cpu"
[ "Returns", "collector", "path", "servers", ".", "host", ".", "cpu", ".", "total", ".", "idle", "return", "cpu" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/metric.py#L132-L146
236,166
python-diamond/Diamond
src/diamond/metric.py
Metric.getMetricPath
def getMetricPath(self): """ Returns the metric path after the collector name servers.host.cpu.total.idle return "total.idle" """ # If we don't have a host name, assume it's just the fourth+ part of the # metric path if self.host is None: path = self.path.split('.')[3:] return '.'.join(path) prefix = '.'.join([self.getPathPrefix(), self.host, self.getCollectorPath()]) offset = len(prefix) + 1 return self.path[offset:]
python
def getMetricPath(self): # If we don't have a host name, assume it's just the fourth+ part of the # metric path if self.host is None: path = self.path.split('.')[3:] return '.'.join(path) prefix = '.'.join([self.getPathPrefix(), self.host, self.getCollectorPath()]) offset = len(prefix) + 1 return self.path[offset:]
[ "def", "getMetricPath", "(", "self", ")", ":", "# If we don't have a host name, assume it's just the fourth+ part of the", "# metric path", "if", "self", ".", "host", "is", "None", ":", "path", "=", "self", ".", "path", ".", "split", "(", "'.'", ")", "[", "3", "...
Returns the metric path after the collector name servers.host.cpu.total.idle return "total.idle"
[ "Returns", "the", "metric", "path", "after", "the", "collector", "name", "servers", ".", "host", ".", "cpu", ".", "total", ".", "idle", "return", "total", ".", "idle" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/metric.py#L148-L164
236,167
python-diamond/Diamond
src/diamond/handler/Handler.py
Handler._process
def _process(self, metric): """ Decorator for processing handlers with a lock, catching exceptions """ if not self.enabled: return try: try: self.lock.acquire() self.process(metric) except Exception: self.log.error(traceback.format_exc()) finally: if self.lock.locked(): self.lock.release()
python
def _process(self, metric): if not self.enabled: return try: try: self.lock.acquire() self.process(metric) except Exception: self.log.error(traceback.format_exc()) finally: if self.lock.locked(): self.lock.release()
[ "def", "_process", "(", "self", ",", "metric", ")", ":", "if", "not", "self", ".", "enabled", ":", "return", "try", ":", "try", ":", "self", ".", "lock", ".", "acquire", "(", ")", "self", ".", "process", "(", "metric", ")", "except", "Exception", "...
Decorator for processing handlers with a lock, catching exceptions
[ "Decorator", "for", "processing", "handlers", "with", "a", "lock", "catching", "exceptions" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/Handler.py#L65-L79
236,168
python-diamond/Diamond
src/diamond/handler/Handler.py
Handler._flush
def _flush(self): """ Decorator for flushing handlers with an lock, catching exceptions """ if not self.enabled: return try: try: self.lock.acquire() self.flush() except Exception: self.log.error(traceback.format_exc()) finally: if self.lock.locked(): self.lock.release()
python
def _flush(self): if not self.enabled: return try: try: self.lock.acquire() self.flush() except Exception: self.log.error(traceback.format_exc()) finally: if self.lock.locked(): self.lock.release()
[ "def", "_flush", "(", "self", ")", ":", "if", "not", "self", ".", "enabled", ":", "return", "try", ":", "try", ":", "self", ".", "lock", ".", "acquire", "(", ")", "self", ".", "flush", "(", ")", "except", "Exception", ":", "self", ".", "log", "."...
Decorator for flushing handlers with an lock, catching exceptions
[ "Decorator", "for", "flushing", "handlers", "with", "an", "lock", "catching", "exceptions" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/Handler.py#L89-L103
236,169
python-diamond/Diamond
src/diamond/handler/Handler.py
Handler._throttle_error
def _throttle_error(self, msg, *args, **kwargs): """ Avoids sending errors repeatedly. Waits at least `self.server_error_interval` seconds before sending the same error string to the error logging facility. If not enough time has passed, it calls `log.debug` instead Receives the same parameters as `Logger.error` an passes them on to the selected logging function, but ignores all parameters but the main message string when checking the last emission time. :returns: the return value of `Logger.debug` or `Logger.error` """ now = time.time() if msg in self._errors: if ((now - self._errors[msg]) >= self.server_error_interval): fn = self.log.error self._errors[msg] = now else: fn = self.log.debug else: self._errors[msg] = now fn = self.log.error return fn(msg, *args, **kwargs)
python
def _throttle_error(self, msg, *args, **kwargs): now = time.time() if msg in self._errors: if ((now - self._errors[msg]) >= self.server_error_interval): fn = self.log.error self._errors[msg] = now else: fn = self.log.debug else: self._errors[msg] = now fn = self.log.error return fn(msg, *args, **kwargs)
[ "def", "_throttle_error", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "now", "=", "time", ".", "time", "(", ")", "if", "msg", "in", "self", ".", "_errors", ":", "if", "(", "(", "now", "-", "self", ".", "_errors...
Avoids sending errors repeatedly. Waits at least `self.server_error_interval` seconds before sending the same error string to the error logging facility. If not enough time has passed, it calls `log.debug` instead Receives the same parameters as `Logger.error` an passes them on to the selected logging function, but ignores all parameters but the main message string when checking the last emission time. :returns: the return value of `Logger.debug` or `Logger.error`
[ "Avoids", "sending", "errors", "repeatedly", ".", "Waits", "at", "least", "self", ".", "server_error_interval", "seconds", "before", "sending", "the", "same", "error", "string", "to", "the", "error", "logging", "facility", ".", "If", "not", "enough", "time", "...
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/Handler.py#L113-L138
236,170
python-diamond/Diamond
src/diamond/handler/Handler.py
Handler._reset_errors
def _reset_errors(self, msg=None): """ Resets the logging throttle cache, so the next error is emitted regardless of the value in `self.server_error_interval` :param msg: if present, only this key is reset. Otherwise, the whole cache is cleaned. """ if msg is not None and msg in self._errors: del self._errors[msg] else: self._errors = {}
python
def _reset_errors(self, msg=None): if msg is not None and msg in self._errors: del self._errors[msg] else: self._errors = {}
[ "def", "_reset_errors", "(", "self", ",", "msg", "=", "None", ")", ":", "if", "msg", "is", "not", "None", "and", "msg", "in", "self", ".", "_errors", ":", "del", "self", ".", "_errors", "[", "msg", "]", "else", ":", "self", ".", "_errors", "=", "...
Resets the logging throttle cache, so the next error is emitted regardless of the value in `self.server_error_interval` :param msg: if present, only this key is reset. Otherwise, the whole cache is cleaned.
[ "Resets", "the", "logging", "throttle", "cache", "so", "the", "next", "error", "is", "emitted", "regardless", "of", "the", "value", "in", "self", ".", "server_error_interval" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/Handler.py#L140-L151
236,171
python-diamond/Diamond
src/diamond/utils/signals.py
signal_to_exception
def signal_to_exception(signum, frame): """ Called by the timeout alarm during the collector run time """ if signum == signal.SIGALRM: raise SIGALRMException() if signum == signal.SIGHUP: raise SIGHUPException() if signum == signal.SIGUSR1: raise SIGUSR1Exception() if signum == signal.SIGUSR2: raise SIGUSR2Exception() raise SignalException(signum)
python
def signal_to_exception(signum, frame): if signum == signal.SIGALRM: raise SIGALRMException() if signum == signal.SIGHUP: raise SIGHUPException() if signum == signal.SIGUSR1: raise SIGUSR1Exception() if signum == signal.SIGUSR2: raise SIGUSR2Exception() raise SignalException(signum)
[ "def", "signal_to_exception", "(", "signum", ",", "frame", ")", ":", "if", "signum", "==", "signal", ".", "SIGALRM", ":", "raise", "SIGALRMException", "(", ")", "if", "signum", "==", "signal", ".", "SIGHUP", ":", "raise", "SIGHUPException", "(", ")", "if",...
Called by the timeout alarm during the collector run time
[ "Called", "by", "the", "timeout", "alarm", "during", "the", "collector", "run", "time" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/utils/signals.py#L6-L18
236,172
python-diamond/Diamond
src/collectors/servertechpdu/servertechpdu.py
ServerTechPDUCollector.collect_snmp
def collect_snmp(self, device, host, port, community): """ Collect stats from device """ # Log self.log.info("Collecting ServerTech PDU statistics from: %s" % device) # Set timestamp timestamp = time.time() inputFeeds = {} # Collect PDU input gauge values for gaugeName, gaugeOid in self.PDU_SYSTEM_GAUGES.items(): systemGauges = self.walk(gaugeOid, host, port, community) for o, gaugeValue in systemGauges.items(): # Get Metric Name metricName = gaugeName # Get Metric Value metricValue = float(gaugeValue) # Get Metric Path metricPath = '.'.join( ['devices', device, 'system', metricName]) # Create Metric metric = Metric(metricPath, metricValue, timestamp, 2) # Publish Metric self.publish_metric(metric) # Collect PDU input feed names inputFeedNames = self.walk( self.PDU_INFEED_NAMES, host, port, community) for o, inputFeedName in inputFeedNames.items(): # Extract input feed name inputFeed = ".".join(o.split(".")[-2:]) inputFeeds[inputFeed] = inputFeedName # Collect PDU input gauge values for gaugeName, gaugeOid in self.PDU_INFEED_GAUGES.items(): inputFeedGauges = self.walk(gaugeOid, host, port, community) for o, gaugeValue in inputFeedGauges.items(): # Extract input feed name inputFeed = ".".join(o.split(".")[-2:]) # Get Metric Name metricName = '.'.join([re.sub(r'\.|\\', '_', inputFeeds[inputFeed]), gaugeName]) # Get Metric Value if gaugeName == "infeedVolts": # Note: Voltage is in "tenth volts", so divide by 10 metricValue = float(gaugeValue) / 10.0 elif gaugeName == "infeedAmps": # Note: Amps is in "hundredth amps", so divide by 100 metricValue = float(gaugeValue) / 100.0 else: metricValue = float(gaugeValue) # Get Metric Path metricPath = '.'.join(['devices', device, 'input', metricName]) # Create Metric metric = Metric(metricPath, metricValue, timestamp, 2) # Publish Metric self.publish_metric(metric)
python
def collect_snmp(self, device, host, port, community): # Log self.log.info("Collecting ServerTech PDU statistics from: %s" % device) # Set timestamp timestamp = time.time() inputFeeds = {} # Collect PDU input gauge values for gaugeName, gaugeOid in self.PDU_SYSTEM_GAUGES.items(): systemGauges = self.walk(gaugeOid, host, port, community) for o, gaugeValue in systemGauges.items(): # Get Metric Name metricName = gaugeName # Get Metric Value metricValue = float(gaugeValue) # Get Metric Path metricPath = '.'.join( ['devices', device, 'system', metricName]) # Create Metric metric = Metric(metricPath, metricValue, timestamp, 2) # Publish Metric self.publish_metric(metric) # Collect PDU input feed names inputFeedNames = self.walk( self.PDU_INFEED_NAMES, host, port, community) for o, inputFeedName in inputFeedNames.items(): # Extract input feed name inputFeed = ".".join(o.split(".")[-2:]) inputFeeds[inputFeed] = inputFeedName # Collect PDU input gauge values for gaugeName, gaugeOid in self.PDU_INFEED_GAUGES.items(): inputFeedGauges = self.walk(gaugeOid, host, port, community) for o, gaugeValue in inputFeedGauges.items(): # Extract input feed name inputFeed = ".".join(o.split(".")[-2:]) # Get Metric Name metricName = '.'.join([re.sub(r'\.|\\', '_', inputFeeds[inputFeed]), gaugeName]) # Get Metric Value if gaugeName == "infeedVolts": # Note: Voltage is in "tenth volts", so divide by 10 metricValue = float(gaugeValue) / 10.0 elif gaugeName == "infeedAmps": # Note: Amps is in "hundredth amps", so divide by 100 metricValue = float(gaugeValue) / 100.0 else: metricValue = float(gaugeValue) # Get Metric Path metricPath = '.'.join(['devices', device, 'input', metricName]) # Create Metric metric = Metric(metricPath, metricValue, timestamp, 2) # Publish Metric self.publish_metric(metric)
[ "def", "collect_snmp", "(", "self", ",", "device", ",", "host", ",", "port", ",", "community", ")", ":", "# Log", "self", ".", "log", ".", "info", "(", "\"Collecting ServerTech PDU statistics from: %s\"", "%", "device", ")", "# Set timestamp", "timestamp", "=", ...
Collect stats from device
[ "Collect", "stats", "from", "device" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/servertechpdu/servertechpdu.py#L66-L129
236,173
python-diamond/Diamond
src/collectors/users/users.py
UsersCollector.get_default_config_help
def get_default_config_help(self): """ Returns the default collector help text """ config_help = super(UsersCollector, self).get_default_config_help() config_help.update({ }) return config_help
python
def get_default_config_help(self): config_help = super(UsersCollector, self).get_default_config_help() config_help.update({ }) return config_help
[ "def", "get_default_config_help", "(", "self", ")", ":", "config_help", "=", "super", "(", "UsersCollector", ",", "self", ")", ".", "get_default_config_help", "(", ")", "config_help", ".", "update", "(", "{", "}", ")", "return", "config_help" ]
Returns the default collector help text
[ "Returns", "the", "default", "collector", "help", "text" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/users/users.py#L29-L36
236,174
python-diamond/Diamond
src/diamond/handler/stats_d.py
StatsdHandler._send
def _send(self): """ Send data to statsd. Fire and forget. Cross fingers and it'll arrive. """ if not statsd: return for metric in self.metrics: # Split the path into a prefix and a name # to work with the statsd module's view of the world. # It will get re-joined by the python-statsd module. # # For the statsd module, you specify prefix in the constructor # so we just use the full metric path. (prefix, name) = metric.path.rsplit(".", 1) logging.debug("Sending %s %s|g", name, metric.value) if metric.metric_type == 'GAUGE': if hasattr(statsd, 'StatsClient'): self.connection.gauge(metric.path, metric.value) else: statsd.Gauge(prefix, self.connection).send( name, metric.value) else: # To send a counter, we need to just send the delta # but without any time delta changes value = metric.raw_value if metric.path in self.old_values: value = value - self.old_values[metric.path] self.old_values[metric.path] = metric.raw_value if hasattr(statsd, 'StatsClient'): self.connection.incr(metric.path, value) else: statsd.Counter(prefix, self.connection).increment( name, value) if hasattr(statsd, 'StatsClient'): self.connection.send() self.metrics = []
python
def _send(self): if not statsd: return for metric in self.metrics: # Split the path into a prefix and a name # to work with the statsd module's view of the world. # It will get re-joined by the python-statsd module. # # For the statsd module, you specify prefix in the constructor # so we just use the full metric path. (prefix, name) = metric.path.rsplit(".", 1) logging.debug("Sending %s %s|g", name, metric.value) if metric.metric_type == 'GAUGE': if hasattr(statsd, 'StatsClient'): self.connection.gauge(metric.path, metric.value) else: statsd.Gauge(prefix, self.connection).send( name, metric.value) else: # To send a counter, we need to just send the delta # but without any time delta changes value = metric.raw_value if metric.path in self.old_values: value = value - self.old_values[metric.path] self.old_values[metric.path] = metric.raw_value if hasattr(statsd, 'StatsClient'): self.connection.incr(metric.path, value) else: statsd.Counter(prefix, self.connection).increment( name, value) if hasattr(statsd, 'StatsClient'): self.connection.send() self.metrics = []
[ "def", "_send", "(", "self", ")", ":", "if", "not", "statsd", ":", "return", "for", "metric", "in", "self", ".", "metrics", ":", "# Split the path into a prefix and a name", "# to work with the statsd module's view of the world.", "# It will get re-joined by the python-statsd...
Send data to statsd. Fire and forget. Cross fingers and it'll arrive.
[ "Send", "data", "to", "statsd", ".", "Fire", "and", "forget", ".", "Cross", "fingers", "and", "it", "ll", "arrive", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/stats_d.py#L106-L145
236,175
python-diamond/Diamond
src/diamond/handler/stats_d.py
StatsdHandler._connect
def _connect(self): """ Connect to the statsd server """ if not statsd: return if hasattr(statsd, 'StatsClient'): self.connection = statsd.StatsClient( host=self.host, port=self.port ).pipeline() else: # Create socket self.connection = statsd.Connection( host=self.host, port=self.port, sample_rate=1.0 )
python
def _connect(self): if not statsd: return if hasattr(statsd, 'StatsClient'): self.connection = statsd.StatsClient( host=self.host, port=self.port ).pipeline() else: # Create socket self.connection = statsd.Connection( host=self.host, port=self.port, sample_rate=1.0 )
[ "def", "_connect", "(", "self", ")", ":", "if", "not", "statsd", ":", "return", "if", "hasattr", "(", "statsd", ",", "'StatsClient'", ")", ":", "self", ".", "connection", "=", "statsd", ".", "StatsClient", "(", "host", "=", "self", ".", "host", ",", ...
Connect to the statsd server
[ "Connect", "to", "the", "statsd", "server" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/stats_d.py#L151-L169
236,176
python-diamond/Diamond
src/diamond/handler/signalfx.py
SignalfxHandler._match_metric
def _match_metric(self, metric): """ matches the metric path, if the metrics are empty, it shorts to True """ if len(self._compiled_filters) == 0: return True for (collector, filter_regex) in self._compiled_filters: if collector != metric.getCollectorPath(): continue if filter_regex.match(metric.getMetricPath()): return True return False
python
def _match_metric(self, metric): if len(self._compiled_filters) == 0: return True for (collector, filter_regex) in self._compiled_filters: if collector != metric.getCollectorPath(): continue if filter_regex.match(metric.getMetricPath()): return True return False
[ "def", "_match_metric", "(", "self", ",", "metric", ")", ":", "if", "len", "(", "self", ".", "_compiled_filters", ")", "==", "0", ":", "return", "True", "for", "(", "collector", ",", "filter_regex", ")", "in", "self", ".", "_compiled_filters", ":", "if",...
matches the metric path, if the metrics are empty, it shorts to True
[ "matches", "the", "metric", "path", "if", "the", "metrics", "are", "empty", "it", "shorts", "to", "True" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/signalfx.py#L55-L66
236,177
python-diamond/Diamond
src/diamond/handler/signalfx.py
SignalfxHandler.process
def process(self, metric): """ Queue a metric. Flushing queue if batch size reached """ if self._match_metric(metric): self.metrics.append(metric) if self.should_flush(): self._send()
python
def process(self, metric): if self._match_metric(metric): self.metrics.append(metric) if self.should_flush(): self._send()
[ "def", "process", "(", "self", ",", "metric", ")", ":", "if", "self", ".", "_match_metric", "(", "metric", ")", ":", "self", ".", "metrics", ".", "append", "(", "metric", ")", "if", "self", ".", "should_flush", "(", ")", ":", "self", ".", "_send", ...
Queue a metric. Flushing queue if batch size reached
[ "Queue", "a", "metric", ".", "Flushing", "queue", "if", "batch", "size", "reached" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/signalfx.py#L103-L110
236,178
python-diamond/Diamond
src/diamond/handler/signalfx.py
SignalfxHandler.into_signalfx_point
def into_signalfx_point(self, metric): """ Convert diamond metric into something signalfx can understand """ dims = { "collector": metric.getCollectorPath(), "prefix": metric.getPathPrefix(), } if metric.host is not None and metric.host != "": dims["host"] = metric.host return { "metric": metric.getMetricPath(), "value": metric.value, "dimensions": dims, # We expect ms timestamps "timestamp": metric.timestamp * 1000, }
python
def into_signalfx_point(self, metric): dims = { "collector": metric.getCollectorPath(), "prefix": metric.getPathPrefix(), } if metric.host is not None and metric.host != "": dims["host"] = metric.host return { "metric": metric.getMetricPath(), "value": metric.value, "dimensions": dims, # We expect ms timestamps "timestamp": metric.timestamp * 1000, }
[ "def", "into_signalfx_point", "(", "self", ",", "metric", ")", ":", "dims", "=", "{", "\"collector\"", ":", "metric", ".", "getCollectorPath", "(", ")", ",", "\"prefix\"", ":", "metric", ".", "getPathPrefix", "(", ")", ",", "}", "if", "metric", ".", "hos...
Convert diamond metric into something signalfx can understand
[ "Convert", "diamond", "metric", "into", "something", "signalfx", "can", "understand" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/signalfx.py#L116-L133
236,179
python-diamond/Diamond
src/diamond/gmetric.py
gmetric_write
def gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP): """ Arguments are in all upper-case to match XML """ packer = Packer() HOSTNAME = "test" SPOOF = 0 # Meta data about a metric packer.pack_int(128) packer.pack_string(HOSTNAME) packer.pack_string(NAME) packer.pack_int(SPOOF) packer.pack_string(TYPE) packer.pack_string(NAME) packer.pack_string(UNITS) packer.pack_int(slope_str2int[SLOPE]) # map slope string to int packer.pack_uint(int(TMAX)) packer.pack_uint(int(DMAX)) # Magic number. Indicates number of entries to follow. Put in 1 for GROUP if GROUP == "": packer.pack_int(0) else: packer.pack_int(1) packer.pack_string("GROUP") packer.pack_string(GROUP) # Actual data sent in a separate packet data = Packer() data.pack_int(128 + 5) data.pack_string(HOSTNAME) data.pack_string(NAME) data.pack_int(SPOOF) data.pack_string("%s") data.pack_string(str(VAL)) return packer.get_buffer(), data.get_buffer()
python
def gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP): packer = Packer() HOSTNAME = "test" SPOOF = 0 # Meta data about a metric packer.pack_int(128) packer.pack_string(HOSTNAME) packer.pack_string(NAME) packer.pack_int(SPOOF) packer.pack_string(TYPE) packer.pack_string(NAME) packer.pack_string(UNITS) packer.pack_int(slope_str2int[SLOPE]) # map slope string to int packer.pack_uint(int(TMAX)) packer.pack_uint(int(DMAX)) # Magic number. Indicates number of entries to follow. Put in 1 for GROUP if GROUP == "": packer.pack_int(0) else: packer.pack_int(1) packer.pack_string("GROUP") packer.pack_string(GROUP) # Actual data sent in a separate packet data = Packer() data.pack_int(128 + 5) data.pack_string(HOSTNAME) data.pack_string(NAME) data.pack_int(SPOOF) data.pack_string("%s") data.pack_string(str(VAL)) return packer.get_buffer(), data.get_buffer()
[ "def", "gmetric_write", "(", "NAME", ",", "VAL", ",", "TYPE", ",", "UNITS", ",", "SLOPE", ",", "TMAX", ",", "DMAX", ",", "GROUP", ")", ":", "packer", "=", "Packer", "(", ")", "HOSTNAME", "=", "\"test\"", "SPOOF", "=", "0", "# Meta data about a metric", ...
Arguments are in all upper-case to match XML
[ "Arguments", "are", "in", "all", "upper", "-", "case", "to", "match", "XML" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/gmetric.py#L103-L138
236,180
python-diamond/Diamond
src/collectors/disktemp/disktemp.py
DiskTemperatureCollector.collect
def collect(self): """ Collect and publish disk temperatures """ instances = {} # Support disks such as /dev/(sd.*) for device in os.listdir('/dev/'): instances.update(self.match_device(device, '/dev/')) # Support disk by id such as /dev/disk/by-id/wwn-(.*) for device_id in os.listdir('/dev/disk/by-id/'): instances.update(self.match_device(device, '/dev/disk/by-id/')) metrics = {} for device, p in instances.items(): output = p.communicate()[0].strip() try: metrics[device + ".Temperature"] = float(output) except: self.log.warn('Disk temperature retrieval failed on ' + device) for metric in metrics.keys(): self.publish(metric, metrics[metric])
python
def collect(self): instances = {} # Support disks such as /dev/(sd.*) for device in os.listdir('/dev/'): instances.update(self.match_device(device, '/dev/')) # Support disk by id such as /dev/disk/by-id/wwn-(.*) for device_id in os.listdir('/dev/disk/by-id/'): instances.update(self.match_device(device, '/dev/disk/by-id/')) metrics = {} for device, p in instances.items(): output = p.communicate()[0].strip() try: metrics[device + ".Temperature"] = float(output) except: self.log.warn('Disk temperature retrieval failed on ' + device) for metric in metrics.keys(): self.publish(metric, metrics[metric])
[ "def", "collect", "(", "self", ")", ":", "instances", "=", "{", "}", "# Support disks such as /dev/(sd.*)", "for", "device", "in", "os", ".", "listdir", "(", "'/dev/'", ")", ":", "instances", ".", "update", "(", "self", ".", "match_device", "(", "device", ...
Collect and publish disk temperatures
[ "Collect", "and", "publish", "disk", "temperatures" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/disktemp/disktemp.py#L76-L100
236,181
python-diamond/Diamond
src/collectors/elasticsearch/elasticsearch.py
ElasticSearchCollector._get
def _get(self, scheme, host, port, path, assert_key=None): """ Execute a ES API call. Convert response into JSON and optionally assert its structure. """ url = '%s://%s:%i/%s' % (scheme, host, port, path) try: request = urllib2.Request(url) if self.config['user'] and self.config['password']: base64string = base64.standard_b64encode( '%s:%s' % (self.config['user'], self.config['password'])) request.add_header("Authorization", "Basic %s" % base64string) response = urllib2.urlopen(request) except Exception as err: self.log.error("%s: %s" % (url, err)) return False try: doc = json.load(response) except (TypeError, ValueError): self.log.error("Unable to parse response from elasticsearch as a" + " json object") return False if assert_key and assert_key not in doc: self.log.error("Bad response from elasticsearch, expected key " "'%s' was missing for %s" % (assert_key, url)) return False return doc
python
def _get(self, scheme, host, port, path, assert_key=None): url = '%s://%s:%i/%s' % (scheme, host, port, path) try: request = urllib2.Request(url) if self.config['user'] and self.config['password']: base64string = base64.standard_b64encode( '%s:%s' % (self.config['user'], self.config['password'])) request.add_header("Authorization", "Basic %s" % base64string) response = urllib2.urlopen(request) except Exception as err: self.log.error("%s: %s" % (url, err)) return False try: doc = json.load(response) except (TypeError, ValueError): self.log.error("Unable to parse response from elasticsearch as a" + " json object") return False if assert_key and assert_key not in doc: self.log.error("Bad response from elasticsearch, expected key " "'%s' was missing for %s" % (assert_key, url)) return False return doc
[ "def", "_get", "(", "self", ",", "scheme", ",", "host", ",", "port", ",", "path", ",", "assert_key", "=", "None", ")", ":", "url", "=", "'%s://%s:%i/%s'", "%", "(", "scheme", ",", "host", ",", "port", ",", "path", ")", "try", ":", "request", "=", ...
Execute a ES API call. Convert response into JSON and optionally assert its structure.
[ "Execute", "a", "ES", "API", "call", ".", "Convert", "response", "into", "JSON", "and", "optionally", "assert", "its", "structure", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/elasticsearch/elasticsearch.py#L107-L135
236,182
python-diamond/Diamond
src/collectors/elasticsearch/elasticsearch.py
ElasticSearchCollector._set_or_sum_metric
def _set_or_sum_metric(self, metrics, metric_path, value): """If we already have a datapoint for this metric, lets add the value. This is used when the logstash mode is enabled.""" if metric_path in metrics: metrics[metric_path] += value else: metrics[metric_path] = value
python
def _set_or_sum_metric(self, metrics, metric_path, value): if metric_path in metrics: metrics[metric_path] += value else: metrics[metric_path] = value
[ "def", "_set_or_sum_metric", "(", "self", ",", "metrics", ",", "metric_path", ",", "value", ")", ":", "if", "metric_path", "in", "metrics", ":", "metrics", "[", "metric_path", "]", "+=", "value", "else", ":", "metrics", "[", "metric_path", "]", "=", "value...
If we already have a datapoint for this metric, lets add the value. This is used when the logstash mode is enabled.
[ "If", "we", "already", "have", "a", "datapoint", "for", "this", "metric", "lets", "add", "the", "value", ".", "This", "is", "used", "when", "the", "logstash", "mode", "is", "enabled", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/elasticsearch/elasticsearch.py#L183-L189
236,183
python-diamond/Diamond
src/collectors/redisstat/redisstat.py
RedisCollector._client
def _client(self, host, port, unix_socket, auth): """Return a redis client for the configuration. :param str host: redis host :param int port: redis port :rtype: redis.Redis """ db = int(self.config['db']) timeout = int(self.config['timeout']) try: cli = redis.Redis(host=host, port=port, db=db, socket_timeout=timeout, password=auth, unix_socket_path=unix_socket) cli.ping() return cli except Exception as ex: self.log.error("RedisCollector: failed to connect to %s:%i. %s.", unix_socket or host, port, ex)
python
def _client(self, host, port, unix_socket, auth): db = int(self.config['db']) timeout = int(self.config['timeout']) try: cli = redis.Redis(host=host, port=port, db=db, socket_timeout=timeout, password=auth, unix_socket_path=unix_socket) cli.ping() return cli except Exception as ex: self.log.error("RedisCollector: failed to connect to %s:%i. %s.", unix_socket or host, port, ex)
[ "def", "_client", "(", "self", ",", "host", ",", "port", ",", "unix_socket", ",", "auth", ")", ":", "db", "=", "int", "(", "self", ".", "config", "[", "'db'", "]", ")", "timeout", "=", "int", "(", "self", ".", "config", "[", "'timeout'", "]", ")"...
Return a redis client for the configuration. :param str host: redis host :param int port: redis port :rtype: redis.Redis
[ "Return", "a", "redis", "client", "for", "the", "configuration", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L209-L227
236,184
python-diamond/Diamond
src/collectors/redisstat/redisstat.py
RedisCollector._precision
def _precision(self, value): """Return the precision of the number :param str value: The value to find the precision of :rtype: int """ value = str(value) decimal = value.rfind('.') if decimal == -1: return 0 return len(value) - decimal - 1
python
def _precision(self, value): value = str(value) decimal = value.rfind('.') if decimal == -1: return 0 return len(value) - decimal - 1
[ "def", "_precision", "(", "self", ",", "value", ")", ":", "value", "=", "str", "(", "value", ")", "decimal", "=", "value", ".", "rfind", "(", "'.'", ")", "if", "decimal", "==", "-", "1", ":", "return", "0", "return", "len", "(", "value", ")", "-"...
Return the precision of the number :param str value: The value to find the precision of :rtype: int
[ "Return", "the", "precision", "of", "the", "number" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L229-L240
236,185
python-diamond/Diamond
src/collectors/redisstat/redisstat.py
RedisCollector._get_info
def _get_info(self, host, port, unix_socket, auth): """Return info dict from specified Redis instance :param str host: redis host :param int port: redis port :rtype: dict """ client = self._client(host, port, unix_socket, auth) if client is None: return None info = client.info() del client return info
python
def _get_info(self, host, port, unix_socket, auth): client = self._client(host, port, unix_socket, auth) if client is None: return None info = client.info() del client return info
[ "def", "_get_info", "(", "self", ",", "host", ",", "port", ",", "unix_socket", ",", "auth", ")", ":", "client", "=", "self", ".", "_client", "(", "host", ",", "port", ",", "unix_socket", ",", "auth", ")", "if", "client", "is", "None", ":", "return", ...
Return info dict from specified Redis instance :param str host: redis host :param int port: redis port :rtype: dict
[ "Return", "info", "dict", "from", "specified", "Redis", "instance" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L252-L267
236,186
python-diamond/Diamond
src/collectors/redisstat/redisstat.py
RedisCollector._get_config
def _get_config(self, host, port, unix_socket, auth, config_key): """Return config string from specified Redis instance and config key :param str host: redis host :param int port: redis port :param str host: redis config_key :rtype: str """ client = self._client(host, port, unix_socket, auth) if client is None: return None config_value = client.config_get(config_key) del client return config_value
python
def _get_config(self, host, port, unix_socket, auth, config_key): client = self._client(host, port, unix_socket, auth) if client is None: return None config_value = client.config_get(config_key) del client return config_value
[ "def", "_get_config", "(", "self", ",", "host", ",", "port", ",", "unix_socket", ",", "auth", ",", "config_key", ")", ":", "client", "=", "self", ".", "_client", "(", "host", ",", "port", ",", "unix_socket", ",", "auth", ")", "if", "client", "is", "N...
Return config string from specified Redis instance and config key :param str host: redis host :param int port: redis port :param str host: redis config_key :rtype: str
[ "Return", "config", "string", "from", "specified", "Redis", "instance", "and", "config", "key" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L269-L285
236,187
python-diamond/Diamond
src/collectors/redisstat/redisstat.py
RedisCollector.collect_instance
def collect_instance(self, nick, host, port, unix_socket, auth): """Collect metrics from a single Redis instance :param str nick: nickname of redis instance :param str host: redis host :param int port: redis port :param str unix_socket: unix socket, if applicable :param str auth: authentication password """ # Connect to redis and get the info info = self._get_info(host, port, unix_socket, auth) if info is None: return # The structure should include the port for multiple instances per # server data = dict() # Role needs to be handled outside the the _KEYS dict # since the value is a string, not a int / float # Also, master_sync_in_progress is only available if the # redis instance is a slave, so default it here so that # the metric is cleared if the instance flips from slave # to master if 'role' in info: if info['role'] == "master": data['replication.master'] = 1 data['replication.master_sync_in_progress'] = 0 else: data['replication.master'] = 0 # Connect to redis and get the maxmemory config value # Then calculate the % maxmemory of memory used maxmemory_config = self._get_config(host, port, unix_socket, auth, 'maxmemory') if maxmemory_config and 'maxmemory' in maxmemory_config.keys(): maxmemory = float(maxmemory_config['maxmemory']) # Only report % used if maxmemory is a non zero value if maxmemory == 0: maxmemory_percent = 0.0 else: maxmemory_percent = info['used_memory'] / maxmemory * 100 maxmemory_percent = round(maxmemory_percent, 2) data['memory.used_percent'] = float("%.2f" % maxmemory_percent) # Iterate over the top level keys for key in self._KEYS: if self._KEYS[key] in info: data[key] = info[self._KEYS[key]] # Iterate over renamed keys for 2.6 support for key in self._RENAMED_KEYS: if self._RENAMED_KEYS[key] in info: data[key] = info[self._RENAMED_KEYS[key]] # Look for databaase speific stats for dbnum in range(0, int(self.config.get('databases', self._DATABASE_COUNT))): db = 'db%i' % dbnum if db in info: for key in info[db]: data['%s.%s' % (db, key)] = info[db][key] # Time since last save for key in ['last_save_time', 'rdb_last_save_time']: if key in info: data['last_save.time_since'] = int(time.time()) - info[key] # Publish the data to graphite for key in data: self.publish(self._publish_key(nick, key), data[key], precision=self._precision(data[key]), metric_type='GAUGE')
python
def collect_instance(self, nick, host, port, unix_socket, auth): # Connect to redis and get the info info = self._get_info(host, port, unix_socket, auth) if info is None: return # The structure should include the port for multiple instances per # server data = dict() # Role needs to be handled outside the the _KEYS dict # since the value is a string, not a int / float # Also, master_sync_in_progress is only available if the # redis instance is a slave, so default it here so that # the metric is cleared if the instance flips from slave # to master if 'role' in info: if info['role'] == "master": data['replication.master'] = 1 data['replication.master_sync_in_progress'] = 0 else: data['replication.master'] = 0 # Connect to redis and get the maxmemory config value # Then calculate the % maxmemory of memory used maxmemory_config = self._get_config(host, port, unix_socket, auth, 'maxmemory') if maxmemory_config and 'maxmemory' in maxmemory_config.keys(): maxmemory = float(maxmemory_config['maxmemory']) # Only report % used if maxmemory is a non zero value if maxmemory == 0: maxmemory_percent = 0.0 else: maxmemory_percent = info['used_memory'] / maxmemory * 100 maxmemory_percent = round(maxmemory_percent, 2) data['memory.used_percent'] = float("%.2f" % maxmemory_percent) # Iterate over the top level keys for key in self._KEYS: if self._KEYS[key] in info: data[key] = info[self._KEYS[key]] # Iterate over renamed keys for 2.6 support for key in self._RENAMED_KEYS: if self._RENAMED_KEYS[key] in info: data[key] = info[self._RENAMED_KEYS[key]] # Look for databaase speific stats for dbnum in range(0, int(self.config.get('databases', self._DATABASE_COUNT))): db = 'db%i' % dbnum if db in info: for key in info[db]: data['%s.%s' % (db, key)] = info[db][key] # Time since last save for key in ['last_save_time', 'rdb_last_save_time']: if key in info: data['last_save.time_since'] = int(time.time()) - info[key] # Publish the data to graphite for key in data: self.publish(self._publish_key(nick, key), data[key], precision=self._precision(data[key]), metric_type='GAUGE')
[ "def", "collect_instance", "(", "self", ",", "nick", ",", "host", ",", "port", ",", "unix_socket", ",", "auth", ")", ":", "# Connect to redis and get the info", "info", "=", "self", ".", "_get_info", "(", "host", ",", "port", ",", "unix_socket", ",", "auth",...
Collect metrics from a single Redis instance :param str nick: nickname of redis instance :param str host: redis host :param int port: redis port :param str unix_socket: unix socket, if applicable :param str auth: authentication password
[ "Collect", "metrics", "from", "a", "single", "Redis", "instance" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L287-L363
236,188
python-diamond/Diamond
src/collectors/redisstat/redisstat.py
RedisCollector.collect
def collect(self): """Collect the stats from the redis instance and publish them. """ if redis is None: self.log.error('Unable to import module redis') return {} for nick in self.instances.keys(): (host, port, unix_socket, auth) = self.instances[nick] self.collect_instance(nick, host, int(port), unix_socket, auth)
python
def collect(self): if redis is None: self.log.error('Unable to import module redis') return {} for nick in self.instances.keys(): (host, port, unix_socket, auth) = self.instances[nick] self.collect_instance(nick, host, int(port), unix_socket, auth)
[ "def", "collect", "(", "self", ")", ":", "if", "redis", "is", "None", ":", "self", ".", "log", ".", "error", "(", "'Unable to import module redis'", ")", "return", "{", "}", "for", "nick", "in", "self", ".", "instances", ".", "keys", "(", ")", ":", "...
Collect the stats from the redis instance and publish them.
[ "Collect", "the", "stats", "from", "the", "redis", "instance", "and", "publish", "them", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/redisstat/redisstat.py#L365-L375
236,189
python-diamond/Diamond
src/collectors/xfs/xfs.py
XFSCollector.get_default_config
def get_default_config(self): """ Returns the xfs collector settings """ config = super(XFSCollector, self).get_default_config() config.update({ 'path': 'xfs' }) return config
python
def get_default_config(self): config = super(XFSCollector, self).get_default_config() config.update({ 'path': 'xfs' }) return config
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "XFSCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'xfs'", "}", ")", "return", "config" ]
Returns the xfs collector settings
[ "Returns", "the", "xfs", "collector", "settings" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/xfs/xfs.py#L25-L33
236,190
python-diamond/Diamond
src/diamond/handler/cloudwatch.py
cloudwatchHandler._bind
def _bind(self): """ Create CloudWatch Connection """ self.log.debug( "CloudWatch: Attempting to connect to CloudWatch at Region: %s", self.region) try: self.connection = boto.ec2.cloudwatch.connect_to_region( self.region) self.log.debug( "CloudWatch: Succesfully Connected to CloudWatch at Region: %s", self.region) except boto.exception.EC2ResponseError: self.log.error('CloudWatch: CloudWatch Exception Handler: ')
python
def _bind(self): self.log.debug( "CloudWatch: Attempting to connect to CloudWatch at Region: %s", self.region) try: self.connection = boto.ec2.cloudwatch.connect_to_region( self.region) self.log.debug( "CloudWatch: Succesfully Connected to CloudWatch at Region: %s", self.region) except boto.exception.EC2ResponseError: self.log.error('CloudWatch: CloudWatch Exception Handler: ')
[ "def", "_bind", "(", "self", ")", ":", "self", ".", "log", ".", "debug", "(", "\"CloudWatch: Attempting to connect to CloudWatch at Region: %s\"", ",", "self", ".", "region", ")", "try", ":", "self", ".", "connection", "=", "boto", ".", "ec2", ".", "cloudwatch...
Create CloudWatch Connection
[ "Create", "CloudWatch", "Connection" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/cloudwatch.py#L163-L178
236,191
python-diamond/Diamond
src/diamond/handler/cloudwatch.py
cloudwatchHandler.process
def process(self, metric): """ Process a metric and send it to CloudWatch """ if not boto: return collector = str(metric.getCollectorPath()) metricname = str(metric.getMetricPath()) # Send the data as ...... for rule in self.rules: self.log.debug( "Comparing Collector: [%s] with (%s) " "and Metric: [%s] with (%s)", str(rule['collector']), collector, str(rule['metric']), metricname ) if ((str(rule['collector']) == collector and str(rule['metric']) == metricname)): if rule['collect_by_instance'] and self.instance_id: self.send_metrics_to_cloudwatch( rule, metric, {'InstanceId': self.instance_id}) if rule['collect_without_dimension']: self.send_metrics_to_cloudwatch( rule, metric, {})
python
def process(self, metric): if not boto: return collector = str(metric.getCollectorPath()) metricname = str(metric.getMetricPath()) # Send the data as ...... for rule in self.rules: self.log.debug( "Comparing Collector: [%s] with (%s) " "and Metric: [%s] with (%s)", str(rule['collector']), collector, str(rule['metric']), metricname ) if ((str(rule['collector']) == collector and str(rule['metric']) == metricname)): if rule['collect_by_instance'] and self.instance_id: self.send_metrics_to_cloudwatch( rule, metric, {'InstanceId': self.instance_id}) if rule['collect_without_dimension']: self.send_metrics_to_cloudwatch( rule, metric, {})
[ "def", "process", "(", "self", ",", "metric", ")", ":", "if", "not", "boto", ":", "return", "collector", "=", "str", "(", "metric", ".", "getCollectorPath", "(", ")", ")", "metricname", "=", "str", "(", "metric", ".", "getMetricPath", "(", ")", ")", ...
Process a metric and send it to CloudWatch
[ "Process", "a", "metric", "and", "send", "it", "to", "CloudWatch" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/cloudwatch.py#L189-L224
236,192
python-diamond/Diamond
src/diamond/handler/cloudwatch.py
cloudwatchHandler.send_metrics_to_cloudwatch
def send_metrics_to_cloudwatch(self, rule, metric, dimensions): """ Send metrics to CloudWatch for the given dimensions """ timestamp = datetime.datetime.utcfromtimestamp(metric.timestamp) self.log.debug( "CloudWatch: Attempting to publish metric: %s to %s " "with value (%s) for dimensions %s @%s", rule['name'], rule['namespace'], str(metric.value), str(dimensions), str(metric.timestamp) ) try: self.connection.put_metric_data( str(rule['namespace']), str(rule['name']), str(metric.value), timestamp, str(rule['unit']), dimensions) self.log.debug( "CloudWatch: Successfully published metric: %s to" " %s with value (%s) for dimensions %s", rule['name'], rule['namespace'], str(metric.value), str(dimensions)) except AttributeError as e: self.log.error( "CloudWatch: Failed publishing - %s ", str(e)) except Exception as e: # Rough connection re-try logic. self.log.error( "CloudWatch: Failed publishing - %s\n%s ", str(e), str(sys.exc_info()[0])) self._bind()
python
def send_metrics_to_cloudwatch(self, rule, metric, dimensions): timestamp = datetime.datetime.utcfromtimestamp(metric.timestamp) self.log.debug( "CloudWatch: Attempting to publish metric: %s to %s " "with value (%s) for dimensions %s @%s", rule['name'], rule['namespace'], str(metric.value), str(dimensions), str(metric.timestamp) ) try: self.connection.put_metric_data( str(rule['namespace']), str(rule['name']), str(metric.value), timestamp, str(rule['unit']), dimensions) self.log.debug( "CloudWatch: Successfully published metric: %s to" " %s with value (%s) for dimensions %s", rule['name'], rule['namespace'], str(metric.value), str(dimensions)) except AttributeError as e: self.log.error( "CloudWatch: Failed publishing - %s ", str(e)) except Exception as e: # Rough connection re-try logic. self.log.error( "CloudWatch: Failed publishing - %s\n%s ", str(e), str(sys.exc_info()[0])) self._bind()
[ "def", "send_metrics_to_cloudwatch", "(", "self", ",", "rule", ",", "metric", ",", "dimensions", ")", ":", "timestamp", "=", "datetime", ".", "datetime", ".", "utcfromtimestamp", "(", "metric", ".", "timestamp", ")", "self", ".", "log", ".", "debug", "(", ...
Send metrics to CloudWatch for the given dimensions
[ "Send", "metrics", "to", "CloudWatch", "for", "the", "given", "dimensions" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/cloudwatch.py#L226-L265
236,193
python-diamond/Diamond
src/collectors/mongodb/mongodb.py
MongoDBCollector._publish_replset
def _publish_replset(self, data, base_prefix): """ Given a response to replSetGetStatus, publishes all numeric values of the instance, aggregate stats of healthy nodes vs total nodes, and the observed statuses of all nodes in the replica set. """ prefix = base_prefix + ['replset'] self._publish_dict_with_prefix(data, prefix) total_nodes = len(data['members']) healthy_nodes = reduce(lambda value, node: value + node['health'], data['members'], 0) self._publish_dict_with_prefix({ 'healthy_nodes': healthy_nodes, 'total_nodes': total_nodes }, prefix) for node in data['members']: replset_node_name = node[self.config['replset_node_name']] node_name = str(replset_node_name.split('.')[0]) self._publish_dict_with_prefix(node, prefix + ['node', node_name])
python
def _publish_replset(self, data, base_prefix): prefix = base_prefix + ['replset'] self._publish_dict_with_prefix(data, prefix) total_nodes = len(data['members']) healthy_nodes = reduce(lambda value, node: value + node['health'], data['members'], 0) self._publish_dict_with_prefix({ 'healthy_nodes': healthy_nodes, 'total_nodes': total_nodes }, prefix) for node in data['members']: replset_node_name = node[self.config['replset_node_name']] node_name = str(replset_node_name.split('.')[0]) self._publish_dict_with_prefix(node, prefix + ['node', node_name])
[ "def", "_publish_replset", "(", "self", ",", "data", ",", "base_prefix", ")", ":", "prefix", "=", "base_prefix", "+", "[", "'replset'", "]", "self", ".", "_publish_dict_with_prefix", "(", "data", ",", "prefix", ")", "total_nodes", "=", "len", "(", "data", ...
Given a response to replSetGetStatus, publishes all numeric values of the instance, aggregate stats of healthy nodes vs total nodes, and the observed statuses of all nodes in the replica set.
[ "Given", "a", "response", "to", "replSetGetStatus", "publishes", "all", "numeric", "values", "of", "the", "instance", "aggregate", "stats", "of", "healthy", "nodes", "vs", "total", "nodes", "and", "the", "observed", "statuses", "of", "all", "nodes", "in", "the...
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/mongodb/mongodb.py#L230-L248
236,194
python-diamond/Diamond
src/diamond/handler/influxdbHandler.py
InfluxdbHandler._send
def _send(self): """ Send data to Influxdb. Data that can not be sent will be kept in queued. """ # Check to see if we have a valid socket. If not, try to connect. try: if self.influx is None: self.log.debug("InfluxdbHandler: Socket is not connected. " "Reconnecting.") self._connect() if self.influx is None: self.log.debug("InfluxdbHandler: Reconnect failed.") else: # build metrics data metrics = [] for path in self.batch: metrics.append({ "points": self.batch[path], "name": path, "columns": ["time", "value"]}) # Send data to influxdb self.log.debug("InfluxdbHandler: writing %d series of data", len(metrics)) self.influx.write_points(metrics, time_precision=self.time_precision) # empty batch buffer self.batch = {} self.batch_count = 0 self.time_multiplier = 1 except Exception: self._close() if self.time_multiplier < 5: self.time_multiplier += 1 self._throttle_error( "InfluxdbHandler: Error sending metrics, waiting for %ds.", 2**self.time_multiplier) raise
python
def _send(self): # Check to see if we have a valid socket. If not, try to connect. try: if self.influx is None: self.log.debug("InfluxdbHandler: Socket is not connected. " "Reconnecting.") self._connect() if self.influx is None: self.log.debug("InfluxdbHandler: Reconnect failed.") else: # build metrics data metrics = [] for path in self.batch: metrics.append({ "points": self.batch[path], "name": path, "columns": ["time", "value"]}) # Send data to influxdb self.log.debug("InfluxdbHandler: writing %d series of data", len(metrics)) self.influx.write_points(metrics, time_precision=self.time_precision) # empty batch buffer self.batch = {} self.batch_count = 0 self.time_multiplier = 1 except Exception: self._close() if self.time_multiplier < 5: self.time_multiplier += 1 self._throttle_error( "InfluxdbHandler: Error sending metrics, waiting for %ds.", 2**self.time_multiplier) raise
[ "def", "_send", "(", "self", ")", ":", "# Check to see if we have a valid socket. If not, try to connect.", "try", ":", "if", "self", ".", "influx", "is", "None", ":", "self", ".", "log", ".", "debug", "(", "\"InfluxdbHandler: Socket is not connected. \"", "\"Reconnecti...
Send data to Influxdb. Data that can not be sent will be kept in queued.
[ "Send", "data", "to", "Influxdb", ".", "Data", "that", "can", "not", "be", "sent", "will", "be", "kept", "in", "queued", "." ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/influxdbHandler.py#L156-L194
236,195
python-diamond/Diamond
src/diamond/handler/influxdbHandler.py
InfluxdbHandler._connect
def _connect(self): """ Connect to the influxdb server """ try: # Open Connection self.influx = InfluxDBClient(self.hostname, self.port, self.username, self.password, self.database, self.ssl) # Log self.log.debug("InfluxdbHandler: Established connection to " "%s:%d/%s.", self.hostname, self.port, self.database) except Exception as ex: # Log Error self._throttle_error("InfluxdbHandler: Failed to connect to " "%s:%d/%s. %s", self.hostname, self.port, self.database, ex) # Close Socket self._close() return
python
def _connect(self): try: # Open Connection self.influx = InfluxDBClient(self.hostname, self.port, self.username, self.password, self.database, self.ssl) # Log self.log.debug("InfluxdbHandler: Established connection to " "%s:%d/%s.", self.hostname, self.port, self.database) except Exception as ex: # Log Error self._throttle_error("InfluxdbHandler: Failed to connect to " "%s:%d/%s. %s", self.hostname, self.port, self.database, ex) # Close Socket self._close() return
[ "def", "_connect", "(", "self", ")", ":", "try", ":", "# Open Connection", "self", ".", "influx", "=", "InfluxDBClient", "(", "self", ".", "hostname", ",", "self", ".", "port", ",", "self", ".", "username", ",", "self", ".", "password", ",", "self", "....
Connect to the influxdb server
[ "Connect", "to", "the", "influxdb", "server" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/influxdbHandler.py#L196-L217
236,196
python-diamond/Diamond
src/diamond/handler/rabbitmq_pubsub.py
rmqHandler.get_config
def get_config(self): """ Get and set config options from config file """ if 'rmq_port' in self.config: self.rmq_port = int(self.config['rmq_port']) if 'rmq_user' in self.config: self.rmq_user = self.config['rmq_user'] if 'rmq_password' in self.config: self.rmq_password = self.config['rmq_password'] if 'rmq_vhost' in self.config: self.rmq_vhost = self.config['rmq_vhost'] if 'rmq_exchange_type' in self.config: self.rmq_exchange_type = self.config['rmq_exchange_type'] if 'rmq_durable' in self.config: self.rmq_durable = bool(self.config['rmq_durable']) if 'rmq_heartbeat_interval' in self.config: self.rmq_heartbeat_interval = int( self.config['rmq_heartbeat_interval'])
python
def get_config(self): if 'rmq_port' in self.config: self.rmq_port = int(self.config['rmq_port']) if 'rmq_user' in self.config: self.rmq_user = self.config['rmq_user'] if 'rmq_password' in self.config: self.rmq_password = self.config['rmq_password'] if 'rmq_vhost' in self.config: self.rmq_vhost = self.config['rmq_vhost'] if 'rmq_exchange_type' in self.config: self.rmq_exchange_type = self.config['rmq_exchange_type'] if 'rmq_durable' in self.config: self.rmq_durable = bool(self.config['rmq_durable']) if 'rmq_heartbeat_interval' in self.config: self.rmq_heartbeat_interval = int( self.config['rmq_heartbeat_interval'])
[ "def", "get_config", "(", "self", ")", ":", "if", "'rmq_port'", "in", "self", ".", "config", ":", "self", ".", "rmq_port", "=", "int", "(", "self", ".", "config", "[", "'rmq_port'", "]", ")", "if", "'rmq_user'", "in", "self", ".", "config", ":", "sel...
Get and set config options from config file
[ "Get", "and", "set", "config", "options", "from", "config", "file" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/rabbitmq_pubsub.py#L63-L85
236,197
python-diamond/Diamond
src/diamond/handler/rabbitmq_pubsub.py
rmqHandler._unbind
def _unbind(self, rmq_server=None): """ Close AMQP connection and unset channel """ try: self.connections[rmq_server].close() except AttributeError: pass self.connections[rmq_server] = None self.channels[rmq_server] = None
python
def _unbind(self, rmq_server=None): try: self.connections[rmq_server].close() except AttributeError: pass self.connections[rmq_server] = None self.channels[rmq_server] = None
[ "def", "_unbind", "(", "self", ",", "rmq_server", "=", "None", ")", ":", "try", ":", "self", ".", "connections", "[", "rmq_server", "]", ".", "close", "(", ")", "except", "AttributeError", ":", "pass", "self", ".", "connections", "[", "rmq_server", "]", ...
Close AMQP connection and unset channel
[ "Close", "AMQP", "connection", "and", "unset", "channel" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/rabbitmq_pubsub.py#L172-L180
236,198
python-diamond/Diamond
src/diamond/handler/rabbitmq_pubsub.py
rmqHandler.process
def process(self, metric): """ Process a metric and send it to RMQ pub socket """ for rmq_server in self.connections.keys(): try: if ((self.connections[rmq_server] is None or self.connections[rmq_server].is_open is False)): self._bind(rmq_server) channel = self.channels[rmq_server] channel.basic_publish(exchange=self.rmq_exchange, routing_key='', body="%s" % metric) except Exception as exception: self.log.error( "Failed publishing to %s, attempting reconnect", rmq_server) self.log.debug("Caught exception: %s", exception) self._unbind(rmq_server) self._bind(rmq_server)
python
def process(self, metric): for rmq_server in self.connections.keys(): try: if ((self.connections[rmq_server] is None or self.connections[rmq_server].is_open is False)): self._bind(rmq_server) channel = self.channels[rmq_server] channel.basic_publish(exchange=self.rmq_exchange, routing_key='', body="%s" % metric) except Exception as exception: self.log.error( "Failed publishing to %s, attempting reconnect", rmq_server) self.log.debug("Caught exception: %s", exception) self._unbind(rmq_server) self._bind(rmq_server)
[ "def", "process", "(", "self", ",", "metric", ")", ":", "for", "rmq_server", "in", "self", ".", "connections", ".", "keys", "(", ")", ":", "try", ":", "if", "(", "(", "self", ".", "connections", "[", "rmq_server", "]", "is", "None", "or", "self", "...
Process a metric and send it to RMQ pub socket
[ "Process", "a", "metric", "and", "send", "it", "to", "RMQ", "pub", "socket" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/diamond/handler/rabbitmq_pubsub.py#L190-L209
236,199
python-diamond/Diamond
src/collectors/netstat/netstat.py
NetstatCollector._load
def _load(): """ Read the table of tcp connections & remove header """ with open(NetstatCollector.PROC_TCP, 'r') as f: content = f.readlines() content.pop(0) return content
python
def _load(): with open(NetstatCollector.PROC_TCP, 'r') as f: content = f.readlines() content.pop(0) return content
[ "def", "_load", "(", ")", ":", "with", "open", "(", "NetstatCollector", ".", "PROC_TCP", ",", "'r'", ")", "as", "f", ":", "content", "=", "f", ".", "readlines", "(", ")", "content", ".", "pop", "(", "0", ")", "return", "content" ]
Read the table of tcp connections & remove header
[ "Read", "the", "table", "of", "tcp", "connections", "&", "remove", "header" ]
0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47
https://github.com/python-diamond/Diamond/blob/0f3eb04327d6d3ed5e53a9967d6c9d2c09714a47/src/collectors/netstat/netstat.py#L62-L67