Hide keyboard shortcuts

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

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

# coding: utf-8 

# Copyright (c) Pymatgen Development Team. 

# Distributed under the terms of the MIT License. 

"""Tools for the submission of Tasks.""" 

from __future__ import unicode_literals, division, print_function 

 

import os 

import time 

import yaml 

import pickle 

 

from collections import deque 

from datetime import timedelta 

from six.moves import cStringIO 

from monty.io import get_open_fds 

from monty.string import boxed, is_string 

from monty.os.path import which 

from monty.collections import AttrDict, dict2namedtuple 

from .utils import as_bool, File, Directory 

from . import qutils as qu 

from pymatgen.util.io_utils import ask_yesno 

 

try: 

import apscheduler 

has_sched_v3 = apscheduler.version >= "3.0.0" 

except ImportError: 

pass 

 

import logging 

logger = logging.getLogger(__name__) 

 

__all__ = [ 

"ScriptEditor", 

"PyLauncher", 

"PyFlowScheduler", 

] 

 

 

def straceback(): 

"""Returns a string with the traceback.""" 

import traceback 

return traceback.format_exc() 

 

class ScriptEditor(object): 

"""Simple editor that simplifies the writing of shell scripts""" 

_shell = '/bin/bash' 

 

def __init__(self): 

self._lines = [] 

 

@property 

def shell(self): 

return self._shell 

 

def _add(self, text, pre=""): 

if is_string(text): 

self._lines.append(pre + text) 

else: 

self._lines.extend([pre + t for t in text]) 

 

def reset(self): 

"""Reset the editor.""" 

try: 

del self._lines 

except AttributeError: 

pass 

 

def shebang(self): 

"""Adds the shebang line.""" 

self._lines.append('#!' + self.shell) 

 

def declare_var(self, key, val): 

"""Declare a env variable. If val is None the variable is unset.""" 

if val is not None: 

line = "export " + key + '=' + str(val) 

else: 

line = "unset " + key 

 

self._add(line) 

 

def declare_vars(self, d): 

"""Declare the variables defined in the dictionary d.""" 

for k, v in d.items(): 

self.declare_var(k, v) 

 

def export_envar(self, key, val): 

"""Export an environment variable.""" 

line = "export " + key + "=" + str(val) 

self._add(line) 

 

def export_envars(self, env): 

"""Export the environment variables contained in the dict env.""" 

for k, v in env.items(): 

self.export_envar(k, v) 

 

def add_emptyline(self): 

"""Add an empty line.""" 

self._add("", pre="") 

 

def add_comment(self, comment): 

"""Add a comment""" 

self._add(comment, pre="# ") 

 

def load_modules(self, modules): 

"""Load the list of specified modules.""" 

for module in modules: 

self.load_module(module) 

 

def load_module(self, module): 

self._add('module load ' + module) 

 

def add_line(self, line): 

self._add(line) 

 

def add_lines(self, lines): 

self._add(lines) 

 

def get_script_str(self, reset=True): 

"""Returns a string with the script and reset the editor if reset is True""" 

s = "\n".join(l for l in self._lines) 

if reset: 

self.reset() 

return s 

 

 

class PyLauncherError(Exception): 

"""Error class for PyLauncher.""" 

 

 

class PyLauncher(object): 

"""This object handle the submission of the tasks contained in a :class:`Flow`""" 

Error = PyLauncherError 

 

def __init__(self, flow, **kwargs): 

""" 

Initialize the object 

 

Args: 

flow: :class:`Flow` object 

max_njobs_inqueue: The launcher will stop submitting jobs when the 

number of jobs in the queue is >= Max number of jobs 

""" 

self.flow = flow 

self.max_njobs_inqueue = kwargs.get("max_njobs_inqueue", 200) 

 

#self.flow.check_pid_file() 

 

def single_shot(self): 

""" 

Run the first :class:`Task` than is ready for execution. 

 

Returns: 

Number of jobs launched. 

""" 

num_launched = 0 

 

# Get the tasks that can be executed in each workflow. 

tasks = [] 

for work in self.flow: 

try: 

task = work.fetch_task_to_run() 

 

if task is not None: 

tasks.append(task) 

else: 

# No task found, this usually happens when we have dependencies. 

# Beware of possible deadlocks here! 

logger.debug("No task to run! Possible deadlock") 

 

except StopIteration: 

logger.info("All tasks completed.") 

 

# Submit the tasks and update the database. 

if tasks: 

tasks[0].start() 

num_launched += 1 

 

self.flow.pickle_dump() 

 

return num_launched 

 

def rapidfire(self, max_nlaunch=-1, max_loops=1, sleep_time=5): 

""" 

Keeps submitting `Tasks` until we are out of jobs or no job is ready to run. 

 

Args: 

max_nlaunch: Maximum number of launches. default: no limit. 

max_loops: Maximum number of loops 

sleep_time: seconds to sleep between rapidfire loop iterations 

 

Returns: 

The number of tasks launched. 

""" 

num_launched, do_exit, launched = 0, False, [] 

 

for count in range(max_loops): 

if do_exit: 

break 

if count > 0: 

time.sleep(sleep_time) 

 

tasks = self.fetch_tasks_to_run() 

 

# I don't know why but we receive duplicated tasks. 

