use of com.bluenimble.platform.api.Api in project serverless by bluenimble.
the class AbstractApiServer method execute.
@Override
public void execute(final ApiRequest request, final ApiResponse response, CodeExecutor.Mode mode) {
if (keys.expiryDate() != null && keys.expiryDate().before(new Date())) {
sendError(response, ApiResponse.FORBIDDEN, "node keys expired");
return;
}
ApiSpace space = null;
Api api = null;
try {
if (!(request instanceof ContainerApiRequest)) {
requestVisitor.visit((AbstractApiRequest) request);
}
// is space resolved
if (Lang.isNullOrEmpty(request.getSpace())) {
sendError(response, ApiResponse.NOT_FOUND, "can't resolve space from request");
request.destroy();
return;
}
if (Lang.isNullOrEmpty(request.getApi())) {
sendError(response, ApiResponse.NOT_FOUND, "can't resolve api namespace from request");
request.destroy();
return;
}
space = space(request.getSpace());
ApiResponse.Status notFoundStatus = null;
String notFoundMessage = null;
if (space == null) {
notFoundStatus = ApiResponse.NOT_FOUND;
notFoundMessage = "space " + request.getSpace() + " not found";
} else if (!space.isStarted()) {
notFoundStatus = ApiResponse.SERVICE_UNAVAILABLE;
notFoundMessage = "space " + request.getSpace() + " is not available";
}
if (notFoundStatus != null) {
sendError(response, notFoundStatus, notFoundMessage);
request.destroy();
return;
}
api = space.api(request.getApi());
if (api == null) {
notFoundStatus = ApiResponse.NOT_FOUND;
notFoundMessage = "api " + request.getApi() + " not found";
} else if (api.status() != ApiStatus.Running) {
notFoundStatus = ApiResponse.SERVICE_UNAVAILABLE;
notFoundMessage = "api " + request.getApi() + " stopped or paused";
}
if (notFoundStatus != null) {
sendError(response, notFoundStatus, notFoundMessage);
request.destroy();
return;
}
} catch (Exception ex) {
tracer.log(Tracer.Level.Error, Lang.BLANK, ex);
request.destroy();
sendError(response, ApiResponse.BAD_REQUEST, ex.getMessage());
return;
}
final Api fApi = api;
try {
space.executor().execute(new Callable<Void>() {
@Override
public Void call() {
if (Thread.currentThread() instanceof SpaceThread) {
final SpaceThread currentThread = (SpaceThread) Thread.currentThread();
currentThread.setRequest(request);
}
try {
interceptor.intercept(fApi, request, response);
} finally {
if (Thread.currentThread() instanceof SpaceThread) {
((SpaceThread) Thread.currentThread()).setRequest(null);
}
}
return null;
}
}, mode);
} catch (CodeExecutorException aaee) {
Throwable e = aaee.getCause();
String error = "Generic";
ApiResponse.Status status = ApiResponse.BAD_REQUEST;
if (e.getClass().equals(CancellationException.class)) {
status = ApiResponse.INSUFFICIENT_SPACE_ON_RESOURCE;
error = "Cancellation";
} else if (e.getClass().equals(TimeoutException.class)) {
status = ApiResponse.REQUEST_TIMEOUT;
error = "Timeout";
}
tracer.log(Tracer.Level.Error, "\tCallback-OnError: ThreadGroup [" + Thread.currentThread().getThreadGroup().getName() + "], Thread [" + Thread.currentThread().getName() + "], " + error + " Error: " + e.getMessage(), e);
sendError(response, status, error + " Error | " + e.getMessage());
request.destroy();
}
}
use of com.bluenimble.platform.api.Api in project serverless by bluenimble.
the class ApiSpaceImpl method describe.
@Override
public JsonObject describe(DescribeOption... options) {
if (options == null || options.length == 0) {
return JsonObject.Blank;
}
Map<DescribeOption.Option, DescribeOption> opts = DescribeUtils.toMap(options);
JsonObject describe = new JsonObject();
if (opts.containsKey(DescribeOption.Option.info)) {
describe.set(ApiSpace.Spec.Namespace, getNamespace());
describe.set(ApiSpace.Spec.Name, getName());
describe.set(ApiSpace.Spec.Description, getDescription());
describe.set(Describe.Status, isStarted() ? ApiStatus.Running.name() : ApiStatus.Stopped.name());
describe.set(ApiSpace.Spec.Blocked, isBlocked());
if (opts.size() == 1) {
return describe;
}
}
descriptor = descriptor.duplicate();
if (opts.containsKey(DescribeOption.Option.keys) && keystore != null) {
List<KeyPair> keys = null;
try {
keys = keystore.list(0, 100);
} catch (SpaceKeyStoreException e) {
tracer.log(Tracer.Level.Error, Lang.BLANK, e);
}
JsonArray aKeys = new JsonArray();
if (keys != null) {
for (KeyPair kp : keys) {
JsonObject okp = kp.toJson().duplicate();
okp.remove(KeyPair.Fields.SecretKey);
aKeys.add(okp);
}
}
describe.set(DescribeOption.Option.keys.name(), aKeys);
}
if (opts.containsKey(DescribeOption.Option.secrets)) {
describe.set(DescribeOption.Option.secrets.name(), descriptor.get(Spec.secrets.class.getSimpleName()));
}
if (opts.containsKey(DescribeOption.Option.features)) {
describe.set(DescribeOption.Option.features.name(), descriptor.get(Spec.Features));
}
if (opts.containsKey(DescribeOption.Option.runtime)) {
describe.set(DescribeOption.Option.runtime.name(), descriptor.get(RuntimeKey));
}
if (opts.containsKey(DescribeOption.Option.apis)) {
final JsonArray aApis = new JsonArray();
describe.set(DescribeOption.Option.apis.name(), aApis);
list(new Selector() {
@Override
public boolean select(Api api) {
aApis.add(api.describe(options));
return false;
}
});
}
if (opts.containsKey(DescribeOption.Option.workers) && executor != null) {
describe.set(DescribeOption.Option.workers.name(), executor.describe());
}
return describe;
}
use of com.bluenimble.platform.api.Api in project serverless by bluenimble.
the class ChangeServiceStatusSpi method execute.
@Override
public ApiOutput execute(Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException {
String apiNs = (String) request.get(CommonSpec.Api);
String sAction = (String) request.getResource()[request.getResource().length - 2];
Action action = null;
try {
action = Action.valueOf(sAction);
} catch (Exception ex) {
// ignore
}
if (action == null) {
throw new ApiServiceExecutionException("unknown change-status action " + sAction).status(ApiResponse.BAD_REQUEST);
}
JsonObject payload = (JsonObject) request.get(ApiRequest.Payload);
String sVerb = Json.getString(payload, ApiService.Spec.Verb).toUpperCase();
String endpoint = Json.getString(payload, ApiService.Spec.Endpoint);
ApiVerb verb = null;
try {
verb = ApiVerb.valueOf(sVerb);
} catch (Exception ex) {
// ignore
}
if (verb == null) {
throw new ApiServiceExecutionException("unknown service verb " + sVerb).status(ApiResponse.BAD_REQUEST);
}
Api targetApi = null;
try {
targetApi = MgmUtils.api(consumer, api, apiNs);
switch(action) {
case start:
targetApi.getServicesManager().start(verb, endpoint);
break;
case stop:
targetApi.getServicesManager().stop(verb, endpoint);
break;
case pause:
targetApi.getServicesManager().get(verb, endpoint).pause();
break;
case resume:
targetApi.getServicesManager().get(verb, endpoint).resume();
break;
default:
break;
}
} catch (Exception ex) {
throw new ApiServiceExecutionException(ex.getMessage(), ex);
}
return new JsonApiOutput((JsonObject) new JsonObject().set(Api.Spec.Status, targetApi.getServicesManager().get(verb, endpoint).status().name()));
}
use of com.bluenimble.platform.api.Api in project serverless by bluenimble.
the class MediaPlugin method onEvent.
@Override
public void onEvent(Event event, Object target) {
if (!Api.class.isAssignableFrom(target.getClass())) {
return;
}
Api api = (Api) target;
if (event.equals(Event.Install)) {
enginesRegistry.add(api, HandlebarsEngine, new HandlebarsTemplateEngine(this, api));
enginesRegistry.add(api, JavascriptEngine, new JavascriptEngine(this, api));
} else if (event.equals(Event.Uninstall)) {
enginesRegistry.remove(api, HandlebarsEngine);
enginesRegistry.remove(api, JavascriptEngine);
}
}
use of com.bluenimble.platform.api.Api in project serverless by bluenimble.
the class FileSystemApiServer method installSpace.
private void installSpace(File spaceHome) throws ServerStartupException {
tracer.log(Tracer.Level.Info, "Install Space {0}", spaceHome.getName());
JsonObject oSpace = null;
File fDescriptor = new File(spaceHome, ConfigKeys.Descriptor.Space);
if (fDescriptor.exists()) {
try {
oSpace = resolve(Json.load(fDescriptor));
} catch (Exception ex) {
failed.put("unnable to load space '" + spaceHome.getName() + "'", ex);
return;
}
}
if (oSpace == null) {
throw new ServerStartupException("space descriptor for " + spaceHome.getName() + " not found");
}
if (!oSpace.containsKey(ApiSpace.Spec.Namespace)) {
oSpace.set(ApiSpace.Spec.Namespace, spaceHome.getName());
}
ApiSpaceImpl space;
try {
space = (ApiSpaceImpl) create(oSpace, false);
// save space descriptor, change maybe made by plugins onEvent/Create
// Json.store (oSpace, fDescriptor);
} catch (Exception ex) {
throw new ServerStartupException(ex.getMessage(), ex);
}
File[] apis = spaceHome.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return file.isDirectory() || (file.isFile() && file.getAbsolutePath().endsWith(ConfigKeys.ApiExt));
}
});
if (apis == null || apis.length == 0) {
tracer.log(Tracer.Level.Info, "\tno apis found in space [{0}]", spaceHome.getName());
return;
}
tracer.log(Tracer.Level.Info, "\tfound ({0}) Api(s) in [{1}]", apis.length, spaceHome.getName());
for (File aFile : apis) {
Api api = null;
if (aFile.isDirectory()) {
try {
api = space.install(aFile);
} catch (Exception ex) {
failed.put(space.getNamespace() + " > " + aFile.getName(), ex);
continue;
}
} else if (aFile.isFile()) {
ApiFileStreamSource is = new ApiFileStreamSource(aFile, ConfigKeys.ApiExt);
try {
api = space.install(is);
} catch (Exception ex) {
failed.put(space.getNamespace() + " > " + aFile.getName(), ex);
continue;
} finally {
IOUtils.closeQuietly(is.stream());
}
try {
FileUtils.delete(aFile);
} catch (IOException ex) {
tracer.log(Tracer.Level.Error, "\tcan't delete api file {0} / {1} > ", spaceHome.getName(), aFile.getName());
}
}
if (api != null && ApiStatus.Failed.equals(api.status())) {
failed.put(space.getNamespace() + "/" + aFile.getName(), api.getFailure());
}
}
}
Aggregations