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

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

#!/usr/bin/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 

# 

# Persistent reference counter. This refcounter can maintain two separate  

# refcounts: one binary (which can have a value of 0 or 1) and one normal. The  

# parameter "binary" specifies which of the two counters to update, while the  

# return value is zero IFF both counters are zero 

# 

# Synchronization must be done at a higher level, by the users of this module 

# 

 

 

import os 

import util 

from lock import Lock 

import errno 

 

class RefCounterException(util.SMException): 

    pass 

 

class RefCounter: 

    """Persistent local-FS file-based reference counter. The 

    operations are get() and put(), and they are atomic.""" 

 

    BASE_DIR = "/var/run/sm/refcount" 

 

    def get(obj, binary, ns = None): 

        """Get (inc ref count) 'obj' in namespace 'ns' (optional).  

        Returns new ref count""" 

        if binary: 

            return RefCounter._adjust(ns, obj, 0, 1) 

        else: 

            return RefCounter._adjust(ns, obj, 1, 0) 

    get = staticmethod(get) 

 

    def put(obj, binary, ns = None): 

        """Put (dec ref count) 'obj' in namespace 'ns' (optional). If ref 

        count was zero already, this operation is a no-op. 

        Returns new ref count""" 

        if binary: 

            return RefCounter._adjust(ns, obj, 0, -1) 

        else: 

            return RefCounter._adjust(ns, obj, -1, 0) 

    put = staticmethod(put) 

 

    def set(obj, count, binaryCount, ns = None): 

        """Set normal & binary counts explicitly to the specified values. 

        Returns new ref count""" 

        (obj, ns) = RefCounter._getSafeNames(obj, ns) 

        assert(count >= 0 and binaryCount >= 0) 

        if binaryCount > 1: 

            raise RefCounterException("Binary count = %d > 1" % binaryCount) 

        RefCounter._set(ns, obj, count, binaryCount) 

    set = staticmethod(set) 

 

    def check(obj, ns = None): 

        """Get the ref count values for 'obj' in namespace 'ns' (optional)""" 

        (obj, ns) = RefCounter._getSafeNames(obj, ns) 

        return RefCounter._get(ns, obj) 

    check = staticmethod(check) 

 

    def checkLocked(obj, ns): 

        """Lock-protected access""" 

        lock = Lock(obj, ns) 

        lock.acquire() 

        try: 

            return RefCounter.check(obj, ns) 

        finally: 

            lock.release() 

    checkLocked = staticmethod(checkLocked) 

 

    def reset(obj, ns = None): 

        """Reset ref counts for 'obj' in namespace 'ns' (optional) to 0.""" 

        RefCounter.resetAll(ns, obj) 

    reset = staticmethod(reset) 

 

    def resetAll(ns = None, obj = None): 

        """Reset ref counts of 'obj' in namespace 'ns' to 0. If obj is not 

        provided, reset all existing objects in 'ns' to 0. If neither obj nor  

        ns are supplied, do this for all namespaces""" 

        if obj: 

            (obj, ns) = RefCounter._getSafeNames(obj, ns) 

        if ns: 

            nsList = [ns] 

        else: 

            if not util.pathexists(RefCounter.BASE_DIR): 

                return 

            try: 

                nsList = os.listdir(RefCounter.BASE_DIR) 

            except OSError: 

                raise RefCounterException("failed to get namespace list") 

        for ns in nsList: 

            RefCounter._reset(ns, obj) 

    resetAll = staticmethod(resetAll) 

 

    def _adjust(ns, obj, delta, binaryDelta): 

        """Add 'delta' to the normal refcount and 'binaryDelta' to the binary 

        refcount of 'obj' in namespace 'ns'.  

        Returns new ref count""" 

