SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Downloaden Sie, um offline zu lesen
Virtualizing Java in Java

How?
Alexey Ragozin

jug.ru
12 Dec 2013
Virtualizing Java in Java
Single JVM hosting
•
•
•
•
•

multiple “pseudo JVMs”, which
Have independent system properties
Have independent statics
May have different classpath
May be forcefully terminated or
suspended/resumed

You can deploy whole distributed application
topology inside of JUnit test
All started with Oracle Coherence
Native Java distributed peer-to-peer key/value storage
With a lot of extension points
 Distributed data processing
 Listeners for remote events
 Read-through / write-through patterns
 Pluggable serialization
And inability to start two cluster members in one JVM
And we need to test
Behavior of very specific features
Serialization/deserialization defects
Data routing and collocation aspects
Code meant for distributed execution
Threading aspects
Classpath differences between cluster
processes
Cluster configuration tweaks
Multiplexing singletons
Custom classloader
Force to reload classes already loaded by
parent (second copy of class loaded)
Got our first cluster-in-JVM alive
 InheritentThreadLocal to add fancy stuff
– Multiplexing system properties
– Multiplexing multiplex console output
Heated competition
Three open source “cluster virtualizing” effort around
Oracle Coherence

 GridKit (ChTest)
code.google.com/p/gridkit
 Oracle tools
github.com/coherence-community/oracle-tools
 Little
www.littlegrid.net
“Distributing” test case
How to start The Application on “virtual cluster”?

Old school
 Main classes and command line arguments
 But if you need to do verification inside of
vinode?
 A separate main for each test case?
But how all this is relevant to me?
Normal client/server application
 You can use your real main classes instead of mocking server

Hadoop / HBase / Cassandra
 Distributed
 Deployment unfriendly
 Ship with single node – cut down versions
“Distributing” test case
Transparent remotting
client1.exec(new Runnable() {
@Override
public void run() {
NamedCache cache = CacheFactory.getCache(cacheName);
Assert.assertNull(cache.get("A"));
cache.put("A", "aaa");
}
});
client2.exec(new Runnable() {
@Override
public void run() {
NamedCache cache = CacheFactory.getCache(cacheName);
Assert.assertEquals("aaa", cache.get("A"));
}
});
We want to test more!
We are in control class loading
— let’s tweak classpath on flight
 Inject resources
 Remove server classes from client
 Test different codebase versions
Backward compatibility testing

Master JVM, client regression test pack
[trunk version]
Case

Client
[version X]

Server
[trunk version]
Cross version tests

Master JVM, client regression test pack
[trunk version]
Case
Client
[version X]

Client
[version Y]

Server
[version Z]
Managing artifacts
… a bunch of black magic to find local repo
and managing classpath as easy as …
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.8</version>
<executions>
<execution>
<id>viconcurrent-0.7.15</id>
<phase>test-compile</phase>
<goals>
<goal>get</goal>
</goals>
<configuration>
<artifact>org.gridkit.lab:viconcurrent:0.7.15</artifact>
</configuration>
</execution>
</executions>
</plugin>
Managing artifacts
How to get needed artifact on local disk
- Maven will disallow two versions of same artifact
- but we can trick it …
ViNode node;
…
node.x(MAVEN).replace("org.gridkit.lab", "viconcurrent", "0.7.15");

Transitive dependencies are not included, though.
Transparent remotting
Own implementation of RMI
 Standard Java serialization
 Serializing of anonymous Runnable/Callable
 Auto export of Remote interfaces

Writing distributed code by convention!
Bidirectional communications
public interface RemotePut extends Remote {
public void put(Object key, Object value);
}

