Search in sources :

Example 6 with ServiceProvider

use of org.platformlayer.xaas.services.ServiceProvider in project platformlayer by platformlayer.

the class ServiceAuthorizationResource method createService.

// We deliberately don't support this at the moment... it's quite restrictive on our data store
// @GET
// @Produces({ APPLICATION_XML, APPLICATION_JSON })
// public <T> ServiceAuthorizationCollection getAll() {
// List<ServiceAuthorization> items = authorizationRepository.getByAccountId(getAccountId());
// ServiceAuthorizationCollection collection = new ServiceAuthorizationCollection();
// collection.items = items;
// return collection;
// }
@POST
@Consumes({ XML, JSON })
@Produces({ XML, JSON })
public <T> ServiceAuthorization createService(final ServiceAuthorization authorization) throws OpsException, RepositoryException {
    ServiceType serviceType = getServiceType();
    authorization.serviceType = serviceType.getKey();
    final ServiceProvider serviceProvider = opsSystem.getServiceProvider(serviceType);
    if (serviceProvider == null) {
        log.warn("Unknown serviceProvider: " + serviceType);
        throw new WebApplicationException(404);
    }
    String data = authorization.data;
    if (Strings.isNullOrEmpty(data)) {
        throw new IllegalArgumentException("Data is required");
    }
    data = data.trim();
    if (data.startsWith("{")) {
        // Convert to XML
        SettingCollection settings = new SettingCollection();
        settings.items = Lists.newArrayList();
        // We presume it's a simple map of keys and values
        try {
            JSONObject json = new JSONObject(data);
            @SuppressWarnings("unchecked") Iterator<String> keys = json.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                String value = json.getString(key);
                Setting setting = new Setting();
                setting.key = key;
                setting.value = value;
                settings.items.add(setting);
            }
        } catch (JSONException e) {
            throw new IllegalArgumentException("Error parsing data", e);
        }
        JaxbHelper jaxbHelper = JaxbHelper.get(SettingCollection.class);
        String xml;
        try {
            xml = jaxbHelper.marshal(settings, false);
        } catch (JAXBException e) {
            throw new IllegalArgumentException("Error converting JSON to XML", e);
        }
        authorization.data = xml;
    }
    // Authentication authentication = getAuthentication();
    //
    // OpsContextBuilder opsContextBuilder = opsSystem.getInjector().getInstance(OpsContextBuilder.class);
    // final OpsContext opsContext = opsContextBuilder.buildOpsContext(serviceType, authentication, false);
    //
    // OpsContext.runInContext(opsContext, new CheckedCallable<Object, Exception>() {
    // @Override
    // public Object call() throws Exception {
    // serviceProvider.validateAuthorization(authorization);
    // return null;
    // }
    // });
    // serviceProvider.validateAuthorization(authorization);
    ServiceAuthorization created = authorizationRepository.createAuthorization(getProject(), authorization);
    // For security, never return the data
    created.data = null;
    return created;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) SettingCollection(org.platformlayer.xaas.model.SettingCollection) Setting(org.platformlayer.xaas.model.Setting) JAXBException(javax.xml.bind.JAXBException) JSONException(org.json.JSONException) ServiceAuthorization(org.platformlayer.xaas.model.ServiceAuthorization) JSONObject(org.json.JSONObject) ServiceType(org.platformlayer.ids.ServiceType) ServiceProvider(org.platformlayer.xaas.services.ServiceProvider) JaxbHelper(org.platformlayer.xml.JaxbHelper) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 7 with ServiceProvider

use of org.platformlayer.xaas.services.ServiceProvider in project platformlayer by platformlayer.

the class ServiceResource method getSshPublicKey.

@GET
@Path("sshkey")
@Produces({ TEXT_PLAIN })
public String getSshPublicKey() throws RepositoryException, OpsException, IOException {
    final ServiceProvider serviceProvider = getServiceProvider();
    if (serviceProvider == null) {
        raiseNotFound();
    }
    OpsContextBuilder opsContextBuilder = opsContextBuilderFactory.get();
    final OpsContext opsContext = opsContextBuilder.buildTemporaryOpsContext(serviceProvider.getServiceType(), getProjectAuthorization());
    PublicKey publicKey = OpsContext.runInContext(opsContext, new CheckedCallable<PublicKey, Exception>() {

        @Override
        public PublicKey call() throws Exception {
            PublicKey publicKey = serviceProvider.getSshPublicKey();
            return publicKey;
        }
    });
    if (publicKey == null) {
        throw new WebApplicationException(404);
    }
    String description = "platformlayer://" + getProject().getKey() + "/" + serviceProvider.getServiceType().getKey();
    return OpenSshUtils.serialize(publicKey, description);
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) PublicKey(java.security.PublicKey) ServiceProvider(org.platformlayer.xaas.services.ServiceProvider) OpsContext(org.platformlayer.ops.OpsContext) RepositoryException(org.platformlayer.RepositoryException) OpsException(org.platformlayer.ops.OpsException) IOException(java.io.IOException) JAXBException(javax.xml.bind.JAXBException) WebApplicationException(javax.ws.rs.WebApplicationException) OpsContextBuilder(org.platformlayer.ops.tasks.OpsContextBuilder) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 8 with ServiceProvider