115        if binaryDelta > 1 or binaryDelta < -1: 

            raise RefCounterException("Binary delta = %d outside [-1;1]" % \ 

                    binaryDelta) 

        (obj, ns) = RefCounter._getSafeNames(obj, ns) 

        (count, binaryCount) = RefCounter._get(ns, obj) 

 

        newCount = count + delta 

        newBinaryCount = binaryCount + binaryDelta 

        if newCount < 0: 

            util.SMlog("WARNING: decrementing normal refcount of 0") 

            newCount = 0 

        if newBinaryCount < 0: 

            util.SMlog("WARNING: decrementing binary refcount of 0") 

            newBinaryCount = 0 

        if newBinaryCount > 1: 

            newBinaryCount = 1 

        util.SMlog("Refcount for %s:%s (%d, %d) + (%d, %d) => (%d, %d)" % \ 

                (ns, obj, count, binaryCount, delta, binaryDelta, 

                    newCount, newBinaryCount)) 

        RefCounter._set(ns, obj, newCount, newBinaryCount) 

        return newCount + newBinaryCount 

    _adjust = staticmethod(_adjust) 

 

    def _get(ns, obj): 

        """Get the ref count values for 'obj' in namespace 'ns'""" 

        objFile = os.path.join(RefCounter.BASE_DIR, ns, obj) 

        (count, binaryCount) = (0, 0) 

        if util.pathexists(objFile): 

            (count, binaryCount) = RefCounter._readCount(objFile) 

        return (count, binaryCount) 

    _get = staticmethod(_get) 

 

    def _set(ns, obj, count, binaryCount): 

        """Set the ref count values for 'obj' in namespace 'ns'""" 

        util.SMlog("Refcount for %s:%s set => (%d, %db)" % \ 

                (ns, obj, count, binaryCount)) 

        if count == 0 and binaryCount == 0: 

            RefCounter._removeObject(ns, obj) 

        else: 

            objFile = os.path.join(RefCounter.BASE_DIR, ns, obj) 

 

            while not RefCounter._writeCount(objFile, count, binaryCount): 

                RefCounter._createNamespace(ns) 

 

    _set = staticmethod(_set) 

 

    def _getSafeNames(obj, ns): 

        """Get a name that can be used as a file name""" 

        if not ns: 

            ns = obj.split('/')[0] 

            if not ns: 

                ns = "default" 

        for char in ['/', '*', '?', '\\']: 

            obj = obj.replace(char, "_") 

        return (obj, ns) 

    _getSafeNames = staticmethod(_getSafeNames) 

 

    def _createNamespace(ns): 

        nsDir = os.path.join(RefCounter.BASE_DIR, ns) 

        try: 

            os.makedirs(nsDir) 

        except OSError, e: 

            if e.errno != errno.EEXIST: 

                raise RefCounterException("failed to makedirs '%s' (%s)" % \ 

                        (nsDir, e)) 

    _createNamespace = staticmethod(_createNamespace) 

 

    def _removeObject(ns, obj): 

        nsDir = os.path.join(RefCounter.BASE_DIR, ns) 

        objFile = os.path.join(nsDir, obj) 

        if not util.pathexists(objFile): 

            return 

        try: 

            os.unlink(objFile) 

        except OSError: 

            raise RefCounterException("failed to remove '%s'" % objFile) 

 

        try: 

            os.rmdir(nsDir) 

        except OSError, e: 

            namespaceAlreadyCleanedUp = e.errno == errno.ENOENT 

            newObjectAddedToNamespace = e.errno == errno.ENOTEMPTY 

 

200            if namespaceAlreadyCleanedUp or newObjectAddedToNamespace: 

                pass 

            else: 

                raise RefCounterException("failed to remove '%s'" % nsDir) 

    _removeObject = staticmethod(_removeObject) 

 

    def _reset(ns, obj = None): 

        nsDir = os.path.join(RefCounter.BASE_DIR, ns) 

        if not util.pathexists(nsDir): 

            return 

        if obj: 