public interface RemotePut extends Remote {

@SuppressWarnings("unused")
@Test
public void bidirectional_remoting() {
// Present for typical single node cluster
cloud.all().presetFastLocalCluster();

public void put(Object key, Object value);

cloud.node("storage.**").localStorage(true);
cloud.node("client.**").localStorage(false);

}

// Simulates DefaultCacheServer based process
cloud.node("storage.**").autoStartServices();
// declaring specific nodes to be created
CohNode storage = cloud.node("storage.1");
CohNode client1 = cloud.node("client.1");
CohNode client2 = cloud.node("client.2");

RemotePut remoteService =
client1.exec(new Callable<RemotePut>() {
@Override
public RemotePut call() {
final NamedCache cache = CacheFactory.getCache(cacheName);

// now we have 3 specific nodes in cloud
// all of then will be initialized in parallel
cloud.all().ensureCluster();
final String cacheName = "distr-a";

return new RemotePut() {
@Override
public void put(Object key, Object value) {
cache.put(key, value);
}
};

RemotePut remoteService =
client1.exec(new Callable<RemotePut>() {
@Override
public RemotePut call() {
final NamedCache cache = CacheFactory.getCache(cacheName);
return new RemotePut() {
@Override
public void put(Object key, Object value) {
cache.put(key, value);
}
};

}
});
}
});

remoteService.put("A", "aaa");

remoteService.put("A", "aaa");

client2.exec(new Runnable() {
@Override
public void run() {
NamedCache cache = CacheFactory.getCache(cacheName);
Assert.assertEquals("aaa", cache.get("A"));
}
});
}
Bidirectional communications
Extending java.rmi.Remotexec
will mark interface for auto export
public interface RemotePut extends Remote {
public void put(Object key, Object value);
}

RemotePut remoteService =
client1.exec(new Callable<RemotePut>() {
@Override
public RemotePut call() {
final NamedCache cache = CacheFactory.getCache(cacheName);
return new RemotePut() {
@Override
public void put(Object key, Object value) {
cache.put(key, value);
}
};

}
});

remoteService.put("A", "aaa");

Here we got a remote stub, not a
real implementation of interface

Unlike Java RMI, there is no need to
declare RemoteException for
every method
Result of callable will be serialized
and transferred to caller
Objects implementing remote
interfaces are automatically replaced
with remote stub during serialization
Call to a stub, will be converted to
“remote” call to instance we have
created in “virtualized” node few
lines above
Sneak peek: Instrumentation
 System.exit() – is still fatal
 Some cases need “virtual time”
 Tweaking monolithic code
 Fault injection
 Mock injection
Sneak peek: Instrumentation
PowerMock
 Recompiles everything (Coherence ~ 5000 classes)

AspectJ
 Static interceptors
ByteMan
 Using agent + weird language
Sneak peek: Instrumentation
ViNode node = ...
ViHookBuilder
.newCallSiteHook()
.onTypes(System.class)
.onMethod("exit")
.doReturn(null)
.apply(node);
node.exec(new Callable<Void>() {
@Override
public Void call() throws Exception {
System.exit(0);
return null;
}
});
LET’S TAKE A BREAK HERE

Questions?
From “virtual” to real cluster

Alexey Ragozin

jug.ru
12 Dec 2013
Virtual stuff is so good
Managing virtual nodes in deterministic way, in
Java, having all luxury of exception handling and
richness of libraries – feeling were so good …
I wished, I could rollout JVMs across real servers
Your network is Big JVM
Same API
3 types of nodes: in-process, local, remote
Transparent remotting
SSH to manage remote server
Automatic classpath replication (with caching)
Zero infrastructure
 Any OS for master host
 SSHd + JVM for slave hosts
New opportunities
Performance testing





deploy system under test
deploy load generators
deploy monitoring agents
gather all result in one place

Deployment (remote execution task for ANT)
Replace your putty with Java IDE
 log scrapping
 parallel execution
As easy as …
@Test
public void remote_hello_world() throws InterruptedException
{
ViManager cloud = CloudFactory.createSimpleSshCloud();
cloud.node("myserver.uk.db.com");
cloud.node("**").exec(new Callable<Void>() {
@Override
public Void call() throws Exception
{
String localHost = InetAddress.getLocalHost().toString();
System.out.println("Hi! I'm running on " + localHost);
return null;
}
});
}
Behind the scene
•
•
•
•

JSCh – SSH client (slightly patched)
Collected classpath artifacts
SCP jars to remote target
Start remote agent (JVM)
 stdOut / stdIn for master – agent communications

• Agent start slave process
• Slave start RMI node and connects (TCP) to master
 agent acts as TCP proxy
Death clock is ticking
Master JVM kills slave processes, unless
 SSH session was interrupted
 someone kill -9 master JVM
 master JVM has crashed (e.g. under debuger)
Death clock is ticking on slave though
 if master is not responding
 slave process will terminate itself
Performance testing
•
•
•
•
•

Master JVM is running on CI
JUnit to start test
Loaded generator farm is deployed on test servers
Monitoring agents deployed on application cluster
Metrics are buffered locally, then send to master and processed

