summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/nsc/CompileSocket.scala
blob: 1e9dcfb2daf86789eb015fdf826a1d80afd03332 (plain) (blame)
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
/* NSC -- new Scala compiler
 * Copyright 2005-2009 LAMP/EPFL
 * @author  Martin Odersky
 */
// $Id$

package scala.tools.nsc

import java.lang.{Thread, System, Runtime}
import java.lang.NumberFormatException
import java.io.{File, IOException, PrintWriter, FileOutputStream}
import java.io.{BufferedReader, FileReader}
import java.util.regex.Pattern
import java.net._

/** This class manages sockets for the fsc offline compiler.  */
class CompileSocket {
  protected def compileClient: StandardCompileClient = CompileClient //todo: lazy val

  /** The prefix of the port identification file, which is followed
   *  by the port number.
   */
  protected def dirName = "scalac-compile-server-port" //todo: lazy val

  protected def cmdName = Properties.cmdName //todo: lazy val

  /** The vm part of the command to start a new scala compile server */
  protected val vmCommand =
    Properties.scalaHome match {
      case null =>
        cmdName
      case dirname =>
        val trial = new File(new File(dirname, "bin"), cmdName)
        if (trial.canRead)
          trial.getPath
        else
          cmdName
    }

  /** The class name of the scala compile server */
  protected val serverClass = "scala.tools.nsc.CompileServer"

  /** A regular expression for checking compiler output for errors */
  val errorRegex = ".*(errors? found|don't know|bad option).*"

  /** A Pattern object for checking compiler output for errors */
  val errorPattern = Pattern.compile(errorRegex)

  protected def error(msg: String) = System.err.println(msg)

  protected def fatal(msg: String) = {
    error(msg)
    exit(1)
  }

  protected def info(msg: String) =
    if (compileClient.verbose) System.out.println(msg)

  /** A temporary directory to use */
  val tmpDir = {
    val totry = List(
        ("scala.home", List("var", "scala-devel")),
        ("user.home", List("tmp")),
        ("java.io.tmpdir", Nil))

    /** Expand a property-extensions pair into a complete File object */
    def expand(trial: (String, List[String])): Option[File] = {
      val (topdirProp, extensions) = trial
      val topdir = System.getProperty(topdirProp)
      if (topdir eq null)
        return None

      val fulldir =
        extensions.foldLeft[File](new File(topdir))(
            (dir,ext) => new File(dir, ext))

      Some(fulldir)
    }

    /** Try to create directory f, and then see if it can
     *  be written into. */
    def isDirWritable(f: File): Boolean = {
      f.mkdirs()
      f.isDirectory && f.canWrite
    }

    val potentials =
      for {
        trial <- totry
        val expanded = expand(trial)
        if !expanded.isEmpty
        if isDirWritable(expanded.get)
      }
      yield expanded.get

    if (potentials.isEmpty)
      fatal("Could not find a directory for temporary files")
    else {
      val d = potentials.head
      d.mkdirs
      info("[Temp directory: " + d + "]")
      d
    }
  }

  /* A directory holding port identification files */
  val portsDir =  new File(tmpDir, dirName)
  portsDir.mkdirs

  /** Maximum number of polls for an available port */
  private val MaxAttempts = 100

  /** Time (in ms) to sleep between two polls */
  private val sleepTime = 20

  /** The command which starts the compile server, given vm arguments.
    *
    *  @param vmArgs  the argument string to be passed to the java or scala command
    *                 the string must be either empty or start with a ' '.
    */
  private def serverCommand(vmArgs: String): String =
    vmCommand + vmArgs + " " + serverClass

  /** Start a new server; returns true iff it succeeds */
  private def startNewServer(vmArgs: String) {
    val cmd = serverCommand(vmArgs)
    info("[Executed command: " + cmd + "]")
    try {
      Runtime.getRuntime().exec(cmd)
//      val exitVal = proc.waitFor()
//      info("[Exit value: " + exitVal + "]")
    } catch {
      case ex: IOException =>
        fatal("Cannot start compilation daemon." +
              "\ntried command: " + cmd)
    }
  }

  /** The port identification file */
  def portFile(port: Int) = new File(portsDir, port.toString())

