Пример #1
0
def graph(request, name):
    """Handle the graph request.

    :param request: The original resmon GRAPH request.
    :type request: HttpRequest
    :param name: The name of the resmon RRD whose graph is desired.
    :type name: str
    :return: The response to the graph request.
    :rtype: HttpResponse
    """
    try:
        period = request.GET.get('period')
        width = request.GET.get('width')
        height = request.GET.get('height')
        dataset = request.GET.get('dataset')  # Space delimited data set
        end_ts = int(time.time())
        start_ts = end_ts - parse_timespec(period)

        if not dataset:
            raise HttpResponseBadRequest('No dataset given')

        resp = RestCmd('resmon/graph', '')

        img = tempfile.mkstemp(suffix=".png", prefix="resmongraph")
        try:
            close(img[0])

            execute_graph_request(name, dataset.split(), img[1], start_ts, end_ts, 'AVERAGE', width, height)

            # Now read in the image file and prepare for the response.
            with open(img[1], 'r') as f:
                img_size = os.path.getsize(img[1])
                if img_size <= 2095104:  # Read maximum 2Mb
                    resp.data = f.read()

                    if 'xml' in request.META.get('HTTP_ACCEPT'):
                        return HttpResponse(ElementTree.tostring(resp.export_xml()), content_type='application/xml')

                    return HttpResponse(resp.export_json(), content_type='application/json')

                else:
                    logger.warning('Image file size {0} exceeded the maximum limit of 2Mb, please retry with smaller dimensions.'
                                   .format(img_size))
                    return HttpResponseServerError('Image file too large')

        finally:
            os.remove(img[1])  # Clean up the temp file.

    except Exception as e:
        tb = sys.exc_info()[2]
        logger.error('Encountered unexpected {0} at {1}'.format(e, traceback.format_tb(tb)))
        return HttpResponseServerError('Unexpected internal server error')