src/HOL/Tools/ATP/watcher.ML
author paulson
Tue, 04 Oct 2005 09:59:01 +0200
changeset 17746 af59c748371d
parent 17716 89932e53f31d
child 17764 fde495b9e24b
permissions -rw-r--r--
fixed the ascii-armouring of goalstring
paulson@15789
     1
(*  Title:      Watcher.ML
paulson@15789
     2
    ID:         $Id$
paulson@15789
     3
    Author:     Claire Quigley
paulson@15789
     4
    Copyright   2004  University of Cambridge
quigley@15642
     5
 *)
quigley@15642
     6
quigley@15642
     7
 (***************************************************************************)
quigley@15642
     8
 (*  The watcher process starts a resolution process when it receives a     *)
quigley@15642
     9
(*  message from Isabelle                                                  *)
quigley@15642
    10
(*  Signals Isabelle, puts output of child into pipe to Isabelle,          *)
quigley@15642
    11
(*  and removes dead processes.  Also possible to kill all the resolution  *)
quigley@15642
    12
(*  processes currently running.                                           *)
quigley@15642
    13
(*  Hardwired version of where to pick up the tptp files for the moment    *)
quigley@15642
    14
(***************************************************************************)
quigley@15642
    15
paulson@17305
    16
signature WATCHER =
paulson@17305
    17
sig
paulson@17305
    18
paulson@17305
    19
(*  Send request to Watcher for multiple spasses to be called for filenames in arg       *)
paulson@17568
    20
