~peter-sabaini/charm-helpers/bcache-helpers

« back to all changes in this revision

Viewing changes to charmhelpers/contrib/storage/linux/bcache.py

  • Committer: Peter Sabaini
  • Date: 2017-05-04 15:34:09 UTC
  • Revision ID: peter.sabaini@canonical.com-20170504153409-v3tayraiwa4bny82
Add bcache support module

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright 2017 Canonical Limited.
 
2
#
 
3
# Licensed under the Apache License, Version 2.0 (the "License");
 
4
# you may not use this file except in compliance with the License.
 
5
# You may obtain a copy of the License at
 
6
#
 
7
#  http://www.apache.org/licenses/LICENSE-2.0
 
8
#
 
9
# Unless required by applicable law or agreed to in writing, software
 
10
# distributed under the License is distributed on an "AS IS" BASIS,
 
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
12
# See the License for the specific language governing permissions and
 
13
# limitations under the License.
 
14
import os
 
15
import json
 
16
 
 
17
from charmhelpers.core.hookenv import log
 
18
 
 
19
stats_intervals = ['stats_day', 'stats_five_minute',
 
20
                   'stats_hour', 'stats_total']
 
21
 
 
22
SYSFS = '/sys'
 
23
 
 
24
 
 
25
class Bcache(object):
 
26
    """Bcache behaviour
 
27
    """
 
28
 
 
29
    def __init__(self, cachepath):
 
30
        self.cachepath = cachepath
 
31
 
 
32
    @classmethod
 
33
    def fromdevice(cls, devname):
 
34
        return cls('{}/block/{}/bcache'.format(SYSFS, devname))
 
35
 
 
36
    def __str__(self):
 
37
        return self.cachepath
 
38
 
 
39
    def get_stats(self, interval):
 
40
        """Get cache stats
 
41
        """
 
42
        intervaldir = 'stats_{}'.format(interval)
 
43
        path = "{}/{}".format(self.cachepath, intervaldir)
 
44
        out = dict()
 
45
        for elem in os.listdir(path):
 
46
            out[elem] = open('{}/{}'.format(path, elem)).read().strip()
 
47
        return out
 
48
 
 
49
 
 
50
def get_bcache_fs():
 
51
    """Return all cache sets
 
52
    """
 
53
    cachesetroot = "{}/fs/bcache".format(SYSFS)
 
54
    try:
 
55
        dirs = os.listdir(cachesetroot)
 
56
    except OSError:
 
57
        log("No bcache fs found")
 
58
        return []
 
59
    cacheset = set([Bcache('{}/{}'.format(cachesetroot, d)) for d in dirs if not d.startswith('register')])
 
60
    return cacheset
 
61
 
 
62
 
 
63
def get_stats_action(cachespec, interval):
 
64
    """Action for getting bcache statistics
 
65
    """
 
66
    if cachespec == 'global':
 
67
        caches = get_bcache_fs()
 
68
    else:
 
69
        caches = [Bcache.fromdevice(cachespec)]
 
70
    res = dict((c.cachepath, c.get_stats(interval)) for c in caches)
 
71
    return json.dumps(res, indent=4, separators=(',', ': '))