if any(task in launched for task in tasks): 

logger.critical("numtasks %d already in launched list:\n%s" % (len(task), launched)) 

 

# Preventive test. 

tasks = [t for t in tasks if t not in launched] 

 

if not tasks: 

continue 

 

for task in tasks: 

fired = task.start() 

if fired: 

launched.append(task) 

num_launched += 1 

 

if num_launched >= max_nlaunch > 0: 

logger.info('num_launched >= max_nlaunch, going back to sleep') 

do_exit = True 

break 

 

# Update the database. 

self.flow.pickle_dump() 

 

return num_launched 

 

def fetch_tasks_to_run(self): 

""" 

Return the list of tasks that can be submitted. 

Empty list if no task has been found. 

""" 

tasks_to_run = [] 

 

for work in self.flow: 

tasks_to_run.extend(work.fetch_alltasks_to_run()) 

 

return tasks_to_run 

 

 

class PyFlowSchedulerError(Exception): 

"""Exceptions raised by `PyFlowScheduler`.""" 

 

 

class PyFlowScheduler(object): 

""" 

This object schedules the submission of the tasks in an :class:`Flow`. 

There are two types of errors that might occur during the execution of the jobs: 

 

#. Python exceptions 

#. Abinit Errors. 

 

Python exceptions are easy to detect and are usually due to a bug in abinitio or random errors such as IOError. 

The set of Abinit Errors is much much broader. It includes wrong input data, segmentation 

faults, problems with the resource manager, etc. Abinitio tries to handle the most common cases 

but there's still a lot of room for improvement. 

Note, in particular, that `PyFlowScheduler` will shutdown automatically if 

 

#. The number of python exceptions is > MAX_NUM_PYEXC 

 

#. The number of Abinit Errors (i.e. the number of tasks whose status is S_ERROR) is > MAX_NUM_ERRORS 

 

#. The number of jobs launched becomes greater than (`safety_ratio` * total_number_of_tasks). 

 

#. The scheduler will send an email to the user (specified by `mailto`) every `remindme_s` seconds. 

If the mail cannot be sent, it will shutdown automatically. 

This check prevents the scheduler from being trapped in an infinite loop. 

""" 

# Configuration file. 

YAML_FILE = "scheduler.yml" 

USER_CONFIG_DIR = os.path.join(os.getenv("HOME"), ".abinit", "abipy") 

 

Error = PyFlowSchedulerError 

 

def __init__(self, **kwargs): 

""" 

Args: 

weeks: number of weeks to wait 

days: number of days to wait 

hours: number of hours to wait 

minutes: number of minutes to wait 

seconds: number of seconds to wait 

verbose: (int) verbosity level 

max_njobs_inque: Limit on the number of jobs that can be present in the queue 

use_dynamic_manager: True if the :class:`TaskManager` must be re-initialized from 

file before launching the jobs. Default: False 

max_nlaunches: Maximum number of tasks launched by radpifire (default -1 i.e. no limit) 

fix_qcritical: True if the launcher should try to fix QCritical Errors (default: True) 

rmflow: If set to True, the scheduler will remove the flow directory if the calculation 

completed successfully. Default: False 

""" 

# Options passed to the scheduler. 

self.sched_options = AttrDict( 

weeks=kwargs.pop("weeks", 0), 

days=kwargs.pop("days", 0), 

hours=kwargs.pop("hours", 0), 

minutes=kwargs.pop("minutes", 0), 

seconds=kwargs.pop("seconds", 0), 

#start_date=kwargs.pop("start_date", None), 

) 

 

if all(not v for v in self.sched_options.values()): 

raise self.Error("Wrong set of options passed to the scheduler.") 

 

self.mailto = kwargs.pop("mailto", None) 

self.verbose = int(kwargs.pop("verbose", 0)) 

self.use_dynamic_manager = kwargs.pop("use_dynamic_manager", False) 

self.max_njobs_inqueue = kwargs.pop("max_njobs_inqueue", 200) 

self.max_ncores_used = kwargs.pop("max_ncores_used", None) 

self.contact_resource_manager = as_bool(kwargs.pop("contact_resource_manager", False)) 

 

self.remindme_s = float(kwargs.pop("remindme_s", 4 * 24 * 3600)) 

self.max_num_pyexcs = int(kwargs.pop("max_num_pyexcs", 0)) 

self.max_num_abierrs = int(kwargs.pop("max_num_abierrs", 0)) 

self.safety_ratio = int(kwargs.pop("safety_ratio", 5)) 

#self.max_etime_s = kwargs.pop("max_etime_s", ) 

self.max_nlaunches = kwargs.pop("max_nlaunches", -1) 

self.debug = kwargs.pop("debug", 0) 

self.fix_qcritical = kwargs.pop("fix_qcritical", True) 

self.rmflow = kwargs.pop("rmflow", False) 

 

self.customer_service_dir = kwargs.pop("customer_service_dir", None) 

if self.customer_service_dir is not None: 

self.customer_service_dir = Directory(self.customer_service_dir) 

self._validate_customer_service() 

 

if kwargs: 

raise self.Error("Unknown arguments %s" % kwargs) 

 

if has_sched_v3: 

logger.warning("Using scheduler v>=3.0.0") 

from apscheduler.schedulers.blocking import BlockingScheduler 

