Search in sources :

Example 76 with OpsException

use of org.platformlayer.ops.OpsException in project platformlayer by platformlayer.

the class LdapMasterPassword method doOperation.

@Handler
public void doOperation(OpsTarget target) throws OpsException {
    // TODO: Make this idempotent
    LdifRecord configLdif;
    {
        Command ldapSearch = Command.build("ldapsearch -Q -LLL -Y EXTERNAL -H ldapi:/// -b cn=config olcRootDN=cn=admin,cn=config dn olcRootDN olcRootPW");
        List<LdifRecord> ldifs = LdifRecord.parse(target.executeCommand(ldapSearch).getStdOut());
        if (ldifs.size() != 1) {
            throw new OpsException("Expected exactly one LDIF record for config");
        }
        configLdif = ldifs.get(0);
    }
    {
        StringBuilder modify = new StringBuilder();
        modify.append("dn: " + configLdif.getLdapDn().toString() + "\n");
        modify.append("replace: olcRootPW\n");
        modify.append("olcRootPW: " + LdapPasswords.getLdapPasswordEncoded(ldapSecret.plaintext()) + "\n");
        modify.append("\n");
        File tempDir = target.createTempDir();
        File modifyFile = new File(tempDir, "modifypw.ldif");
        FileUpload.upload(target, modifyFile, modify.toString());
        Command ldapModify = Command.build("ldapmodify -Q -Y EXTERNAL -H ldapi:/// -f {0}", modifyFile);
        target.executeCommand(ldapModify);
    }
    ldap.writeLdapServerPassword(target, ldapSecret);
}
Also used : OpsException(org.platformlayer.ops.OpsException) Command(org.platformlayer.ops.Command) List(java.util.List) File(java.io.File) Handler(org.platformlayer.ops.Handler)

Example 77 with OpsException

use of org.platformlayer.ops.OpsException in project platformlayer by platformlayer.

the class TypedItemMapper method promoteToTyped.

public <T> T promoteToTyped(UntypedItem untypedItem, Class<T> itemClass) throws OpsException {
    JaxbHelper jaxbHelper = JaxbHelper.get(itemClass);
    T typedItem;
    try {
        Element element = ((UntypedItemXml) untypedItem).getDataElement();
        String xmlElementName = jaxbHelper.getXmlElementName();
        String nodeName = element.getLocalName();
        if (!Objects.equal(xmlElementName, nodeName)) {
            String type = element.getAttribute("xsi:type");
            if (type != null && type.endsWith(":" + xmlElementName)) {
            // OK
            } else {
                throw new OpsException("Incorrect element type: " + xmlElementName + " vs " + nodeName);
            }
        }
        T object = jaxbHelper.unmarshal(element, itemClass);
        if (!(object.getClass().isAssignableFrom(itemClass))) {
            System.out.println("XML = " + ((UntypedItemXml) untypedItem).serialize());
        }
        typedItem = Casts.checkedCast(object, itemClass);
    } catch (JAXBException e) {
        throw new OpsException("Error deserializing item", e);
    }
    return typedItem;
}
Also used : OpsException(org.platformlayer.ops.OpsException) Element(org.w3c.dom.Element) JAXBException(javax.xml.bind.JAXBException) JaxbHelper(org.platformlayer.xml.JaxbHelper)

Example 78 with OpsException

use of org.platformlayer.ops.OpsException in project platformlayer by platformlayer.

the class ItemServiceImpl method ensureItem.