Real test
• Four servers – application
• 50 servers – load farm
• Over 200 – slaves processes
Coding for 200+ processes
Driver - concept
• Driver – Java interface encapsulates test
action
• One way methods
• Friendly for remotting for parallel invokation
+ some utility for parallel execution, workflow
etc
Example:
https://gridkit.googlecode.com/svn/grid-lab/trunk/examples/zk-benchmark-sample
Monitoring
Sigar - http://www.hyperic.com/products/sigar
• collecting common system metrics
Attach API – built-n JVM monitoring
SJK – spin-off CLI tool for JVM diagnostics
• https://github.com/aragozin/jvm-tools
Links
NanoCloud
• https://code.google.com/p/gridkit/wiki/NanoCloudTutorial
• Maven Central: org.gridkit.lab:telecontrol-ssh:0.7.22
• http://blog.ragozin.info/2013/01/remote-code-execution-in-java-made.html

ANT task
• https://github.com/gridkit/gridant

ChTest (Coherence test tool)
• https://code.google.com/p/gridkit/wiki/ChTest
• Maven Central: org.gridkit.coherence-tools:chtest:0.2.4
Thank you
http://blog.ragozin.info
- my articles
http://code.google.com/p/gridkit
http://github.com/gridkit
- my open source code
http://aragozin.timepad.ru
- tech meetups in Moscow

Alexey Ragozin
alexey.ragozin@gmail.com

Weitere ähnliche Inhalte

Was ist angesagt?

77739818 troubleshooting-web-logic-103
77739818 troubleshooting-web-logic-10377739818 troubleshooting-web-logic-103
77739818 troubleshooting-web-logic-103
shashank_ibm
 
London devops logging
London devops loggingLondon devops logging
London devops logging
Tomas Doran
 
Effective testing for spark programs Strata NY 2015
Effective testing for spark programs   Strata NY 2015Effective testing for spark programs   Strata NY 2015
Effective testing for spark programs Strata NY 2015
Holden Karau
 

Was ist angesagt? (20)

77739818 troubleshooting-web-logic-103
77739818 troubleshooting-web-logic-10377739818 troubleshooting-web-logic-103
77739818 troubleshooting-web-logic-103
 
Performance tests with Gatling
Performance tests with GatlingPerformance tests with Gatling
Performance tests with Gatling
 
Java Performance Tuning
Java Performance TuningJava Performance Tuning
Java Performance Tuning
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoring
 
자바 성능 강의
자바 성능 강의자바 성능 강의
자바 성능 강의
 
Problems with PostgreSQL on Multi-core Systems with MultiTerabyte Data
Problems with PostgreSQL on Multi-core Systems with MultiTerabyte DataProblems with PostgreSQL on Multi-core Systems with MultiTerabyte Data
Problems with PostgreSQL on Multi-core Systems with MultiTerabyte Data
 
Java performance tuning
Java performance tuningJava performance tuning
Java performance tuning
 
London devops logging
London devops loggingLondon devops logging
London devops logging
 
Java Performance Monitoring & Tuning
Java Performance Monitoring & TuningJava Performance Monitoring & Tuning
Java Performance Monitoring & Tuning
 
PostgreSQL Extensions: A deeper look
PostgreSQL Extensions:  A deeper lookPostgreSQL Extensions:  A deeper look
PostgreSQL Extensions: A deeper look
 
Advanced Oracle Troubleshooting
Advanced Oracle TroubleshootingAdvanced Oracle Troubleshooting
Advanced Oracle Troubleshooting
 
High Availability PostgreSQL with Zalando Patroni
High Availability PostgreSQL with Zalando PatroniHigh Availability PostgreSQL with Zalando Patroni
High Availability PostgreSQL with Zalando Patroni
 
Cassandra - lesson learned
Cassandra  - lesson learnedCassandra  - lesson learned
Cassandra - lesson learned
 
Java performance tuning
Java performance tuningJava performance tuning
Java performance tuning
 
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
Erik Skytthe - Monitoring Mesos, Docker, Containers with Zabbix | ZabConf2016
 
DIY Java Profiling
DIY Java ProfilingDIY Java Profiling
DIY Java Profiling
 
Oracle Latch and Mutex Contention Troubleshooting
Oracle Latch and Mutex Contention TroubleshootingOracle Latch and Mutex Contention Troubleshooting
Oracle Latch and Mutex Contention Troubleshooting
 