(* callResProvers (outstreamtoWatcher, prover name,prover-command, (settings,file) list *)
paulson@17305
    21
paulson@17305
    22
val callResProvers :
paulson@17422
    23
    TextIO.outstream * (string*string*string*string*string) list 
paulson@17305
    24
    -> unit
paulson@17305
    25
paulson@17305
    26
(* Send message to watcher to kill currently running resolution provers *)
paulson@17305
    27
val callSlayer : TextIO.outstream -> unit
paulson@17305
    28
paulson@17305
    29
(* Start a watcher and set up signal handlers             *)
paulson@17484
    30
val createWatcher : 
paulson@17484
    31
    thm * (ResClause.clause * thm) Array.array -> 
paulson@17484
    32
    TextIO.instream * TextIO.outstream * Posix.Process.pid
paulson@17305
    33
paulson@17305
    34
(* Kill watcher process                                   *)
paulson@17305
    35
val killWatcher : Posix.Process.pid -> unit
paulson@17488
    36
val killWatcher' : int -> unit
paulson@17305
    37
end
paulson@17305
    38
paulson@17305
    39
quigley@15642
    40
quigley@15642
    41
structure Watcher: WATCHER =
paulson@17484
    42
struct
quigley@15642
    43
paulson@17488
    44
open Recon_Transfer
wenzelm@16805
    45
quigley@15642
    46
val goals_being_watched = ref 0;
quigley@15642
    47
paulson@17583
    48
val trace_path = Path.basic "watcher_trace";
paulson@17583
    49
paulson@17690
    50
fun trace s = if !Output.show_debug_msgs then File.append (File.tmp_path trace_path) s 
paulson@17690
    51
              else ();
paulson@17583
    52
quigley@16039
    53
(*  The result of calling createWatcher  *)
quigley@16039
    54
datatype proc = PROC of {
quigley@16039
    55
        pid : Posix.Process.pid,
quigley@16039
    56
        instr : TextIO.instream,
quigley@16039
    57
        outstr : TextIO.outstream
quigley@16039
    58
      };
quigley@16039
    59
quigley@16039
    60
(*  The result of calling executeToList  *)
quigley@16039
    61
datatype cmdproc = CMDPROC of {
paulson@17568
    62
        prover: string,       (* Name of the resolution prover used, e.g. Vampire*)
paulson@17568
    63
        cmd:  string,         (* The file containing the goal for res prover to prove *)     
paulson@17568
    64
        goalstring: string,   (* string representation of subgoal*) 
quigley@16039
    65
        proc_handle : (TextIO.instream,TextIO.outstream) Unix.proc,
quigley@16039
    66
        instr : TextIO.instream,   (*  Input stream to child process *)
paulson@17568
    67
        outstr : TextIO.outstream};  (*  Output stream from child process *)
quigley@16039
    68
quigley@16039
    69
type signal = Posix.Signal.signal
quigley@16039
    70
datatype exit_status = datatype Posix.Process.exit_status
quigley@16039
    71
quigley@16039
    72
val fromStatus = Posix.Process.fromStatus
quigley@16039
    73
quigley@16039
    74
fun reap(pid, instr, outstr) =
paulson@17317
    75
  let val u = TextIO.closeIn instr;
paulson@17317
    76
      val u = TextIO.closeOut outstr;
paulson@17317
    77
      val (_, status) = Posix.Process.waitpid(Posix.Process.W_CHILD pid, [])
paulson@17568
    78
  in status end
quigley@16039
    79
quigley@16039
    80
fun fdReader (name : string, fd : Posix.IO.file_desc) =
quigley@16039
    81
	  Posix.IO.mkTextReader {initBlkMode = true,name = name,fd = fd };
quigley@16039
    82
quigley@16039
    83
fun fdWriter (name, fd) =
quigley@16039
    84
          Posix.IO.mkTextWriter {
quigley@16039
    85
	      appendMode = false,
quigley@16039
    86
              initBlkMode = true,
quigley@16039
    87
              name = name,  
quigley@16039
    88
              chunkSize=4096,
paulson@17317
    89
              fd = fd};
quigley@16039
    90
quigley@16039
    91
fun openOutFD (name, fd) =
quigley@16039
    92
	  TextIO.mkOutstream (
quigley@16039
    93
	    TextIO.StreamIO.mkOutstream (
quigley@16039
    94
	      fdWriter (name, fd), IO.BLOCK_BUF));
quigley@16039
    95
quigley@16039
    96
fun openInFD (name, fd) =
quigley@16039
    97
	  TextIO.mkInstream (
quigley@16039
    98
	    TextIO.StreamIO.mkInstream (
quigley@16039
    99
	      fdReader (name, fd), ""));
quigley@16039
   100
quigley@16039
   101
fun childInfo (PROC{pid,instr,outstr }) = (pid,(instr,outstr));
quigley@16039
   102
quigley@16039
   103
fun cmdstreamsOf (CMDPROC{instr,outstr,...}) = (instr, outstr);
quigley@16039
   104
paulson@17317
   105
fun cmdInStream (CMDPROC{instr,outstr,...}) = instr;
quigley@16039
   106
paulson@17422
   107
fun cmdchildInfo (CMDPROC{prover,cmd,proc_handle,goalstring,instr,outstr}) = 
paulson@17317
   108
  (prover,(cmd, (instr,outstr)));
quigley@16039
   109
paulson@17422
   110
fun cmdchildHandle (CMDPROC{prover,cmd,goalstring,proc_handle,instr,outstr})  = 
paulson@17317
   111
  proc_handle;
quigley@16039
   112
paulson@17422
   113
fun cmdProver (CMDPROC{prover,cmd,goalstring,proc_handle,instr,outstr})  =
paulson@17317
   114
  prover;
quigley@16039
   115
paulson@17422
   116
fun cmdGoal (CMDPROC{prover,cmd,goalstring,proc_handle,instr,outstr})  =
paulson@17317
   117
  goalstring;
quigley@15642
   118
quigley@15642
   119
quigley@15642
   120
(*    gets individual args from instream and concatenates them into a list      *)
paulson@17317
   121
fun getArgs (fromParentStr, toParentStr, ys) =  
paulson@17317
   122
  let val thisLine = TextIO.input fromParentStr
paulson@17317
   123
  in ys@[thisLine] end
quigley@15642
   124
quigley@15642
   125
                            
quigley@15642
   126
(*  Send request to Watcher for a vampire to be called for filename in arg      *)
paulson@17568
   127
                   
paulson@17231
   128
fun callResProver (toWatcherStr,  arg) = 
paulson@17317
   129
      (TextIO.output (toWatcherStr, arg^"\n"); 
paulson@17231
   130
       TextIO.flushOut toWatcherStr)
quigley@15642
   131
quigley@15642
   132
(*****************************************************************************************)
quigley@16357
   133
(*  Send request to Watcher for multiple provers to be called for filenames in arg       *)
quigley@16357
   134
(*  need to do the dfg stuff in the watcher, not here! send over the clasimp and stuff files too*)
quigley@15642
   135
(*****************************************************************************************)
quigley@15642
   136
quigley@16357
   137
    
paulson@17305
   138
(*Uses the $-character to separate items sent to watcher*)
paulson@16475
   139
fun callResProvers (toWatcherStr,  []) = 
paulson@17317
   140
      (TextIO.output (toWatcherStr, "End of calls\n");  TextIO.flushOut toWatcherStr)
paulson@16475
   141
|   callResProvers (toWatcherStr,
paulson@17422
   142
                    (prover,goalstring, proverCmd,settings, 
paulson@17422
   143
                     probfile)  ::  args) =
paulson@17690
   144
      let val _ = trace (space_implode "\n" 
paulson@17690
   145
		         (["\ncallResProvers:",prover,goalstring,proverCmd,settings,
paulson@17690
   146
			  probfile]))
paulson@17317
   147
      in TextIO.output (toWatcherStr,    
paulson@17746
   148
                        prover^"$"^proverCmd^"$"^ settings^"$"^probfile^"$\n");
paulson@17746
   149
         TextIO.output (toWatcherStr, String.toString goalstring^"\n");
paulson@17746
   150
              (*goalstring is a single string literal, with all specials escaped.*)
paulson@16475
   151
         goals_being_watched := (!goals_being_watched) + 1;
paulson@16475
   152
	 TextIO.flushOut toWatcherStr;
paulson@16475
   153
	 callResProvers (toWatcherStr,args)
paulson@16475
   154
      end   
quigley@16357
   155
                                                
paulson@17305
   156
                                    
quigley@15642
   157
 
quigley@15642
   158
(**************************************************************)
quigley@15642
   159
(* Send message to watcher to kill currently running vampires *)
quigley@15642
   160
(**************************************************************)
quigley@15642
   161
paulson@17317
   162
fun callSlayer toWatcherStr = (TextIO.output (toWatcherStr, "Kill vampires\n"); 
quigley@15642
   163
                            TextIO.flushOut toWatcherStr)
quigley@15642
   164
paulson@17746
   165
                    
quigley@15642
   166
(**************************************************************)
quigley@15642
   167
(* Get commands from Isabelle                                 *)
quigley@15642
   168
(**************************************************************)
quigley@15642
   169
fun getCmds (toParentStr,fromParentStr, cmdList) = 
paulson@16475
   170
  let val thisLine = TextIO.inputLine fromParentStr 
paulson@17690
   171
      val _ = trace("\nGot command from parent: " ^ thisLine)
paulson@16475
   172
  in
paulson@17568
   173
     if thisLine = "End of calls\n" orelse thisLine = "" then cmdList
paulson@17422
   174
     else if thisLine = "Kill children\n"
paulson@17568
   175
     then (TextIO.output (toParentStr,thisLine ); 
paulson@17568
   176
	   TextIO.flushOut toParentStr;
paulson@17568
   177
	   (("","","Kill children",[],"")::cmdList)  )
paulson@17746
   178
     else
paulson@17746
   179
       let val [prover,proverCmd,settingstr,probfile,_] = 
paulson@17746
   180
                   String.tokens (fn c => c = #"$") thisLine
paulson@17746
   181
           val settings = String.tokens (fn c => c = #"%") settingstr
paulson@17746
   182
	   val goalstring = TextIO.inputLine fromParentStr 
paulson@17746
   183
       in
paulson@17746
   184
           trace ("\nprover: " ^ prover ^ "  prover path: " ^ proverCmd^
paulson@17746
   185
                  "  problem file: " ^ probfile ^ 
paulson@17746
   186
		  "\ngoalstring:  "^goalstring);
paulson@17746
   187
           getCmds (toParentStr, fromParentStr, 
paulson@17746
   188
                    (prover, goalstring, proverCmd, settings, probfile)::cmdList) 
paulson@17746
   189
       end
paulson@16475
   190
  end
paulson@16475
   191
	    
quigley@16357
   192
                                                                  
quigley@15642
   193
(**************************************************************)
quigley@15642
   194
(*  Get Io-descriptor for polling of an input stream          *)
quigley@15642
   195
(**************************************************************)
quigley@15642
   196
quigley@15642
   197
fun getInIoDesc someInstr = 
quigley@15642
   198
    let val (rd, buf) = TextIO.StreamIO.getReader(TextIO.getInstream someInstr)
paulson@15702
   199
        val _ = TextIO.output (TextIO.stdOut, buf)
quigley@15642
   200
        val ioDesc = 
quigley@15642
   201
	    case rd
quigley@15642
   202
	      of TextPrimIO.RD{ioDesc = SOME iod, ...} =>SOME iod
quigley@15642
   203
	       | _ => NONE
quigley@15642
   204
     in (* since getting the reader will have terminated the stream, we need
quigley@15642
   205
	 * to build a new stream. *)
quigley@15642
   206
	TextIO.setInstream(someInstr, TextIO.StreamIO.mkInstream(rd, buf));
quigley@15642
   207
	ioDesc
quigley@15642
   208
    end
quigley@15642
   209
quigley@15642
   210
quigley@15642
   211
(*************************************)
quigley@15642
   212
(*  Set up a Watcher Process         *)
quigley@15642
   213
(*************************************)
quigley@15642
   214
paulson@17422
   215
fun getProofCmd (a,c,d,e,f) = d
paulson@17422
   216
paulson@17716
   217
(* for tracing: encloses each string element in brackets. *)
paulson@17716
   218
val concat_with_and = space_implode " & " o map (enclose "(" ")");
paulson@17716
   219
paulson@17484
   220
fun prems_string_of th =
paulson@17716
   221
  concat_with_and (map (Sign.string_of_term (sign_of_thm th)) (prems_of th))
paulson@17484
   222
paulson@17525
   223
fun killChild proc = (Unix.kill(proc, Posix.Signal.kill); Unix.reap proc);
paulson@17525
   224
paulson@17525
   225
fun killChildren procs = List.app (ignore o killChild) procs;
paulson@17502
   226
paulson@17568
   227
 (*************************************************************)
paulson@17568
   228
 (* take an instream and poll its underlying reader for input *)
paulson@17568
   229
 (*************************************************************)
paulson@17568
   230
 
paulson@17568
   231
 fun pollParentInput (fromParentIOD, fromParentStr, toParentStr) = 
paulson@17690
   232
   case OS.IO.pollDesc fromParentIOD of
paulson@17690
   233
      SOME pd =>
paulson@17690
   234
	 (case OS.IO.poll ([OS.IO.pollIn pd], SOME (Time.fromSeconds 2)) of
paulson@17690
   235
	      [] => NONE
paulson@17690
   236
	    | pd''::_ => if OS.IO.isIn pd''
paulson@17690
   237
	 	         then SOME (getCmds (toParentStr, fromParentStr, []))
paulson@17690
   238
	 	         else NONE)
paulson@17568
   239
   | NONE => NONE;
paulson@17568
   240
paulson@17583
   241
(*get the number of the subgoal from the filename: the last digit string*)
paulson@17583
   242
fun number_from_filename s =
paulson@17583
   243
  case String.tokens (not o Char.isDigit) s of
paulson@17690
   244
      [] => (trace "\nWatcher could not read subgoal nunber!!"; raise ERROR)
paulson@17583
   245
    | numbers => valOf (Int.fromString (List.last numbers));
paulson@17583
   246
paulson@17484
   247
fun setupWatcher (thm,clause_arr) = 
paulson@16061
   248
  let
paulson@16061
   249
    (** pipes for communication between parent and watcher **)
paulson@16061
   250
    val p1 = Posix.IO.pipe ()
paulson@16061
   251
    val p2 = Posix.IO.pipe ()
paulson@17317
   252
    fun closep () = 
paulson@17317
   253
	 (Posix.IO.close (#outfd p1); 
paulson@16061
   254
	  Posix.IO.close (#infd p1);
paulson@16061
   255
	  Posix.IO.close (#outfd p2); 
paulson@17317
   256
	  Posix.IO.close (#infd p2))
paulson@16061
   257
    (***********************************************************)
paulson@16061
   258
    (****** fork a watcher process and get it set up and going *)
paulson@16061
   259
    (***********************************************************)
paulson@17317
   260
    fun startWatcher procList =
paulson@17234
   261
     (case  Posix.Process.fork() (***************************************)
paulson@17234
   262
      of SOME pid =>  pid           (* parent - i.e. main Isabelle process *)
paulson@17234
   263
				    (***************************************)
quigley@15642
   264
paulson@17234
   265
				      (*************************)
paulson@17234
   266
       | NONE => let                  (* child - i.e. watcher  *)
paulson@17690
   267
	  val oldchildin = #infd p1   (*************************)
paulson@17690
   268
	  val fromParent = Posix.FileSys.wordToFD 0w0
paulson@17690
   269
	  val oldchildout = #outfd p2
paulson@17690
   270
	  val toParent = Posix.FileSys.wordToFD 0w1
paulson@17690
   271
	  val fromParentIOD = Posix.FileSys.fdToIOD fromParent
paulson@17690
   272
	  val fromParentStr = openInFD ("_exec_in_parent", fromParent)
paulson@17690
   273
	  val toParentStr = openOutFD ("_exec_out_parent", toParent)
paulson@17690
   274
	  val _ = debug ("subgoals forked to startWatcher: "^ prems_string_of thm);
paulson@17568
   275
	 
paulson@17317
   276
	  fun pollChildInput fromStr = 
paulson@17690
   277
	     case getInIoDesc fromStr of
paulson@17690
   278
	       SOME iod => 
paulson@17690
   279
		 (case OS.IO.pollDesc iod of
paulson@17690
   280
		    SOME pd =>
paulson@17690
   281
			let val pd' = OS.IO.pollIn pd
paulson@17690
   282
			in
paulson@17690
   283
			  case OS.IO.poll ([pd'], SOME (Time.fromSeconds 2)) of
paulson@17690
   284
			      [] => false
paulson@17690
   285
			    | pd''::_ => OS.IO.isIn pd''
paulson@17690
   286
			end
paulson@17690
   287
		   | NONE => false)
paulson@17690
   288
	     | NONE => false
quigley@15642
   289
paulson@17690
   290
paulson@17690
   291
	  (* Check all ATP processes currently running for output                 *)
paulson@17690
   292
	  fun checkChildren ([], toParentStr) = []  (* no children to check *)
paulson@17690
   293
	  |   checkChildren (childProc::otherChildren, toParentStr) = 
paulson@17690
   294
	       let val _ = trace ("\nIn check child, length of queue:"^
paulson@17690
   295
			          Int.toString (length (childProc::otherChildren)))
paulson@17568
   296
		   val (childInput,childOutput) = cmdstreamsOf childProc
paulson@17568
   297
		   val child_handle = cmdchildHandle childProc
paulson@17690
   298
		   (* childCmd is the file that the problem is in *)
paulson@17234
   299
		   val childCmd = fst(snd (cmdchildInfo childProc))
paulson@17690
   300
		   val _ = trace ("\nchildCmd = " ^ childCmd)
paulson@17583
   301
		   val sg_num = number_from_filename childCmd
paulson@17234
   302
		   val childIncoming = pollChildInput childInput
paulson@17234
   303
		   val parentID = Posix.ProcEnv.getppid()
paulson@17234
   304
		   val prover = cmdProver childProc
paulson@17484
   305
		   val prems_string = prems_string_of thm
paulson@17234
   306
		   val goalstring = cmdGoal childProc							
paulson@17234
   307
	       in 
paulson@17690
   308
		 trace("\nsubgoals forked to checkChildren: " ^ goalstring);
paulson@17690
   309
		 if childIncoming
paulson@17234
   310
		 then 
paulson@17306
   311
		   (* check here for prover label on child*)
paulson@17690
   312
		   let val _ = trace ("\nInput available from child: " ^
paulson@17690
   313
				      childCmd ^ 
paulson@17746
   314
				      "\ngoalstring is " ^ goalstring)
paulson@17306
   315
		       val childDone = (case prover of
paulson@17488
   316
			   "vampire" => AtpCommunication.checkVampProofFound(childInput, toParentStr, parentID,goalstring, childCmd, clause_arr)  
paulson@17488
   317
			    | "E" => AtpCommunication.checkEProofFound(childInput, toParentStr, parentID,goalstring, childCmd, clause_arr)             
paulson@17484
   318
			  |"spass" => AtpCommunication.checkSpassProofFound(childInput, toParentStr, parentID,goalstring, childCmd, thm, sg_num,clause_arr)  )
paulson@17306
   319
		    in
paulson@17484
   320
		     if childDone
paulson@17306
   321
		     then (* child has found a proof and transferred it *)
paulson@17306
   322
			(* Remove this child and go on to check others*)
paulson@17306
   323
			(Unix.reap child_handle;
paulson@17716
   324
			 OS.FileSys.remove childCmd;
paulson@17306
   325
			 checkChildren(otherChildren, toParentStr))
paulson@17690
   326
		     else (* Keep this child and go on to check others  *)
paulson@17690
   327
		       childProc :: checkChildren (otherChildren, toParentStr)
paulson@17306
   328
		  end
paulson@17690
   329
		else (trace "\nNo child output";
paulson@17690
   330
		      childProc::(checkChildren (otherChildren, toParentStr)))
paulson@17234
   331
	       end
quigley@15642
   332
paulson@17234
   333
	
paulson@17234
   334
     (********************************************************************)                  
paulson@17234
   335
     (* call resolution processes                                        *)
paulson@17234
   336
     (* settings should be a list of strings                             *)
paulson@17234
   337
     (* e.g. ["-t 300", "-m 100000"]         (TextIO.input instr)^                            *)
paulson@17234
   338
     (* takes list of (string, string, string list, string)list proclist *)
paulson@17234
   339
     (********************************************************************)
quigley@16039
   340
quigley@15642
   341
paulson@16061
   342
(*** add subgoal id num to this *)
paulson@17234
   343
	fun execCmds  [] procList = procList
paulson@17422
   344
	|   execCmds  ((prover, goalstring,proverCmd,settings,file)::cmds) procList  =
paulson@17690
   345
	      let val _ = trace 
paulson@17317
   346
	                    (space_implode "\n" 
paulson@17690
   347
	                      (["\nAbout to execute command for goal:",
paulson@17317
   348
	                        goalstring, proverCmd] @ settings @
paulson@17317
   349
	                       [file, Date.toString(Date.fromTimeLocal(Time.now()))]))
paulson@17317
   350
	          val childhandle:(TextIO.instream,TextIO.outstream) Unix.proc  = 
paulson@17234
   351
		       (Unix.execute(proverCmd, (settings@[file])))
paulson@17234
   352
		  val (instr, outstr) = Unix.streamsOf childhandle
paulson@17234
   353
		  val newProcList = (CMDPROC{
paulson@17234
   354
				       prover = prover,
paulson@17234
   355
				       cmd = file,
paulson@17234
   356
				       goalstring = goalstring,
paulson@17234
   357
				       proc_handle = childhandle,
paulson@17234
   358
				       instr = instr,
paulson@17234
   359
				       outstr = outstr }) :: procList
paulson@17234
   360
     
paulson@17690
   361
		  val _ = trace ("\nFinished at " ^
paulson@17690
   362
			         Date.toString(Date.fromTimeLocal(Time.now())))
paulson@17690
   363
	      in execCmds cmds newProcList end
quigley@16039
   364
paulson@16061
   365
paulson@17234
   366
     (****************************************)                  
paulson@17234
   367
     (* call resolution processes remotely   *)
paulson@17234
   368
     (* settings should be a list of strings *)
paulson@17317
   369
     (* e.g. ["-t300", "-m100000"]         *)
paulson@17234
   370
     (****************************************)
paulson@16061
   371
paulson@17234
   372
      (*  fun execRemoteCmds  [] procList = procList
paulson@17422
   373
	|   execRemoteCmds ((prover, goalstring,proverCmd ,settings,file)::cmds) procList  =  
paulson@17422
   374
	      let val  newProcList =  mySshExecuteToList ("/usr/bin/ssh",([prover,goalstring,"-t", "shep"]@[proverCmd]@settings@[file]), procList)
paulson@17422
   375
		  in
paulson@17422
   376
		       execRemoteCmds  cmds newProcList
paulson@17422
   377
		  end
quigley@16039
   378
*)
quigley@15642
   379
paulson@17234
   380
     (**********************************************)                  
paulson@17234
   381
     (* Watcher Loop                               *)
paulson@17234
   382
     (**********************************************)
paulson@17583
   383
         val iterations_left = ref 500;  (*don't let it run forever*)
quigley@15642
   384
paulson@17568
   385
	 fun keepWatching (procList) = 
paulson@17317
   386
	   let fun loop procList =  
paulson@17690
   387
		let val _ = trace ("\nCalling pollParentInput: " ^ 
paulson@17690
   388
			           Int.toString (!iterations_left));
paulson@17568
   389
		    val cmdsFromIsa = pollParentInput 
paulson@17568
   390
		                       (fromParentIOD, fromParentStr, toParentStr)
paulson@17234
   391
		in 
paulson@17690
   392
		   OS.Process.sleep (Time.fromMilliseconds 100);
paulson@17306
   393
		   iterations_left := !iterations_left - 1;
paulson@17568
   394
		   if !iterations_left <= 0 
paulson@17690
   395
		   then 
paulson@17690
   396
		    (trace "\nTimeout: Killing proof processes";
paulson@17568
   397
	             TextIO.output(toParentStr, "Timeout: Killing proof processes!\n");
paulson@17502
   398
		     TextIO.flushOut toParentStr;
paulson@17583
   399
		     killChildren (map cmdchildHandle procList);
paulson@17583
   400
		     exit 0)
paulson@17306
   401
		   else if isSome cmdsFromIsa
paulson@17234
   402
		   then (*  deal with input from Isabelle *)
paulson@17306
   403
		     if getProofCmd(hd(valOf cmdsFromIsa)) = "Kill children" 
paulson@17234
   404
		     then 
paulson@17234
   405
		       let val child_handles = map cmdchildHandle procList 
paulson@17234
   406
		       in
paulson@17234
   407
			  killChildren child_handles;
paulson@17306
   408
			  loop []
paulson@17234
   409
		       end
paulson@17234
   410
		     else
paulson@17306
   411
		       if length procList < 5     (********************)
paulson@17234
   412
		       then                        (* Execute locally  *)
paulson@17234
   413
			 let 
paulson@17234
   414
			   val newProcList = execCmds (valOf cmdsFromIsa) procList
paulson@17568
   415
			   val _ = Posix.ProcEnv.getppid()
paulson@17690
   416
			   val _ = trace "\nJust execed a child"
paulson@17484
   417
			   val newProcList' = checkChildren (newProcList, toParentStr) 
paulson@17234
   418
			 in
paulson@17690
   419
			   trace ("\nOff to keep watching: " ^ 
paulson@17690
   420
			          Int.toString (!iterations_left));
paulson@17306
   421
			   loop newProcList'
paulson@17234
   422
			 end
paulson@17234
   423
		       else  (* Execute remotely              *)
paulson@17234
   424
			     (* (actually not remote for now )*)
paulson@17234
   425
			 let 
paulson@17234
   426
			   val newProcList = execCmds (valOf cmdsFromIsa) procList
paulson@17568
   427
			   val _ = Posix.ProcEnv.getppid()
paulson@17234
   428
			   val newProcList' =checkChildren (newProcList, toParentStr) 
paulson@17234
   429
			 in
paulson@17306
   430
			   loop newProcList'
paulson@17234
   431
			 end
paulson@17234
   432
		   else (* No new input from Isabelle *)
paulson@17317
   433
		     let val newProcList = checkChildren (procList, toParentStr)
paulson@17234
   434
		     in
paulson@17690
   435
		       trace ("\nNo new input, still watching: " ^ 
paulson@17690
   436
			      Int.toString (!iterations_left));
paulson@17306
   437
		       loop newProcList
paulson@17234
   438
		     end
paulson@17234
   439
		 end
paulson@17234
   440
	   in  
paulson@17306
   441
	       loop procList
paulson@17234
   442
	   end
paulson@17234
   443
	   
quigley@15642
   444
paulson@17234
   445
	   in
paulson@17234
   446
	    (***************************)
paulson@17234
   447
	    (*** Sort out pipes ********)
paulson@17234
   448
	    (***************************)
quigley@15642
   449
paulson@17234
   450
	     Posix.IO.close (#outfd p1);
paulson@17234
   451
	     Posix.IO.close (#infd p2);
paulson@17234
   452
	     Posix.IO.dup2{old = oldchildin, new = fromParent};
paulson@17234
   453
	     Posix.IO.close oldchildin;
paulson@17234
   454
	     Posix.IO.dup2{old = oldchildout, new = toParent};
paulson@17234
   455
	     Posix.IO.close oldchildout;
paulson@17234
   456
paulson@17234
   457
	     (***************************)
paulson@17234
   458
	     (* start the watcher loop  *)
paulson@17234
   459
	     (***************************)
paulson@17568
   460
	     keepWatching (procList);
paulson@17234
   461
	     (****************************************************************************)
paulson@17234
   462
(* fake return value - actually want the watcher to loop until killed *)
paulson@17234
   463
	     (****************************************************************************)
paulson@17234
   464
	     Posix.Process.wordToPid 0w0
paulson@17234
   465
	   end);
paulson@17234
   466
     (* end case *)
quigley@15642
   467
quigley@15642
   468
paulson@16061
   469
    val _ = TextIO.flushOut TextIO.stdOut
quigley@15642
   470
paulson@16061
   471
    (*******************************)
paulson@16061
   472
    (***  set watcher going ********)
paulson@16061
   473
    (*******************************)
quigley@15642
   474
paulson@16061
   475
    val procList = []
paulson@17317
   476
    val pid = startWatcher procList
paulson@16061
   477
    (**************************************************)
paulson@16061
   478
    (* communication streams to watcher               *)
paulson@16061
   479
    (**************************************************)
paulson@16061
   480
paulson@16061
   481
    val instr = openInFD ("_exec_in", #infd p2)
paulson@16061
   482
    val outstr = openOutFD ("_exec_out", #outfd p1)
paulson@16061
   483
    
paulson@17568
   484
  in
paulson@17568
   485
   (*******************************)
paulson@17568
   486
   (* close the child-side fds    *)
paulson@17568
   487
   (*******************************)
paulson@17568
   488
    Posix.IO.close (#outfd p2);
paulson@17568
   489
    Posix.IO.close (#infd p1);
paulson@17568
   490
    (* set the fds close on exec *)
paulson@17568
   491
    Posix.IO.setfd (#infd p2, Posix.IO.FD.flags [Posix.IO.FD.cloexec]);
paulson@17568
   492
    Posix.IO.setfd (#outfd p1, Posix.IO.FD.flags [Posix.IO.FD.cloexec]);
paulson@17568
   493
     
paulson@17568
   494
   (*******************************)
paulson@17568
   495
   (* return value                *)
paulson@17568
   496
   (*******************************)
paulson@17568
   497
    PROC{pid = pid, instr = instr, outstr = outstr}
paulson@17568
   498
  end;
quigley@15642
   499
quigley@15642
   500
quigley@15642
   501
quigley@15642
   502
(**********************************************************)
quigley@15642
   503
(* Start a watcher and set up signal handlers             *)
quigley@15642
   504
(**********************************************************)
quigley@16039
   505
paulson@17484
   506
fun killWatcher pid = Posix.Process.kill(Posix.Process.K_PROC pid, Posix.Signal.kill);
quigley@16039
   507
paulson@17488
   508
val killWatcher' = killWatcher o ResLib.pidOfInt;
paulson@17488
   509
quigley@16039
   510
fun reapWatcher(pid, instr, outstr) =
paulson@17484
   511
  (TextIO.closeIn instr; TextIO.closeOut outstr;
paulson@17484
   512
   Posix.Process.waitpid(Posix.Process.W_CHILD pid, []); ())
quigley@15642
   513
paulson@17484
   514
fun createWatcher (thm, clause_arr) =
paulson@17484
   515
 let val (childpid,(childin,childout)) = childInfo (setupWatcher(thm,clause_arr))
paulson@17435
   516
     fun decr_watched() =
paulson@17502
   517
	  (goals_being_watched := !goals_being_watched - 1;
paulson@17435
   518
	   if !goals_being_watched = 0
paulson@17435
   519
	   then 
paulson@17716
   520
	     (debug ("\nReaping a watcher, childpid = "^
paulson@17690
   521
		     LargeWord.toString (Posix.Process.pidToWord childpid));
paulson@17484
   522
	      killWatcher childpid; reapWatcher (childpid,childin, childout))
paulson@17435
   523
	    else ())
paulson@17484
   524
     val _ = debug ("subgoals forked to createWatcher: "^ prems_string_of thm);
paulson@17484
   525
     fun proofHandler n = 
paulson@17484
   526
       let val outcome = TextIO.inputLine childin
paulson@17746
   527
	   val goalstring = valOf (String.fromString (TextIO.inputLine childin))
paulson@17484
   528
	   val _ = debug ("In signal handler. outcome = \"" ^ outcome ^ 
paulson@17484
   529
		        "\"\ngoalstring = " ^ goalstring ^
paulson@17568
   530
		        "\ngoals_being_watched: "^  Int.toString (!goals_being_watched))
paulson@17502
   531
       in 
paulson@17502
   532
	 if String.isPrefix "[" outcome (*indicates a proof reconstruction*)
paulson@17690
   533
	 then (priority (Recon_Transfer.apply_res_thm outcome goalstring);
paulson@17435
   534
	       decr_watched())
paulson@17484
   535
	 else if String.isPrefix "Invalid" outcome
paulson@17746
   536
	 then (priority ("Subgoal is not provable:\n" ^ goalstring);
paulson@17484
   537
	       decr_watched())
paulson@17484
   538
	 else if String.isPrefix "Failure" outcome
paulson@17746
   539
	 then (priority ("Proof attempt failed:\n" ^ goalstring);
paulson@17435
   540
	       decr_watched()) 
paulson@17216
   541
	(* print out a list of rules used from clasimpset*)
paulson@17484
   542
	 else if String.isPrefix "Success" outcome
paulson@17746
   543
	 then (priority (outcome ^ goalstring);
paulson@17435
   544
	       decr_watched())
paulson@17216
   545
	  (* if proof translation failed *)
paulson@17484
   546
	 else if String.isPrefix "Translation failed" outcome
paulson@17746
   547
	 then (priority (outcome ^ goalstring);
paulson@17435
   548
	       decr_watched())
paulson@17690
   549
	 else (priority "System error in proof handler";
paulson@17435
   550
	       decr_watched())
paulson@17484
   551
       end
paulson@17484
   552
 in IsaSignal.signal (IsaSignal.usr2, IsaSignal.SIG_HANDLE proofHandler);
paulson@17216
   553
    (childin, childout, childpid)
paulson@16100
   554
  end
quigley@15642
   555
quigley@15642
   556
end (* structure Watcher *)