Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

#!/usr/bin/env python 

# 

# Copyright (C) Citrix Systems Inc. 

# 

# This program is free software; you can redistribute it and/or modify  

# it under the terms of the GNU Lesser General Public License as published  

# by the Free Software Foundation; version 2.1 only. 

# 

# This program is distributed in the hope that it will be useful,  

# but WITHOUT ANY WARRANTY; without even the implied warranty of  

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  

# GNU Lesser General Public License for more details. 

# 

# You should have received a copy of the GNU Lesser General Public License 

# along with this program; if not, write to the Free Software Foundation, Inc., 

# 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA 

 

import os 

import blktap2 

import glob 

import SR 

from stat import * # S_ISBLK(), ... 

 

SECTOR_SHIFT = 9 

 

class CachingTap(object): 

 

    def __init__(self, tapdisk, stats): 

        self.tapdisk = tapdisk 

        self.stats   = stats 

 

    @classmethod 

    def from_tapdisk(cls, tapdisk, stats): 

 

        # pick the last image. if it's a VHD, we got a parent 

        # cache. the leaf case is an aio node sitting on a 

        # parent-caching tapdev. always checking the complementary 

        # case, so we bail on unexpected chains. 

 

        images = stats['images'] 

        image  = images[-1] 

        path   = image['name'] 

        _type  = image['driver']['name'] 

 

        def __assert(cond): 

            if not cond: 

                raise cls.NotACachingTapdisk(tapdisk, stats) 

 

        if _type == 'vhd': 

            # parent 

 

            return ParentCachingTap(tapdisk, stats) 

 

        elif _type == 'aio': 

            # leaf 

            st = os.stat(path) 

 

            __assert(S_ISBLK(st.st_mode)) 

 

            major = os.major(st.st_rdev) 

            minor = os.minor(st.st_rdev) 

 

            __assert(major == tapdisk.major()) 

 

            return LeafCachingTap(tapdisk, stats, minor) 

 

        __assert(0) 

 

    class NotACachingTapdisk(Exception): 

 

        def __init__(self, tapdisk, stats): 

            self.tapdisk = tapdisk 

            self.stats   = stats 

 

        def __str__(self): 

            return \ 

                "Tapdisk %s in state '%s' not found caching." % \ 

                (self.tapdisk, self.stats) 

 

class ParentCachingTap(CachingTap): 

 

    def __init__(self, tapdisk, stats): 

        CachingTap.__init__(self, tapdisk, stats) 

        self.leaves = [] 

 

    def add_leaves(self, tapdisks): 

        for t in tapdisks: 

            if t.is_child_of(self): 

                self.leaves.append(t) 

 

    def vdi_stats(self): 

        """Parent caching hits/miss count.""" 

 

        images = self.stats['images'] 

        total  = self.stats['secs'][0] 

 

        rd_Gc = images[0]['hits'][0] 

        rd_lc = images[1]['hits'][0] 

 

        rd_hits = rd_Gc 

        rd_miss = total - rd_hits 

 

        return (rd_hits, rd_miss) 

 

    def vdi_stats_total(self): 

        """VDI total stats, including leaf hits/miss counts.""" 

 

        rd_hits, rd_miss = self.vdi_stats() 

        wr_rdir = 0 

 

        for leaf in self.leaves: 

            l_rd_hits, l_rd_miss, l_wr_rdir = leaf.vdi_stats() 

            rd_hits += l_rd_hits 

            rd_miss += l_rd_miss 

            wr_rdir += l_wr_rdir 

 

        return rd_hits, rd_miss, wr_rdir 

 

    def __str__(self): 

        return "%s(%s, minor=%s)" % \ 

            (self.__class__.__name__, 

             self.tapdisk.path, self.tapdisk.minor) 

 