Profiling & Testing with Spark
Profiling & Testing with SparkProfiling & Testing with Spark
Profiling & Testing with Spark
 
Effective testing for spark programs Strata NY 2015
Effective testing for spark programs   Strata NY 2015Effective testing for spark programs   Strata NY 2015
Effective testing for spark programs Strata NY 2015
 

Andere mochten auch

Andere mochten auch (6)

Filtering 100M objects in Coherence cache. What can go wrong?
Filtering 100M objects in Coherence cache. What can go wrong?Filtering 100M objects in Coherence cache. What can go wrong?
Filtering 100M objects in Coherence cache. What can go wrong?
 
Garbage collection in JVM
Garbage collection in JVMGarbage collection in JVM
Garbage collection in JVM
 
Java GC tuning and monitoring (by Alexander Ashitkin)
Java GC tuning and monitoring (by Alexander Ashitkin)Java GC tuning and monitoring (by Alexander Ashitkin)
Java GC tuning and monitoring (by Alexander Ashitkin)
 
Cборка мусора в Java без пауз (HighLoad++ 2013)
Cборка мусора в Java без пауз  (HighLoad++ 2013)Cборка мусора в Java без пауз  (HighLoad++ 2013)
Cборка мусора в Java без пауз (HighLoad++ 2013)
 
Performance Test Driven Development (CEE SERC 2013 Moscow)
Performance Test Driven Development (CEE SERC 2013 Moscow)Performance Test Driven Development (CEE SERC 2013 Moscow)
Performance Test Driven Development (CEE SERC 2013 Moscow)
 
JIT-компиляция в виртуальной машине Java (HighLoad++ 2013)
JIT-компиляция в виртуальной машине Java (HighLoad++ 2013)JIT-компиляция в виртуальной машине Java (HighLoad++ 2013)
JIT-компиляция в виртуальной машине Java (HighLoad++ 2013)
 

Ähnlich wie Virtualizing Java in Java (jug.ru)

Nanocloud cloud scale jvm
Nanocloud   cloud scale jvmNanocloud   cloud scale jvm
Nanocloud cloud scale jvm
aragozin
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Paul King
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Distributed Objects and JAVA
Distributed Objects and JAVADistributed Objects and JAVA
Distributed Objects and JAVA
elliando dias
 

Ähnlich wie Virtualizing Java in Java (jug.ru) (20)

Nanocloud cloud scale jvm
Nanocloud   cloud scale jvmNanocloud   cloud scale jvm
Nanocloud cloud scale jvm
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVM
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
Nodejs Intro Part One
Nodejs Intro Part OneNodejs Intro Part One
Nodejs Intro Part One
 
Beyond Unit Testing
Beyond Unit TestingBeyond Unit Testing
Beyond Unit Testing
 
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
Industrial Strength Groovy - Tools for the Professional Groovy Developer: Pau...
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!Integration tests: use the containers, Luke!
Integration tests: use the containers, Luke!
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Advanced akka features
Advanced akka featuresAdvanced akka features
Advanced akka features
 
It pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_enIt pro dev_birbilis_20101127_en
It pro dev_birbilis_20101127_en
 
Java util concurrent
Java util concurrentJava util concurrent
Java util concurrent
 
Harmonious Development: Via Vagrant and Puppet
Harmonious Development: Via Vagrant and PuppetHarmonious Development: Via Vagrant and Puppet
Harmonious Development: Via Vagrant and Puppet
 
Jdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsJdk Tools For Performance Diagnostics
Jdk Tools For Performance Diagnostics
 
Cp7 rpc
Cp7 rpcCp7 rpc
Cp7 rpc
 
Testing in android
Testing in androidTesting in android
Testing in android
 
Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015Akka Cluster in Java - JCConf 2015
Akka Cluster in Java - JCConf 2015
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Distributed Objects and JAVA
Distributed Objects and JAVADistributed Objects and JAVA
Distributed Objects and JAVA
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 

Mehr von aragozin

Блеск и нищета распределённых кэшей
Блеск и нищета распределённых кэшейБлеск и нищета распределённых кэшей
Блеск и нищета распределённых кэшей
aragozin
 
Распределённый кэш или хранилище данных. Что выбрать?
Распределённый кэш или хранилище данных. Что выбрать?Распределённый кэш или хранилище данных. Что выбрать?
Распределённый кэш или хранилище данных. Что выбрать?
aragozin
 
