Example #1
0
    def __call__(self, *args, **kwargs):
        """
            extract token id, test token expiration, and return token
        """
        # test for uuid
        if self.uuid is None:
            self.request.response.setStatus(503)
            self.request.response.write( "System uninitialized - please execute setup wizard")
            return

        tokenId = self.request.get('id', None)
        if tokenId is None:
            tokenId = self.request.getHeader(ZAUTH_HEADER_ID)

        # missing token id
        if tokenId is None:
            self.request.response.setStatus(401)
            self.request.response.write( "Missing Token Id")
            return

        authorization = IAuthorizationTool( self.context.context)

        #grab token to handle edge case, when expiration happens after expiration test
        tokenId = tokenId.strip('"')
        token = authorization.getToken(tokenId)
        if authorization.tokenExpired(tokenId):
            self.request.response.setStatus(401)
            self.request.response.write( "Token Expired")
            return

        self.request.response.setHeader( 'X-ZAuth-TokenId', token['id'])
        self.request.response.setHeader( 'X-ZAuth-TokenExpiration', token['expires'])
        self.request.response.setHeader( 'X-ZAuth-TenantId', self.uuid)
        return json.dumps(token)
Example #2
0
    def __init__(self, context):
        super(MetricFacade, self).__init__(context)

        authorization = IAuthorizationTool(self.context)

        auth_token = None
        credentials = None

        global_credentials_dict = authorization.extractGlobalConfCredentials()
        global_credentials = (global_credentials_dict['login'],
                              global_credentials_dict['password'])

        if _isRunningFromUI(context):
            auth_token = context.REQUEST.cookies.get(Z_AUTH_TOKEN, None)
            if not auth_token:
                credentials_dict = authorization.extractCredentials(context.REQUEST)
                login = credentials_dict.get('login', None) or credentials_dict.get('auth0_userid', None)
                passwd = credentials_dict.get('password', None) or credentials_dict.get('auth0_userid', None)
                credentials = (login,
                               passwd)
        else:
            credentials = None

        agent_suffix = 'python'
        if sys.argv[0]:
            agent_suffix = os.path.basename(sys.argv[0].rstrip(".py"))

        self._metrics_connection = MetricConnection(auth_token, credentials,
                                                    global_credentials,
                                                    agent_suffix)
Example #3
0
    def __call__(self, *args, **kwargs):
        """
        Extract login/password credentials, test authentication, and create a token
        """
        # test for uuid
        if self.uuid is None:
            self.request.response.setStatus(503)
            self.request.response.write("System uninitialized - please execute setup wizard")
            transaction.abort()
            return

        authorization = IAuthorizationTool(self.context.context)
        creds = authorization.extractCredentials(self.request)

        # no credentials to test authentication
        if not creds:
            self.request.response.setStatus(401)
            self.request.response.write("Missing Authentication Credentials")
            transaction.abort()
            return

        # test authentication
        if not authorization.authenticateCredentials(creds):
            self.request.response.setStatus(401)
            self.request.response.write("Failed Authentication")
            transaction.abort()
            return

        # create the session data
        token = authorization.createAuthToken(self.request)
        self.request.response.setHeader('X-ZAuth-TokenId', token['id'])
        self.request.response.setHeader('X-ZAuth-TokenExpiration', token['expires'])
        self.request.response.setHeader('X-ZAuth-TenantId', self.uuid)
        return json.dumps(token)
Example #4
0
    def __call__(self, *args, **kwargs):
        """
            extract token id, test token expiration, and return token
        """
        tokenId = self.request.get('id', None)
        if tokenId is None:
            tokenId = self.request.getHeader(ZAUTH_HEADER_ID)

        # missing token id
        if tokenId is None:
            self.request.response.setStatus(401)
            self.request.response.write( "Missing Token Id")
            return

        authorization = IAuthorizationTool( self.context.context)

        #grab token to handle edge case, when expiration happens after expiration test
        tokenId = tokenId.strip('"')
        token = authorization.getToken(tokenId)
        if authorization.tokenExpired(tokenId):
            self.request.response.setStatus(401)
            self.request.response.write( "Token Expired")
            return

        return json.dumps(token)