209            if not util.pathexists(os.path.join(nsDir, obj)): 

                return 

            objList = [obj] 

        else: 

            try: 

                objList = os.listdir(nsDir) 

            except OSError: 

                raise RefCounterException("failed to list '%s'" % ns) 

        for obj in objList: 

            RefCounter._removeObject(ns, obj) 

    _reset = staticmethod(_reset) 

 

    def _readCount(fn): 

        try: 

            f = open(fn, 'r') 

            line = f.readline() 

            nums = line.split() 

            count = int(nums[0]) 

            binaryCount = int(nums[1]) 

            f.close() 

        except IOError: 

            raise RefCounterException("failed to read file '%s'" % fn) 

        return (count, binaryCount) 

    _readCount = staticmethod(_readCount) 

 

    def _writeCount(fn, count, binaryCount): 

        try: 

            f = open(fn, 'w') 

            f.write("%d %d\n" % (count, binaryCount)) 

            f.close() 

            return True 

        except IOError, e: 

            fileNotFound = e.errno == errno.ENOENT 

243            if fileNotFound: 

                return False 

            raise RefCounterException("failed to write '(%d %d)' to '%s': %s" \ 

                    % (count, binaryCount, fn, e)) 

    _writeCount = staticmethod(_writeCount) 

 

 

    def _runTests(): 

        "Unit tests" 

 

        RefCounter.resetAll() 

 

        # A 

        (cnt, bcnt) = RefCounter.check("X", "A") 

256        if cnt != 0 or bcnt != 0: 

            print "Error: check = %d != 0 in the beginning" % cnt 

            return -1 

 

        cnt = RefCounter.get("X", False, "A") 

261        if cnt != 1: 

            print "Error: count = %d != 1 after first get()" % cnt 

            return -1 

        (cnt, bcnt) = RefCounter.check("X", "A") 

265        if cnt != 1: 

            print "Error: check = %d != 1 after first get()" % cnt 

            return -1 

 

        cnt = RefCounter.put("X", False, "A") 

270        if cnt != 0: 

            print "Error: count = %d != 0 after get-put" % cnt 

            return -1 

        (cnt, bcnt) = RefCounter.check("X", "A") 

274        if cnt != 0: 

            print "Error: check = %d != 0 after get-put" % cnt 

            return -1 

 

        cnt = RefCounter.get("X", False, "A") 

279        if cnt != 1: 

            print "Error: count = %d != 1 after get-put-get" % cnt 

            return -1 

 

        cnt = RefCounter.get("X", False, "A") 

284        if cnt != 2: 

            print "Error: count = %d != 2 after second get()" % cnt 

            return -1 

 

        cnt = RefCounter.get("X", False, "A") 

289        if cnt != 3: 

            print "Error: count = %d != 3 after third get()" % cnt 

            return -1 

        (cnt, bcnt) = RefCounter.check("X", "A") 

293        if cnt != 3: 

            print "Error: check = %d != 3 after third get()" % cnt 

            return -1 

 

        cnt = RefCounter.put("Y", False, "A") 

298        if cnt != 0: 

            print "Error: count = %d != 0 after first put()" % cnt 

            return -1 

        (cnt, bcnt) = RefCounter.check("Y", "A") 

302        if cnt != 0: 

            print "Error: check = %d != 0 after first put()" % cnt 

            return -1 

 

        cnt = RefCounter.put("X", False, "A") 

307        if cnt != 2: 

            print "Error: count = %d != 2 after 3get-1put" % cnt 

            return -1 

 

        cnt = RefCounter.put("X", False, "A") 

312        if cnt != 1: 

            print "Error: count = %d != 1 after 3get-2put" % cnt 

            return -1 

 

        cnt = RefCounter.get("X", False, "A") 

317        if cnt != 2: 

            print "Error: count = %d != 2 after 4get-2put" % cnt 

            return -1 

        (cnt, bcnt) = RefCounter.check("X", "A") 

321        if cnt != 2: 

            print "Error: check = %d != 2 after 4get-2put" % cnt 

            return -1 

 

        cnt = RefCounter.put("X", False, "A") 

326        if cnt != 1: 

            print "Error: count = %d != 0 after 4get-3put" % cnt 

            return -1 

 

        cnt = RefCounter.put("X", False, "A") 

331        if cnt != 0: 

            print "Error: count = %d != 0 after 4get-4put" % cnt 

            return -1 

        (cnt, bcnt) = RefCounter.check("X", "A") 

