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

# This file is part of Buildbot.  Buildbot is free software: you can 

# redistribute it and/or modify it under the terms of the GNU General Public 

# License as published by the Free Software Foundation, version 2. 

# 

# 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 General Public License for more 

# details. 

# 

# You should have received a copy of the GNU 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. 

# 

# Copyright Buildbot Team Members 

 

# N.B.: don't import anything that might pull in a reactor yet. Some of our 

# subcommands want to load modules that need the gtk reactor. 

import os, sys, re, time 

from twisted.python import usage 

 

def isBuildslaveDir(dir): 

    buildbot_tac = os.path.join(dir, "buildbot.tac") 

    if not os.path.isfile(buildbot_tac): 

        print "no buildbot.tac" 

        return False 

 

    contents = open(buildbot_tac, "r").read() 

    return "Application('buildslave')" in contents 

 

# the create/start/stop commands should all be run as the same user, 

# preferably a separate 'buildbot' account. 

 

# Note that the terms 'options' and 'config' are used intechangeably here - in 

# fact, they are intercanged several times.  Caveat legator. 

 

class Maker: 

    def __init__(self, config): 

        self.config = config 

        self.basedir = config['basedir'] 

        self.force = config.get('force', False) 

        self.quiet = config['quiet'] 

 

    def mkdir(self): 

        if os.path.exists(self.basedir): 

            if not self.quiet: 

                print "updating existing installation" 

            return 

        if not self.quiet: 

            print "mkdir", self.basedir 

        os.mkdir(self.basedir) 

 

    def mkinfo(self): 

        path = os.path.join(self.basedir, "info") 

        if not os.path.exists(path): 

            if not self.quiet: 

                print "mkdir", path 

            os.mkdir(path) 

        created = False 

        admin = os.path.join(path, "admin") 

        if not os.path.exists(admin): 

            if not self.quiet: 

                print "Creating info/admin, you need to edit it appropriately" 

            f = open(admin, "wt") 

            f.write("Your Name Here <admin@youraddress.invalid>\n") 

            f.close() 

            created = True 

        host = os.path.join(path, "host") 

        if not os.path.exists(host): 

            if not self.quiet: 

                print "Creating info/host, you need to edit it appropriately" 

            f = open(host, "wt") 

            f.write("Please put a description of this build host here\n") 

            f.close() 

            created = True 

        access_uri = os.path.join(path, "access_uri") 

        if not os.path.exists(access_uri): 

            if not self.quiet: 

                print "Not creating info/access_uri - add it if you wish" 

        if created and not self.quiet: 

            print "Please edit the files in %s appropriately." % path 

 

    def chdir(self): 

        if not self.quiet: 

            print "chdir", self.basedir 

        os.chdir(self.basedir) 

 

    def makeTAC(self, contents, secret=False): 

        tacfile = "buildbot.tac" 

        if os.path.exists(tacfile): 

            oldcontents = open(tacfile, "rt").read() 

            if oldcontents == contents: 

                if not self.quiet: 

                    print "buildbot.tac already exists and is correct" 

                return 

            if not self.quiet: 

                print "not touching existing buildbot.tac" 

                print "creating buildbot.tac.new instead" 

            tacfile = "buildbot.tac.new" 

        f = open(tacfile, "wt") 

        f.write(contents) 

        f.close() 

        if secret: 

            os.chmod(tacfile, 0600) 

 

slaveTACTemplate = [""" 

import os 

 

from twisted.application import service 

from buildslave.bot import BuildSlave 

 

basedir = r'%(basedir)s' 

rotateLength = %(log-size)s 

maxRotatedFiles = %(log-count)s 

 

# if this is a relocatable tac file, get the directory containing the TAC 

if basedir == '.': 

    import os.path 

    basedir = os.path.abspath(os.path.dirname(__file__)) 

 

# note: this line is matched against to check that this is a buildslave 

# directory; do not edit it. 

application = service.Application('buildslave') 

""", 

""" 

try: 

  from twisted.python.logfile import LogFile 

  from twisted.python.log import ILogObserver, FileLogObserver 

  logfile = LogFile.fromFullPath(os.path.join(basedir, "twistd.log"), rotateLength=rotateLength, 

                                 maxRotatedFiles=maxRotatedFiles) 

  application.setComponent(ILogObserver, FileLogObserver(logfile).emit) 

except ImportError: 

  # probably not yet twisted 8.2.0 and beyond, can't set log yet 

  pass 

""", 

""" 

buildmaster_host = '%(host)s' 

port = %(port)d 

slavename = '%(name)s' 

passwd = '%(passwd)s' 

keepalive = %(keepalive)d 

usepty = %(usepty)d 

umask = %(umask)s 

maxdelay = %(maxdelay)d 

 

s = BuildSlave(buildmaster_host, port, slavename, passwd, basedir, 

               keepalive, usepty, umask=umask, maxdelay=maxdelay) 

s.setServiceParent(application) 

 

"""] 

 

