1 /* 2 * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 25 /* @test 26 * @bug 4607272 6814948 6842687 27 * @summary Unit test for AsynchronousFileChannel#lock method 28 */ 29 30 import java.net.*; 31 import java.nio.ByteBuffer; 32 import java.nio.charset.Charset; 33 import java.nio.file.*; 34 import static java.nio.file.StandardOpenOption.*; 35 import java.nio.channels.*; 36 import java.io.File; 37 import java.io.IOException; 38 import java.io.InputStream; 39 import java.util.Random; 40 import java.util.concurrent.*; 41 42 public class Lock { 43 44 static final Random rand = new Random(); 45 46 public static void main(String[] args) throws Exception { 47 if (args.length > 0 && args[0].equals("-lockslave")) { 48 int port = Integer.parseInt(args[1]); 49 runLockSlave(port); 50 System.exit(0); 51 } 52 53 LockSlaveMirror slave = startLockSlave(); 54 try { 55 56 // create temporary file 57 File blah = File.createTempFile("blah", null); 58 blah.deleteOnExit(); 59 60 // run tests 61 testLockProtocol(blah, slave); 62 testAsyncClose(blah, slave); 63 64 // eagerly clean-up 65 blah.delete(); 66 67 } finally { 68 slave.shutdown(); 69 } 70 } 71 72 // test locking protocol 73 static void testLockProtocol(File file, LockSlaveMirror slave) 74 throws Exception 75 { 76 FileLock fl; 77 78 // slave VM opens file and acquires exclusive lock 79 slave.open(file.getPath()).lock(); 80 81 AsynchronousFileChannel ch = AsynchronousFileChannel 82 .open(file.toPath(), READ, WRITE); 83 84 // this VM tries to acquire lock 85 // (lock should not be acquire until released by slave VM) 86 Future<FileLock> result = ch.lock(); 87 try { 88 result.get(2, TimeUnit.SECONDS); 89 throw new RuntimeException("Timeout expected"); 90 } catch (TimeoutException x) { 91 } 92 93 // slave VM releases lock 94 slave.unlock(); 95 96 // this VM should now acquire lock 97 fl = result.get(); 98 fl.release(); 99 100 // slave VM acquires lock on range 101 slave.lock(0, 10, false); 102 103 // this VM acquires lock on non-overlapping range 104 fl = ch.lock(10, 10, false).get(); 105 fl.release(); 106 107 // done 108 ch.close(); 109 slave.close(); 110 } 111 112 // test close of channel with outstanding lock operation 113 static void testAsyncClose(File file, LockSlaveMirror slave) throws Exception { 114 // slave VM opens file and acquires exclusive lock 115 slave.open(file.getPath()).lock(); 116 117 for (int i=0; i<100; i++) { 118 AsynchronousFileChannel ch = AsynchronousFileChannel 119 .open(file.toPath(), READ, WRITE); 120 121 // try to lock file (should not complete because file is locked by slave) 122 Future<FileLock> result = ch.lock(); 123 try { 124 result.get(rand.nextInt(100), TimeUnit.MILLISECONDS); 125 throw new RuntimeException("Timeout expected"); 126 } catch (TimeoutException x) { 127 } 128 129 // close channel with lock operation outstanding 130 ch.close(); 131 132 // operation should complete with AsynchronousCloseException 133 try { 134 result.get(); 135 throw new RuntimeException("ExecutionException expected"); 136 } catch (ExecutionException x) { 137 if (!(x.getCause() instanceof AsynchronousCloseException)) { 138 x.getCause().printStackTrace(); 139 throw new RuntimeException("AsynchronousCloseException expected"); 140 } 141 } 142 } 143 144 slave.close(); 145 } 146 147 // starts a "lock slave" in another process, returning a mirror object to 148 // control the slave 149 static LockSlaveMirror startLockSlave() throws Exception { 150 ServerSocketChannel ssc = ServerSocketChannel.open() 151 .bind(new InetSocketAddress(0)); 152 int port = ((InetSocketAddress)(ssc.getLocalAddress())).getPort(); 153 154 String sep = FileSystems.getDefault().getSeparator(); 155 156 String command = System.getProperty("java.home") + 157 sep + "bin" + sep + "java"; 158 String testClasses = System.getProperty("test.classes"); 159 if (testClasses != null) 160 command += " -cp " + testClasses; 161 command += " Lock -lockslave " + port; 162 163 Process p = Runtime.getRuntime().exec(command); 164 IOHandler.handle(p.getInputStream()); 165 IOHandler.handle(p.getErrorStream()); 166 167 // wait for slave to connect 168 SocketChannel sc = ssc.accept(); 169 return new LockSlaveMirror(sc); 170 } 171 172 // commands that the slave understands 173 static final String OPEN_CMD = "open"; 174 static final String CLOSE_CMD = "close"; 175 static final String LOCK_CMD = "lock"; 176 static final String UNLOCK_CMD = "unlock"; 177 static final char TERMINATOR = ';'; 178 179 // provides a proxy to a "lock slave" 180 static class LockSlaveMirror { 181 private final SocketChannel sc; 182 183 LockSlaveMirror(SocketChannel sc) { 184 this.sc = sc; 185 } 186 187 private void sendCommand(String cmd, String... params) 188 throws IOException 189 { 190 for (String s: params) { 191 cmd += " " + s; 192 } 193 cmd += TERMINATOR; 194 195 ByteBuffer buf = Charset.defaultCharset().encode(cmd); 196 while (buf.hasRemaining()) { 197 sc.write(buf); 198 } 199 200 // wait for ack 201 buf = ByteBuffer.allocate(1); 202 int n = sc.read(buf); 203 if (n != 1) 204 throw new RuntimeException("Reply expected"); 205 if (buf.get(0) != TERMINATOR) 206 throw new RuntimeException("Terminated expected"); 207 } 208 209 LockSlaveMirror open(String file) throws IOException { 210 sendCommand(OPEN_CMD, file); 211 return this; 212 } 213 214 void close() throws IOException { 215 sendCommand(CLOSE_CMD); 216 } 217 218 LockSlaveMirror lock() throws IOException { 219 sendCommand(LOCK_CMD); 220 return this; 221 } 222 223 224 LockSlaveMirror lock(long position, long size, boolean shared) 225 throws IOException 226 { 227 sendCommand(LOCK_CMD, position + "," + size + "," + shared); 228 return this; 229 } 230 231 LockSlaveMirror unlock() throws IOException { 232 sendCommand(UNLOCK_CMD); 233 return this; 234 } 235 236 void shutdown() throws IOException { 237 sc.close(); 238 } 239 } 240 241 // Helper class to direct process output to the parent System.out 242 static class IOHandler implements Runnable { 243 private final InputStream in; 244 245 IOHandler(InputStream in) { 246 this.in = in; 247 } 248 249 static void handle(InputStream in) { 250 IOHandler handler = new IOHandler(in); 251 Thread thr = new Thread(handler); 252 thr.setDaemon(true); 253 thr.start(); 254 } 255 256 public void run() { 257 try { 258 byte b[] = new byte[100]; 259 for (;;) { 260 int n = in.read(b); 261 if (n < 0) return; 262 for (int i=0; i<n; i++) { 263 System.out.print((char)b[i]); 264 } 265 } 266 } catch (IOException ioe) { } 267 } 268 } 269 270 // slave process that responds to simple commands a socket connection 271 static void runLockSlave(int port) throws Exception { 272 273 // establish connection to parent 274 SocketChannel sc = SocketChannel.open(new InetSocketAddress(port)); 275 ByteBuffer buf = ByteBuffer.allocateDirect(1024); 276 277 FileChannel fc = null; 278 FileLock fl = null; 279 try { 280 for (;;) { 281 282 // read command (ends with ";") 283 buf.clear(); 284 int n, last = 0; 285 do { 286 n = sc.read(buf); 287 if (n < 0) 288 return; 289 if (n == 0) 290 throw new AssertionError(); 291 last += n; 292 } while (buf.get(last-1) != TERMINATOR); 293 294 // decode into command and optional parameter 295 buf.flip(); 296 String s = Charset.defaultCharset().decode(buf).toString(); 297 int sp = s.indexOf(" "); 298 String cmd = (sp < 0) ? s.substring(0, s.length()-1) : 299 s.substring(0, sp); 300 String param = (sp < 0) ? "" : s.substring(sp+1, s.length()-1); 301 302 // execute 303 if (cmd.equals(OPEN_CMD)) { 304 if (fc != null) 305 throw new RuntimeException("File already open"); 306 fc = FileChannel.open(Paths.get(param),READ, WRITE); 307 } 308 if (cmd.equals(CLOSE_CMD)) { 309 if (fc == null) 310 throw new RuntimeException("No file open"); 311 fc.close(); 312 fc = null; 313 fl = null; 314 } 315 if (cmd.equals(LOCK_CMD)) { 316 if (fl != null) 317 throw new RuntimeException("Already holding lock"); 318 319 if (param.length() == 0) { 320 fl = fc.lock(); 321 } else { 322 String[] values = param.split(","); 323 if (values.length != 3) 324 throw new RuntimeException("Lock parameter invalid"); 325 long position = Long.parseLong(values[0]); 326 long size = Long.parseLong(values[1]); 327 boolean shared = Boolean.parseBoolean(values[2]); 328 fl = fc.lock(position, size, shared); 329 } 330 } 331 332 if (cmd.equals(UNLOCK_CMD)) { 333 if (fl == null) 334 throw new RuntimeException("Not holding lock"); 335 fl.release(); 336 fl = null; 337 } 338 339 // send reply 340 byte[] reply = { TERMINATOR }; 341 n = sc.write(ByteBuffer.wrap(reply)); 342 } 343 344 } finally { 345 sc.close(); 346 if (fc != null) fc.close(); 347 } 348 } 349 }