summaryrefslogtreecommitdiffstats
path: root/jack/src/com/android/jack/server/Server.java
blob: 65bd99a3e87d1152cf430fb360953f117553437c (plain)
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
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.jack.server;

import com.android.sched.util.config.cli.TokenIterator;
import com.android.sched.util.file.AbstractStreamFile;
import com.android.sched.util.file.CannotSetPermissionException;
import com.android.sched.util.file.FileOrDirectory;
import com.android.sched.util.file.FileOrDirectory.ChangePermission;
import com.android.sched.util.file.FileOrDirectory.Permission;
import com.android.sched.util.file.OutputStreamFile;
import com.android.sched.util.location.FileLocation;
import com.android.sched.util.location.NoLocation;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;

/**
 * XXX
 */
public class Server {
  @Nonnull
  private static ServerTask service = new ServerTask() {
    @Nonnull
    private final Random rnd = new Random();

    @Override
    public int run(@Nonnull PrintStream out, @Nonnull PrintStream err, @Nonnull File workingDir,
        @Nonnull TokenIterator args) {
      String cmd = null;
      try {
        args.hasNext();
        cmd = args.next();
      } catch (Throwable e) {
        e.printStackTrace();
      }

      out.println("Pre-test stdout for '" + workingDir.getPath() + "'");
      err.println("Pre-test stderr for '" + cmd + "'");

      try {
        Thread.sleep(rnd.nextInt(30000));
      } catch (InterruptedException e) {
        // Doesn't matter
      }

      out.println("Post-test stdout for '" + workingDir.getPath() + "'");
      err.println("Post-test stderr for '" + cmd + "'");

      return rnd.nextInt(30);
    }
  };

  @Nonnull
  private static Logger logger = Logger.getLogger(Server.class.getSimpleName());

  private static final int CMD_IDX_CMD  = 0;
  private static final int CMD_IDX_OUT  = 1;
  private static final int CMD_IDX_ERR  = 2;
  private static final int CMD_IDX_EXIT = 3;
  private static final int CMD_IDX_CLI  = 4;
  private static final int CMD_IDX_END  = 5;

  private static final int CLI_IDX_MAX     = 0;
  private static final int CLI_IDX_TIEMOUT = 1;
  private static final int CLI_IDX_FIFO    = 2;
  private static final int CLI_IDX_END     = 3;

  @Nonnull
  private static File fifo;
  @CheckForNull
  private static LineNumberReader in;

  private static int timeout;

  @Nonnull
  private static AtomicInteger nbMax = new AtomicInteger(0);
  @Nonnull
  private static AtomicLong nbCurrent = new AtomicLong(0);;

  public static void main(String[] args) throws InterruptedException {
    if (args.length != CLI_IDX_END) {
      logger.log(Level.SEVERE, "Usage: <max-compile> <timeout-s> <path-fifo>");
      abort();
    }

    int nbInstance = 0;
    try {
      nbInstance = Integer.parseInt(args[CLI_IDX_MAX]);
    } catch (NumberFormatException e) {
      logger.log(Level.SEVERE, "Cannot parse instance count '" + args[CLI_IDX_MAX] + "'");
      abort();
    }

    try {
      timeout = Integer.parseInt(args[CLI_IDX_TIEMOUT]) * 1000;
    } catch (NumberFormatException e) {
      logger.log(Level.SEVERE, "Cannot parse timeout '" + args[CLI_IDX_TIEMOUT] + "'");
      abort();
    }

    fifo = new File(args[CLI_IDX_FIFO]);
    if (fifo.canWrite()) {
      logger.log(Level.WARNING, "Already running, aborting");
      abort();
    }

    Runtime.getRuntime().addShutdownHook(new Thread(){
      @Override
      public void run() {
        cancelTimer();
        shutdownFifo();
      }
    });

    try {
      AbstractStreamFile.check(fifo, new FileLocation(fifo));
    } catch (IOException e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
      abort();
    }

    startFifo();
    try {
      in = new LineNumberReader(new FileReader(fifo));
    } catch (FileNotFoundException e) {
      throw new AssertionError(e);
    }

    logger.log(Level.INFO, "Starting server on '" + fifo.getPath() + "'");
    ExecutorService executor = Executors.newFixedThreadPool(nbInstance);
    for (int i = 0; i < nbInstance; i++) {
      logger.log(Level.INFO, "Launching task #" + i);
      executor.execute(new Task());
    }

    executor.shutdown();
    executor.awaitTermination(1, TimeUnit.HOURS);

    logger.log(Level.INFO, "Shutdown server");
    logger.log(Level.INFO, "# service runs " + nbCurrent.get());
  }