self.sched = BlockingScheduler() 

else: 

from apscheduler.scheduler import Scheduler 

self.sched = Scheduler(standalone=True) 

 

self.nlaunch = 0 

self.num_reminders = 1 

 

# Used to keep track of the exceptions raised while the scheduler is running 

self.exceptions = deque(maxlen=self.max_num_pyexcs + 10) 

 

# Used to push additional info during the execution. 

self.history = deque(maxlen=100) 

 

@classmethod 

def from_file(cls, filepath): 

"""Read the configuration parameters from a Yaml file.""" 

with open(filepath, "r") as fh: 

return cls(**yaml.load(fh)) 

 

@classmethod 

def from_string(cls, s): 

"""Create an istance from string s containing a YAML dictionary.""" 

stream = cStringIO(s) 

stream.seek(0) 

return cls(**yaml.load(stream)) 

 

@classmethod 

def from_user_config(cls): 

""" 

Initialize the :class:`PyFlowScheduler` from the YAML file 'scheduler.yml'. 

Search first in the working directory and then in the configuration directory of abipy. 

 

Raises: 

`RuntimeError` if file is not found. 

""" 

# Try in the current directory. 

path = os.path.join(os.getcwd(), cls.YAML_FILE) 

 

if os.path.exists(path): 

return cls.from_file(path) 

 

# Try in the configuration directory. 

path = os.path.join(cls.USER_CONFIG_DIR, cls.YAML_FILE) 

 

if os.path.exists(path): 

return cls.from_file(path) 

 

raise cls.Error("Cannot locate %s neither in current directory nor in %s" % (cls.YAML_FILE, path)) 

 

def __str__(self): 

"""String representation.""" 

lines = [self.__class__.__name__ + ", Pid: %d" % self.pid] 

app = lines.append 

 

app("Scheduler options: %s" % str(self.sched_options)) 

app(80 * "=") 

app(str(self.flow)) 

 

return "\n".join(lines) 

 

@property 

def pid(self): 

"""The pid of the process associated to the scheduler.""" 

try: 

return self._pid 

except AttributeError: 

self._pid = os.getpid() 

return self._pid 

 

@property 

def pid_file(self): 

""" 

Absolute path of the file with the pid. 

The file is located in the workdir of the flow 

""" 

return self._pid_file 

 

@property 

def flow(self): 

"""`Flow`.""" 

return self._flow 

 

@property 

def num_excs(self): 

"""Number of exceptions raised so far.""" 

return len(self.exceptions) 

 

def get_delta_etime(self): 

"""Returns a `timedelta` object representing with the elapsed time.""" 

return timedelta(seconds=(time.time() - self.start_time)) 

 

def add_flow(self, flow): 

"""Add an :class:`Flow` flow to the scheduler.""" 

if hasattr(self, "_flow"): 

raise self.Error("Only one flow can be added to the scheduler.") 

 

# Check if we are already using a scheduler to run this flow 

flow.check_pid_file() 

flow.set_spectator_mode(False) 

 

# Build dirs and files (if not yet done) 

flow.build() 

 

with open(flow.pid_file, "w") as fh: 

fh.write(str(self.pid)) 

 

self._pid_file = flow.pid_file 

self._flow = flow 

 

def _validate_customer_service(self): 

""" 

Validate input parameters if customer service is on then 

create directory for tarball files with correct premissions for user and group. 

""" 

direc = self.customer_service_dir 

if not direc.exists: 

mode = 0o750 

print("Creating customer_service_dir %s with mode %s" % (direc, mode)) 

direc.makedirs() 

os.chmod(direc.path, mode) 

 

if self.mailto is None: 

raise RuntimeError("customer_service_dir requires mailto option in scheduler.yml") 

 

def _do_customer_service(self): 

""" 

This method is called before the shutdown of the scheduler. 

If customer_service is on and the flow didn't completed successfully, 

a lightweight tarball file with inputs and the most important output files  

is created in customer_servide_dir. 

""" 

if self.customer_service_dir is None: return 

doit = self.exceptions or not self.flow.all_ok 

doit = True 

if not doit: return 

 

prefix = os.path.basename(self.flow.workdir) + "_" 

 

import tempfile, datetime 

suffix = str(datetime.datetime.now()).replace(" ", "-") 

# Remove milliseconds 

i = suffix.index(".") 

if i != -1: suffix = suffix[:i] 

suffix += ".tar.gz" 

 

#back = os.getcwd() 

#os.chdir(self.customer_service_dir.path) 

 

_, tmpname = tempfile.mkstemp(suffix="_" + suffix, prefix=prefix, 

dir=self.customer_service_dir.path, text=False) 

 

print("Dear customer,\n We are about to generate a tarball in\n %s" % tmpname) 

self.flow.make_light_tarfile(name=tmpname) 

#os.chdir(back) 

 

def start(self): 

""" 

Starts the scheduler in a new thread. Returns 0 if success. 

In standalone mode, this method will block until there are no more scheduled jobs. 

""" 

self.history.append("Started on %s" % time.asctime()) 

self.start_time = time.time() 

 

if has_sched_v3: 

self.sched.add_job(self.callback, "interval", **self.sched_options) 

else: 

self.sched.add_interval_job(self.callback, **self.sched_options) 

 