Tech talk network - friend or foe
Tech talk   network - friend or foeTech talk   network - friend or foe
Tech talk network - friend or foe
aragozin
 
Поиск на своем сайте, обзор open source решений
Поиск на своем сайте, обзор open source решенийПоиск на своем сайте, обзор open source решений
Поиск на своем сайте, обзор open source решений
aragozin
 
Coherence SIG: Advanced usage of indexes in coherence
Coherence SIG: Advanced usage of indexes in coherenceCoherence SIG: Advanced usage of indexes in coherence
Coherence SIG: Advanced usage of indexes in coherence
aragozin
 

Mehr von aragozin (17)

Распределённое нагрузочное тестирование на Java
Распределённое нагрузочное тестирование на JavaРаспределённое нагрузочное тестирование на Java
Распределённое нагрузочное тестирование на Java
 
Java profiling Do It Yourself
Java profiling Do It YourselfJava profiling Do It Yourself
Java profiling Do It Yourself
 
DIY Java Profiler
DIY Java ProfilerDIY Java Profiler
DIY Java Profiler
 
Java black box profiling
Java black box profilingJava black box profiling
Java black box profiling
 
Блеск и нищета распределённых кэшей
Блеск и нищета распределённых кэшейБлеск и нищета распределённых кэшей
Блеск и нищета распределённых кэшей
 
JIT compilation in modern platforms – challenges and solutions
JIT compilation in modern platforms – challenges and solutionsJIT compilation in modern platforms – challenges and solutions
JIT compilation in modern platforms – challenges and solutions
 
Casual mass parallel computing
Casual mass parallel computingCasual mass parallel computing
Casual mass parallel computing
 
Борьба с GС паузами в JVM
Борьба с GС паузами в JVMБорьба с GС паузами в JVM
Борьба с GС паузами в JVM
 
Распределённый кэш или хранилище данных. Что выбрать?
Распределённый кэш или хранилище данных. Что выбрать?Распределённый кэш или хранилище данных. Что выбрать?
Распределённый кэш или хранилище данных. Что выбрать?
 
Devirtualization of method calls
Devirtualization of method callsDevirtualization of method calls
Devirtualization of method calls
 
Tech talk network - friend or foe
Tech talk   network - friend or foeTech talk   network - friend or foe
Tech talk network - friend or foe
 
Database backed coherence cache
Database backed coherence cacheDatabase backed coherence cache
Database backed coherence cache
 
ORM and distributed caching
ORM and distributed cachingORM and distributed caching
ORM and distributed caching
 
Секреты сборки мусора в Java [DUMP-IT 2012]
Секреты сборки мусора в Java [DUMP-IT 2012]Секреты сборки мусора в Java [DUMP-IT 2012]
Секреты сборки мусора в Java [DUMP-IT 2012]
 
Поиск на своем сайте, обзор open source решений
Поиск на своем сайте, обзор open source решенийПоиск на своем сайте, обзор open source решений
Поиск на своем сайте, обзор open source решений
 
High Performance Computing - Cloud Point of View
High Performance Computing - Cloud Point of ViewHigh Performance Computing - Cloud Point of View
High Performance Computing - Cloud Point of View
 
