Search in sources :

Example 36 with Promise

use of org.nustaq.kontraktor.Promise in project kontraktor by RuedigerMoeller.

the class RxJava method remotingTest.

@Test
public void remotingTest() {
    Observable<Integer> range = Observable.range(0, NUM_MSG / 4);
    Publisher<Integer> pub = RxReactiveStreams.toPublisher(range);
    KxReactiveStreams.get().asKxPublisher(pub).serve(new TCPNIOPublisher().port(3456));
    RateMeasure rm = new RateMeasure("events");
    AtomicInteger cnt = new AtomicInteger(0);
    Promise<Integer> finished = new Promise<>();
    KxReactiveStreams.get().connect(Integer.class, new TCPConnectable().host("localhost").port(3456)).subscribe((r, e) -> {
        rm.count();
        if (Actors.isResult(e))
            cnt.incrementAndGet();
        else
            finished.resolve(cnt.get());
    });
    Assert.assertTrue(finished.await(50000) == NUM_MSG / 4);
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Promise(org.nustaq.kontraktor.Promise) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TCPConnectable(org.nustaq.kontraktor.remoting.tcp.TCPConnectable) RateMeasure(org.nustaq.kontraktor.util.RateMeasure) TCPNIOPublisher(org.nustaq.kontraktor.remoting.tcp.TCPNIOPublisher) Test(org.junit.Test)

Example 37 with Promise

use of org.nustaq.kontraktor.Promise in project kontraktor by RuedigerMoeller.

the class TableSpaceSharding method createOrLoadTable.

@Override
public IPromise<RealLiveTable> createOrLoadTable(TableDescription desc) {
    Promise<RealLiveTable> res = new Promise();
    ArrayList<IPromise<RealLiveTable>> results = new ArrayList();
    for (int i = 0; i < shards.length; i++) {
        TableSpaceActor shard = shards[i];
        IPromise<RealLiveTable> table = shard.createOrLoadTable(desc.clone().shardNo(i));
        Promise p = new Promise();
        results.add(p);
        final int finalI = i;
        table.then((r, e) -> {
            if (e == null)
                Log.Info(this, "table creation: " + desc.getName() + " " + finalI);
            else if (e instanceof Throwable)
                Log.Info(this, (Throwable) e, "failed table creation: " + desc.getName() + " " + finalI);
            else
                Log.Info(this, "failed table creation: " + desc.getName() + " " + finalI + " " + e);
            p.complete(r, e);
        });
    }
    List<IPromise<RealLiveTable>> tables = Actors.all(results).await();
    RealLiveTable[] tableShards = new RealLiveTable[tables.size()];
    boolean errors = false;
    for (int i = 0; i < tables.size(); i++) {
        if (tables.get(i).get() == null) {
            res.reject(tables.get(i).getError());
            errors = true;
            break;
        } else {
            // tables[i].get().shardNo();
            int sno = i;
            if (tableShards[sno] != null) {
                res.reject("shard " + sno + " is present more than once");
                errors = true;
                break;
            }
            tableShards[sno] = tables.get(i).get();
        }
    }
    if (!errors) {
        TableSharding ts = new TableSharding(func, tableShards, desc);
        tableMap.put(desc.getName(), ts);
        tableDescriptionMap.put(desc.getName(), desc);
        res.resolve(ts);
    }
    return res;
}
Also used : RealLiveTable(org.nustaq.reallive.api.RealLiveTable) ArrayList(java.util.ArrayList) TableSharding(org.nustaq.reallive.impl.actors.TableSharding) Promise(org.nustaq.kontraktor.Promise) IPromise(org.nustaq.kontraktor.IPromise) IPromise(org.nustaq.kontraktor.IPromise)

Example 38 with Promise

use of org.nustaq.kontraktor.Promise in project kontraktor by RuedigerMoeller.

the class ProcessStarter method terminateProcess.

public IPromise<Integer> terminateProcess(String procid, boolean force, int timeoutSec) {
    ProcessInfo processInfo = processes.get(procid);
    if (processInfo == null)
        return resolve(null);
    if (processInfo.getProc() == null) {
        StarterDesc sd = siblings.get(processInfo.getStarterId());
        if (sd != null)
            return sd.getRemoteRef().terminateProcess(procid, force, timeoutSec);
        else
            return reject("unknown starter:" + processInfo.getStarterId());
    }
    long pid = -1;
    try {
        Field f = processInfo.getProc().getClass().getDeclaredField("pid");
        f.setAccessible(true);
        pid = f.getLong(processInfo.getProc());
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
    if (pid != -1) {
        try {
            Process kl = Runtime.getRuntime().exec("kill -9 " + pid);
            kl.waitFor(timeoutSec, TimeUnit.SECONDS);
            self().distribute(TERMINATED, processInfo, null);
            return resolve(new Integer(kl.exitValue()));
        } catch (IOException e) {
            e.printStackTrace();
            return reject(e);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } else {
        if (force)
            processInfo.getProc().destroyForcibly();
        else
            processInfo.getProc().destroy();
    }
    Promise res = new Promise();
    final Process proc = processInfo.getProc();
    execInThreadPool(() -> {
        proc.waitFor(timeoutSec, TimeUnit.SECONDS);
        if (proc.isAlive()) {
            res.reject("timeout");
        } else {
            processes.remove(processInfo.getId());
            self().distribute(TERMINATED, processInfo, null);
            res.resolve(proc.exitValue());
        }
        return null;
    });
    return res;
}
Also used : Field(java.lang.reflect.Field) Promise(org.nustaq.kontraktor.Promise) IPromise(org.nustaq.kontraktor.IPromise)

Example 39 with Promise

use of org.nustaq.kontraktor.Promise in project kontraktor by RuedigerMoeller.

the class ReactApp method getDirectRequestResponse.

@Override
protected IPromise<String> getDirectRequestResponse(String path) {
    String[] split = path.split("/");
    if (split.length == 0)
        return resolve("<html>Invalid Link</html>");
    Promise res = new Promise();
    sessionStorage.takeToken(split[split.length - 1], false).then((token, err) -> {
        if (token != null) {
            res.resolve("<html>User confirmed: '" + token.getUserId() + "' data:" + token.getData() + "</html>");
            // lets increment a count for that
            // note: not atomic
            sessionStorage.getUser(token.getUserId()).then(record -> {
                // increment
                record.put("count", record.getInt("count") + 1);
                // save
                sessionStorage.putUser(record);
                // session cached record is stale now => update
                // this is a bad example, should use events instead and ofc
                // default session storage is not a database replacement
                sessions.values().stream().filter(sess -> sess.getUserKey().equals(token.getUserId())).forEach(sess -> ((ReactAppSession) sess).updateUserRecord(record));
            });
        } else
            res.reject("<html>Expired or invalid Link</html>");
    });
    return res;
}
Also used : Secured(org.nustaq.kontraktor.annotations.Secured) MapRecord(org.nustaq.reallive.records.MapRecord) IPromise(org.nustaq.kontraktor.IPromise) Promise(org.nustaq.kontraktor.Promise) BasicWebAppActor(org.nustaq.kontraktor.weblication.BasicWebAppActor) Remoted(org.nustaq.kontraktor.annotations.Remoted) IPromise(org.nustaq.kontraktor.IPromise) Promise(org.nustaq.kontraktor.Promise)

Example 40 with Promise

use of org.nustaq.kontraktor.Promise in project kontraktor by RuedigerMoeller.

the class StatelessService method getTime.

@Override
public IPromise<Long> getTime(long delay) {
    Promise p = promise();
    long now = System.currentTimeMillis();
    delayed(delay, () -> {
        measure.count();
        p.resolve(now);
    });
    return p;
}
Also used : IPromise(org.nustaq.kontraktor.IPromise) Promise(org.nustaq.kontraktor.Promise)

Aggregations

Promise (org.nustaq.kontraktor.Promise)67 IPromise (org.nustaq.kontraktor.IPromise)62 Test (org.junit.Test)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 Actor (org.nustaq.kontraktor.Actor)6 Remoted (org.nustaq.kontraktor.annotations.Remoted)6 IOException (java.io.IOException)4 Actors (org.nustaq.kontraktor.Actors)4 RateMeasure (org.nustaq.kontraktor.util.RateMeasure)4 JsonObject (com.eclipsesource.json.JsonObject)3 ByteBuffer (java.nio.ByteBuffer)3 KeyManagementException (java.security.KeyManagementException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 CertificateException (java.security.cert.CertificateException)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 Consumer (java.util.function.Consumer)3 ActorServer (org.nustaq.kontraktor.remoting.base.ActorServer)3 TCPConnectable (org.nustaq.kontraktor.remoting.tcp.TCPConnectable)3 TableSpaceActor (org.nustaq.reallive.impl.tablespace.TableSpaceActor)3 EOFException (java.io.EOFException)2