Example #5
0
    def __call__(self, *args, **kwargs):
        """
        Extract login/password credentials, test authentication, and create a token
        """

        authorization = IAuthorizationTool( self.context.context)

        credentials = authorization.extractCredentials(self.request)

        login = credentials.get('login', None)
        password = credentials.get('password', None)

        # no credentials to test authentication
        if login is None or password is None:
            self.request.response.setStatus(401)
            self.request.response.write( "Missing Authentication Credentials")
            return

        # test authentication
        if not authorization.authenticateCredentials(login, password):
            self.request.response.setStatus(401)
            self.request.response.write( "Failed Authentication")
            return

        # create the session data
        token = authorization.createAuthToken(self.request)

        return json.dumps(token)
Example #6
0
    def __init__(self, context):
        super(MetricFacade, self).__init__(context)

        authorization = IAuthorizationTool(self.context)

        auth_token = None
        credentials = None

        global_credentials_dict = authorization.extractGlobalConfCredentials()
        global_credentials = (global_credentials_dict['login'],
                              global_credentials_dict['password'])

        if _isRunningFromUI(context):
            auth_token = context.REQUEST.cookies.get(Z_AUTH_TOKEN, None)
            if not auth_token:
                credentials_dict = authorization.extractCredentials(
                    context.REQUEST)
                credentials = (credentials_dict['login'],
                               credentials_dict['password'])
        else:
            credentials = None

        agent_suffix = 'python'
        if sys.argv[0]:
            agent_suffix = os.path.basename(sys.argv[0].rstrip(".py"))

        self._metrics_connection = MetricConnection(auth_token, credentials,
                                                    global_credentials,
                                                    agent_suffix)
Example #7
0
 def _setAuthorizationCookie(self):
     authorization = IAuthorizationTool(self.context)
     token = authorization.createAuthToken(self.request)
     self.request.response.setCookie(ZAUTH_COOKIE,
                                     token['id'],
                                     path="/",
                                     secure=True,
                                     http_only=True)
Example #8
0
    def __init__(self, context):
        super(MetricFacade, self).__init__(context)
        self._metric_url = getGlobalConfiguration().get('metric-url', 'http://localhost:8080/')

        self._cookies = cookielib.CookieJar()
        self._authorization = IAuthorizationTool( self.context)
        if _isRunningFromUI( context):
            self._credentials = self._authorization.extractCredentials( context.REQUEST)
        else:
            self._credentials = self._authorization.extractGlobalConfCredentials()
Example #9
0
    def __init__(self, context):
        super(MetricFacade, self).__init__(context)
        self._metric_url = getGlobalConfiguration().get(
            'metric-url', 'http://localhost:8080/')

        self._req_session = requests.Session()
        self._authCookie = {}
        self._authorization = IAuthorizationTool(self.context)
        self._credentials = None
        if _isRunningFromUI(context):
            token = context.REQUEST.cookies.get('ZAuthToken', None)
            if token:
                self._authCookie = {'ZAuthToken': token}
            else:
                self._credentials = self._authorization.extractCredentials(
                    context.REQUEST)
        else:
            self._credentials = self._authorization.extractGlobalConfCredentials(
            )
Example #10
0
    def __call__(self, *args, **kwargs):
        """
        Extract login/password credentials, test authentication, and create a token
        """

        # test for uuid
        if self.uuid is None:
            self.request.response.setStatus(503)
            self.request.response.write(
                "System uninitialized - please execute setup wizard")
            transaction.abort()
            return

        authorization = IAuthorizationTool(self.context.context)
        credentials = authorization.extractCredentials(self.request)

        login = credentials.get('login', None)
        password = credentials.get('password', None)

        # no credentials to test authentication
        if login is None or password is None:
            self.request.response.setStatus(401)
            self.request.response.write("Missing Authentication Credentials")
            transaction.abort()
            return

        # test authentication
        if not authorization.authenticateCredentials(login, password):
            self.request.response.setStatus(401)
            self.request.response.write("Failed Authentication")
            transaction.abort()
            return

        # create the session data
        token = authorization.createAuthToken(self.request)
        self.request.response.setHeader('X-ZAuth-TokenId', token['id'])
        self.request.response.setHeader('X-ZAuth-TokenExpiration',
                                        token['expires'])
        self.request.response.setHeader('X-ZAuth-TenantId', self.uuid)
        return json.dumps(token)
