Repository: quarkusio/quarkus
Issue: Openshift extension fails to deploy when on RHEL

### Describe the bug

I have an application(resteasy, two endpoints) which I wan to deploy to Openshift via quarkus-openshift extension. After an update to 3.2.0.CR2, the deployment process succeeds on Fedora and fails on RHEL 8 with "Connection was closed" error. This happens robustly.

### Expected behavior

Successful deployment as for 3.1.0.Final and on Fedora

### Actual behavior

```
[ERROR] 	[error]: Build step io.quarkus.container.image.openshift.deployment.OpenshiftProcessor#openshiftBuildFromJar threw an exception: io.fabric8.kubernetes.client.KubernetesClientException: Connection was closed
[ERROR] 	at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.waitForResult(OperationSupport.java:520)
[ERROR] 	at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.handleResponse(OperationSupport.java:535)
[ERROR] 	at io.fabric8.kubernetes.client.dsl.internal.OperationSupport.handleGet(OperationSupport.java:478)
[ERROR] 	at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.handleGet(BaseOperation.java:741)
[ERROR] 	at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.requireFromServer(BaseOperation.java:185)
[ERROR] 	at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.get(BaseOperation.java:141)
[ERROR] 	at io.fabric8.kubernetes.client.dsl.internal.BaseOperation.get(BaseOperation.java:92)
[ERROR] 	at io.quarkus.container.image.openshift.deployment.OpenshiftProcessor.openshiftBuild(OpenshiftProcessor.java:462)
[ERROR] 	at io.quarkus.container.image.openshift.deployment.OpenshiftProcessor.lambda$openshiftBuild$10(OpenshiftProcessor.java:429)
[ERROR] 	at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
[ERROR] 	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
[ERROR] 	at java.base/java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:177)
[ERROR] 	at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1655)
[ERROR] 	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
[ERROR] 	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
[ERROR] 	at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
[ERROR] 	at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
[ERROR] 	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
[ERROR] 	at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
[ERROR] 	at io.quarkus.container.image.openshift.deployment.OpenshiftProcessor.openshiftBuild(OpenshiftProcessor.java:429)
[ERROR] 	at io.quarkus.container.image.openshift.deployment.OpenshiftProcessor.createContainerImage(OpenshiftProcessor.java:388)
[ERROR] 	at io.quarkus.container.image.openshift.deployment.OpenshiftProcessor.openshiftBuildFromJar(OpenshiftProcessor.java:285)
[ERROR] 	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[ERROR] 	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
[ERROR] 	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
[ERROR] 	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
[ERROR] 	at io.quarkus.deployment.ExtensionLoader$3.execute(ExtensionLoader.java:909)
[ERROR] 	at io.quarkus.builder.BuildContext.run(BuildContext.java:282)
[ERROR] 	at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
[ERROR] 	at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2513)
[ERROR] 	at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1538)
[ERROR] 	at java.base/java.lang.Thread.run(Thread.java:829)
[ERROR] 	at org.jboss.threads.JBossThread.run(JBossThread.java:501)
[ERROR] Caused by: io.vertx.core.http.HttpClosedException: Connection was closed
```

### How to Reproduce?

1. `git clone https://github.com/fedinskiy/reproducer -b opeshift-extension-rhel-disconnect`
2. `oc new-project rhel-disconnect && cd reproducer`
3. `mvn package -Dquarkus.kubernetes.deploy=true -Dquarkus.openshift.expose=true -Dquarkus.openshift.route.expose=true -Dquarkus.application.name=app -Dquarkus.kubernetes-client.trust-certs=true -Dquarkus.kubernetes.deployment-target=openshift` fails
4. `mvn package -Dquarkus.kubernetes.deploy=true -Dquarkus.openshift.expose=true -Dquarkus.openshift.route.expose=true -Dquarkus.application.name=app -Dquarkus.kubernetes-client.trust-certs=true -Dquarkus.kubernetes.deployment-target=openshift  -Dquarkus.platform.version=3.1.0.Final` succeeds (in another project)

### Output of `uname -a` or `ver`

4.18.0-477.13.1.el8_8.x86_64

### Output of `java -version`

 11.0.13, vendor: Red Hat, Inc

### GraalVM version (if different from Java)

_No response_

### Quarkus version or git rev

3.2.0.CR2

### Build tool (ie. output of `mvnw --version` or `gradlew --version`)

Apache Maven 3.8.6 (84538c9988a25aec085021c365c560670ad80f63)

### Additional information