use of org.platformlayer.xaas.services.ServiceProvider in project platformlayer by platformlayer.

the class ServiceResource method getSchema.

@GET
@Path("schema")
@Produces({ XML })
public String getSchema() throws IOException, JAXBException {
    ServiceProvider serviceProvider = getServiceProvider();
    String namespace = null;
    List<Class<?>> javaClasses = Lists.newArrayList();
    for (ModelClass<?> modelClass : serviceProvider.getModels().all()) {
        javaClasses.add(modelClass.getJavaClass());
        String modelNamespace = modelClass.getPrimaryNamespace();
        if (namespace == null) {
            namespace = modelNamespace;
        } else if (!namespace.equals(modelNamespace)) {
            throw new IllegalStateException();
        }
    }
    JAXBContext jaxbContext = JAXBContext.newInstance(javaClasses.toArray(new Class<?>[javaClasses.size()]));
    MemorySchemaOutputResolver schemaOutputResolver = new MemorySchemaOutputResolver();
    jaxbContext.generateSchema(schemaOutputResolver);
    Map<String, StringWriter> writers = schemaOutputResolver.getWriters();
    StringWriter writer = writers.get(namespace);
    if (writer == null) {
        throw new IllegalArgumentException();
    }
    return writer.getBuffer().toString();
}
Also used : MemorySchemaOutputResolver(org.platformlayer.xml.MemorySchemaOutputResolver) StringWriter(java.io.StringWriter) ServiceProvider(org.platformlayer.xaas.services.ServiceProvider) ModelClass(org.platformlayer.xaas.services.ModelClass) JAXBContext(javax.xml.bind.JAXBContext) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 9 with ServiceProvider

use of org.platformlayer.xaas.services.ServiceProvider in project platformlayer by platformlayer.

the class DirectPlatformLayerClient method getModelClass.

protected ModelClass<?> getModelClass(ServiceType serviceType, ItemType itemType) throws PlatformLayerClientException {
    ServiceProvider serviceProvider = getServiceProvider(serviceType);
    if (serviceProvider == null) {
        log.warn("Unknown serviceType: " + serviceType);
        throw new PlatformLayerClientException("Service type not recognized: " + serviceType.getKey());
    }
    ModelClass<?> modelClass = serviceProvider.getModels().find(itemType);
    if (modelClass == null) {
        log.warn("Unknown itemtype: " + itemType);
        throw new PlatformLayerClientException("Item type not recognized: " + itemType.getKey());
    }
    return modelClass;
}
Also used : PlatformLayerClientException(org.platformlayer.PlatformLayerClientException) ServiceProvider(org.platformlayer.xaas.services.ServiceProvider)

Example 10 with ServiceProvider

use of org.platformlayer.xaas.services.ServiceProvider in project platformlayer by platformlayer.

the class OperationWorker method doOperation.