errors = self.flow.look_before_you_leap() 

if errors: 

self.exceptions.append(errors) 

return 1 

 

# Try to run the job immediately. If something goes wrong return without initializing the scheduler. 

self._runem_all() 

 

if self.exceptions: 

self.cleanup() 

self.send_email(msg="Error while trying to run the flow for the first time!\n %s" % self.exceptions) 

return 1 

 

try: 

self.sched.start() 

return 0 

 

except KeyboardInterrupt: 

self.shutdown(msg="KeyboardInterrupt from user") 

if ask_yesno("Do you want to cancel all the jobs in the queue? [Y/n]"): 

print("Number of jobs cancelled:", self.flow.cancel()) 

 

self.flow.pickle_dump() 

return -1 

 

def _runem_all(self): 

""" 

This function checks the status of all tasks, 

tries to fix tasks that went unconverged, abicritical, or queuecritical 

and tries to run all the tasks that can be submitted.+ 

""" 

excs = [] 

flow = self.flow 

 

# Allow to change the manager at run-time 

if self.use_dynamic_manager: 

from pymatgen.io.abinit.tasks import TaskManager 

new_manager = TaskManager.from_user_config() 

for work in flow: 

work.set_manager(new_manager) 

 

nqjobs = 0 

if self.contact_resource_manager: 

# This call is expensive and therefore it's optional 

nqjobs = flow.get_njobs_in_queue() 

if nqjobs is None: 

nqjobs = 0 

if flow.manager.has_queue: logger.warning('Cannot get njobs_inqueue') 

 

if nqjobs >= self.max_njobs_inqueue: 

print("Too many jobs in the queue: %s, returning" % nqjobs) 

return 

 

if self.max_nlaunches == -1: 

max_nlaunch = self.max_njobs_inqueue - nqjobs 

else: 

max_nlaunch = min(self.max_njobs_inqueue - nqjobs, self.max_nlaunches) 

 

# check status. 

flow.check_status(show=False) 

 

# This check is not perfect, we should make a list of tasks to sumbit 

# and select only the subset so that we don't exceeed mac_ncores_used  

# Many sections of this code should be rewritten. 

#if self.max_ncores_used is not None and flow.ncores_used > self.max_ncores_used: 

if self.max_ncores_used is not None and flow.ncores_allocated > self.max_ncores_used: 

print("Cannot exceed max_ncores_used %s" % self.max_ncores_used) 

logger.info("Cannot exceed max_ncores_used %s" % self.max_ncores_used) 

return 

 

# Try to restart the unconverged tasks 

# TODO: do not fire here but prepare for fireing in rapidfire 

for task in self.flow.unconverged_tasks: 

try: 

logger.info("Flow will try restart task %s" % task) 

fired = task.restart() 

if fired: 

self.nlaunch += 1 

max_nlaunch -= 1 

if max_nlaunch == 0: 

logger.info("Restart: too many jobs in the queue, returning") 

flow.pickle_dump() 

return 

 

except task.RestartError: 

excs.append(straceback()) 

 

# Temporarily disable by MG because I don't know if fix_critical works after the 

# introduction of the new qadapters 

# reenabled by MsS disable things that do not work at low level 

# fix only prepares for restarting, and sets to ready 

if self.fix_qcritical: 

nfixed = flow.fix_queue_critical() 

if nfixed: print("Fixed %d QCritical error(s)" % nfixed) 

 

nfixed = flow.fix_abicritical() 

if nfixed: print("Fixed %d AbiCritical error(s)" % nfixed) 

 

# update database 

flow.pickle_dump() 

 

# Submit the tasks that are ready. 

try: 

nlaunch = PyLauncher(flow).rapidfire(max_nlaunch=max_nlaunch, sleep_time=10) 

self.nlaunch += nlaunch 

 

if nlaunch: 

print("[%s] Number of launches: %d" % (time.asctime(), nlaunch)) 

 

except Exception: 

excs.append(straceback()) 

 

# check status. 

#flow.check_status(show=True) 

flow.show_status() 

 

if excs: 

logger.critical("*** Scheduler exceptions:\n *** %s" % "\n".join(excs)) 

self.exceptions.extend(excs) 

 

def callback(self): 

"""The function that will be executed by the scheduler.""" 

try: 

return self._callback() 

except: 

# All exceptions raised here will trigger the shutdown! 

s = straceback() 

self.exceptions.append(s) 

 

# This is useful when debugging  

#try: 

# print("Exception in callback, will cancel all tasks") 

# for task in self.flow.iflat_tasks(): 

# task.cancel() 

#except Exception: 

# pass 

 

self.shutdown(msg="Exception raised in callback!\n" + s) 

 

def _callback(self): 

"""The actual callback.""" 

if self.debug: 

# Show the number of open file descriptors 

print(">>>>> _callback: Number of open file descriptors: %s" % get_open_fds()) 

 

self._runem_all() 

 

# Mission accomplished. Shutdown the scheduler. 

all_ok = self.flow.all_ok 

if all_ok: 

return self.shutdown(msg="All tasks have reached S_OK. Will shutdown the scheduler and exit") 

 

# Handle failures. 

err_lines = [] 

 

# Shall we send a reminder to the user? 

delta_etime = self.get_delta_etime() 

 