oc version(same on both Fedora and RHEL):
```
Client Version: 4.13.0-202305312300.p0.g05d83ef.assembly.stream-05d83ef
Kustomize Version: v4.5.7
Kubernetes Version: v1.26.5+7a891f0
```

Changed files:
extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftProcessor.java

diff --git a/extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftProcessor.java b/extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftProcessor.java
index 1839dc50436..35d2ce3c248 100644
--- a/extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftProcessor.java
+++ b/extensions/container-image/container-image-openshift/deployment/src/main/java/io/quarkus/container/image/openshift/deployment/OpenshiftProcessor.java
@@ -26,7 +26,6 @@
 import java.util.concurrent.TimeUnit;
 import java.util.function.Predicate;
 import java.util.stream.Collectors;
-import java.util.stream.Stream;
 
 import org.jboss.logging.Logger;
 
@@ -385,7 +384,7 @@ public static void createContainerImage(KubernetesClientBuilder kubernetesClient
                     .collect(Collectors.toList());
 
             applyOpenshiftResources(openShiftClient, buildResources);
-            openshiftBuild(openShiftClient, buildResources, tar, openshiftConfig);
+            openshiftBuild(buildResources, tar, openshiftConfig, kubernetesClientBuilder);
         }
     }
 
@@ -423,73 +422,85 @@ private static void applyOpenshiftResources(OpenShiftClient client, List<HasMeta
         }
     }
 