Example #11
0
    def __call__(self, *args, **kwargs):
        """
            extract token id, test token expiration, and return token
        """
        # test for uuid
        if self.uuid is None:
            self.request.response.setStatus(503)
            self.request.response.write(
                "System uninitialized - please execute setup wizard")
            return

        tokenId = self.request.get('id', None)
        if tokenId is None:
            tokenId = self.request.getHeader(ZAUTH_HEADER_ID)

        # missing token id
        if tokenId is None:
            self.request.response.setStatus(401)
            self.request.response.write("Missing Token Id")
            return

        authorization = IAuthorizationTool(self.context.context)

        #grab token to handle edge case, when expiration happens after expiration test
        tokenId = tokenId.strip('"')
        token = authorization.getToken(tokenId)
        if authorization.tokenExpired(tokenId):
            self.request.response.setStatus(401)
            self.request.response.write("Token Expired")
            return

        self.request.response.setHeader('X-ZAuth-TokenId', token['id'])
        self.request.response.setHeader('X-ZAuth-TokenExpiration',
                                        token['expires'])
        self.request.response.setHeader('X-ZAuth-TenantId', self.uuid)
        return json.dumps(token)
Example #12
0
    def handleLogin(self, env, start_response):
        basic = env.get('HTTP_AUTHORIZATION', None)
        if basic is None:
            return self._challenge(start_response)
        response = WSGIResponse()
        request = HTTPRequest(env['wsgi.input'], env, response)
        with self.db as db:
            db.sync()
            authorization = IAuthorizationTool(db.dmd())
            credentials = authorization.extractCredentials(request)

        login = credentials.get('login', None)
        password = credentials.get('password', None)
        # no credentials to test authentication
        if login is None or password is None:
            return self._unauthorized("Missing Authentication Credentials", start_response)

        # test authentication
        if not authorization.authenticateCredentials(login, password):
            return self._unauthorized( "Failed Authentication", start_response)

        # create the session data
        with self.db as db:
            db.sync()
            db.browser_id_manager().REQUEST = request
            tokenId = db.browser_id_manager().getBrowserId(create=1)
        expires = time.time() + 60 * 20
        token = dict(id=tokenId, expires=expires)
        with self.db as db:
            db.sync()
            session = db.session_data()
            if session.get(tokenId) is None:
                session[tokenId] = token
                db.commit()
        start_response('200 OK', [('Content-Type', 'text/html')])
        return json.dumps(token)
 def __init__(self, userAgent):
     self._aggMapping = AGGREGATION_MAPPING
     urlstart = getGlobalConfiguration().get('metric-url',
                                             'http://localhost:8080')
     self._metric_url = '%s/%s' % (urlstart, METRIC_URL_PATH)
     self._metric_url_v2 = '%s/%s' % (urlstart, WILDCARD_URL_PATH)
     creds = IAuthorizationTool(None).extractGlobalConfCredentials()
     auth = base64.b64encode('{login}:{password}'.format(**creds))
     self.agent = CookieAgent(
         Agent(reactor, pool=getPool(), connectTimeout=30), self.cookieJar)
     self._headers = Headers({
         'Authorization': ['basic %s' % auth],
         'content-type': ['application/json'],
         'User-Agent': ['Zenoss: %s' % userAgent]
     })
     self.onMetricsFetched = None
Example #14
0
    def __init__(self, context):
        super(MetricFacade, self).__init__(context)
        self._metric_url = getGlobalConfiguration().get('metric-url', 'http://localhost:8080/')

        self._req_session = requests.Session()
        self._authCookie = {}
        self._authorization = IAuthorizationTool(self.context)
        self._credentials = None
        if _isRunningFromUI( context):
            token = context.REQUEST.cookies.get('ZAuthToken', None)
            if token:
                self._authCookie = {'ZAuthToken': token}
            else:
                self._credentials = self._authorization.extractCredentials( context.REQUEST)
        else:
            self._credentials = self._authorization.extractGlobalConfCredentials()
Example #15
0
    def _setAuthorizationCookie(self):
        session = ISession(self.context.REQUEST)
        authorization = IAuthorizationTool(self.context)
        token = authorization.createAuthToken(self.request)

        self.request.response.setCookie(ZAUTH_COOKIE, token['id'], path="/", secure=session.secure, http_only=True)