Coherence SIG: Advanced usage of indexes in coherence
Coherence SIG: Advanced usage of indexes in coherenceCoherence SIG: Advanced usage of indexes in coherence
Coherence SIG: Advanced usage of indexes in coherence
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Virtualizing Java in Java (jug.ru)

  • 1. Virtualizing Java in Java How? Alexey Ragozin jug.ru 12 Dec 2013
  • 2. Virtualizing Java in Java Single JVM hosting • • • • • multiple “pseudo JVMs”, which Have independent system properties Have independent statics May have different classpath May be forcefully terminated or suspended/resumed You can deploy whole distributed application topology inside of JUnit test
  • 3. All started with Oracle Coherence Native Java distributed peer-to-peer key/value storage With a lot of extension points  Distributed data processing  Listeners for remote events  Read-through / write-through patterns  Pluggable serialization And inability to start two cluster members in one JVM
  • 4. And we need to test Behavior of very specific features Serialization/deserialization defects Data routing and collocation aspects Code meant for distributed execution Threading aspects Classpath differences between cluster processes Cluster configuration tweaks
  • 5. Multiplexing singletons Custom classloader Force to reload classes already loaded by parent (second copy of class loaded) Got our first cluster-in-JVM alive  InheritentThreadLocal to add fancy stuff – Multiplexing system properties – Multiplexing multiplex console output
  • 6. Heated competition Three open source “cluster virtualizing” effort around Oracle Coherence  GridKit (ChTest) code.google.com/p/gridkit  Oracle tools github.com/coherence-community/oracle-tools  Little www.littlegrid.net
  • 7. “Distributing” test case How to start The Application on “virtual cluster”? Old school  Main classes and command line arguments  But if you need to do verification inside of vinode?  A separate main for each test case?
  • 8. But how all this is relevant to me? Normal client/server application  You can use your real main classes instead of mocking server Hadoop / HBase / Cassandra  Distributed  Deployment unfriendly  Ship with single node – cut down versions
  • 9. “Distributing” test case Transparent remotting client1.exec(new Runnable() { @Override public void run() { NamedCache cache = CacheFactory.getCache(cacheName); Assert.assertNull(cache.get("A")); cache.put("A", "aaa"); } }); client2.exec(new Runnable() { @Override public void run() { NamedCache cache = CacheFactory.getCache(cacheName); Assert.assertEquals("aaa", cache.get("A")); } });
  • 10. We want to test more! We are in control class loading — let’s tweak classpath on flight  Inject resources  Remove server classes from client  Test different codebase versions
  • 11. Backward compatibility testing Master JVM, client regression test pack [trunk version] Case Client [version X] Server [trunk version]
  • 12. Cross version tests Master JVM, client regression test pack [trunk version] Case Client [version X] Client [version Y] Server [version Z]
  • 13. Managing artifacts … a bunch of black magic to find local repo and managing classpath as easy as … <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.8</version> <executions> <execution> <id>viconcurrent-0.7.15</id> <phase>test-compile</phase> <goals> <goal>get</goal> </goals> <configuration> <artifact>org.gridkit.lab:viconcurrent:0.7.15</artifact> </configuration> </execution> </executions> </plugin>
  • 14. Managing artifacts How to get needed artifact on local disk - Maven will disallow two versions of same artifact - but we can trick it … ViNode node; … node.x(MAVEN).replace("org.gridkit.lab", "viconcurrent", "0.7.15"); Transitive dependencies are not included, though.
  • 15. Transparent remotting Own implementation of RMI  Standard Java serialization  Serializing of anonymous Runnable/Callable  Auto export of Remote interfaces Writing distributed code by convention!
  • 16. Bidirectional communications public interface RemotePut extends Remote { public void put(Object key, Object value); } public interface RemotePut extends Remote { @SuppressWarnings("unused") @Test public void bidirectional_remoting() { // Present for typical single node cluster cloud.all().presetFastLocalCluster(); public void put(Object key, Object value); cloud.node("storage.**").localStorage(true); cloud.node("client.**").localStorage(false); } // Simulates DefaultCacheServer based process cloud.node("storage.**").autoStartServices(); // declaring specific nodes to be created CohNode storage = cloud.node("storage.1"); CohNode client1 = cloud.node("client.1"); CohNode client2 = cloud.node("client.2"); RemotePut remoteService = client1.exec(new Callable<RemotePut>() { @Override public RemotePut call() { final NamedCache cache = CacheFactory.getCache(cacheName); // now we have 3 specific nodes in cloud // all of then will be initialized in parallel cloud.all().ensureCluster(); final String cacheName = "distr-a"; return new RemotePut() { @Override public void put(Object key, Object value) { cache.put(key, value); } }; RemotePut remoteService = client1.exec(new Callable<RemotePut>() { @Override public RemotePut call() { final NamedCache cache = CacheFactory.getCache(cacheName); return new RemotePut() { @Override public void put(Object key, Object value) { cache.put(key, value); } }; } }); } }); remoteService.put("A", "aaa"); remoteService.put("A", "aaa"); client2.exec(new Runnable() { @Override public void run() { NamedCache cache = CacheFactory.getCache(cacheName); Assert.assertEquals("aaa", cache.get("A")); } }); }
  • 17. Bidirectional communications Extending java.rmi.Remotexec will mark interface for auto export public interface RemotePut extends Remote { public void put(Object key, Object value); } RemotePut remoteService = client1.exec(new Callable<RemotePut>() { @Override public RemotePut call() { final NamedCache cache = CacheFactory.getCache(cacheName); return new RemotePut() { @Override public void put(Object key, Object value) { cache.put(key, value); } }; } }); remoteService.put("A", "aaa"); Here we got a remote stub, not a real implementation of interface Unlike Java RMI, there is no need to declare RemoteException for every method Result of callable will be serialized and transferred to caller Objects implementing remote interfaces are automatically replaced with remote stub during serialization Call to a stub, will be converted to “remote” call to instance we have created in “virtualized” node few lines above
  • 18. Sneak peek: Instrumentation  System.exit() – is still fatal  Some cases need “virtual time”  Tweaking monolithic code  Fault injection  Mock injection
  • 19. Sneak peek: Instrumentation PowerMock  Recompiles everything (Coherence ~ 5000 classes) AspectJ  Static interceptors ByteMan  Using agent + weird language
  • 20. Sneak peek: Instrumentation ViNode node = ... ViHookBuilder .newCallSiteHook() .onTypes(System.class) .onMethod("exit") .doReturn(null) .apply(node); node.exec(new Callable<Void>() { @Override public Void call() throws Exception { System.exit(0); return null; } });
  • 21. LET’S TAKE A BREAK HERE Questions?
  • 22. From “virtual” to real cluster Alexey Ragozin jug.ru 12 Dec 2013
  • 23. Virtual stuff is so good Managing virtual nodes in deterministic way, in Java, having all luxury of exception handling and richness of libraries – feeling were so good … I wished, I could rollout JVMs across real servers
  • 24. Your network is Big JVM Same API 3 types of nodes: in-process, local, remote Transparent remotting SSH to manage remote server Automatic classpath replication (with caching) Zero infrastructure  Any OS for master host  SSHd + JVM for slave hosts
  • 25. New opportunities Performance testing     deploy system under test deploy load generators deploy monitoring agents gather all result in one place Deployment (remote execution task for ANT) Replace your putty with Java IDE  log scrapping  parallel execution
  • 26. As easy as … @Test public void remote_hello_world() throws InterruptedException { ViManager cloud = CloudFactory.createSimpleSshCloud(); cloud.node("myserver.uk.db.com"); cloud.node("**").exec(new Callable<Void>() { @Override public Void call() throws Exception { String localHost = InetAddress.getLocalHost().toString(); System.out.println("Hi! I'm running on " + localHost); return null; } }); }
  • 27. Behind the scene • • • • JSCh – SSH client (slightly patched) Collected classpath artifacts SCP jars to remote target Start remote agent (JVM)  stdOut / stdIn for master – agent communications • Agent start slave process • Slave start RMI node and connects (TCP) to master  agent acts as TCP proxy
  • 28. Death clock is ticking Master JVM kills slave processes, unless  SSH session was interrupted  someone kill -9 master JVM  master JVM has crashed (e.g. under debuger) Death clock is ticking on slave though  if master is not responding  slave process will terminate itself
  • 29. Performance testing • • • • • Master JVM is running on CI JUnit to start test Loaded generator farm is deployed on test servers Monitoring agents deployed on application cluster Metrics are buffered locally, then send to master and processed Real test • Four servers – application • 50 servers – load farm • Over 200 – slaves processes
  • 30. Coding for 200+ processes Driver - concept • Driver – Java interface encapsulates test action • One way methods • Friendly for remotting for parallel invokation + some utility for parallel execution, workflow etc Example: https://gridkit.googlecode.com/svn/grid-lab/trunk/examples/zk-benchmark-sample
  • 31. Monitoring Sigar - http://www.hyperic.com/products/sigar • collecting common system metrics Attach API – built-n JVM monitoring SJK – spin-off CLI tool for JVM diagnostics • https://github.com/aragozin/jvm-tools
  • 32. Links NanoCloud • https://code.google.com/p/gridkit/wiki/NanoCloudTutorial • Maven Central: org.gridkit.lab:telecontrol-ssh:0.7.22 • http://blog.ragozin.info/2013/01/remote-code-execution-in-java-made.html ANT task • https://github.com/gridkit/gridant ChTest (Coherence test tool) • https://code.google.com/p/gridkit/wiki/ChTest • Maven Central: org.gridkit.coherence-tools:chtest:0.2.4
  • 33. Thank you http://blog.ragozin.info - my articles http://code.google.com/p/gridkit http://github.com/gridkit - my open source code http://aragozin.timepad.ru - tech meetups in Moscow Alexey Ragozin alexey.ragozin@gmail.com