  /**
   * STOPSHIP
   */
  public static class Task implements Runnable {
    @Override
    public void run() {
      while (true) {
        String line;

        try {
          line = getLine();
          logger.log(Level.INFO, "Read command '" + line + "'");
        } catch (IOException e) {
          logger.log(Level.INFO, "Shutdown task");
          return;
        }

        String[] command = line.split(" ");

        if (command[CMD_IDX_CMD].equals("-")) {
          cancelTimer();
          shutdownFifo();
          continue;
        }

        if (!command[CMD_IDX_CMD].equals("+")) {
          logger.log(Level.SEVERE, "Command error '" + line + "'");
          continue;
        }

        if (command.length != CMD_IDX_END) {
          logger.log(Level.SEVERE, "Command format error '" + line + "'");
          continue;
        }

        logger.log(Level.INFO, "Open standard output '" + command[CMD_IDX_OUT] + "'");
        PrintStream out = null;
        try {
          out = new OutputStreamFile(command[CMD_IDX_OUT]).getPrintStream();
        } catch (IOException e) {
          logger.log(Level.SEVERE, e.getMessage(), e);
          continue;
        }

        logger.log(Level.INFO, "Open standard error '" + command[CMD_IDX_ERR] + "'");
        PrintStream err = null;
        try {
          err = new OutputStreamFile(command[CMD_IDX_ERR]).getPrintStream();
        } catch (IOException e) {
          logger.log(Level.SEVERE, e.getMessage(), e);
          continue;
        }

        logger.log(Level.INFO, "Parse command line");
        TokenIterator args = new TokenIterator(new NoLocation(), "@" + command[CMD_IDX_CLI]);
        args.allowFileReferenceInFile();

        if (!args.hasNext()) {
          logger.log(Level.WARNING, "Cli format error");
          continue;
        }
        String workingDir;
        try {
          workingDir = args.next();
        } catch (IOException e) {
          logger.log(Level.WARNING, "Cli format error");
          continue;
        }

        if (nbMax.getAndIncrement() == 0) {
          cancelTimer();
        }

        int code;
        try {
          logger.log(Level.INFO, "Run service");
          nbCurrent.incrementAndGet();
          code = service.run(out, err, new File(workingDir), args);
        } finally {
          if (nbMax.decrementAndGet() == 0) {
            startTimer();
          }
        }

        assert out != null;
        out.close();
        assert err != null;
        err.close();

        try {
          logger.log(Level.INFO, "Open exit fifo  '" + command[CMD_IDX_EXIT] + "'");
          PrintStream exit = new OutputStreamFile(command[CMD_IDX_EXIT]).getPrintStream();
          logger.log(Level.INFO, "Write exit code '" + code + "'");
          exit.println(code);
          exit.close();
        } catch (IOException e) {
          logger.log(Level.SEVERE, e.getMessage(), e);
          continue;
        }

      }
    }
  }

  @Nonnull
  private static Object lockRead = new Object();

  @Nonnull
  public static String getLine() throws IOException {
    synchronized (lockRead) {
      String str = in.readLine();
      while (str == null) {
        try {
          in.close();
        } catch (IOException e1) {
          // Best effort
        }

        in = new LineNumberReader(new FileReader(fifo));
        str = in.readLine();
      }

      return str;
    }
  }

  private static void startFifo() {
    logger.log(Level.FINE, "Start FIFO");

    try {
      FileOrDirectory.setPermissions(fifo, new FileLocation(fifo),
          Permission.READ | Permission.WRITE, ChangePermission.OWNER);
    } catch (CannotSetPermissionException e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
      abort();
    }
  }

  private static void shutdownFifo() {
    OutputStream out = null;

    logger.log(Level.FINE, "Shutdown FIFO");

    try {
      out = new FileOutputStream(fifo);
    } catch (FileNotFoundException e) {
      // Best effort
    }

    try {
      FileOrDirectory.unsetPermissions(fifo, new FileLocation(fifo), Permission.READ
          | Permission.WRITE, ChangePermission.OWNER);
    } catch (CannotSetPermissionException e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
      abort();
    }

    if (out != null) {
      try {
        out.close();
      } catch (IOException e) {
        // Best effort
      }
    }
  }

  private static void abort() {
    System.exit(1);
  }

  @CheckForNull
  private static Timer timer;

  @Nonnull
  private static Object lockTimer = new Object();

  private static void startTimer() {
    synchronized (lockTimer) {
      if (timer != null) {
        cancelTimer();
      }

      logger.log(Level.INFO, "Start timer");

      timer = new Timer("jack-server-timeout");
      timer.schedule(new TimerTask() {
        @Override
        public void run() {
          shutdownFifo();
          cancelTimer();
        }
      }, timeout);
    }
  }

  private static void cancelTimer() {
    synchronized (lockTimer) {
      if (timer != null) {
        logger.log(Level.INFO, "Cancel timer");

        timer.cancel();
        timer.purge();
        timer = null;
      }
    }
  }
}