Object doOperation() throws OpsException {
    final Action action = activeJob.getAction();
    final PlatformLayerKey targetItemKey = activeJob.getTargetItemKey();
    RenameThread rename = new RenameThread(action.getClass().getSimpleName() + " " + targetItemKey);
    try {
        OpsContextBuilder opsContextBuilder = opsSystem.getInjector().getInstance(OpsContextBuilder.class);
        final ProjectAuthorization project = activeJob.getProjectAuthorization();
        final OpsContext opsContext = opsContextBuilder.buildOpsContext(activeJob);
        final ServiceType serviceType = activeJob.getServiceType();
        final ServiceProvider serviceProvider = opsSystem.getServiceProvider(serviceType);
        try {
            return OpsContext.runInContext(opsContext, new CheckedCallable<Object, Exception>() {

                @Override
                public Object call() throws Exception {
                    log.info("Starting job");
                    activeJob.setState(JobState.RUNNING);
                    ItemBase item;
                    ManagedItemRepository repository = opsSystem.getManagedItemRepository();
                    try {
                        boolean fetchTags = true;
                        item = repository.getManagedItem(targetItemKey, fetchTags, SecretProvider.from(project));
                    } catch (RepositoryException e) {
                        throw new OpsException("Error reading item from repository", e);
                    }
                    if (item == null) {
                        throw new WebApplicationException(404);
                    }
                    List<Object> scopeItems = Lists.newArrayList();
                    addActionScopeItems(action, item, scopeItems);
                    Object controller = serviceProvider.getController(item);
                    scopeItems.add(item);
                    scopeItems.add(action);
                    BindingScope scope = BindingScope.push(scopeItems);
                    opsContext.recurseOperation(scope, controller);
                    // TODO: Should we run a verify operation before -> ACTIVE??
                    // (we need to fix the states as well)
                    ManagedItemState newState = finishAction(action, scope);
                    if (newState != null) {
                        repository.changeState(targetItemKey, newState);
                        item.state = newState;
                    }
                    log.info("Job finished with SUCCESS");
                    activeJob.setState(JobState.SUCCESS);
                    return null;
                }

                private ManagedItemState finishAction(Action action, BindingScope scope) throws OpsException {
                    ManagedItemState newState = null;
                    if (action instanceof ConfigureAction) {
                        newState = ManagedItemState.ACTIVE;
                    }
                    if (action instanceof ValidateAction) {
                    // TODO: Change state to healthy??
                    }
                    if (action instanceof DeleteAction) {
                        newState = ManagedItemState.DELETED;
                    }
                    if (action instanceof BackupAction) {
                        BackupContext backupContext = scope.getInstance(BackupContext.class);
                        backupContext.writeDescriptor();
                    }
                    return newState;
                }

                private void addActionScopeItems(Action action, ItemBase item, List<Object> scopeItems) throws OpsException {
                    if (action instanceof BackupAction) {
                        // TODO: Don't hard-code this
                        BackupHelpers backupHelpers = opsSystem.getInjector().getInstance(BackupHelpers.class);
                        BackupContext backupContext = backupHelpers.createBackupContext(item);
                        scopeItems.add(backupContext);
                    }
                }
            });
        } catch (Throwable e) {
            log.warn("Error running operation", e);
            log.warn("Job finished with FAILED");
            // boolean isDone = false; // We will retry
            activeJob.setState(JobState.FAILED);
            TimeSpan retry = null;
            HasRetryInfo retryInfo = ExceptionHelpers.findRetryInfo(e);
            if (retryInfo != null) {
                retry = retryInfo.getRetry();
            }
            if (retry == null) {
                // TODO: Eventually give up??
                retry = ApplicationMode.isDevelopment() ? TimeSpan.ONE_MINUTE : TimeSpan.FIVE_MINUTES;
            }
            // TODO: State transition??
            // managedItem.setState(ManagedItemState.ACTIVE, true);
            log.warn("Scheduling retry in " + retry);
            activeJob.enqueueRetry(retry);
            return null;
        } finally {
            try {
                activeJob.recordJobEnd();
            } catch (OpsException e) {
                log.error("Error recording job in registry", e);
            }
        }
    } finally {
        IoUtils.safeClose(rename);
    }
}
Also used : ValidateAction(org.platformlayer.core.model.ValidateAction) ConfigureAction(org.platformlayer.core.model.ConfigureAction) DeleteAction(org.platformlayer.core.model.DeleteAction) BackupAction(org.platformlayer.core.model.BackupAction) Action(org.platformlayer.core.model.Action) OpsException(org.platformlayer.ops.OpsException) WebApplicationException(javax.ws.rs.WebApplicationException) BackupHelpers(org.platformlayer.ops.backups.BackupHelpers) ManagedItemRepository(org.platformlayer.xaas.repository.ManagedItemRepository) OpsContext(org.platformlayer.ops.OpsContext) TimeSpan(com.fathomdb.TimeSpan) BackupAction(org.platformlayer.core.model.BackupAction) ServiceType(org.platformlayer.ids.ServiceType) BackupContext(org.platformlayer.ops.backups.BackupContext) HasRetryInfo(org.platformlayer.exceptions.HasRetryInfo) List(java.util.List) BindingScope(org.platformlayer.ops.BindingScope) ConfigureAction(org.platformlayer.core.model.ConfigureAction) ItemBase(org.platformlayer.core.model.ItemBase) PlatformLayerKey(org.platformlayer.core.model.PlatformLayerKey) RepositoryException(org.platformlayer.RepositoryException) RepositoryException(org.platformlayer.RepositoryException) OpsException(org.platformlayer.ops.OpsException) WebApplicationException(javax.ws.rs.WebApplicationException) ServiceProvider(org.platformlayer.xaas.services.ServiceProvider) ProjectAuthorization(org.platformlayer.model.ProjectAuthorization) DeleteAction(org.platformlayer.core.model.DeleteAction) ValidateAction(org.platformlayer.core.model.ValidateAction) ManagedItemState(org.platformlayer.core.model.ManagedItemState)

Aggregations

ServiceProvider (org.platformlayer.xaas.services.ServiceProvider)19 RepositoryException (org.platformlayer.RepositoryException)9 OpsContext (org.platformlayer.ops.OpsContext)9 OpsException (org.platformlayer.ops.OpsException)8 ServiceType (org.platformlayer.ids.ServiceType)7 ItemBase (org.platformlayer.core.model.ItemBase)6 Produces (javax.ws.rs.Produces)5 JAXBException (javax.xml.bind.JAXBException)5 OpsContextBuilder (org.platformlayer.ops.tasks.OpsContextBuilder)5 ModelClass (org.platformlayer.xaas.services.ModelClass)5 Path (javax.ws.rs.Path)4 WebApplicationException (javax.ws.rs.WebApplicationException)4 IOException (java.io.IOException)3 GET (javax.ws.rs.GET)3 ServiceInfo (org.platformlayer.core.model.ServiceInfo)3 BindingScope (org.platformlayer.ops.BindingScope)3 List (java.util.List)2 POST (javax.ws.rs.POST)2 SecretProvider (org.platformlayer.auth.crypto.SecretProvider)2 PlatformLayerKey (org.platformlayer.core.model.PlatformLayerKey)2