Example #16
0
class MetricFacade(ZuulFacade):

    def __init__(self, context):
        super(MetricFacade, self).__init__(context)
        self._metric_url = getGlobalConfiguration().get('metric-url', 'http://localhost:8080/')

        self._cookies = cookielib.CookieJar()
        self._authorization = IAuthorizationTool( self.context)
        if _isRunningFromUI( context):
            self._credentials = self._authorization.extractCredentials( context.REQUEST)
        else:
            self._credentials = self._authorization.extractGlobalConfCredentials()

    def getLastValue(self, context, metric):
        """
        Convenience method for retrieving the last value for a metric on a context. Will return -1 if not found.
        """
        result = self.getValues(context, [metric])
        if result and metric in result:
            return result[metric]
        return -1

    def getMultiValues(self, contexts, metrics, start=None, end=None, returnSet="LAST"):
        """
        Use this method when you need one or more metrics on multiple contexts.

        Returns all the values for the given contexts and the given metrics over the date range specified by start to end
        @param contexts: array of either uids or model objects
        @param metrics: name of metrics (datapoints).
        @param start: defaults to now - dmd.defaultDateRange can be either a timestamp or a string in DATE_FORMAT format
        @param end: defaults to now, can be either a timestamp or a string in DATE_FORMAT format
        @param returnSet: default "LAST" (which returns the last value) the other options are ALL which returns everthing, and EXACT which returns what is in the date range
        If the returnSet is EXACT or ALL, then you are returned metrics in this form:
        {
            # context UUID
            '55d1bbf8-efab-4175-b585-1d748b275b2a': {
                # metric id, is a list of timestamp and values
                'sysUpTime': [{timestamp=1234567, value=1}, {timestamp=1234568, value=2}]
                'laLoadInt5': [{timestamp=1234567, value=100}, {timestamp=1234568, value=200}]
            }

        }
        If the returnSet is LAST then you get the results of the form
        {
            '55d1bbf8-efab-4175-b585-1d748b275b2a': {
                'sysUpTime': 2
                'laLoadInt5': 4
            }

        }
        """
        results = {}
        data = self._queryServer(contexts, metrics, start=start, end=end, returnSet=returnSet)
        if returnSet == "LAST":
            return data
        # if the returnSet is exact or all then organize the results into something more digestable
        for row in data:
            uuid, metric = row['metric'].split('_', 1)
            if not results.get(uuid):
                results[uuid] = defaultdict(list)
            results[uuid][metric].append(dict(timestamp=row['timestamp'], value=row['value']))
        return results

    def getValues(self, context, metrics, start=None, end=None,
                     format="%.2lf", extraRpn="", cf="avg", returnSet="LAST"):
        """
        Return a dict of key value pairs where metric names are the keys and
        the most recent value in the given time range is the value.

        Note: all dates must be passed in in the format: strftime("%Y/%m/%d-%H:%M:%S-%z") or as an unix timestamp.

        Use this method when you need to get one or more metrics for a single context.

        @param context: One or more model object for which we are fetching metrics for
        @param dataPointIds: array of the ids of datapoints. An example would be: ['sysUpTime']
        @param start: start of the date range we are examining metrics for, defaults to now - context.defaultDateRange (defined in DataRoot.py). Does accept unix timestamps.
        @param end: end time of the date range, defaults to now. Does accept unix timestamps.
        @param format: the format we are returning the data in
        @param extraRpn: an extra rpn expression appended to the datapoint RPN expression
        @param cf: Consolidation functions, valid consolidation functions are avg, min, max, and sum
        @param returnSet: default "LAST" (which returns the last value) the other options are ALL which returns everthing, and EXACT which returns what is in the date range
        @return: Dictionary of [dataPointId: value]
        """
        results = self._queryServer(context, metrics, start=start, end=end, format=format, extraRpn=extraRpn, cf=cf, returnSet=returnSet)
        if len(results.values()):
            return results.values()[0]
        return {}

    def _queryServer(self, contexts, metrics, start=None, end=None,
                     format="%.2lf", extraRpn="", cf="avg", returnSet="LAST"):
        subjects = []
        # make sure we are always dealing with a list
        if not isinstance(contexts, (list, tuple)):
            contexts = [contexts]

        for context in contexts:
            if isinstance(context, basestring):
                subjects.append(self._getObject(context))
            else:
                subjects.append(context)

        # build the metrics section of the query
        datapoints = []
        for ds in metrics:
            # find the first occurrence of a datapoint on a context.
            # in theory it is possible that a passed in metric exists on one context
            # but not another.
            for subject in subjects:
                dp = next((d for d in subject._getRRDDataPointsGen() if ds in d.name()), None)
                if dp is None:
                    continue
                else:
                    # we have found a definition for a datapoint, use it and continue onp
                    for subject in subjects:
                        datapoints.append(self._buildMetric(subject, dp, cf, extraRpn, format))
                    break

        # no valid datapoint names were entered
        if not datapoints:
            return {}

        # check to see if the user entered a unix timestamp
        if isinstance(start, (int, long, float)):
            start = self._formatTime(datetime.fromtimestamp(start))

        if isinstance(end, (int, long, float)):
            end = self._formatTime(datetime.fromtimestamp(end))

        # if no start time or end time specified use the
        # defaultDateRange (which is acquired from the dmd)
        if end is None:
            end = self._formatTime(datetime.today())
        if start is None:
            start = self._formatTime(datetime.today() - timedelta(seconds = self._dmd.defaultDateRange))

        request = self._buildRequest(subjects, datapoints, start, end, returnSet)

        # submit it to the client
        try:
            response = self._post_request( self._uri(METRIC_URL_PATH), request)
            content = response.json()
        except ServiceResponseError, e:
            # there was an error returned by the metric service, log it here
            log.error("Error fetching request: %s \nResponse from the server: %s", request, e.content)
            return {}
        
        if content and content.get('results') is not None and returnSet=="LAST":
           # Output of this request should be something like this:
           # [{u'timestamp': 1376477481, u'metric': u'sysUpTime',
           #   u'value': 2418182400.0, u'tags': {u'device':
           #   u'55d1bbf8-efab-4175-b585-1d748b275b2a', u'uuid':
           #   u'55d1bbf8-efab-4175-b585-1d748b275b2a', u'datasource':
           #   u'sysUpTime'}}]
           #
           results = defaultdict(dict)
           for r in content['results']:
               uuid, metric = r['metric'].split('_', 1)
               results[uuid][metric] = r['value']
           return results
        else:
           return content.get('results')