if delta_etime.total_seconds() > self.num_reminders * self.remindme_s: 

self.num_reminders += 1 

msg = ("Just to remind you that the scheduler with pid %s, flow %s\n has been running for %s " % 

(self.pid, self.flow, delta_etime)) 

retcode = self.send_email(msg, tag="[REMINDER]") 

 

if retcode: 

# Cannot send mail, shutdown now! 

msg += ("\nThe scheduler tried to send an e-mail to remind the user\n" + 

" but send_email returned %d. Aborting now" % retcode) 

err_lines.append(msg) 

 

#if delta_etime.total_seconds() > self.max_etime_s: 

# err_lines.append("\nExceeded max_etime_s %s. Will shutdown the scheduler and exit" % self.max_etime_s) 

 

# Too many exceptions. Shutdown the scheduler. 

if self.num_excs > self.max_num_pyexcs: 

msg = "Number of exceptions %s > %s. Will shutdown the scheduler and exit" % ( 

self.num_excs, self.max_num_pyexcs) 

err_lines.append(boxed(msg)) 

 

# Paranoid check: disable the scheduler if we have submitted 

# too many jobs (it might be due to some bug or other external reasons  

# such as race conditions between difference callbacks!) 

if self.nlaunch > self.safety_ratio * self.flow.num_tasks: 

msg = "Too many jobs launched %d. Total number of tasks = %s, Will shutdown the scheduler and exit" % ( 

self.nlaunch, self.flow.num_tasks) 

err_lines.append(boxed(msg)) 

 

# Count the number of tasks with status == S_ERROR. 

if self.flow.num_errored_tasks > self.max_num_abierrs: 

msg = "Number of tasks with ERROR status %s > %s. Will shutdown the scheduler and exit" % ( 

self.flow.num_errored_tasks, self.max_num_abierrs) 

err_lines.append(boxed(msg)) 

 

# Test on the presence of deadlocks. 

#""" 

g = self.flow.find_deadlocks() 

if g.deadlocked: 

# Check the flow again so that status are updated.  

self.flow.check_status() 

 

g = self.flow.find_deadlocks() 

print("deadlocked:\n", g.deadlocked, "\nrunnables:\n", g.runnables, "\nrunning\n", g.running) 

if g.deadlocked and not g.runnables and not g.running: 

err_lines.append("No runnable job with deadlocked tasks:\n%s." % str(g.deadlocked)) 

 

if not g.runnables and not g.running: 

# Check the flow again to that status are updated.  

self.flow.check_status() 

g = self.flow.find_deadlocks() 

if not g.runnables and not g.running: 

err_lines.append("No task is running and cannot find other tasks to submit.") 

#""" 

 

if err_lines: 

# Something wrong. Quit 

self.shutdown("\n".join(err_lines)) 

 

return len(self.exceptions) 

 

def cleanup(self): 

"""Cleanup routine: remove the pid file and save the pickle database""" 

try: 

os.remove(self.pid_file) 

except OSError as exc: 

logger.critical("Could not remove pid_file: %s", exc) 

 

# Save the final status of the flow. 

self.flow.pickle_dump() 

 

def shutdown(self, msg): 

"""Shutdown the scheduler.""" 

try: 

self.cleanup() 

 

self.history.append("Completed on %s" % time.asctime()) 

self.history.append("Elapsed time %s" % self.get_delta_etime()) 

 

if self.debug: 

print(">>>>> shutdown: Number of open file descriptors: %s" % get_open_fds()) 

 

retcode = self.send_email(msg) 

if self.debug: 

print("send_mail retcode", retcode) 

 

# Write file with the list of exceptions: 

if self.exceptions: 

dump_file = os.path.join(self.flow.workdir, "_exceptions") 

with open(dump_file, "w") as fh: 

fh.writelines(self.exceptions) 

fh.write("Shutdown message:\n%s" % msg) 

 

# Cancel all jobs. 

#try: 

# for task in self.flow.iflat_tasks() 

# task.cancel() 

#except: 

# pass 

 

lines = [] 

app = lines.append 

app("Submitted on %s" % time.ctime(self.start_time)) 

app("Completed on %s" % time.asctime()) 

app("Elapsed time %s" % str(self.get_delta_etime())) 

 

if self.flow.all_ok: 

app("Flow completed successfully") 

else: 

app("Flow %s didn't complete successfully" % repr(self.flow.workdir)) 

app("Shutdown message:\n%s" % msg) 

 

print("") 

print("\n".join(lines)) 

print("") 

 

self._do_customer_service() 

 

if self.flow.all_ok: 

print("Calling flow.finalize()") 

self.flow.finalize() 

if self.rmflow: 

app("Flow directory will be removed...") 

try: 

self.flow.rmtree() 

except Exception: 

logger.warning("Ignoring exception while trying to remove flow dir.") 

 

finally: 

# Shutdown the scheduler thus allowing the process to exit. 

logger.debug('this should be the shutdown of the scheduler') 

 

# Unschedule all the jobs before calling shutdown 

#self.sched.print_jobs() 

if not has_sched_v3: 

for job in self.sched.get_jobs(): 

self.sched.unschedule_job(job) 

#self.sched.print_jobs() 

 

self.sched.shutdown() 

# Uncomment the line below if shutdown does not work! 

