use of io.fabric8.kubernetes.client.Watch in project fabric8-maven-plugin by fabric8io.
the class SpringBootWatcher method runRemoteSpringApplication.
private void runRemoteSpringApplication(String url) {
log.info("Running RemoteSpringApplication against endpoint: " + url);
Properties properties = SpringBootUtil.getSpringBootApplicationProperties(getContext().getProject());
String remoteSecret = properties.getProperty(DEV_TOOLS_REMOTE_SECRET, System.getProperty(DEV_TOOLS_REMOTE_SECRET));
if (Strings.isNullOrBlank(remoteSecret)) {
log.warn("There is no `%s` property defined in your src/main/resources/application.properties. Please add one!", DEV_TOOLS_REMOTE_SECRET);
throw new IllegalStateException("No " + DEV_TOOLS_REMOTE_SECRET + " property defined in application.properties or system properties");
}
ClassLoader classLoader = getClass().getClassLoader();
if (classLoader instanceof URLClassLoader) {
URLClassLoader pluginClassLoader = (URLClassLoader) classLoader;
URLClassLoader projectClassLoader = ClassUtil.createProjectClassLoader(getContext().getProject(), log);
URLClassLoader[] classLoaders = { projectClassLoader, pluginClassLoader };
StringBuilder buffer = new StringBuilder("java -cp ");
int count = 0;
for (URLClassLoader urlClassLoader : classLoaders) {
URL[] urLs = urlClassLoader.getURLs();
for (URL u : urLs) {
if (count++ > 0) {
buffer.append(File.pathSeparator);
}
try {
URI uri = u.toURI();
File file = new File(uri);
buffer.append(file.getCanonicalPath());
} catch (Exception e) {
throw new IllegalStateException("Failed to create classpath: " + e, e);
}
}
}
// Add dev tools to the classpath (the main class is not read from BOOT-INF/lib)
try {
File devtools = getSpringBootDevToolsJar(getContext().getProject());
buffer.append(File.pathSeparator);
buffer.append(devtools.getCanonicalPath());
} catch (Exception e) {
throw new IllegalStateException("Failed to include devtools in the classpath: " + e, e);
}
buffer.append(" -Dspring.devtools.remote.secret=");
buffer.append(remoteSecret);
buffer.append(" org.springframework.boot.devtools.RemoteSpringApplication ");
buffer.append(url);
try {
String command = buffer.toString();
log.debug("Running: " + command);
final Process process = Runtime.getRuntime().exec(command);
final AtomicBoolean outputEnabled = new AtomicBoolean(true);
Runtime.getRuntime().addShutdownHook(new Thread("fabric8:watch [spring-boot] shutdown hook") {
@Override
public void run() {
log.info("Terminating the Spring remote client...");
outputEnabled.set(false);
process.destroy();
}
});
Logger logger = new PrefixedLogger("Spring-Remote", log);
Thread stdOutPrinter = startOutputProcessor(logger, process.getInputStream(), false, outputEnabled);
Thread stdErrPrinter = startOutputProcessor(logger, process.getErrorStream(), true, outputEnabled);
int status = process.waitFor();
stdOutPrinter.join();
stdErrPrinter.join();
if (status != 0) {
log.warn("Process returned status: %s", status);
}
} catch (Exception e) {
throw new RuntimeException("Failed to run RemoteSpringApplication: " + e, e);
}
} else {
throw new IllegalStateException("ClassLoader must be a URLClassLoader but it is: " + classLoader.getClass().getName());
}
}
use of io.fabric8.kubernetes.client.Watch in project watchdog by isdream.
the class KubernetesListener method start.
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void start(Object client, Configure config) throws Exception {
// System.out.println(config.getApiVersion());
if (ObjectUtils.isNull(client) && ObjectUtils.isNull(config)) {
throw new Exception("Invalid paremeters");
}
// it may throw Exception if wrong PROPERTY_KIND values
Object model = getModelParamtersGenerator().getKindModel(client, config.getKind());
if (model instanceof Namespaceable || model instanceof AnyNamespaceable) {
String namespace = config.getProperties().getOrDefault(PROPERTY_NAMESPACE, ALL_NAMESPACE);
if (ALL_NAMESPACE.equals(namespace)) {
model = ((AnyNamespaceable) model).inAnyNamespace();
} else {
model = ((Namespaceable) model).inNamespace(namespace);
}
}
List<String> handlers = config.getHandlers();
if (handlers.isEmpty()) {
throw new Exception("No handlers");
}
Handler handler = (Handler) Class.forName(handlers.remove(0)).newInstance();
Handler thisHandler = handler;
for (String name : handlers) {
Handler nextHandler = (Handler) Class.forName(name).newInstance();
thisHandler.setNextHandler(nextHandler);
thisHandler = nextHandler;
}
System.out.println(model.getClass());
((Watchable) model).watch(new KubernetesWatcher(handler));
}
use of io.fabric8.kubernetes.client.Watch in project hono by eclipse.
the class KubernetesBasedAdapterInstanceStatusServiceTest method testServiceReactivatesAfterWatchClosed.
/**
* Verifies that when the pod watcher of the status service is closed, a new watcher gets created
* and subsequently added pods get detected.
*
* @throws InterruptedException if test execution gets interrupted.
*/
@Test
public void testServiceReactivatesAfterWatchClosed() throws InterruptedException {
// 3 events: 2x on initAdaptersListAndWatch() + 1x on WatchEvent
final CountDownLatch eventLatch = new CountDownLatch(3);
final Pod pod0 = createAdapterPodWithRunningContainer("testPod0");
final String pod0ContainerId = KubernetesBasedAdapterInstanceStatusService.getShortContainerId(pod0.getStatus().getContainerStatuses().get(0).getContainerID());
assertThat(pod0ContainerId).isNotNull();
server.expect().withPath("/api/v1/namespaces/test/pods").andReturn(200, new PodListBuilder().addToItems(pod0).build()).times(2);
final Pod pod1 = createAdapterPodWithRunningContainer("testPod1");
final String pod1ContainerId = KubernetesBasedAdapterInstanceStatusService.getShortContainerId(pod1.getStatus().getContainerStatuses().get(0).getContainerID());
assertThat(pod1ContainerId).isNotNull();
server.expect().withPath("/api/v1/namespaces/test/pods?allowWatchBookmarks=true&watch=true").andUpgradeToWebSocket().open().waitFor(10).andEmit(outdatedEvent()).done().once();
server.expect().withPath("/api/v1/namespaces/test/pods?allowWatchBookmarks=true&watch=true").andUpgradeToWebSocket().open().waitFor(10).andEmit(new WatchEvent(pod1, "MODIFIED")).done().once();
statusService = new KubernetesBasedAdapterInstanceStatusService(client) {
@Override
protected void onAdapterContainerAdded(final String containerId) {
LOG.debug("onAdapterContainerAdded; containerId: '{}'", containerId);
eventLatch.countDown();
}
};
assertThat(statusService).isNotNull();
if (eventLatch.await(10, TimeUnit.SECONDS)) {
assertThat(statusService.getActiveAdapterInstanceContainerIds().isPresent()).isTrue();
assertThat(statusService.getActiveAdapterInstanceContainerIds().get()).containsExactly(pod0ContainerId, pod1ContainerId);
final String adapterInstanceId0 = pod0.getMetadata().getName() + "_" + pod0ContainerId + "_1";
assertThat(statusService.getStatus(adapterInstanceId0)).isEqualTo(AdapterInstanceStatus.ALIVE);
final String adapterInstanceId1 = pod1.getMetadata().getName() + "_" + pod1ContainerId + "_1";
assertThat(statusService.getStatus(adapterInstanceId1)).isEqualTo(AdapterInstanceStatus.ALIVE);
} else {
fail("added pod not detected");
}
}
use of io.fabric8.kubernetes.client.Watch in project hono by eclipse.
the class KubernetesBasedAdapterInstanceStatusService method stop.
@Override
public Future<Void> stop() {
LOG.trace("stopping status service");
if (active.getAndSet(-1) == -1) {
// already stopped
return Future.succeededFuture();
}
final Watch w = watch;
if (w != null) {
w.close();
}
client.close();
return Future.succeededFuture();
}
use of io.fabric8.kubernetes.client.Watch in project docker-maven-plugin by fabric8io.
the class WatchService method watch.
public synchronized void watch(WatchContext context, BuildService.BuildContext buildContext, List<ImageConfiguration> images) throws DockerAccessException, MojoExecutionException {
// Important to be be a single threaded scheduler since watch jobs must run serialized
ScheduledExecutorService executor = null;
try {
executor = Executors.newSingleThreadScheduledExecutor();
for (StartOrderResolver.Resolvable resolvable : runService.getImagesConfigsInOrder(queryService, images)) {
final ImageConfiguration imageConfig = (ImageConfiguration) resolvable;
String imageId = queryService.getImageId(imageConfig.getName());
String containerId = runService.lookupContainer(imageConfig.getName());
ImageWatcher watcher = new ImageWatcher(imageConfig, context, imageId, containerId);
long interval = watcher.getInterval();
WatchMode watchMode = watcher.getWatchMode(imageConfig);
log.info("Watching " + imageConfig.getName() + (watchMode != null ? " using " + watchMode.getDescription() : ""));
ArrayList<String> tasks = new ArrayList<>();
if (imageConfig.getBuildConfiguration() != null) {
for (AssemblyConfiguration assemblyConfiguration : imageConfig.getBuildConfiguration().getAssemblyConfigurations()) {
if (watcher.isCopy()) {
String containerBaseDir = assemblyConfiguration.getTargetDir();
schedule(executor, createCopyWatchTask(watcher, assemblyConfiguration.getName(), context.getMojoParameters(), containerBaseDir), interval);
tasks.add("copying artifacts");
}
if (watcher.isBuild()) {
schedule(executor, createBuildWatchTask(watcher, assemblyConfiguration.getName(), context.getMojoParameters(), watchMode == WatchMode.both, buildContext), interval);
tasks.add("rebuilding");
}
}
}
if (watcher.isRun() && watcher.getContainerId() != null) {
schedule(executor, createRestartWatchTask(watcher), interval);
tasks.add("restarting");
}
if (tasks.size() > 0) {
log.info("%s: Watch for %s", imageConfig.getDescription(), StringUtils.join(tasks.toArray(), " and "));
}
}
log.info("Waiting ...");
if (!context.isKeepRunning()) {
runService.addShutdownHookForStoppingContainers(context.isKeepContainer(), context.isRemoveVolumes(), context.isAutoCreateCustomNetworks());
}
wait();
} catch (InterruptedException e) {
log.warn("Interrupted");
} finally {
if (executor != null) {
executor.shutdownNow();
}
}
}
Aggregations