/
ToreeLauncher.scala
314 lines (257 loc) · 10.4 KB
/
ToreeLauncher.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
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
/**
* Copyright (c) Jupyter Development Team.
* Distributed under the terms of the Modified BSD License.
*/
package launcher
import java.io.{BufferedWriter, File, FileWriter, PrintStream}
import java.nio.file.{Files, Paths}
import java.net.{InetAddress, ServerSocket, Socket}
import org.apache.toree.Main
import play.api.libs.json._
import java.lang.management.ManagementFactory
import scala.io.BufferedSource
import scala.collection.mutable.ArrayBuffer
import sun.misc.Signal
import launcher.utils.{SecurityUtils, SocketUtils}
import org.apache.toree.utils.LogLike
object ToreeLauncher extends LogLike {
val minPortRangeSize = sys.env.getOrElse("MIN_PORT_RANGE_SIZE", "1000").toInt
val kernelTempDir : String = "jupyter-kernel"
var profilePath : String = _
var kernelId : String = _
var portLowerBound : Int = -1
var portUpperBound : Int = -1
var responseAddress : String = _
var publicKey : String = _
var alternateSigint : String = _
var initMode : String = "lazy"
var toreeArgs = ArrayBuffer[String]()
private def pathExists(filePath : String) : Boolean =
if (filePath == null) false
else Files.exists(Paths.get(filePath))
private def writeToFile(outputPath : String, content : String): Unit = {
val file = new File(outputPath)
if(!pathExists(file.getParentFile.toString)) {
file.getParentFile.mkdirs // mkdir if not exists
}
val bw = new BufferedWriter(new FileWriter(file))
try{
bw.write(content)
} finally {
bw.close()
}
}
private def initPortRange(portRange: String): Unit = {
val ports = portRange.split("\\.\\.")
this.portLowerBound = ports(0).toInt
this.portUpperBound = ports(1).toInt
logger.info("Port Range: lower bound ( %s ) / upper bound ( %s )"
.format(this.portLowerBound, this.portUpperBound))
if (this.portLowerBound != this.portUpperBound) { // Range of zero disables port restrictions
if (this.portLowerBound < 0 || this.portUpperBound < 0 ||
(this.portUpperBound - this.portLowerBound < minPortRangeSize)) {
logger.error("Invalid port range, use --port-range <LowerBound>..<UpperBound>, " +
"range must be >= MIN_PORT_RANGE_SIZE ($minPortRangeSize)")
sys.exit(-1)
}
}
}
private def initArguments(args: Array[String]): Unit = {
logger.info("Toree launcher arguments (initial):")
args.foreach(logger.info(_))
logger.info("---------------------------")
// Walk the arguments, collecting launcher options along the way and buildup a
// new toree arguments list. There's got to be a better way to do this.
var i = 0
while ( i < args.length ) {
var arg: String = args(i)
arg match {
// Alternate sigint is a straight pass-thru to toree
case "--alternate-sigint" =>
i += 1
alternateSigint = args(i).trim
toreeArgs += arg
toreeArgs += alternateSigint
// Initialization mode requires massaging for toree
case "--spark-context-initialization-mode" =>
i += 1
initMode = args(i).trim
initMode match {
case "none" =>
toreeArgs += "--nosparkcontext"
case _ =>
toreeArgs += "--spark-context-initialization-mode"
toreeArgs += initMode
}
// Port range doesn't apply to toree, consume here
case "--port-range" =>
i += 1
initPortRange(args(i).trim)
// Response address doesn't apply to toree, consume here
case "--response-address" =>
i += 1
responseAddress = args(i).trim
// kernel id doesn't apply to toree, consume here
case "--kernel-id" =>
i += 1
kernelId = args(i).trim
// Public key doesn't apply to toree, consume here
case "--public-key" =>
i += 1
publicKey = args(i).trim
// All other arguments should pass-thru to toree
case _ => toreeArgs += args(i).trim
}
i += 1
}
}
// Borrowed from toree to avoid dependency
private def deleteDirRecur(file: File): Unit = {
// delete directory recursively
if (file != null){
if (file.isDirectory){
file.listFiles.foreach(deleteDirRecur)
}
if (file.exists){
file.delete
}
}
}
private def determineConnectionFile(connectionFile: String, kernelId: String): String = {
// We know the connection file does not exist, so create a temporary directory
// and derive the filename from kernelId, if not null.
// If kernelId is null, then use the filename in the connectionFile.
val tmpPath = Files.createTempDirectory(kernelTempDir)
// tmpPath.toFile.deleteOnExit() doesn't appear to work, use system hook
sys.addShutdownHook{
deleteDirRecur(tmpPath.toFile)
}
val fileName = if (kernelId != null) "kernel-" + kernelId + ".json"
else Paths.get(connectionFile).getFileName.toString
val newPath = Paths.get(tmpPath.toString, fileName)
val newConnectionFile = newPath.toString
toreeArgs += "--profile"
toreeArgs += newConnectionFile
newConnectionFile
}
private def getPID : String = {
// Return the current process ID. If not an integer string, server will ignore.
ManagementFactory.getRuntimeMXBean.getName.split('@')(0)
}
private def initProfile(args : Array[String]): ServerSocket = {
var commSocket : ServerSocket = null
initArguments(args)
if (kernelId == null) {
logger.error("Parameter '--kernel-id' must be provided - exiting!")
sys.exit(-1)
}
if (publicKey == null) {
logger.error("Parameter '--public-key' must be provided - exiting!")
sys.exit(-1)
}
profilePath = determineConnectionFile(profilePath, kernelId)
logger.info("The profile %s doesn't exist, now creating it...".format(profilePath))
val content = KernelProfile.createJsonProfile(this.portLowerBound, this.portUpperBound)
writeToFile(profilePath, content)
if (pathExists(profilePath)) {
logger.info("%s saved".format(profilePath))
} else {
logger.error("Failed to create: %s".format(profilePath))
sys.exit(-1)
}
var connectionJson = Json.parse(content)
// Now need to also return the PID info in connection JSON
connectionJson = connectionJson.as[JsObject] ++ Json.obj("pid" -> getPID)
// Add kernelId
connectionJson = connectionJson.as[JsObject] ++ Json.obj("kernel_id" -> kernelId)
// Server wants to establish socket communication. Create socket and
// convey port number back to the server.
commSocket = SocketUtils.findSocket(this.portLowerBound, this.portUpperBound)
connectionJson = connectionJson.as[JsObject] ++ Json.obj("comm_port" -> commSocket.getLocalPort)
val jsonContent = Json.toJson(connectionJson).toString()
if (responseAddress != null){
logger.info("JSON Payload: '%s'".format(jsonContent))
val payload = SecurityUtils.encrypt(publicKey, jsonContent)
logger.info("Encrypted Payload: '%s'".format(payload))
SocketUtils.writeToSocket(responseAddress, payload)
}
commSocket
}
private def getServerRequest(commSocket : ServerSocket): String = {
val s = commSocket.accept()
val data = new BufferedSource(s.getInputStream).getLines.mkString
s.close()
data
}
private def getReconciledSignalName(sigNum: Int): String = {
// To raise the signal, we must map the signal number back to the appropriate
// name as follows: Take the common case and assume interrupt and check if an
// alternate interrupt signal has been given. If sigNum = 9, use "TERM", else
// if no alternate has been provided use "INT". Note that use of SIGINT won't
// get received because the JVM won't propagate to background threads, buy it's
// the best we can do. We'll still issue a warning in the log.
require(sigNum > 0, "sigNum must be greater than zero")
if (sigNum == 9) "TERM"
else {
if (alternateSigint == null) {
logger.warn("--alternate-sigint is not defined and signum %d has been " +
"requested. Using SIGINT, which probably won't get received due to JVM " +
"preventing interrupts on background processes. " +
"Define --alternate-sigint using __TOREE_OPTS__."
.format(sigNum))
"INT"
}
else alternateSigint
}
}
private def serverListener(commSocket : ServerSocket): Unit = {
var stop = false
while (!stop) {
val requestData = getServerRequest(commSocket)
// Handle each of the requests. Note that we do not make an assumption that these are
// mutually exclusive - although that will probably be the case for now. Over time,
// this should probably get refactored into a) better scala and b) token/classes for
// each request.
val requestJson = Json.parse(requestData).as[JsObject].value
// Signal the kernel...
if ( requestJson.contains("signum")) {
val sigNum = requestJson("signum").asInstanceOf[JsNumber].value.toInt
if ( sigNum > 0 ) {
// If sigNum anything but 0 (for poll), use Signal.raise(signal) to signal the kernel.
val sigName = getReconciledSignalName(sigNum)
val sigToRaise = new Signal(sigName)
logger.info("Server listener raising signal: '%s' (%d) for signum: %d".
format(sigToRaise.getName, sigToRaise.getNumber, sigNum))
Signal.raise(sigToRaise)
}
}
// Stop the listener...
if ( requestJson.contains("shutdown")) {
val shutdown = requestJson("shutdown").asInstanceOf[JsNumber].value.toInt
if ( shutdown == 1 ) {
// The server has been instructed to shutdown the kernel, so let's stop
// the listener so that it doesn't interfere with poll() calls.
logger.info("Stopping server listener.")
stop = true
}
}
}
}
def main(args: Array[String]) {
val commSocket = initProfile(args)
// if commSocket is not null, start a thread to listen on socket
if ( commSocket != null ){
val serverListenerThread = new Thread {
override def run() {
serverListener(commSocket)
}
}
logger.info("Starting server listener...")
serverListenerThread.start()
}
logger.info("Toree kernel arguments (final):")
toreeArgs.foreach(logger.info(_))
logger.info("---------------------------")
Main.main(toreeArgs.toArray)
}
}