#os.system("kill -9 %d" % os.getpid()) 

 

def send_email(self, msg, tag=None): 

""" 

Send an e-mail before completing the shutdown. 

Returns 0 if success. 

""" 

try: 

return self._send_email(msg, tag) 

except: 

self.exceptions.append(straceback()) 

return -2 

 

def _send_email(self, msg, tag): 

if self.mailto is None: 

return -1 

 

header = msg.splitlines() 

app = header.append 

 

app("Submitted on %s" % time.ctime(self.start_time)) 

app("Completed on %s" % time.asctime()) 

app("Elapsed time %s" % str(self.get_delta_etime())) 

app("Number of errored tasks: %d" % self.flow.num_errored_tasks) 

app("Number of unconverged tasks: %d" % self.flow.num_unconverged_tasks) 

 

strio = cStringIO() 

strio.writelines("\n".join(header) + 4 * "\n") 

 

# Add the status of the flow. 

self.flow.show_status(stream=strio) 

 

if self.exceptions: 

# Report the list of exceptions. 

strio.writelines(self.exceptions) 

 

if tag is None: 

tag = " [ALL OK]" if self.flow.all_ok else " [WARNING]" 

 

return sendmail(subject=self.flow.name + tag, text=strio.getvalue(), mailto=self.mailto) 

 

 

def sendmail(subject, text, mailto, sender=None): 

""" 

Sends an e-mail with unix sendmail. 

 

Args: 

subject: String with the subject of the mail. 

text: String with the body of the mail. 

mailto: String or list of string with the recipients. 

sender: string with the sender address. 

If sender is None, username@hostname is used. 

 

Returns: 

Exit status 

""" 

def user_at_host(): 

from socket import gethostname 

return os.getlogin() + "@" + gethostname() 

 

# Body of the message. 

try: 

sender = user_at_host() if sender is None else sender 

except OSError: 

sender = 'abipyscheduler@youknowwhere' 

 

if is_string(mailto): mailto = [mailto] 

 

from email.mime.text import MIMEText 

 

mail = MIMEText(text) 

mail["Subject"] = subject 

mail["From"] = sender 

mail["To"] = ", ".join(mailto) 

 

msg = mail.as_string() 

 

# sendmail works much better than the python interface. 

# Note that sendmail is available only on Unix-like OS. 

from subprocess import Popen, PIPE 

 

sendmail = which("sendmail") 

if sendmail is None: return -1 

p = Popen([sendmail, "-t"], stdin=PIPE, stderr=PIPE) 

 

outdata, errdata = p.communicate(msg) 

return len(errdata) 

 

 

def __test_sendmail(): 

retcode = sendmail("sendmail_test", text="hello\nworld", mailto="nobody@nowhere.com") 

print("Retcode", retcode) 

assert retcode == 0 

 

 

class BatchLauncherError(Exception): 

"""Exceptions raised by :class:`BatchLauncher`.""" 

 

 

class BatchLauncher(object): 

""" 

This object automates the execution of multiple flow. It generates a job script 

that uses abirun.py to run each flow stored in self with a scheduler. 

The execution of the flows is done in sequential but each scheduler will start 

to submit the tasks of the flow in autparal mode. 

 

The `BatchLauncher` is pickleable, hence one can reload it, check if all flows are completed 

and rerun only those that are not completed due to the timelimit.  

""" 

PICKLE_FNAME = "__BatchLauncher__.pickle" 

 

Error = BatchLauncherError 

 

@classmethod 

def from_dir(cls, top, workdir=None, name=None, manager=None, max_depth=2): 

""" 

Find all flows located withing the directory `top` and build the `BatchLauncher`. 

 

Args: 

top: Top level directory or list of directories. 

workdir: Batch workdir. 

name: 

manager: :class:`TaskManager` object. If None, the manager is read from `manager.yml` 

In this case the YAML file must provide the entry `batch_manager` that defined 

the queue adapter used to submit the batch script. 

max_depth: Search in directory only if it is N or fewer levels below top 

""" 

from .flows import Flow 

def find_pickles(dirtop): 

# Walk through each directory inside path and find the pickle database. 

paths = [] 

for dirpath, dirnames, filenames in os.walk(dirtop): 

fnames = [f for f in filenames if f == Flow.PICKLE_FNAME] 

paths.extend([os.path.join(dirpath, f) for f in fnames]) 

return paths 

 

if is_string(top): 

pickle_paths = find_pickles(top) 

else: 

# List of directories. 

pickle_paths = [] 

for p in top: 

pickle_paths.extend(find_pickles(p)) 

 

#workdir = os.path.join(top, "batch") if workdir is None else workdir 

workdir = "batch" if workdir is None else workdir 

new = cls(workdir, name=name, manager=manager) 

 

for path in pickle_paths: 

new.add_flow(path) 

 

return new 

 

@classmethod 

def pickle_load(cls, filepath): 

""" 

Loads the object from a pickle file. 

 

Args: 

filepath: Filename or directory name. It filepath is a directory, we 

scan the directory tree starting from filepath and we 

read the first pickle database. Raise RuntimeError if multiple 

databases are found. 

""" 

if os.path.isdir(filepath): 

# Walk through each directory inside path and find the pickle database. 