class LeafCachingTap(CachingTap): 

 

    def __init__(self, tapdisk, stats, parent_minor): 

        CachingTap.__init__(self, tapdisk, stats) 

        self.parent_minor = parent_minor 

 

    def is_child_of(self, parent): 

        return parent.tapdisk.minor == self.parent_minor 

 

    def vdi_stats(self): 

        images = self.stats['images'] 

        total  = self.stats['secs'][0] 

 

        rd_Ac = images[0]['hits'][0] 

        rd_A  = images[1]['hits'][0] 

 

        rd_hits  = rd_Ac 

        rd_miss  = rd_A 

        wr_rdir = self.stats['FIXME_enospc_redirect_count'] 

 

        return rd_hits, rd_miss, wr_rdir 

 

    def __str__(self): 

        return "%s(%s, minor=%s)" % \ 

            (self.__class__.__name__, 

             self.tapdisk.path, self.tapdisk.minor) 

 

class CacheFileSR(object): 

 

    CACHE_NODE_EXT = '.vhdcache' 

 

    def __init__(self, sr_path): 

        self.sr_path = sr_path 

 

    def is_mounted(self): 

        # NB. a basic check should do, currently only for CLI usage. 

        return os.path.exists(self.sr_path) 

 

    class NotAMountPoint(Exception): 

 

        def __init__(self, path): 

            self.path = path 

 

        def __str__(self): 

            return "Not a mount point: %s" % self.path 

 

    @classmethod 

    def from_uuid(cls, sr_uuid): 

        import SR 

        sr_path = "%s/%s" % (SR.MOUNT_BASE, sr_uuid) 

 

        cache_sr = cls(sr_path) 

 

        if not cache_sr.is_mounted(): 

            raise cls.NotAMountPoint(sr_path) 

 

        return cache_sr 

 

    @classmethod 

    def from_session(cls, session): 

        import util 

        import SR as sm 

 

        host_ref = util.get_localhost_uuid(session) 

 

        _host = session.xenapi.host 

        sr_ref = _host.get_local_cache_sr(host_ref) 

        if not sr_ref: 

            raise util.SMException("Local cache SR not specified") 

 

        if sr_ref == 'OpaqueRef:NULL': 

            raise util.SMException("Local caching not enabled.") 

 

        _SR = session.xenapi.SR 

        sr_uuid = _SR.get_uuid(sr_ref) 

 

        target = sm.SR.from_uuid(session, sr_uuid) 

 

        return cls(target.path) 

 

    @classmethod 

    def from_cli(cls): 

        import XenAPI 

 

        session = XenAPI.xapi_local() 

        session.xenapi.login_with_password('root', '', '', 'SM') 

 

        return cls.from_session(session) 

 

    def statvfs(self): 

        return os.statvfs(self.sr_path) 

 

    def _fast_find_nodes(self): 

        pattern = "%s/*%s" % (self.sr_path, self.CACHE_NODE_EXT) 

 

        found = glob.glob(pattern) 

 

        return list(found) 

 

    def xapi_vfs_stats(self): 

        import util 

 

        f =  self.statvfs() 

        if not f.f_frsize: 

            raise util.SMException("Cache FS does not report utilization.") 

 

        fs_size = f.f_frsize * f.f_blocks 

        fs_free = f.f_frsize * f.f_bfree 

 

        fs_cache_total = 0 

        for path in self._fast_find_nodes(): 

            st = os.stat(path) 

            fs_cache_total += st.st_size 

 

        return { 

            'FREE_CACHE_SPACE_AVAILABLE': 

                fs_free, 

            'TOTAL_CACHE_UTILISATION': 

                fs_cache_total, 

            'TOTAL_UTILISATION_BY_NON_CACHE_DATA': 

                fs_size - fs_free - fs_cache_total 

            } 

 

    @classmethod 

    def _fast_find_tapdisks(cls): 

        import errno 

 

        # NB. we're only about to gather stats here, so take the 

        # fastpath, bypassing agent based VBD[currently-attached] -> 

        # VDI[allow-caching] -> Tap resolution altogether. Instead, we 

        # list all tapdisk and match by path suffix. 

 

        tapdisks = [] 

 

        for tapdisk in blktap2.Tapdisk.list(): 

            try: 

                ext = os.path.splitext(tapdisk.path)[1] 

            except: 

                continue 

 

            if ext != cls.CACHE_NODE_EXT: continue 

 

            try: 

                stats = tapdisk.stats() 

            except blktap2.TapCtl.CommandFailure, e: 

                if e.errno != errno.ENOENT: raise 

                continue # shut down 

 

            caching = CachingTap.from_tapdisk(tapdisk, stats) 

            tapdisks.append(caching) 

 

        return tapdisks 

 

    def fast_scan_topology(self): 

 

        # NB. gather all tapdisks. figure out which ones are leaves 

        # and which ones cache parents. 

 

        parents = [] 

        leaves  = [] 

 

        for caching in self._fast_find_tapdisks(): 

            if type(caching) == ParentCachingTap: 

                parents.append(caching) 

            else: 

                leaves.append(caching) 

 

        for parent in parents: 

            parent.add_leaves(leaves) 

 

        return parents 

 

    def vdi_stats_total(self): 

 

        parents = self.fast_scan_topology() 

 

        rd_hits, rd_miss, wr_rdir = 0, 0, 0 

 

        for parent in parents: 

            p_rd_hits, p_rd_miss, p_wr_rdir = parent.vdi_stats_total() 

            rd_hits += p_rd_hits 

            rd_miss += p_rd_miss 

            wr_rdir += p_wr_rdir 

 

        return rd_hits, rd_miss, wr_rdir 

 

    def xapi_vdi_stats(self): 

        rd_hits, rd_miss, wr_rdir = self.vdi_stats_total() 

 

        return { 

            'TOTAL_CACHE_HITS': 

                rd_hits << SECTOR_SHIFT, 

            'TOTAL_CACHE_MISSES': 

                rd_miss << SECTOR_SHIFT, 

            'TOTAL_CACHE_ENOSPACE_REDIRECTS': 

                wr_rdir << SECTOR_SHIFT, 

            } 

 

    def xapi_stats(self): 

 

        vfs = self.xapi_vfs_stats() 

        vdi = self.xapi_vdi_stats() 

 

        vfs.update(vdi) 

        return vfs 

 

