-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathExternalJSRun.scala
199 lines (165 loc) · 5.94 KB
/
ExternalJSRun.scala
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
/*
* Scala.js JS Envs (https://github.com/scala-js/scala-js-js-envs)
*
* Copyright EPFL.
*
* Licensed under Apache License 2.0
* (https://www.apache.org/licenses/LICENSE-2.0).
*
* See the NOTICE file distributed with this work for
* additional information regarding copyright ownership.
*/
package org.scalajs.jsenv
import java.io.{IOException, OutputStream}
import scala.concurrent.{Future, Promise}
import scala.util.control.NonFatal
/** Support for creating a [[JSRun]] via an external process. */
object ExternalJSRun {
/** Starts a [[JSRun]] in an external process.
*
* [[ExternalJSRun]] redirects the I/O of the external process according to
* [[Config#runConfig]].
*
* @see [[supports]] for the exact options it currently supports.
*
* @param command Binary to execute including arguments.
* @param config Configuration.
* @param input Function to inform about creation of stdin for the external process.
* `input` should feed the required stdin to the passed
* [[java.io.OutputStream OutputStream]] and close it.
*/
def start(command: List[String], config: Config)(
input: OutputStream => Unit): JSRun = {
require(command.nonEmpty, "command may not be empty")
try {
val process = startProcess(command, config.env, config.runConfig)
try {
notifyOutputStreams(config.runConfig, process)
new ExternalJSRun(process, input, config.closingFails)
} catch {
case t: Throwable =>
process.destroyForcibly()
throw t
}
} catch {
case NonFatal(t) => JSRun.failed(t)
}
}
/** Informs the given [[RunConfig.Validator]] about the options an
* [[ExternalJSRun]] supports.
*
* Use this method to automatically benefit from improvements to
* [[ExternalJSRun]] without modifying the client [[JSEnv]].
*
* Currently, this calls
* - [[RunConfig.Validator#supportsInheritIO supportsInheritIO]]
* - [[RunConfig.Validator#supportsOnOutputStream supportsOnOutputStream]]
*
* Note that in consequence, a [[JSEnv]] ''may not'' handle these options if
* it uses [[ExternalJSRun]].
*/
def supports(validator: RunConfig.Validator): RunConfig.Validator = {
validator
.supportsInheritIO()
.supportsOnOutputStream()
}
/** Configuration for a [[ExternalJSRun]]
*
* @param env Additional environment variables. The environment of the host
* JVM is inherited.
* @param runConfig Configuration for the run. See [[ExternalJSRun.supports]]
* for details about the currently supported configuration.
* @param closingFails Whether calling [[JSRun#close]] on a still running
* [[JSRun]] fails the run. While this defaults to true, [[JSEnv]]s that
* do not support automatic termination (and do not expect the JS program
* itself to explicitly terminate) typically want to set this to false
* (at least for non-com runs), since otherwise there is no successful
* way of terminating a [[JSRun]].
*/
final class Config private (
val env: Map[String, String],
val runConfig: RunConfig,
val closingFails: Boolean
) {
private def this() = {
this(
env = Map.empty,
runConfig = RunConfig(),
closingFails = true)
}
def withEnv(env: Map[String, String]): Config =
copy(env = env)
def withRunConfig(runConfig: RunConfig): Config =
copy(runConfig = runConfig)
def withClosingFails(closingFails: Boolean): Config =
copy(closingFails = closingFails)
private def copy(env: Map[String, String] = env,
runConfig: RunConfig = runConfig,
closingFails: Boolean = closingFails) = {
new Config(env, runConfig, closingFails)
}
}
object Config {
def apply(): Config = new Config()
}
private def notifyOutputStreams(config: RunConfig, process: Process) = {
def opt[T](b: Boolean, v: => T) = if (b) Some(v) else None
val out = opt(!config.inheritOutput, process.getInputStream())
val err = opt(!config.inheritError, process.getErrorStream())
config.onOutputStream.foreach(f => f(out, err))
}
private def startProcess(command: List[String], env: Map[String, String],
config: RunConfig) = {
val builder = new ProcessBuilder(command: _*)
if (config.inheritOutput)
builder.redirectOutput(ProcessBuilder.Redirect.INHERIT)
if (config.inheritError)
builder.redirectError(ProcessBuilder.Redirect.INHERIT)
for ((name, value) <- env)
builder.environment().put(name, value)
config.logger.debug("Starting process: " + command.mkString(" "))
builder.start()
}
final case class NonZeroExitException(retVal: Int)
extends Exception(s"exited with code $retVal")
final case class ClosedException()
extends Exception("Termination was requested by user")
}
private final class ExternalJSRun(process: Process,
input: OutputStream => Unit, closingFails: Boolean) extends JSRun {
private[this] val promise = Promise[Unit]()
@volatile
private[this] var closing = false
def future: Future[Unit] = promise.future
def close(): Unit = {
closing = true
process.destroyForcibly()
}
private val waiter = new Thread {
setName("ExternalJSRun waiter")
override def run(): Unit = {
try {
try {
input(process.getOutputStream())
} catch {
case _: IOException if closing =>
// We got closed while writing. Exception is expected.
}
val retVal = process.waitFor()
if (retVal == 0 || closing && !closingFails)
promise.success(())
else if (closing)
promise.failure(new ExternalJSRun.ClosedException)
else
promise.failure(new ExternalJSRun.NonZeroExitException(retVal))
} catch {
case t: Throwable =>
process.destroyForcibly()
promise.failure(t)
if (!NonFatal(t))
throw t
}
}
}
waiter.start()
}