for dirpath, dirnames, filenames in os.walk(filepath): 

fnames = [f for f in filenames if f == cls.PICKLE_FNAME] 

if fnames: 

if len(fnames) == 1: 

filepath = os.path.join(dirpath, fnames[0]) 

break # Exit os.walk 

else: 

err_msg = "Found multiple databases:\n %s" % str(fnames) 

raise RuntimeError(err_msg) 

else: 

err_msg = "Cannot find %s inside directory %s" % (cls.PICKLE_FNAME, filepath) 

raise ValueError(err_msg) 

 

with open(filepath, "rb") as fh: 

new = pickle.load(fh) 

 

# new.flows is a list of strings with the workdir of the flows (see __getstate__). 

# Here we read the Flow from the pickle file so that we have 

# and up-to-date version and we set the flow in visitor_mode 

from .flows import Flow 

flow_workdirs, new.flows = new.flows, [] 

for flow in map(Flow.pickle_load, flow_workdirs): 

new.add_flow(flow) 

 

return new 

 

def pickle_dump(self): 

"""Save the status of the object in pickle format.""" 

with open(os.path.join(self.workdir, self.PICKLE_FNAME), mode="wb") as fh: 

pickle.dump(self, fh) 

 

def __getstate__(self): 

""" 

Return state is pickled as the contents for the instance. 

 

Here we replace the flow objects with their workdir because we are observing  

the flows and we want to have the updated version when we reload the `BatchLauncher` from pickle. 

""" 

d = {k: v for k, v in self.__dict__.items() if k not in ["flows"]} 

d["flows"] = [flow.workdir for flow in self.flows] 

return d 

 

def __init__(self, workdir, name=None, flows=None, manager=None, timelimit=None): 

""" 

Args: 

workdir: Working directory 

name: Name assigned to the `BatchLauncher`. 

flows: List of `Flow` objects. 

manager: :class:`TaskManager` object responsible for the submission of the jobs. 

If manager is None, the object is initialized from the yaml file 

located either in the working directory or in the user configuration dir. 

timelimit: Time limit (int with seconds or string with time given with  

the slurm convention: "days-hours:minutes:seconds". 

If timelimit is None, the default value specified in the `batch_adapter` is taken. 

""" 

self.workdir = os.path.abspath(workdir) 

 

if not os.path.exists(self.workdir): 

os.makedirs(self.workdir) 

else: 

pass 

#raise RuntimeError("Directory %s already exists. Use BatchLauncher.pickle_load()" % self.workdir) 

 

self.name = os.path.basename(self.workdir) if name is None else name 

self.script_file = File(os.path.join(self.workdir, "run.sh")) 

self.qerr_file = File(os.path.join(self.workdir, "queue.qerr")) 

self.qout_file = File(os.path.join(self.workdir, "queue.qout")) 

self.log_file = File(os.path.join(self.workdir, "run.log")) 

self.batch_pidfile = File(os.path.join(self.workdir, "batch.pid")) 

 

from .tasks import TaskManager 

manager = TaskManager.as_manager(manager) 

 

# Extract the qadapater to be used for the batch script. 

try: 

self.qadapter = qad = manager.batch_adapter 

except AttributeError: 

raise RuntimeError("Your manager.yml file does not define an entry for the batch_adapter") 

 

if qad is None: 

raise RuntimeError("Your manager.yml file does not define an entry for the batch_adapter") 

 

# Set mpi_procs to 1 just to be on the safe side  

# Then allow the user to change the timelimit via __init__ 

qad.set_mpi_procs(1) 

if timelimit is not None: 

self.set_timelimit(timelimit) 

# FIXME: Remove me! 

self.set_timelimit(36000) 

 

# Initialize list of flows. 

if flows is None: flows = [] 

if not isinstance(flows, (list, tuple)): flows = [flows] 

self.flows = flows 

 

def set_timelimit(self, timelimit): 

""" 

Set the timelimit of the batch launcher. 

 

Args: 

timelimit: Time limit (int with seconds or string with time given 

with the slurm convention: "days-hours:minutes:seconds". 

""" 

self.qad.set_timelimit(qu.timelimit_parser(timelimit)) 

 

def to_string(self, **kwargs): 

lines = [] 

lines.extend(str(self.qadapter).splitlines()) 

 

for i, flow in enumerate(self.flows): 

lines.append("Flow [%d] " % i + str(flow)) 

 

return "\n".join(lines) 

 

def __str__(self): 

return self.to_string() 

 

def add_flow(self, flow): 

""" 

Add a flow. Accept filepath or :class:`Flow` object. Return 1 if flow was added else 0. 

""" 

from .flows import Flow 

flow = Flow.as_flow(flow) 

 

if flow in self.flows: 

raise self.Error("Cannot add same flow twice!") 

 

if not flow.allocated: 

# Set the workdir of the flow here. Create a dir in self.workdir with name flow.name 

flow_workdir = os.path.join(self.workdir, os.path.basename(flow.name)) 

if flow_workdir in (flow.workdir for flow in self.flows): 

raise self.Error("Two flows have the same name and hence the same workdir!") 

flow.allocate(workdir=flow_workdir) 

 

# Check if we are already using a scheduler to run this flow 

flow.check_pid_file() 

flow.set_spectator_mode(False) 

 