335        if cnt != 0: 

            print "Error: check = %d != 0 after 4get-4put" % cnt 

            return -1 

 

        # B 

        cnt = RefCounter.put("Z", False, "B") 

341        if cnt != 0: 

            print "Error: count = %d != 0 after new put()" % cnt 

            return -1 

 

        cnt = RefCounter.get("Z", False, "B") 

346        if cnt != 1: 

            print "Error: count = %d != 1 after put-get" % cnt 

            return -1 

 

        cnt = RefCounter.put("Z", False, "B") 

351        if cnt != 0: 

            print "Error: count = %d != 0 after put-get-put" % cnt 

            return -1 

        (cnt, bcnt) = RefCounter.check("Z", "B") 

355        if cnt != 0: 

            print "Error: check = %d != 0 after put-get-put" % cnt 

            return -1 

 

        cnt = RefCounter.get("Z", False, "B") 

360        if cnt != 1: 

            print "Error: count = %d != 1 after put-get-put-get" % cnt 

            return -1 

        (cnt, bcnt) = RefCounter.check("Z", "B") 

364        if cnt != 1: 

            print "Error: check = %d != 1 after put-get-put-get" % cnt 

            return -1 

 

        # set 

        (cnt, bcnt) = RefCounter.check("a/b") 

370        if cnt != 0: 

            print "Error: count = %d != 0 initially" % cnt 

            return -1 

        RefCounter.set("a/b", 2, 0) 

        (cnt, bcnt) = RefCounter.check("a/b") 

375        if cnt != 2 or bcnt != 0: 

            print "Error: count = (%d,%d) != (2,0) after set(2,0)" % (cnt, bcnt) 

            return -1 

        cnt = RefCounter.put("a/b", False) 

379        if cnt != 1: 

            print "Error: count = %d != 1 after set(2)-put" % cnt 

            return -1 

        cnt = RefCounter.get("a/b", False) 

383        if cnt != 2: 

            print "Error: count = %d != 2 after set(2)-put-get" % cnt 

            return -1 

        RefCounter.set("a/b", 100, 0) 

        (cnt, bcnt) = RefCounter.check("a/b") 

388        if cnt != 100 or bcnt != 0: 

            print "Error: cnt,bcnt = (%d,%d) != (100,0) after set(100,0)" % \ 

                    (cnt, bcnt) 

            return -1 

        cnt = RefCounter.get("a/b", False) 

393        if cnt != 101: 

            print "Error: count = %d != 101 after get" % cnt 

            return -1 

        RefCounter.set("a/b", 100, 1) 

        (cnt, bcnt) = RefCounter.check("a/b") 

398        if cnt != 100 or bcnt != 1: 

            print "Error: cnt,bcnt = (%d,%d) != (100,1) after set(100,1)" % \ 

                    (cnt, bcnt) 

            return -1 

        RefCounter.reset("a/b") 

        (cnt, bcnt) = RefCounter.check("a/b") 

404        if cnt != 0: 

            print "Error: check = %d != 0 after reset" % cnt 

            return -1 

 

        # binary 

        cnt = RefCounter.get("A", True) 

410        if cnt != 1: 

            print "Error: count = %d != 1 after get(bin)" % cnt 

            return -1 

        cnt = RefCounter.get("A", True) 

414        if cnt != 1: 

            print "Error: count = %d != 1 after get(bin)*2" % cnt 

            return -1 

        cnt = RefCounter.put("A", True) 

418        if cnt != 0: 

            print "Error: count = %d != 0 after get(bin)*2-put(bin)" % cnt 

            return -1 

        cnt = RefCounter.put("A", True) 

422        if cnt != 0: 

            print "Error: count = %d != 0 after get(bin)*2-put(bin)*2" % cnt 

            return -1 

        try: 

            RefCounter.set("A", 0, 2) 

            print "Error: set(0,2) was allowed" 

            return -1 

        except RefCounterException: 

            pass 

        cnt = RefCounter.get("A", True) 

432        if cnt != 1: 

            print "Error: count = %d != 1 after get(bin)" % cnt 

            return -1 

        cnt = RefCounter.get("A", False) 