<T extends ItemBase> T ensureItem(final ProjectAuthorization auth, final T item, final boolean canExist, final boolean generateUniqueName, final String uniqueTagKey) throws OpsException {
    final ModelClass<T> modelClass = (ModelClass<T>) serviceProviderDirectory.getModelClass(item.getClass());
    if (modelClass == null) {
        throw new IllegalStateException("Unknown item type");
    }
    final Class<T> javaClass = modelClass.getJavaClass();
    // JaxbHelper jaxbHelper = JaxbHelper.get(javaClass);
    final ServiceProvider serviceProvider = modelClass.getProvider();
    String id = item.getId();
    if (Strings.isNullOrEmpty(id)) {
        if (generateUniqueName) {
            id = serviceProvider.buildItemId(modelClass, item);
        } else {
            // otherwise we end up with lots of randomly named items
            throw new OpsException("Must specify item id");
        // id = UUID.randomUUID().toString();
        // item.setId(id);
        }
    }
    ProjectId project = getProjectId(auth);
    PlatformLayerKey itemKey = new PlatformLayerKey(null, project, modelClass.getServiceType(), modelClass.getItemType(), new ManagedItemId(id));
    item.setKey(itemKey);
    item.state = ManagedItemState.CREATION_REQUESTED;
    final OpsContext opsContext = buildTemporaryOpsContext(modelClass.getServiceType(), auth);
    T created = OpsContext.runInContext(opsContext, new CheckedCallable<T, Exception>() {

        @Override
        public T call() throws Exception {
            PlatformLayerKey itemKey = item.getKey();
            T existing;
            SecretProvider secretProvider = SecretProvider.from(auth);
            if (uniqueTagKey != null) {
                boolean fetchTags = true;
                Tag uniqueTag = null;
                for (Tag tag : item.getTags()) {
                    if (Objects.equal(tag.getKey(), uniqueTagKey)) {
                        uniqueTag = tag;
                    }
                }
                if (uniqueTag == null) {
                    throw new IllegalArgumentException("Could not find unique tag");
                }
                Filter filter = TagFilter.byTag(uniqueTag);
                filter = StateFilter.excludeDeleted(filter);
                existing = null;
                List<T> existingList = repository.findAll(modelClass, itemKey.getProject(), fetchTags, secretProvider, filter);
                if (!existingList.isEmpty()) {
                    if (existingList.size() != 1) {
                        throw new IllegalArgumentException("Found multiple items with unique tag");
                    }
                    existing = existingList.get(0);
                }
                if (existing == null) {
                    itemKey = findUniqueId(item, itemKey, secretProvider);
                }
            } else {
                if (generateUniqueName) {
                    itemKey = findUniqueId(item, itemKey, secretProvider);
                }
                try {
                    boolean fetchTags = true;
                    existing = Casts.checkedCast(repository.getManagedItem(itemKey, fetchTags, secretProvider), javaClass);
                } catch (RepositoryException e) {
                    throw new OpsException("Error fetching item from database", e);
                }
            }
            if (!canExist && existing != null) {
                throw new OpsException("Item already exists");
            }
            serviceProvider.beforeCreateItem(item);
            ProjectId project = getProjectId(auth);
            T newItem;
            try {
                if (existing == null) {
                    newItem = repository.createManagedItem(project, item);
                } else {
                    item.secret = existing.secret;
                    item.setKey(existing.getKey());
                    newItem = repository.updateManagedItem(project, item);
                    TagChanges tagChanges = new TagChanges();
                    for (Tag tag : item.getTags()) {
                        if (newItem.getTags().hasTag(tag)) {
                            continue;
                        }
                        boolean uniqueTagKey = false;
                        if (tag.getKey().equals(Tag.PARENT.getKey())) {
                            uniqueTagKey = true;
                        }
                        tagChanges.addTags.add(tag);
                        if (uniqueTagKey) {
                            for (Tag oldTag : newItem.getTags().findTags(tag.getKey())) {
                                tagChanges.removeTags.add(oldTag);
                            }
                        }
                    }
                    if (!tagChanges.isEmpty()) {
                        repository.changeTags(modelClass, project, newItem.getKey().getItemId(), tagChanges, null);
                    }
                }
            } catch (RepositoryException e) {
                throw new OpsException("Error writing object to database", e);
            }
            itemKey = newItem.getKey();
            JobData jobKey = changeQueue.notifyChange(auth, itemKey, ManagedItemState.CREATION_REQUESTED);
            return newItem;
        }

        private <T extends ItemBase> PlatformLayerKey findUniqueId(final T item, final PlatformLayerKey itemKey, SecretProvider secretProvider) throws RepositoryException {
            int sequence = 0;
            while (true) {
                String tryId = item.getId();
                if (sequence != 0) {
                    tryId += sequence;
                }
                final PlatformLayerKey tryKey = itemKey.withId(new ManagedItemId(tryId));
                boolean fetchTags = false;
                ItemBase found = repository.getManagedItem(tryKey, fetchTags, secretProvider);
                if (found == null) {
                    item.setKey(tryKey);
                    return tryKey;
                }
                sequence++;
            }
        }
    });
    return created;
}
Also used : OpsException(org.platformlayer.ops.OpsException) ItemBase(org.platformlayer.core.model.ItemBase) ProjectId(org.platformlayer.ids.ProjectId) PlatformLayerKey(org.platformlayer.core.model.PlatformLayerKey) RepositoryException(org.platformlayer.RepositoryException) OpsContext(org.platformlayer.ops.OpsContext) TagChanges(org.platformlayer.core.model.TagChanges) ManagedItemId(org.platformlayer.ids.ManagedItemId) RepositoryException(org.platformlayer.RepositoryException) OpsException(org.platformlayer.ops.OpsException) ModelClass(org.platformlayer.xaas.services.ModelClass) StateFilter(org.platformlayer.StateFilter) TagFilter(org.platformlayer.TagFilter) Filter(org.platformlayer.Filter) ServiceProvider(org.platformlayer.xaas.services.ServiceProvider) List(java.util.List) Tag(org.platformlayer.core.model.Tag) JobData(org.platformlayer.jobs.model.JobData) SecretProvider(org.platformlayer.auth.crypto.SecretProvider)