CacheSR = CacheFileSR 

 

if __name__ == '__main__': 

 

    import sys 

    from pprint import pprint 

 

    args = list(sys.argv) 

    prog = args.pop(0) 

    prog = os.path.basename(prog) 

 

    def usage(stream): 

        if prog == 'tapdisk-cache-stats': 

            print >>stream, \ 

                "usage: tapdisk-cache-stats [<sr-uuid>]" 

        else: 

            print >>stream, \ 

                "usage: %s sr.{stats|topology} [<sr-uuid>]" % prog 

 

    def usage_error(): 

        usage(sys.stderr) 

        sys.exit(1) 

 

    if prog == 'tapdisk-cache-stats': 

        cmd = 'sr.stats' 

    else: 

        try: 

            cmd = args.pop(0) 

        except IndexError: 

            usage_error() 

 

    try: 

        _class, method = cmd.split('.') 

    except: 

        usage(sys.stderr) 

        sys.exit(1) 

 

    if _class == 'sr': 

        try: 

            uuid = args.pop(0) 

        except IndexError: 

            cache_sr = CacheSR.from_cli() 

        else: 

            cache_sr = CacheSR.from_uuid(uuid) 

 

        if method == 'stats': 

 

            d = cache_sr.xapi_stats() 

            for item in d.iteritems(): 

                print "%s=%s" % item 

 

        elif method == 'topology': 

            parents = cache_sr.fast_scan_topology() 

 

            for parent in parents: 

                print parent, "hits/miss=%s total=%s" % \ 

                    (parent.vdi_stats(), parent.vdi_stats_total()) 

                pprint(parent.stats) 

 

                for leaf in parent.leaves: 

                    print leaf, "hits/miss=%s" % str(leaf.vdi_stats()) 

                    pprint(leaf.stats) 

 

            print "sr.total=%s" % str(cache_sr.vdi_stats_total()) 

 

        else: 

            usage_error() 

    else: 

        usage_error()