436        if cnt != 2: 

            print "Error: count = %d != 2 after get(bin)-get" % cnt 

            return -1 

        cnt = RefCounter.get("A", False) 

440        if cnt != 3: 

            print "Error: count = %d != 3 after get(bin)-get-get" % cnt 

            return -1 

        cnt = RefCounter.get("A", True) 

444        if cnt != 3: 

            print "Error: count = %d != 3 after get(bin)-get*2-get(bin)" % cnt 

            return -1 

        cnt = RefCounter.put("A", False) 

448        if cnt != 2: 

            print "Error: count = %d != 2 after get(bin)*2-get*2-put" % cnt 

            return -1 

        cnt = RefCounter.put("A", True) 

452        if cnt != 1: 

            print "Error: cnt = %d != 1 after get(b)*2-get*2-put-put(b)" % cnt 

            return -1 

        cnt = RefCounter.put("A", False) 

456        if cnt != 0: 

            print "Error: cnt = %d != 0 after get(b)*2-get*2-put*2-put(b)" % cnt 

            return -1 

 

        # names 

        cnt = RefCounter.get("Z", False) 

462        if cnt != 1: 

            print "Error: count = %d != 1 after get (no ns 1)" % cnt 

            return -1 

 

        cnt = RefCounter.get("Z/", False) 

467        if cnt != 1: 

            print "Error: count = %d != 1 after get (no ns 2)" % cnt 

            return -1 

 

        cnt = RefCounter.get("/Z", False) 

472        if cnt != 1: 

            print "Error: count = %d != 1 after get (no ns 3)" % cnt 

            return -1 

 

        cnt = RefCounter.get("/Z/*/?/\\", False) 

477        if cnt != 1: 

            print "Error: count = %d != 1 after get (no ns 4)" % cnt 

            return -1 

 

        cnt = RefCounter.get("Z", False) 

482        if cnt != 2: 

            print "Error: count = %d != 2 after get (no ns 1)" % cnt 

            return -1 

 

        cnt = RefCounter.get("Z/", False) 

487        if cnt != 2: 

            print "Error: count = %d != 2 after get (no ns 2)" % cnt 

            return -1 

 

        cnt = RefCounter.get("/Z", False) 

492        if cnt != 2: 

            print "Error: count = %d != 2 after get (no ns 3)" % cnt 

            return -1 

 

        cnt = RefCounter.get("/Z/*/?/\\", False) 

497        if cnt != 2: 

            print "Error: count = %d != 2 after get (no ns 4)" % cnt 

            return -1 

 

        # resetAll 

        RefCounter.resetAll("B") 

        cnt = RefCounter.get("Z", False, "B") 

504        if cnt != 1: 

            print "Error: count = %d != 1 after resetAll-get" % cnt 

            return -1 

 

        cnt = RefCounter.get("Z", False, "C") 

509        if cnt != 1: 

            print "Error: count = %d != 1 after C.get" % cnt 

            return -1 

 

        RefCounter.resetAll("B") 

        cnt = RefCounter.get("Z", False, "B") 

515        if cnt != 1: 

            print "Error: count = %d != 1 after second resetAll-get" % cnt 

            return -1 

 

        cnt = RefCounter.get("Z", False, "C") 

520        if cnt != 2: 

            print "Error: count = %d != 2 after second C.get" % cnt 

            return -1 

 

        RefCounter.resetAll("D") 

        RefCounter.resetAll() 

        cnt = RefCounter.put("Z", False, "B") 

527        if cnt != 0: 

            print "Error: count = %d != 0 after resetAll-put" % cnt 

            return -1 

 

        cnt = RefCounter.put("Z", False, "C") 

532        if cnt != 0: 

            print "Error: count = %d != 0 after C.resetAll-put" % cnt 

            return -1 

 

        RefCounter.resetAll() 

 

        return 0 

    _runTests = staticmethod(_runTests) 

 

 

542if __name__ == '__main__': 

    print "Running unit tests..." 

    try: 

        if RefCounter._runTests() == 0: 

            print "All done, no errors" 

    except RefCounterException, e: 

        print "FAIL: Got exception: %s" % e 

        raise