def createSlave(config): 

    m = Maker(config) 

    m.mkdir() 

    m.chdir() 

    if config['relocatable']: 

        config['basedir'] = '.' 

    try: 

        master = config['master'] 

        port = None 

        host, port = re.search(r'^([^:]+)(?:[:](\d+))?', master).groups() 

        if port == None: 

            port = '9989' 

        config['host'] = host 

        config['port'] = int(port) 

    except: 

        print "unparseable master location '%s'" % master 

        print " expecting something more like localhost:8007 or localhost" 

        raise 

 

    if config['no-logrotate']: 

        slaveTAC = "".join([slaveTACTemplate[0]] + slaveTACTemplate[2:]) 

    else: 

        slaveTAC = "".join(slaveTACTemplate) 

    contents = slaveTAC % config 

 

    m.makeTAC(contents, secret=True) 

    m.mkinfo() 

 

    if not m.quiet: 

        print "buildslave configured in %s" % m.basedir 

 

 

 

def stop(config, signame="TERM", wait=False, returnFalseOnNotRunning=False): 

    import signal 

    basedir = config['basedir'] 

    quiet = config['quiet'] 

 

    if not isBuildslaveDir(config['basedir']): 

        print "not a buildslave directory" 

        sys.exit(1) 

 

    os.chdir(basedir) 

    try: 

        f = open("twistd.pid", "rt") 

    except: 

        if returnFalseOnNotRunning: 

            return False 

        if not quiet: print "buildslave not running." 

        sys.exit(0) 

    pid = int(f.read().strip()) 

    signum = getattr(signal, "SIG"+signame) 

    timer = 0 

    try: 

        os.kill(pid, signum) 

    except OSError, e: 

        if e.errno != 3: 

            raise 

 

    if not wait: 

        if not quiet: 

            print "sent SIG%s to process" % signame 

        return 

    time.sleep(0.1) 

    while timer < 10: 

        # poll once per second until twistd.pid goes away, up to 10 seconds 

        try: 

            os.kill(pid, 0) 

        except OSError: 

            if not quiet: 

                print "buildslave process %d is dead" % pid 

            return 

        timer += 1 

        time.sleep(1) 

    if not quiet: 

        print "never saw process go away" 

 

def restart(config): 

    quiet = config['quiet'] 

 

    if not isBuildslaveDir(config['basedir']): 

        print "not a buildslave directory" 

        sys.exit(1) 

 

    from buildslave.scripts.startup import start 

    if not stop(config, wait=True, returnFalseOnNotRunning=True): 

        if not quiet: 

            print "no old buildslave process found to stop" 

    if not quiet: 

        print "now restarting buildslave process.." 

    start(config) 

 

 

class MakerBase(usage.Options): 

    optFlags = [ 

        ['help', 'h', "Display this message"], 

        ["quiet", "q", "Do not emit the commands being run"], 

        ] 

 

    longdesc = """ 

    Operates upon the specified <basedir> (or the current directory, if not 

    specified). 

    """ 

 

    opt_h = usage.Options.opt_help 

 

    def parseArgs(self, *args): 

        if len(args) > 0: 

            self['basedir'] = args[0] 

        else: 

            # Use the current directory if no basedir was specified. 

            self['basedir'] = os.getcwd() 

        if len(args) > 1: 

            raise usage.UsageError("I wasn't expecting so many arguments") 

 

    def postOptions(self): 

        self['basedir'] = os.path.abspath(self['basedir']) 

 

class StartOptions(MakerBase): 

    optFlags = [ 

        ['quiet', 'q', "Don't display startup log messages"], 

        ['nodaemon', None, "Don't daemonize (stay in foreground)"], 

        ] 

    def getSynopsis(self): 

        return "Usage:    buildslave start [<basedir>]" 

 

class StopOptions(MakerBase): 

    def getSynopsis(self): 

        return "Usage:    buildslave stop [<basedir>]" 

 

class RestartOptions(MakerBase): 

    optFlags = [ 

        ['quiet', 'q', "Don't display startup log messages"], 

        ['nodaemon', None, "Don't daemonize (stay in foreground)"], 

        ] 

    def getSynopsis(self): 

        return "Usage:    buildslave restart [<basedir>]" 

 

class UpgradeSlaveOptions(MakerBase): 

    optFlags = [ 

        ] 

    optParameters = [ 

        ] 

 

    def getSynopsis(self): 

        return "Usage:    buildslave upgrade-slave [<basedir>]" 

 

    longdesc = """ 

    This command takes an existing buildslave working directory and 

    upgrades it to the current version. 

    """ 

 