Example #17
0
 def _setAuthorizationCookie(self):
     authorization = IAuthorizationTool(self.context)
     token = authorization.createAuthToken(self.request)
     self.request.response.setCookie(ZAUTH_COOKIE, token['id'], path="/")
Example #18
0
class MetricFacade(ZuulFacade):
    def __init__(self, context):
        super(MetricFacade, self).__init__(context)
        self._metric_url = getGlobalConfiguration().get(
            'metric-url', 'http://localhost:8080/')

        self._req_session = requests.Session()
        self._authCookie = {}
        self._authorization = IAuthorizationTool(self.context)
        self._credentials = None
        if _isRunningFromUI(context):
            token = context.REQUEST.cookies.get('ZAuthToken', None)
            if token:
                self._authCookie = {'ZAuthToken': token}
            else:
                self._credentials = self._authorization.extractCredentials(
                    context.REQUEST)
        else:
            self._credentials = self._authorization.extractGlobalConfCredentials(
            )

    def getLastValue(self, context, metric):
        """
        Convenience method for retrieving the last value for a metric on a context. Will return -1 if not found.
        """
        result = self.getValues(context, [metric])
        if result and metric in result:
            return result[metric]
        return -1

    def getMultiValues(self,
                       contexts,
                       metrics,
                       start=None,
                       end=None,
                       returnSet="LAST",
                       downsample=None):
        """
        Use this method when you need one or more metrics on multiple contexts.

        Returns all the values for the given contexts and the given metrics over the date range specified by start to end
        @param contexts: array of either uids or model objects
        @param metrics: name of metrics (datapoints).
        @param start: defaults to now - dmd.defaultDateRange can be either a timestamp or a string in DATE_FORMAT format
        @param end: defaults to now, can be either a timestamp or a string in DATE_FORMAT format
        @param returnSet: default "LAST" (which returns the last value) the other options are ALL which returns everthing, and EXACT which returns what is in the date range
        @param downsample: can be either the string of the form 1m-avg or a number which will be assumed to be seconds averaged
        If the returnSet is EXACT or ALL, then you are returned metrics in this form:
        {
            # context UUID
            '55d1bbf8-efab-4175-b585-1d748b275b2a': {
                # metric id, is a list of timestamp and values
                'sysUpTime': [{timestamp=1234567, value=1}, {timestamp=1234568, value=2}]
                'laLoadInt5': [{timestamp=1234567, value=100}, {timestamp=1234568, value=200}]
            }

        }
        If the returnSet is LAST then you get the results of the form
        {
            '55d1bbf8-efab-4175-b585-1d748b275b2a': {
                'sysUpTime': 2
                'laLoadInt5': 4
            }

        }
        """
        results = {}
        data = self.queryServer(contexts,
                                metrics,
                                start=start,
                                end=end,
                                returnSet=returnSet,
                                downsample=downsample)
        if returnSet == "LAST":
            return data
        # if the returnSet is exact or all then organize the results into something more digestable
        for row in data:
            key, metric = row['metric'].split('|', 1)
            if not results.get(key):
                results[key] = defaultdict(list)
            for dp in row.get('datapoints', []):
                if not dp['value'] is None and dp['value'] != u'NaN':
                    results[key][metric].append(
                        dict(timestamp=dp['timestamp'], value=dp['value']))
        return results

    def getValues(self,
                  context,
                  metrics,
                  start=None,
                  end=None,
                  format="%.2lf",
                  extraRpn="",
                  cf="avg",
                  returnSet="LAST",
                  downsample=None):
        """
        Return a dict of key value pairs where metric names are the keys and
        the most recent value in the given time range is the value.

        Note: all dates must be passed in in the format: strftime("%Y/%m/%d-%H:%M:%S-%z") or as an unix timestamp.

        Use this method when you need to get one or more metrics for a single context.

        @param context: One or more model object for which we are fetching metrics for
        @param dataPointIds: array of the ids of datapoints. An example would be: ['sysUpTime']
        @param start: start of the date range we are examining metrics for, defaults to now - context.defaultDateRange (defined in DataRoot.py). Does accept unix timestamps.
        @param end: end time of the date range, defaults to now. Does accept unix timestamps.
        @param format: the format we are returning the data in
        @param extraRpn: an extra rpn expression appended to the datapoint RPN expression
        @param cf: Consolidation functions, valid consolidation functions are avg, min, max, and sum
        @param returnSet: default "LAST" (which returns the last value) the other options are ALL which returns everthing, and EXACT which returns what is in the date range
        @param downsample: can be either the string of the form 1m-avg or a number which will be assumed to be seconds averaged
        @return: Dictionary of [dataPointId: value]
        """
        results = self.queryServer(context,
                                   metrics,
                                   start=start,
                                   end=end,
                                   format=format,
                                   extraRpn=extraRpn,
                                   cf=cf,
                                   returnSet=returnSet,
                                   downsample=downsample)
        if len(results.values()):
            return results.values()[0]
        return {}

    def queryServer(self,
                    contexts,
                    metrics,
                    start=None,
                    end=None,
                    format="%.2lf",
                    extraRpn="",
                    cf="avg",
                    returnSet="LAST",
                    downsample=None):
        subjects = []
        # make sure we are always dealing with a list
        if not isinstance(contexts, (list, tuple)):
            contexts = [contexts]

        for context in contexts:
            if isinstance(context, basestring):
                subjects.append(self._getObject(context))
            else:
                subjects.append(context)

        # build the metrics section of the query
        datapoints = []
        metricnames = {}
        for ds in metrics:
            # find the first occurrence of a datapoint on a context.
            # in theory it is possible that a passed in metric exists on one context
            # but not another.
            for subject in subjects:
                dp = next((d for d in subject._getRRDDataPointsGen()
                           if ds in d.name()), None)
                if dp is None:
                    continue
                else:
                    # we have found a definition for a datapoint, use it and continue onp
                    metricnames[dp.name()] = ds
                    for subject in subjects:
                        datapoints.append(
                            self._buildMetric(subject, dp, cf, extraRpn,
                                              format))
                    break

        # no valid datapoint names were entered
        if not datapoints:
            return {}

        # check to see if the user entered a unix timestamp
        if isinstance(start, (int, long, float)):
            start = self._formatTime(datetime.fromtimestamp(start))

        if isinstance(end, (int, long, float)):
            end = self._formatTime(datetime.fromtimestamp(end))

        # if no start time or end time specified use the
        # defaultDateRange (which is acquired from the dmd)
        if end is None:
            end = self._formatTime(datetime.today())
        if start is None and returnSet != "LAST":
            start = self._formatTime(datetime.today() - timedelta(
                seconds=self._dmd.defaultDateRange))
        elif start is None and returnSet == "LAST":
            start = self._formatTime(datetime.today() -
                                     timedelta(seconds=3600))
        request = self._buildRequest(subjects, datapoints, start, end,
                                     returnSet, downsample)

        # submit it to the client
        try:
            response = self._post_request(self._uri(METRIC_URL_PATH), request)
            content = response.json()
        except ServiceResponseError, e:
            # there was an error returned by the metric service, log it here
            log.error(
                "Error fetching request: %s \nResponse from the server: %s",
                request, e.content)
            return {}
        except ServiceConnectionError, e:
            log.error("Error connecting with request: %s \n%s", request, e)
            return {}