flow.check_status(show=False) 

 

#if flow.all_ok: 

# print("flow.all_ok: Ignoring %s" % flow) 

# return 0 

 

self.flows.append(flow) 

#print("Flow %s added to the BatchLauncher" % flow) 

 

return 1 

 

def submit(self, **kwargs): 

""" 

Submit a job script that will run the schedulers with `abirun.py`. 

 

Args: 

verbose: Verbosity level 

dry_run: Don't submit the script if dry_run. Default: False 

 

Returns: 

namedtuple with attributes: 

retcode: Return code as returned by the submission script. 

qjob: :class:`QueueJob` object. 

num_flows_inbatch: Number of flows executed by the batch script 

 

Return code of the job script submission. 

""" 

verbose, dry_run = kwargs.pop("verbose", 0), kwargs.pop("dry_run", False) 

 

if not self.flows: 

print("Cannot submit an empty list of flows!") 

return 0 

 

if hasattr(self, "qjob"): 

# This usually happens when we have loaded the object from pickle 

# and we have already submitted to batch script to the queue. 

# At this point we need to understand if the previous batch job 

# is still running before trying to submit it again. There are three cases: 

#  

# 1) The batch script has completed withing timelimit and therefore 

# the pid_file has been removed by the script. In this case, we 

# should not try to submit it again. 

 

# 2) The batch script has been killed due to timelimit (other reasons are possible 

# but we neglect them). In this case the pid_file exists but there's no job with 

# this pid runnig and we can resubmit it again. 

 

# 3) The batch script is still running. 

print("BatchLauncher has qjob %s" % self.qjob) 

 

if not self.batch_pid_file.exists: 

print("It seems that the batch script reached the end. Wont' try to submit it again") 

return 0 

 

msg = ("Here I have to understand if qjob is in the queue." 

" but I need an abstract API that can retrieve info from the queue id") 

raise RuntimeError(msg) 

 

# TODO: Temptative API 

if self.qjob.in_status("Running|Queued"): 

print("Job is still running. Cannot submit") 

else: 

del self.qjob 

 

script, num_flows_inbatch = self._get_script_nflows() 

 

if num_flows_inbatch == 0: 

print("All flows have reached all_ok! Batch script won't be submitted") 

return 0 

 

if verbose: 

print("*** submission script ***") 

print(script) 

 

# Write the script. 

self.script_file.write(script) 

self.script_file.chmod(0o740) 

 

# Builf the flow. 

for flow in self.flows: 

flow.build_and_pickle_dump() 

 

# Submit the task and save the queue id. 

if dry_run: return -1 

 

print("Will submit %s flows in batch script" % len(self.flows)) 

self.qjob, process = self.qadapter.submit_to_queue(self.script_file.path) 

 

# Save the queue id in the pid file 

# The file will be removed by the job script if execution is completed. 

self.batch_pidfile.write(str(self.qjob.qid)) 

 

self.pickle_dump() 

process.wait() 

 

return dict2namedtuple(retcode=process.returncode, qjob=self.qjob, 

num_flows_inbatch=num_flows_inbatch) 

 

def _get_script_nflows(self): 

""" 

Write the submission script. Return (script, num_flows_in_batch) 

""" 

flows_torun = [f for f in self.flows if not f.all_ok] 

if not flows_torun: 

return "", 0 

 

executable = [ 

'export _LOG=%s' % self.log_file.path, 

'date1=$(date +"%s")', 

'echo Running abirun.py in batch mode > ${_LOG}', 

" ", 

] 

app = executable.append 

 

# Build list of abirun commands and save the name of the log files. 

self.sched_logs, num_flows = [], len(flows_torun) 

for i, flow in enumerate(flows_torun): 

 

logfile = os.path.join(self.workdir, "log_" + os.path.basename(flow.workdir)) 

 

app("echo Starting flow %d/%d on: `date` >> ${LOG}" % (i+1, num_flows)) 

app("\nabirun.py %s scheduler > %s" % (flow.workdir, logfile)) 

app("echo Returning from abirun on `date` with retcode $? >> ${_LOG}") 

 

assert logfile not in self.sched_logs 

self.sched_logs.append(logfile) 

 

# Remove the batch pid_file and compute elapsed time. 

executable.extend([ 

" ", 

"# Remove batch pid file", 

'rm %s' % self.batch_pidfile.path, 

" ", 

"# Compute elapsed time", 

'date2=$(date +"%s")', 

'diff=$(($date2-$date1))', 

'echo $(($diff / 60)) minutes and $(($diff % 60)) seconds elapsed. >> ${_LOG}' 

]) 

 

return self.qadapter.get_script_str( 

job_name=self.name, 

launch_dir=self.workdir, 

executable=executable, 

qout_path=self.qout_file.path, 

qerr_path=self.qerr_file.path, 

), num_flows 

 

def show_summary(self, **kwargs): 

""" 

Show a summary with the status of the flows. 

""" 

for flow in self.flows: 

flow.show_summary() 

 

def show_status(self, **kwargs): 

""" 

Report the status of the flows. 

 

Args: 

stream: File-like object, Default: sys.stdout 

verbose: Verbosity level (default 0). > 0 to show only the works that are not finalized. 

""" 

for flow in self.flows: 

flow.show_status(**kwargs)