def upgradeSlave(config): 

    basedir = os.path.expanduser(config['basedir']) 

    buildbot_tac = open(os.path.join(basedir, "buildbot.tac")).read() 

    new_buildbot_tac = buildbot_tac.replace( 

        "from buildbot.slave.bot import BuildSlave", 

        "from buildslave.bot import BuildSlave") 

    if new_buildbot_tac != buildbot_tac: 

        open(os.path.join(basedir, "buildbot.tac"), "w").write(new_buildbot_tac) 

        print "buildbot.tac updated" 

    else: 

        print "No changes made" 

 

    return 0 

 

 

class SlaveOptions(MakerBase): 

    optFlags = [ 

        ["force", "f", "Re-use an existing directory"], 

        ["relocatable", "r", 

         "Create a relocatable buildbot.tac"], 

        ["no-logrotate", "n", 

         "Do not permit buildmaster rotate logs by itself"] 

        ] 

    optParameters = [ 

        ["keepalive", "k", 600, 

         "Interval at which keepalives should be sent (in seconds)"], 

        ["usepty", None, 0, 

         "(1 or 0) child processes should be run in a pty (default 0)"], 

        ["umask", None, "None", 

         "controls permissions of generated files. Use --umask=022 to be world-readable"], 

        ["maxdelay", None, 300, 

         "Maximum time between connection attempts"], 

        ["log-size", "s", "10000000", 

         "size at which to rotate twisted log files"], 

        ["log-count", "l", "10", 

         "limit the number of kept old twisted log files (None for unlimited)"], 

        ] 

 

    longdesc = """ 

    This command creates a buildslave working directory and buildbot.tac 

    file. The bot will use the <name> and <passwd> arguments to authenticate 

    itself when connecting to the master. All commands are run in a 

    build-specific subdirectory of <basedir>. <master> is a string of the 

    form 'hostname[:port]', and specifies where the buildmaster can be reached. 

    port defaults to 9989 

 

    The appropriate values for <name>, <passwd>, and <master> should be 

    provided to you by the buildmaster administrator. You must choose <basedir> 

    yourself. 

    """ 

 

    def getSynopsis(self): 

        return "Usage:    buildslave create-slave [options] <basedir> <master> <name> <passwd>" 

 

    def parseArgs(self, *args): 

        if len(args) < 4: 

            raise usage.UsageError("command needs more arguments") 

        basedir, master, name, passwd = args 

        if master[:5] == "http:": 

            raise usage.UsageError("<master> is not a URL - do not use URL") 

        self['basedir'] = basedir 

        self['master'] = master 

        self['name'] = name 

        self['passwd'] = passwd 

 

    def postOptions(self): 

        MakerBase.postOptions(self) 

        self['usepty'] = int(self['usepty']) 

        self['keepalive'] = int(self['keepalive']) 

        self['maxdelay'] = int(self['maxdelay']) 

        if not re.match('^\d+$', self['log-size']): 

            raise usage.UsageError("log-size parameter needs to be an int") 

        if not re.match('^\d+$', self['log-count']) and \ 

                self['log-count'] != 'None': 

            raise usage.UsageError("log-count parameter needs to be an int "+ 

                                   " or None") 

 

class Options(usage.Options): 

    synopsis = "Usage:    buildslave <command> [command options]" 

 

    subCommands = [ 

        # the following are all admin commands 

        ['create-slave', None, SlaveOptions, 

         "Create and populate a directory for a new buildslave"], 

        ['upgrade-slave', None, UpgradeSlaveOptions, 

         "Upgrade an existing buildslave directory for the current version"], 

        ['start', None, StartOptions, "Start a buildslave"], 

        ['stop', None, StopOptions, "Stop a buildslave"], 

        ['restart', None, RestartOptions, 

         "Restart a buildslave"], 

        ] 

 

    def opt_version(self): 

        import buildslave 

        print "Buildslave version: %s" % buildslave.version 

        usage.Options.opt_version(self) 

 

    def opt_verbose(self): 

        from twisted.python import log 

        log.startLogging(sys.stderr) 

 

    def postOptions(self): 

        if not hasattr(self, 'subOptions'): 

            raise usage.UsageError("must specify a command") 

 

 

def run(): 

    config = Options() 

    try: 

        config.parseOptions() 

    except usage.error, e: 

        print "%s:  %s" % (sys.argv[0], e) 

        print 

        c = getattr(config, 'subOptions', config) 

        print str(c) 

        sys.exit(1) 

 

    command = config.subCommand 

    so = config.subOptions 

 

    if command == "create-slave": 

        createSlave(so) 

    elif command == "upgrade-slave": 

        upgradeSlave(so) 

    elif command == "start": 

        if not isBuildslaveDir(so['basedir']): 

            print "not a buildslave directory" 

            sys.exit(1) 

 

        from buildslave.scripts.startup import start 

        start(so) 

    elif command == "stop": 

        stop(so, wait=True) 

    elif command == "restart": 

        restart(so) 

    sys.exit(0)