Skip to content

Commit 0c05ed7

Browse files
committed
[GR-28392] More fixes for sockets
PullRequest: graalpython/1603
2 parents dc150c2 + 085fba5 commit 0c05ed7

File tree

5 files changed

+58
-46
lines changed

5 files changed

+58
-46
lines changed

graalpython/com.oracle.graal.python.test/src/graalpytest.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -577,10 +577,12 @@ def run(cls, items=None):
577577
return instance
578578
for k, v in items:
579579
if k.startswith("test"):
580+
testfn = getattr(instance, k, v)
580581
if patterns:
581-
if not any(p in k for p in patterns):
582+
import fnmatch
583+
if not any(fnmatch.fnmatch(testfn.__qualname__, p) for p in patterns):
582584
continue
583-
instance.run_test(getattr(instance, k, v))
585+
instance.run_test(testfn)
584586
if hasattr(instance, "tearDownClass"):
585587
instance.run_safely(instance.tearDownClass)
586588
return instance
@@ -752,7 +754,10 @@ class TextTestResult():
752754
if argv[idx] == "-k":
753755
argv.pop(idx)
754756
try:
755-
patterns.append(argv.pop(idx))
757+
pattern = argv.pop(idx)
758+
if '*' not in pattern:
759+
pattern = '*' + pattern + '*'
760+
patterns.append(pattern)
756761
except IndexError:
757762
print("-k needs an argument")
758763
else:

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/socket/SocketBuiltins.java

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@
4848
import java.io.IOException;
4949
import java.net.InetAddress;
5050
import java.net.InetSocketAddress;
51-
import java.net.SocketAddress;
5251
import java.nio.ByteBuffer;
5352
import java.nio.channels.NotYetConnectedException;
5453
import java.nio.channels.ServerSocketChannel;
@@ -82,6 +81,7 @@
8281
import com.oracle.graal.python.nodes.function.builtins.PythonBinaryBuiltinNode;
8382
import com.oracle.graal.python.nodes.function.builtins.PythonBinaryClinicBuiltinNode;
8483
import com.oracle.graal.python.nodes.function.builtins.PythonTernaryBuiltinNode;
84+
import com.oracle.graal.python.nodes.function.builtins.PythonTernaryClinicBuiltinNode;
8585
import com.oracle.graal.python.nodes.function.builtins.PythonUnaryBuiltinNode;
8686
import com.oracle.graal.python.nodes.function.builtins.clinic.ArgumentClinicProvider;
8787
import com.oracle.graal.python.nodes.util.CannotCastException;
@@ -129,16 +129,18 @@ Object accept(PSocket socket) {
129129
if (acceptSocket == null) {
130130
throw raiseOSError(null, OSErrorEnum.EWOULDBLOCK);
131131
}
132-
SocketAddress addr = acceptSocket.getLocalAddress();
133-
if (!acceptSocket.socket().isBound() || addr == null) {
132+
InetSocketAddress remoteAddress = (InetSocketAddress) acceptSocket.getRemoteAddress();
133+
if (!acceptSocket.socket().isBound() || remoteAddress == null) {
134134
throw raise(OSError);
135135
}
136136
PSocket newSocket = factory().createSocket(socket.getFamily(), socket.getType(), socket.getProto());
137137
int fd = getContext().getResources().openSocket(newSocket);
138138
newSocket.setFileno(fd);
139139
newSocket.setSocket(acceptSocket);
140-
Object[] output = {fd, ((InetSocketAddress) addr).getAddress().getHostAddress()};
141-
return factory().createTuple(output);
140+
SocketUtils.setBlocking(newSocket, socket.isBlocking());
141+
newSocket.setTimeout(socket.getTimeout());
142+
PTuple addressTuple = factory().createTuple(new Object[]{remoteAddress.getAddress().getHostAddress(), remoteAddress.getPort()});
143+
return factory().createTuple(new Object[]{fd, addressTuple});
142144
} catch (IOException e) {
143145
throw raise(OSError);
144146
}
@@ -174,20 +176,12 @@ abstract static class CloseNode extends PythonUnaryBuiltinNode {
174176
@TruffleBoundary
175177
Object close(PSocket socket) {
176178
if (socket.getSocket() != null) {
177-
if (!socket.getSocket().isOpen()) {
178-
throw raise(OSError, ErrorMessages.BAD_FILE_DESCRIPTOR);
179-
}
180-
181179
try {
182180
socket.getSocket().close();
183181
} catch (IOException e) {
184182
throw raise(OSError, ErrorMessages.BAD_FILE_DESCRIPTOR);
185183
}
186184
} else if (socket.getServerSocket() != null) {
187-
if (!socket.getServerSocket().isOpen()) {
188-
throw raise(OSError, ErrorMessages.BAD_FILE_DESCRIPTOR);
189-
}
190-
191185
try {
192186
socket.getServerSocket().close();
193187
} catch (IOException e) {
@@ -337,9 +331,11 @@ Object listen(PSocket socket, PNone backlog) {
337331
}
338332

339333
// recv(bufsize[, flags])
340-
@Builtin(name = "recv", minNumOfPositionalArgs = 2, maxNumOfPositionalArgs = 3)
334+
@Builtin(name = "recv", minNumOfPositionalArgs = 2, numOfPositionalOnlyArgs = 3, parameterNames = {"$self", "nbytes", "flags"})
335+
@ArgumentClinic(name = "nbytes", conversion = ArgumentClinic.ClinicConversion.Index)
336+
@ArgumentClinic(name = "flags", conversion = ArgumentClinic.ClinicConversion.Int, defaultValue = "0")
341337
@GenerateNodeFactory
342-
abstract static class RecvNode extends PythonTernaryBuiltinNode {
338+
abstract static class RecvNode extends PythonTernaryClinicBuiltinNode {
343339
@Specialization
344340
Object recv(VirtualFrame frame, PSocket socket, int bufsize, int flags) {
345341
ByteBuffer readBytes = PythonUtils.allocateByteBuffer(bufsize);
@@ -353,6 +349,10 @@ Object recv(VirtualFrame frame, PSocket socket, int bufsize, int flags) {
353349
}
354350
}
355351

352+
@Override
353+
protected ArgumentClinicProvider getArgumentClinic() {
354+
return SocketBuiltinsClinicProviders.RecvNodeClinicProviderGen.INSTANCE;
355+
}
356356
}
357357

358358
// recvfrom(bufsize[, flags])

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/EmulatedPosixSupport.java

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,6 @@
9090
import java.util.Map;
9191
import java.util.Set;
9292
import java.util.concurrent.TimeUnit;
93-
import java.util.function.Function;
9493
import java.util.logging.Level;
9594

9695
import org.graalvm.nativeimage.ImageInfo;
@@ -425,9 +424,24 @@ public int[] pipeMessage() throws PosixException {
425424
public SelectResult select(int[] readfds, int[] writefds, int[] errorfds, Timeval timeout) throws PosixException {
426425
SelectableChannel[] readChannels = getSelectableChannels(readfds);
427426
SelectableChannel[] writeChannels = getSelectableChannels(writefds);
428-
SelectableChannel[] errChannels = getSelectableChannels(errorfds);
427+
// Java doesn't support any exceptional conditions we could apply on errfds, report a
428+
// warning if errfds is not a subset of readfds & writefds
429+
errfdsCheck: for (int fd : errorfds) {
430+
for (int fd2 : readfds) {
431+
if (fd == fd2) {
432+
continue errfdsCheck;
433+
}
434+
}
435+
for (int fd2 : writefds) {
436+
if (fd == fd2) {
437+
continue errfdsCheck;
438+
}
439+
}
440+
compatibilityIgnored("POSIX emultaion layer doesn't support waiting on exceptional conditions in select()");
441+
break;
442+
}
429443

430-
boolean[] wasBlocking = new boolean[readChannels.length + writeChannels.length + errChannels.length];
444+
boolean[] wasBlocking = new boolean[readChannels.length + writeChannels.length];
431445
int i = 0;
432446

433447
for (SelectableChannel channel : readChannels) {
@@ -436,25 +450,19 @@ public SelectResult select(int[] readfds, int[] writefds, int[] errorfds, Timeva
436450
for (SelectableChannel channel : writeChannels) {
437451
wasBlocking[i++] = channel.isBlocking();
438452
}
439-
for (SelectableChannel channel : errChannels) {
440-
wasBlocking[i++] = channel.isBlocking();
441-
}
453+
454+
final int readOps = SelectionKey.OP_READ | SelectionKey.OP_ACCEPT;
455+
final int writeOps = SelectionKey.OP_WRITE;
442456

443457
try (Selector selector = Selector.open()) {
444458
for (SelectableChannel channel : readChannels) {
445459
channel.configureBlocking(false);
446-
channel.register(selector, (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT) & channel.validOps());
460+
channel.register(selector, readOps & channel.validOps());
447461
}
448462

449463
for (SelectableChannel channel : writeChannels) {
450464
channel.configureBlocking(false);
451-
channel.register(selector, SelectionKey.OP_WRITE);
452-
}
453-
454-
for (SelectableChannel channel : errChannels) {
455-
// TODO(fa): not sure if these ops are representing "exceptional condition pending"
456-
channel.configureBlocking(false);
457-
channel.register(selector, SelectionKey.OP_CONNECT);
465+
channel.register(selector, writeOps);
458466
}
459467

460468
// IMPORTANT: The meaning of the timeout value is slightly different: 'timeout == 0.0'
@@ -478,9 +486,9 @@ public SelectResult select(int[] readfds, int[] writefds, int[] errorfds, Timeva
478486
int selected = useSelectNow ? selector.selectNow() : selector.select(timeoutMs);
479487

480488
// remove non-selected channels from given lists
481-
boolean[] resReadfds = createSelectedMap(readfds, readChannels, selector, SelectionKey::isReadable);
482-
boolean[] resWritefds = createSelectedMap(writefds, writeChannels, selector, SelectionKey::isWritable);
483-
boolean[] resErrfds = createSelectedMap(errorfds, errChannels, selector, key -> key.isAcceptable() || key.isConnectable());
489+
boolean[] resReadfds = createSelectedMap(readfds, readChannels, selector, readOps);
490+
boolean[] resWritefds = createSelectedMap(writefds, writeChannels, selector, writeOps);
491+
boolean[] resErrfds = new boolean[errorfds.length];
484492

485493
assert selected == countSelected(resReadfds) + countSelected(resWritefds) + countSelected(resErrfds);
486494
return new SelectResult(resReadfds, resWritefds, resErrfds);
@@ -499,23 +507,18 @@ public SelectResult select(int[] readfds, int[] writefds, int[] errorfds, Timeva
499507
channel.configureBlocking(true);
500508
}
501509
}
502-
for (SelectableChannel channel : errChannels) {
503-
if (wasBlocking[i++]) {
504-
channel.configureBlocking(true);
505-
}
506-
}
507510
} catch (IOException e) {
508511
// We didn't manage to restore the blocking status, ignore
509512
}
510513
}
511514
}
512515

513-
private static boolean[] createSelectedMap(int[] fds, SelectableChannel[] channels, Selector selector, Function<SelectionKey, Boolean> selectedPredicate) {
516+
private static boolean[] createSelectedMap(int[] fds, SelectableChannel[] channels, Selector selector, int op) {
514517
boolean[] result = new boolean[fds.length];
515518
for (int i = 0; i < channels.length; i++) {
516519
SelectableChannel channel = channels[i];
517520
SelectionKey selectionKey = channel.keyFor(selector);
518-
result[i] = selectedPredicate.apply(selectionKey);
521+
result[i] = (selectionKey.readyOps() & op) != 0;
519522
}
520523
return result;
521524
}

mx.graalpython/mx_graalpython.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -523,8 +523,8 @@ def _hpy_test_root():
523523
def graalpytest(args):
524524
parser = ArgumentParser(prog='mx graalpytest')
525525
parser.add_argument('--python', type=str, action='store', default="", help='Run tests with custom Python binary.')
526-
parser.add_argument('-v', "--verbose", action="store_true", help='Verbose output.')
527-
parser.add_argument('-k', dest="filter", default=[], help='Test pattern.')
526+
parser.add_argument('-v', "--verbose", action="store_true", help='Verbose output.', default=True)
527+
parser.add_argument('-k', dest="filter", default='', help='Test pattern.')
528528
parser.add_argument('test', nargs="*", default=[], help='Test file to run (specify absolute or relative; e.g. "/path/to/test_file.py" or "cpyext/test_object.py") ')
529529
args, unknown_args = parser.parse_known_args(args)
530530

mx.graalpython/mx_graalpython_bisect.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,7 @@ def _bisect_benchmark(argv, initial_branch, email_to):
204204
def benchmark_callback(suite, commit):
205205
suite.vc.update_to_branch(suite.vc_dir, commit)
206206
mx.run_mx(['sforceimports'], suite=suite)
207+
mx.run_mx(['--env', 'ce', 'sforceimports'], suite=get_suite('/vm'))
207208
if args.enterprise and suite.name != 'vm-enterprise':
208209
checkout_args = ['--dynamicimports', '/vm-enterprise', 'checkout-downstream', 'vm', 'vm-enterprise']
209210
if fetched_enterprise[0]:
@@ -215,8 +216,11 @@ def benchmark_callback(suite, commit):
215216
fetched_enterprise[0] = True
216217
suite.vc.update_to_branch(suite.vc_dir, commit)
217218
mx.run_mx(['sforceimports'], suite=suite)
218-
print("debug: graalpython={} graal={} graal-enterprise={}"
219-
.format(*(get_commit(get_suite(s)) for s in ('graalpython', '/vm', '/vm-enterprise'))))
219+
debug_str = "debug: graalpython={} graal={}".format(
220+
get_commit(get_suite('graalpython')), get_commit(get_suite('/vm')))
221+
if args.enterprise:
222+
debug_str += " graal-enterprise={}".format(get_commit(get_suite('/vm-enterprise')))
223+
print(debug_str)
220224
env = os.environ.copy()
221225
env['MX_ALT_OUTPUT_ROOT'] = 'mxbuild-{}'.format(commit)
222226
retcode = mx.run(shlex.split(args.build_command), env=env, nonZeroIsFatal=False)

0 commit comments

Comments
 (0)