'Record the metering data in batch.
:param samples: a list of samples dict.'

def record_metering_data_batch(self, samples):

    samples = copy.deepcopy(samples)
    for sample in samples:
        sample.pop('monotonic_time', None)
    sorted_samples = sorted(copy.deepcopy(samples), key=(lambda s: (s['resource_id'], s['timestamp'])))
    res_grouped_samples = itertools.groupby(sorted_samples, key=operator.itemgetter('resource_id'))
    samples_to_update_resource = []
    for (resource_id, g_samples) in res_grouped_samples:
        g_samples = list(g_samples)
        g_samples[(-1)]['meter'] = [{'counter_name': s['counter_name'], 'counter_type': s['counter_type'], 'counter_unit': s['counter_unit']} for s in g_samples]
        g_samples[(-1)]['last_sample_timestamp'] = g_samples[(-1)]['timestamp']
        g_samples[(-1)]['first_sample_timestamp'] = g_samples[0]['timestamp']
        samples_to_update_resource.append(g_samples[(-1)])
    for sample in samples_to_update_resource:
        sample['resource_metadata'] = pymongo_utils.improve_keys(sample.pop('resource_metadata'))
        resource = self.db.resource.find_one_and_update({'_id': sample['resource_id']}, {'$set': {'project_id': sample['project_id'], 'user_id': sample['user_id'], 'source': sample['source']}, '$setOnInsert': {'metadata': sample['resource_metadata'], 'first_sample_timestamp': sample['timestamp'], 'last_sample_timestamp': sample['timestamp']}, '$addToSet': {'meter': {'$each': sample['meter']}}}, upsert=True, return_document=pymongo.ReturnDocument.AFTER)
        last_sample_timestamp = resource.get('last_sample_timestamp')
        if ((last_sample_timestamp is None) or (last_sample_timestamp <= sample['last_sample_timestamp'])):
            self.db.resource.update_one({'_id': sample['resource_id']}, {'$set': {'metadata': sample['resource_metadata'], 'last_sample_timestamp': sample['last_sample_timestamp']}})
        first_sample_timestamp = resource.get('first_sample_timestamp')
        if ((first_sample_timestamp is not None) and (first_sample_timestamp > sample['first_sample_timestamp'])):
            self.db.resource.update_one({'_id': sample['resource_id']}, {'$set': {'first_sample_timestamp': sample['first_sample_timestamp']}})
    record = copy.deepcopy(samples)
    for s in record:
        s['recorded_at'] = timeutils.utcnow()
        s['resource_metadata'] = pymongo_utils.improve_keys(s.pop('resource_metadata'))
    self.db.meter.insert_many(record)