Example 79 with OpsException

use of org.platformlayer.ops.OpsException in project platformlayer by platformlayer.

the class ItemServiceImpl method deleteItem.

@Override
public JobData deleteItem(final ProjectAuthorization auth, final PlatformLayerKey targetItemKey) throws OpsException {
    SecretProvider secretProvider = SecretProvider.from(auth);
    boolean fetchTags = true;
    ItemBase targetItem;
    try {
        targetItem = repository.getManagedItem(targetItemKey, fetchTags, secretProvider);
    } catch (RepositoryException e) {
        throw new OpsException("Error reading item", e);
    }
    if (targetItem == null) {
        throw new IllegalStateException("Item not found");
    }
    targetItem.state = ManagedItemState.DELETE_REQUESTED;
    final ServiceProvider serviceProvider = serviceProviderDirectory.getServiceProvider(targetItemKey.getServiceType());
    if (serviceProvider == null) {
        throw new IllegalStateException("Unknown service type");
    }
    final OpsContext opsContext = buildTemporaryOpsContext(targetItemKey.getServiceType(), auth);
    JobData jobKey = OpsContext.runInContext(opsContext, new CheckedCallable<JobData, Exception>() {

        @Override
        public JobData call() throws Exception {
            try {
                repository.changeState(targetItemKey, ManagedItemState.DELETE_REQUESTED);
            } catch (RepositoryException e) {
                throw new OpsException("Error writing object to database", e);
            }
            return changeQueue.notifyChange(auth, targetItemKey, ManagedItemState.DELETE_REQUESTED);
        }
    });
    return jobKey;
}
Also used : OpsException(org.platformlayer.ops.OpsException) ItemBase(org.platformlayer.core.model.ItemBase) ServiceProvider(org.platformlayer.xaas.services.ServiceProvider) RepositoryException(org.platformlayer.RepositoryException) JobData(org.platformlayer.jobs.model.JobData) OpsContext(org.platformlayer.ops.OpsContext) RepositoryException(org.platformlayer.RepositoryException) OpsException(org.platformlayer.ops.OpsException) SecretProvider(org.platformlayer.auth.crypto.SecretProvider)

Example 80 with OpsException

use of org.platformlayer.ops.OpsException in project platformlayer by platformlayer.

the class ItemServiceImpl method findItem.

@Override
public <T extends ItemBase> T findItem(ProjectAuthorization auth, Class<T> itemClass, String id) throws OpsException {
    ModelClass<T> modelClass = serviceProviderDirectory.getModelClass(itemClass);
    // Class<T> javaClass = modelClass.getJavaClass();
    ProjectId project = getProjectId(auth);
    PlatformLayerKey modelKey = new PlatformLayerKey(null, project, modelClass.getServiceType(), modelClass.getItemType(), new ManagedItemId(id));
    boolean fetchTags = true;
    T managedItem;
    try {
        managedItem = Casts.checkedCast(repository.getManagedItem(modelKey, fetchTags, SecretProvider.from(auth)), itemClass);
    } catch (RepositoryException e) {
        throw new OpsException("Error fetching item from database", e);
    }
    return managedItem;
}
Also used : OpsException(org.platformlayer.ops.OpsException) ProjectId(org.platformlayer.ids.ProjectId) PlatformLayerKey(org.platformlayer.core.model.PlatformLayerKey) RepositoryException(org.platformlayer.RepositoryException) ManagedItemId(org.platformlayer.ids.ManagedItemId)

Aggregations

OpsException (org.platformlayer.ops.OpsException)142 IOException (java.io.IOException)39 File (java.io.File)19 ItemBase (org.platformlayer.core.model.ItemBase)19 RepositoryException (org.platformlayer.RepositoryException)18 PlatformLayerKey (org.platformlayer.core.model.PlatformLayerKey)17 Handler (org.platformlayer.ops.Handler)17 Tag (org.platformlayer.core.model.Tag)16 Command (org.platformlayer.ops.Command)16 Machine (org.platformlayer.ops.Machine)13 TagChanges (org.platformlayer.core.model.TagChanges)11 OpsTarget (org.platformlayer.ops.OpsTarget)11 TimeoutException (java.util.concurrent.TimeoutException)10 OpenstackException (org.openstack.client.OpenstackException)10 OpsContext (org.platformlayer.ops.OpsContext)10 X509Certificate (java.security.cert.X509Certificate)9 InetAddress (java.net.InetAddress)8 ProjectId (org.platformlayer.ids.ProjectId)8 ProcessExecution (org.platformlayer.ops.process.ProcessExecution)8 List (java.util.List)7