use of io.fabric8.maven.watcher.api.Watcher in project fabric8 by jboss-fuse.
the class ZooKeeperUtils method getProperties.
public static Properties getProperties(CuratorFramework curator, String path, Watcher watcher) throws Exception {
String value = getStringData(curator, path, watcher);
Properties properties = new Properties();
if (value != null) {
try {
properties.load(new StringReader(value));
} catch (IOException ignore) {
}
}
return properties;
}
use of io.fabric8.maven.watcher.api.Watcher in project strimzi by strimzi.
the class PodOperatorTest method testCreateReadUpdate.
@Test
public void testCreateReadUpdate(TestContext context) {
vertx.createSharedWorkerExecutor("kubernetes-ops-pool", 10);
KubernetesClient client = server.getKubernetesClient();
PodOperator pr = new PodOperator(vertx, client);
context.assertEquals(emptyList(), pr.list(NAMESPACE, Labels.EMPTY));
Async async = context.async(1);
pr.createOrUpdate(resource()).setHandler(createResult -> {
context.assertTrue(createResult.succeeded());
context.assertEquals(singletonList(RESOURCE_NAME), pr.list(NAMESPACE, Labels.EMPTY).stream().map(p -> p.getMetadata().getName()).collect(Collectors.toList()));
// Pod got = pr.get(NAMESPACE, RESOURCE_NAME);
// context.assertNotNull(got);
// context.assertNotNull(got.getMetadata());
// context.assertEquals(RESOURCE_NAME, got.getMetadata().getName());
context.assertFalse(pr.isReady(NAMESPACE, RESOURCE_NAME));
/*pr.watch(NAMESPACE, RESOURCE_NAME, new Watcher<Pod>() {
@Override
public void eventReceived(Action action, Pod resource) {
if (action == Action.DELETED) {
context.assertEquals(RESOURCE_NAME, resource.getMetadata().getName());
} else {
context.fail();
}
async.countDown();
}
@Override
public void onClose(KubernetesClientException cause) {
}
});*/
/*Pod modified = resource();
modified.getSpec().setHostname("bar");
Async patchAsync = context.async();
pr.patch(NAMESPACE, RESOURCE_NAME, modified, patchResult -> {
context.assertTrue(patchResult.succeeded());
patchAsync.complete();
});
patchAsync.await();*/
pr.reconcile(NAMESPACE, RESOURCE_NAME, null).setHandler(deleteResult -> {
context.assertTrue(deleteResult.succeeded());
async.countDown();
});
});
}
use of io.fabric8.maven.watcher.api.Watcher in project strimzi by strimzi.
the class ClusterController method createConfigMapWatch.
private void createConfigMapWatch(Handler<AsyncResult<Watch>> handler) {
getVertx().executeBlocking(future -> {
Watch watch = client.configMaps().inNamespace(namespace).withLabels(selector.toMap()).watch(new Watcher<ConfigMap>() {
@Override
public void eventReceived(Action action, ConfigMap cm) {
Labels labels = Labels.fromResource(cm);
AssemblyType type;
try {
type = labels.type();
} catch (IllegalArgumentException e) {
log.warn("Unknown {} label {} received in Config Map {} in namespace {}", Labels.STRIMZI_TYPE_LABEL, cm.getMetadata().getLabels().get(Labels.STRIMZI_TYPE_LABEL), cm.getMetadata().getName(), namespace);
return;
}
final AbstractAssemblyOperator cluster;
if (type == null) {
log.warn("Missing label {} in Config Map {} in namespace {}", Labels.STRIMZI_TYPE_LABEL, cm.getMetadata().getName(), namespace);
return;
} else {
switch(type) {
case KAFKA:
cluster = kafkaAssemblyOperator;
break;
case CONNECT:
cluster = kafkaConnectAssemblyOperator;
break;
case CONNECT_S2I:
cluster = kafkaConnectS2IAssemblyOperator;
break;
default:
return;
}
}
String name = cm.getMetadata().getName();
switch(action) {
case ADDED:
case DELETED:
case MODIFIED:
Reconciliation reconciliation = new Reconciliation("watch", type, namespace, name);
log.info("{}: ConfigMap {} in namespace {} was {}", reconciliation, name, namespace, action);
cluster.reconcileAssembly(reconciliation, result -> {
if (result.succeeded()) {
log.info("{}: assembly reconciled", reconciliation);
} else {
log.error("{}: Failed to reconcile", reconciliation);
}
});
break;
case ERROR:
log.error("Failed ConfigMap {} in namespace{} ", name, namespace);
reconcileAll("watch error");
break;
default:
log.error("Unknown action: {} in namespace {}", name, namespace);
reconcileAll("watch unknown");
}
}
@Override
public void onClose(KubernetesClientException e) {
if (e != null) {
log.error("Watcher closed with exception in namespace {}", namespace, e);
} else {
log.info("Watcher closed in namespace {}", namespace);
}
recreateConfigMapWatch();
}
});
future.complete(watch);
}, res -> {
if (res.succeeded()) {
log.info("ConfigMap watcher running for labels {}", selector);
handler.handle(Future.succeededFuture((Watch) res.result()));
} else {
log.info("ConfigMap watcher failed to start", res.cause());
handler.handle(Future.failedFuture("ConfigMap watcher failed to start"));
}
});
}
use of io.fabric8.maven.watcher.api.Watcher in project fabric8-maven-plugin by fabric8io.
the class DebugMojo method waitForRunningPodWithEnvVar.
private String waitForRunningPodWithEnvVar(final KubernetesClient kubernetes, final String namespace, LabelSelector selector, final Map<String, String> envVars) throws MojoExecutionException {
// wait for the newest pod to be ready with the given env var
FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> pods = withSelector(kubernetes.pods().inNamespace(namespace), selector, log);
log.info("Waiting for debug pod with selector " + selector + " and environment variables " + envVars);
podWaitLog = createExternalProcessLogger("[[Y]][W][[Y]] ");
PodList list = pods.list();
if (list != null) {
Pod latestPod = KubernetesResourceUtil.getNewestPod(list.getItems());
if (latestPod != null && podHasEnvVars(latestPod, envVars)) {
return getName(latestPod);
}
}
podWatcher = pods.watch(new Watcher<Pod>() {
@Override
public void eventReceived(Watcher.Action action, Pod pod) {
podWaitLog.info(getName(pod) + " status: " + getPodStatusDescription(pod) + getPodStatusMessagePostfix(action));
if (isAddOrModified(action) && isPodRunning(pod) && isPodReady(pod) && podHasEnvVars(pod, envVars)) {
foundPod = pod;
terminateLatch.countDown();
}
}
@Override
public void onClose(KubernetesClientException e) {
// ignore
}
});
// now lets wait forever?
while (terminateLatch.getCount() > 0) {
try {
terminateLatch.await();
} catch (InterruptedException e) {
// ignore
}
if (foundPod != null) {
return getName(foundPod);
}
}
throw new MojoExecutionException("Could not find a running pod with environment variables " + envVars);
}
use of io.fabric8.maven.watcher.api.Watcher in project fabric8-maven-plugin by fabric8io.
the class PortForwardService method forwardPortAsync.
/**
* Forwards a port to the newest pod matching the given selector.
* If another pod is created, it forwards connections to the new pod once it's ready.
*/
public Closeable forwardPortAsync(final Logger externalProcessLogger, final LabelSelector podSelector, final int remotePort, final int localPort) throws Fabric8ServiceException {
final Lock monitor = new ReentrantLock(true);
final Condition podChanged = monitor.newCondition();
final Pod[] nextForwardedPod = new Pod[1];
final Thread forwarderThread = new Thread() {
@Override
public void run() {
Pod currentPod = null;
Closeable currentPortForward = null;
try {
monitor.lock();
while (true) {
if (podEquals(currentPod, nextForwardedPod[0])) {
podChanged.await();
} else {
// may be null
Pod nextPod = nextForwardedPod[0];
try {
monitor.unlock();
if (currentPortForward != null) {
log.info("Closing port-forward from pod %s", KubernetesHelper.getName(currentPod));
currentPortForward.close();
currentPortForward = null;
}
if (nextPod != null) {
log.info("Starting port-forward to pod %s", KubernetesHelper.getName(nextPod));
currentPortForward = forwardPortAsync(externalProcessLogger, KubernetesHelper.getName(nextPod), remotePort, localPort);
} else {
log.info("Waiting for a pod to become ready before starting port-forward");
}
currentPod = nextPod;
} finally {
monitor.lock();
}
}
}
} catch (InterruptedException e) {
log.debug("Port-forwarding thread interrupted", e);
Thread.currentThread().interrupt();
} catch (Exception e) {
log.warn("Error while port-forwarding to pod", e);
} finally {
monitor.unlock();
if (currentPortForward != null) {
try {
currentPortForward.close();
} catch (Exception e) {
}
}
}
}
};
// Switching forward to the current pod if present
Pod newPod = getNewestPod(podSelector);
nextForwardedPod[0] = newPod;
final Watch watch = KubernetesClientUtil.withSelector(kubernetes.pods(), podSelector, log).watch(new Watcher<Pod>() {
@Override
public void eventReceived(Action action, Pod pod) {
monitor.lock();
try {
List<Pod> candidatePods;
if (nextForwardedPod[0] != null) {
candidatePods = new LinkedList<>();
candidatePods.add(nextForwardedPod[0]);
candidatePods.add(pod);
} else {
candidatePods = Collections.singletonList(pod);
}
// may be null
Pod newPod = getNewestPod(candidatePods);
if (!podEquals(nextForwardedPod[0], newPod)) {
nextForwardedPod[0] = newPod;
podChanged.signal();
}
} finally {
monitor.unlock();
}
}
@Override
public void onClose(KubernetesClientException e) {
// don't care
}
});
forwarderThread.start();
final Closeable handle = new Closeable() {
@Override
public void close() throws IOException {
try {
watch.close();
} catch (Exception e) {
}
try {
forwarderThread.interrupt();
forwarderThread.join(15000);
} catch (Exception e) {
}
}
};
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
handle.close();
} catch (Exception e) {
// suppress
}
}
});
return handle;
}
Aggregations