-    private static void openshiftBuild(OpenShiftClient client, List<HasMetadata> buildResources, File binaryFile,
-            OpenshiftConfig openshiftConfig) {
+    private static void openshiftBuild(List<HasMetadata> buildResources, File binaryFile,
+            OpenshiftConfig openshiftConfig, KubernetesClientBuilder kubernetesClientBuilder) {
         distinct(buildResources).stream().filter(i -> i instanceof BuildConfig).map(i -> (BuildConfig) i)
-                .forEach(bc -> openshiftBuild(client, bc, binaryFile, openshiftConfig));
+                .forEach(bc -> {
+                    Build build = startOpenshiftBuild(bc, binaryFile, openshiftConfig, kubernetesClientBuilder);
+                    waitForOpenshiftBuild(build, openshiftConfig, kubernetesClientBuilder);
+                });
     }
 
     /**
      * Performs the binary build of the specified {@link BuildConfig} with the given
      * binary input.
      *
-     * @param client The openshift client instance
      * @param buildConfig The build config
      * @param binaryFile The binary file
      * @param openshiftConfig The openshift configuration
+     * @param kubernetesClientBuilder The kubernetes client builder
      */
-    private static void openshiftBuild(OpenShiftClient client, BuildConfig buildConfig, File binaryFile,
-            OpenshiftConfig openshiftConfig) {
-        Build build;
-        try {
-            build = client.buildConfigs().withName(buildConfig.getMetadata().getName())
-                    .instantiateBinary()
-                    .withTimeoutInMillis(openshiftConfig.buildTimeout.toMillis())
-                    .fromFile(binaryFile);
-        } catch (Exception e) {
-            Optional<Build> running = runningBuildsOf(client, buildConfig).findFirst();
-            if (running.isPresent()) {
-                LOG.warn("An exception: '" + e.getMessage()
-                        + " ' occurred while instantiating the build, however the build has been started.");
-                build = running.get();
-            } else {
-                throw openshiftException(e);
+    private static Build startOpenshiftBuild(BuildConfig buildConfig, File binaryFile,
+            OpenshiftConfig openshiftConfig, KubernetesClientBuilder kubernetesClientBuilder) {
+        try (KubernetesClient kubernetesClient = kubernetesClientBuilder.build()) {
+            OpenShiftClient client = toOpenshiftClient(kubernetesClient);
+            try {
+                return client.buildConfigs().withName(buildConfig.getMetadata().getName())
+                        .instantiateBinary()
+                        .withTimeoutInMillis(openshiftConfig.buildTimeout.toMillis())
+                        .fromFile(binaryFile);
+            } catch (Exception e) {
+                Optional<Build> running = buildsOf(client, buildConfig).stream().findFirst();
+                if (running.isPresent()) {
+                    LOG.warn("An exception: '" + e.getMessage()
+                            + " ' occurred while instantiating the build, however the build has been started.");
+                    return running.get();
+                } else {
+                    throw openshiftException(e);
+                }
             }
         }
+    }
+
+    private static void waitForOpenshiftBuild(Build build, OpenshiftConfig openshiftConfig,
+            KubernetesClientBuilder kubernetesClientBuilder) {
 
         while (isNew(build) || isPending(build) || isRunning(build)) {
             final String buildName = build.getMetadata().getName();
-            Build updated = client.builds().withName(buildName).get();
-            if (updated == null) {
-                throw new IllegalStateException("Build:" + build.getMetadata().getName() + " is no longer present!");
-            } else if (updated.getStatus() == null) {
-                throw new IllegalStateException("Build:" + build.getMetadata().getName() + " has no status!");
-            } else if (isNew(updated) || isPending(updated) || isRunning(updated)) {
-                build = updated;
-                try (LogWatch w = client.builds().withName(buildName).withPrettyOutput().watchLog();
-                        Reader reader = new InputStreamReader(w.getOutput())) {
-                    display(reader, openshiftConfig.buildLogLevel);
-                } catch (IOException e) {
-                    // This may happen if the LogWatch is closed while we are still reading.
-                    // We shouldn't let the build fail, so let's log a warning and display last few lines of the log
-                    LOG.warn("Log stream closed, redisplaying last " + LOG_TAIL_SIZE + " entries:");
-                    try {
-                        display(client.builds().withName(buildName).tailingLines(LOG_TAIL_SIZE).getLogReader(),
-                                Logger.Level.WARN);
-                    } catch (IOException ex) {
-                        // Let's ignore this.
+            try (KubernetesClient kubernetesClient = kubernetesClientBuilder.build()) {
+                OpenShiftClient client = toOpenshiftClient(kubernetesClient);
+                Build updated = client.builds().withName(buildName).get();
+                if (updated == null) {
+                    throw new IllegalStateException("Build:" + build.getMetadata().getName() + " is no longer present!");
+                } else if (updated.getStatus() == null) {
+                    throw new IllegalStateException("Build:" + build.getMetadata().getName() + " has no status!");
+                } else if (isNew(updated) || isPending(updated) || isRunning(updated)) {
+                    build = updated;
+                    try (LogWatch w = client.builds().withName(buildName).withPrettyOutput().watchLog();
+                            Reader reader = new InputStreamReader(w.getOutput())) {
+                        display(reader, openshiftConfig.buildLogLevel);
+                    } catch (IOException | KubernetesClientException ex) {
+                        // This may happen if the LogWatch is closed while we are still reading.
+                        // We shouldn't let the build fail, so let's log a warning and display last few lines of the log
+                        LOG.warn("Log stream closed, redisplaying last " + LOG_TAIL_SIZE + " entries:");
+                        try {
+                            display(client.builds().withName(buildName).tailingLines(LOG_TAIL_SIZE).getLogReader(),
+                                    Logger.Level.WARN);
+                        } catch (IOException | KubernetesClientException ignored) {
+                            // Let's ignore this.
+                        }
                     }
+                } else if (isComplete(updated)) {
+                    return;
+                } else if (isCancelled(updated)) {
+                    throw new IllegalStateException("Build:" + buildName + " cancelled!");
+                } else if (isFailed(updated)) {
+                    throw new IllegalStateException(
+                            "Build:" + buildName + " failed! " + updated.getStatus().getMessage());
+                } else if (isError(updated)) {
+                    throw new IllegalStateException(
+                            "Build:" + buildName + " encountered error! " + updated.getStatus().getMessage());
                 }
-            } else if (isComplete(updated)) {
-                return;
-            } else if (isCancelled(updated)) {
-                throw new IllegalStateException("Build:" + buildName + " cancelled!");
-            } else if (isFailed(updated)) {
-                throw new IllegalStateException(
-                        "Build:" + buildName + " failed! " + updated.getStatus().getMessage());
-            } else if (isError(updated)) {
-                throw new IllegalStateException(
-                        "Build:" + buildName + " encountered error! " + updated.getStatus().getMessage());
             }
         }
     }
@@ -508,10 +519,6 @@ private static List<Build> buildsOf(OpenShiftClient client, BuildConfig config)
         return client.builds().withLabel(BUILD_CONFIG_NAME, config.getMetadata().getName()).list().getItems();
     }
 
-    private static Stream<Build> runningBuildsOf(OpenShiftClient client, BuildConfig config) {
-        return buildsOf(client, config).stream().filter(b -> RUNNING.equalsIgnoreCase(b.getStatus().getPhase()));
-    }
-
     private static RuntimeException openshiftException(Throwable t) {
         if (t instanceof KubernetesClientException) {
             KubernetesClientErrorHandler.handle((KubernetesClientException) t);