  /** Poll for a server port number; return -1 if none exists yet */
  private def pollPort(): Int = {
    val hits = portsDir.listFiles()
    if (hits.length == 0) -1
    else
      try {
        for (i <- 1 until hits.length) hits(i).delete()
        hits(0).getName.toInt
      } catch {
        case ex: NumberFormatException =>
          fatal(ex.toString() +
                "\nbad file in temp directory: " +
                hits(0).getAbsolutePath() +
                "\nplease remove the file and try again")
      }
  }

  /** Get the port number to which a scala compile server is connected;
   *  If no server is running yet, then create one.
   */
  def getPort(vmArgs: String): Int = {
    var attempts = 0
    var port = pollPort()

    if (port < 0)
      startNewServer(vmArgs)
    while (port < 0 && attempts < MaxAttempts) {
      attempts += 1
      Thread.sleep(sleepTime)
      port = pollPort()
    }
    info("[Port number: " + port + "]")
    if (port < 0)
      fatal("Could not connect to compilation daemon.")
    port
  }

  /** Set the port number to which a scala compile server is connected */
  def setPort(port: Int) {
    try {
      val f = new PrintWriter(new FileOutputStream(portFile(port)))
      f.println(new java.security.SecureRandom().nextInt.toString)
      f.close()
    } catch {
      case ex: /*FileNotFound+Security*/Exception =>
        fatal("Cannot create file: " +
              portFile(port).getAbsolutePath())
    }
  }

  /** Delete the port number to which a scala compile server was connected */
  def deletePort(port: Int) { portFile(port).delete() }

  /** Get a socket connected to a daemon.  If create is true, then
    * create a new daemon if necessary.  Returns null if the connection
    * cannot be established.
    */
  def getOrCreateSocket(vmArgs: String, create: Boolean): Socket = {
    val nAttempts = 49  // try for about 5 seconds
    def getsock(attempts: Int): Socket =
      if (attempts == 0) {
        error("Unable to establish connection to compilation daemon")
        null
      } else {
        val port = if(create) getPort(vmArgs) else pollPort()
        if(port < 0) return null
        val hostAdr = InetAddress.getLocalHost()
        try {
          val result = new Socket(hostAdr, port)
          info("[Connected to compilation daemon at port " + port + "]")
          result
        } catch {
          case e: /*IO+Security*/Exception =>
            info(e.toString)
            info("[Connecting to compilation daemon at port "  +
                 port + " failed; re-trying...]")

            if (attempts % 2 == 0)
              portFile(port).delete // 50% chance to stop trying on this port

            Thread.sleep(100) // delay before retrying

            getsock(attempts - 1)
        }
      }
    getsock(nAttempts)
  }

  /** Same as getOrCreateSocket(vmArgs, true). */
  def getOrCreateSocket(vmArgs: String): Socket =
    getOrCreateSocket(vmArgs, true)

  def getSocket(serverAdr: String): Socket = {
    val cpos = serverAdr indexOf ':'
    if (cpos < 0)
      fatal("Malformed server address: " + serverAdr + "; exiting")
    else {
      val hostName = serverAdr.substring(0, cpos)
      val port = try {
        serverAdr.substring(cpos+1).toInt
      } catch {
        case ex: Throwable =>
          fatal("Malformed server address: " + serverAdr + "; exiting")
      }
      getSocket(hostName, port)
    }
  }

  def getSocket(hostName: String, port: Int): Socket =
    try {
      new Socket(hostName, port)
    } catch {
      case e: /*IO+Security*/Exception =>
        fatal("Unable to establish connection to server " +
              hostName + ":" + port + "; exiting")
    }

  def getPassword(port: Int): String = {
    val ff=portFile(port)
    val f = new BufferedReader(new FileReader(ff))
    // allow some time for the server to start up
    var retry=50
    while (ff.length()==0 && retry>0) {
      Thread.sleep(100)
      retry-=1
    }
    if (ff.length()==0) {
      ff.delete()
      fatal("Unable to establish connection to server.")
    }
    val result = f.readLine()
    f.close()
    result
  }
}


object CompileSocket extends CompileSocket