Search in sources :

Example 1 with WineryVersion

use of org.eclipse.winery.common.version.WineryVersion in project winery by eclipse.

the class EnhancementUtils method getAvailableFeaturesForTopology.

// region ******************** Add Management Features ********************
/**
 * Gathers all feature NodeTypes available for the given topology.
 *
 * If the underlying implementation of the feature does not matter, use <code>null</code>.
 *
 * <p>
 * Note: If feature NodeTypes are used in the topology, they cannot be enhanced with more features.
 * </p>
 *
 * @param topology               The topology to update.
 * @param deploymentTechnologies Deployment technology descriptors contained in the service template
 */
public static Map<String, Map<QName, String>> getAvailableFeaturesForTopology(TTopologyTemplate topology, List<DeploymentTechnologyDescriptor> deploymentTechnologies) {
    IRepository repository = RepositoryFactory.getRepository();
    Map<String, Map<QName, String>> availableFeatures = new HashMap<>();
    Map<QName, TNodeType> nodeTypes = repository.getQNameToElementMapping(NodeTypeId.class);
    topology.getNodeTemplates().forEach(node -> {
        List<String> nodeDeploymentTechnologies = deploymentTechnologies.stream().filter(deploymentTechnologyDescriptor -> deploymentTechnologyDescriptor.getManagedIds().contains(node.getId())).map(DeploymentTechnologyDescriptor::getTechnologyId).collect(Collectors.toList());
        Map<TNodeType, String> featureChildren = ModelUtilities.getAvailableFeaturesOfType(node.getType(), nodeTypes, nodeDeploymentTechnologies);
        Map<QName, String> applicableFeatures = new HashMap<>();
        // Check requirements
        featureChildren.forEach((featureType, value) -> {
            if (listIsNotNullOrEmpty(featureType.getRequirementDefinitions())) {
                List<TRequirementDefinition> requirements = featureType.getRequirementDefinitions().stream().filter(req -> req.getRequirementType().equals(OpenToscaBaseTypes.managementFeatureRequirement)).collect(Collectors.toList());
                requirements.forEach(req -> {
                    boolean applicable = ModelUtilities.getHostedOnSuccessors(topology, node).stream().anyMatch(hosts -> {
                        WineryVersion reqVersion = VersionUtils.getVersion(req.getName());
                        String reqName = VersionUtils.getNameWithoutVersion(req.getName());
                        String type = hosts.getType().getLocalPart();
                        if (VersionUtils.getNameWithoutVersion(type).equals(reqName)) {
                            return reqVersion.getComponentVersion().isEmpty() || reqVersion.getComponentVersion().equals(VersionUtils.getVersion(type).getComponentVersion());
                        }
                        return false;
                    });
                    if (applicable) {
                        applicableFeatures.put(featureType.getQName(), value);
                    }
                });
            } else {
                applicableFeatures.put(featureType.getQName(), value);
            }
        });
        if (featureChildren.size() > 0) {
            availableFeatures.put(node.getId(), applicableFeatures);
        }
    });
    return availableFeatures;
}
Also used : TNodeTypeImplementation(org.eclipse.winery.model.tosca.TNodeTypeImplementation) TRequirementDefinition(org.eclipse.winery.model.tosca.TRequirementDefinition) OpenToscaInterfaces(org.eclipse.winery.model.tosca.constants.OpenToscaInterfaces) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) OpenToscaBaseTypes(org.eclipse.winery.model.tosca.constants.OpenToscaBaseTypes) TTopologyTemplate(org.eclipse.winery.model.tosca.TTopologyTemplate) NamespaceProperties(org.eclipse.winery.repository.backend.filebased.NamespaceProperties) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) WineryVersion(org.eclipse.winery.common.version.WineryVersion) Map(java.util.Map) TNodeTemplate(org.eclipse.winery.model.tosca.TNodeTemplate) NodeTypeImplementationId(org.eclipse.winery.model.ids.definitions.NodeTypeImplementationId) Logger(org.slf4j.Logger) ListUtils.listIsNotNullOrEmpty(org.eclipse.winery.common.ListUtils.listIsNotNullOrEmpty) Collection(java.util.Collection) IOException(java.io.IOException) DeploymentTechnologyDescriptor(org.eclipse.winery.model.tosca.DeploymentTechnologyDescriptor) TNodeType(org.eclipse.winery.model.tosca.TNodeType) WinerysPropertiesDefinition(org.eclipse.winery.model.tosca.extensions.kvproperties.WinerysPropertiesDefinition) Collectors(java.util.stream.Collectors) TInterface(org.eclipse.winery.model.tosca.TInterface) RelationshipTypeId(org.eclipse.winery.model.ids.definitions.RelationshipTypeId) RepositoryFactory(org.eclipse.winery.repository.backend.RepositoryFactory) Objects(java.util.Objects) List(java.util.List) PropertyDefinitionKV(org.eclipse.winery.model.tosca.extensions.kvproperties.PropertyDefinitionKV) NamespaceManager(org.eclipse.winery.repository.backend.NamespaceManager) VersionUtils(org.eclipse.winery.common.version.VersionUtils) IRepository(org.eclipse.winery.repository.backend.IRepository) TRelationshipType(org.eclipse.winery.model.tosca.TRelationshipType) TRelationshipTemplate(org.eclipse.winery.model.tosca.TRelationshipTemplate) ModelUtilities(org.eclipse.winery.model.tosca.utils.ModelUtilities) QName(javax.xml.namespace.QName) ToscaBaseTypes(org.eclipse.winery.model.tosca.constants.ToscaBaseTypes) NodeTypeId(org.eclipse.winery.model.ids.definitions.NodeTypeId) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) QName(javax.xml.namespace.QName) TNodeType(org.eclipse.winery.model.tosca.TNodeType) IRepository(org.eclipse.winery.repository.backend.IRepository) TRequirementDefinition(org.eclipse.winery.model.tosca.TRequirementDefinition) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) WineryVersion(org.eclipse.winery.common.version.WineryVersion)

Example 2 with WineryVersion

use of org.eclipse.winery.common.version.WineryVersion in project winery by eclipse.

the class MySqlDbmsRefinementPlugin method apply.

@Override
public Set<String> apply(TTopologyTemplate template) {
    Set<String> discoveredNodeIds = new HashSet<>();
    try {
        Session session = InstanceModelUtils.createJschSession(template, this.matchToBeRefined.nodeIdsToBeReplaced);
        String mySQL_DBMS_version = InstanceModelUtils.executeCommand(session, "sudo /usr/bin/mysql --help | grep Distrib | awk '{print $5}' | sed -r 's/([0-9]+),$/\\1/'");
        String mySQL_DBMS_port = InstanceModelUtils.executeCommand(session, "sudo netstat -tulpen | grep mysqld | awk '{print $4}' | sed -r 's/.*:([0-9]+)$/\\1/'");
        session.disconnect();
        template.getNodeTemplates().stream().filter(node -> this.matchToBeRefined.nodeIdsToBeReplaced.contains(node.getId()) && Objects.requireNonNull(node.getType()).getLocalPart().toLowerCase().startsWith("MySQL-DBMS".toLowerCase())).findFirst().ifPresent(mySQL -> {
            WineryVersion version = VersionUtils.getVersion(Objects.requireNonNull(mySQL.getType()).getLocalPart());
            String[] split = mySQL_DBMS_version.split("\\.");
            discoveredNodeIds.add(mySQL.getId());
            if (version.getComponentVersion() == null || !version.getComponentVersion().startsWith(split[0])) {
                if ("5".equals(split[0]) && "5".equals(split[1])) {
                    mySQL.setType(mySql_5_5_QName);
                } else if ("5".equals(split[0]) && "7".equals(split[1])) {
                    mySQL.setType(mySql_5_7_QName);
                }
            }
            if (mySQL.getProperties() == null) {
                mySQL.setProperties(new TEntityTemplate.WineryKVProperties());
            }
            if (mySQL.getProperties() instanceof TEntityTemplate.WineryKVProperties) {
                TEntityTemplate.WineryKVProperties properties = (TEntityTemplate.WineryKVProperties) mySQL.getProperties();
                properties.getKVProperties().put("DBMSPort", mySQL_DBMS_port);
            }
        });
    } catch (RuntimeException e) {
        logger.error("Error while retrieving Tomcat information...", e);
    }
    return discoveredNodeIds;
}
Also used : TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) HashSet(java.util.HashSet) Session(com.jcraft.jsch.Session) WineryVersion(org.eclipse.winery.common.version.WineryVersion)

Example 3 with WineryVersion

use of org.eclipse.winery.common.version.WineryVersion in project winery by eclipse.

the class TomcatRefinementPlugin method apply.

@Override
public Set<String> apply(TTopologyTemplate template) {
    Set<String> discoveredNodeIds = new HashSet<>();
    try {
        Session session = InstanceModelUtils.createJschSession(template, this.matchToBeRefined.nodeIdsToBeReplaced);
        String tomcatVersion = InstanceModelUtils.executeCommand(session, "sudo cat /opt/tomcat/latest/RELEASE-NOTES | grep 'Apache Tomcat Version' | awk '{print $4}'");
        logger.info("Retrieved Tomcat version: {}", tomcatVersion);
        String tomcatPort = InstanceModelUtils.executeCommand(session, "sudo cat /opt/tomcat/latest/conf/server.xml | grep '<Connector port=\".*\" protocol=\"HTTP/1.1\"' | awk '{print $2}' | sed -r 's/.*\"([0-9]+)\"$/\\1/'");
        logger.info("Retrieved Tomcat port: {}", tomcatPort);
        session.disconnect();
        template.getNodeTemplates().stream().filter(node -> this.matchToBeRefined.nodeIdsToBeReplaced.contains(node.getId()) && Objects.requireNonNull(node.getType()).getLocalPart().toLowerCase().startsWith("Tomcat".toLowerCase())).findFirst().ifPresent(tomcat -> {
            discoveredNodeIds.add(tomcat.getId());
            WineryVersion version = VersionUtils.getVersion(Objects.requireNonNull(tomcat.getType()).getLocalPart());
            String[] split = tomcatVersion.split("\\.");
            if (version.getComponentVersion() == null || !version.getComponentVersion().startsWith(split[0])) {
                if ("7".equals(split[0])) {
                    tomcat.setType(tomcat7QName);
                } else if ("8".equals(split[0])) {
                    tomcat.setType(tomcat8QName);
                } else if ("9".equals(split[0])) {
                    tomcat.setType(tomcat9QName);
                }
            }
            if (tomcat.getProperties() == null) {
                tomcat.setProperties(new TEntityTemplate.WineryKVProperties());
            }
            if (tomcat.getProperties() instanceof TEntityTemplate.WineryKVProperties) {
                TEntityTemplate.WineryKVProperties properties = (TEntityTemplate.WineryKVProperties) tomcat.getProperties();
                properties.getKVProperties().put("Port", tomcatPort);
            }
        });
    } catch (RuntimeException e) {
        logger.error("Error while retrieving Tomcat information...", e);
    }
    return discoveredNodeIds;
}
Also used : TEntityTemplate(org.eclipse.winery.model.tosca.TEntityTemplate) HashSet(java.util.HashSet) Session(com.jcraft.jsch.Session) WineryVersion(org.eclipse.winery.common.version.WineryVersion)

Example 4 with WineryVersion

use of org.eclipse.winery.common.version.WineryVersion in project winery by eclipse.

the class YamlRepository method getDefinitionsChildIds.

/**
 * Creates Set of Definitions Child Id Mapps xml definition to compatible yaml definition
 *
 * @param inputIdClass            requested id class
 * @param omitDevelopmentVersions omit development versions
 * @return set of definitions child id
 */
@Override
public <T extends DefinitionsChildId> SortedSet<T> getDefinitionsChildIds(Class<T> inputIdClass, boolean omitDevelopmentVersions) {
    SortedSet<T> res = new TreeSet<>();
    List<Class<T>> idClasses = new ArrayList<>();
    idClasses.add(inputIdClass);
    idClasses = convertDefinitionsChildIdIfNeeded(idClasses);
    for (Class<T> idClass : idClasses) {
        String rootPathFragment = IdUtil.getRootPathFragment(idClass);
        Path dir = this.getRepositoryRoot().resolve(rootPathFragment);
        if (!Files.exists(dir)) {
            // return empty list if no ids are available
            return res;
        }
        assert (Files.isDirectory(dir));
        final OnlyNonHiddenDirectories onhdf = new OnlyNonHiddenDirectories();
        // list all directories contained in this directory
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, onhdf)) {
            for (Path nsP : ds) {
                // the current path is the namespace
                Namespace ns = new Namespace(nsP.getFileName().toString(), true);
                try (DirectoryStream<Path> idDS = Files.newDirectoryStream(nsP, onhdf)) {
                    for (Path idP : idDS) {
                        List<XmlId> xmlIds = new ArrayList<>();
                        if (ArtifactTemplateId.class.isAssignableFrom(inputIdClass)) {
                            List<String> artifactNames = getAllArtifactNamesFromType(idP, idClass, ns.getDecoded());
                            for (String artifactName : artifactNames) {
                                xmlIds.add(new XmlId(artifactName + "@" + IdUtil.getFolderName(idClass), true));
                            }
                        } else {
                            xmlIds.add(new XmlId(idP.getFileName().toString(), true));
                        }
                        for (XmlId xmlId : xmlIds) {
                            if (omitDevelopmentVersions) {
                                WineryVersion version = VersionUtils.getVersion(xmlId.getDecoded());
                                if (version.toString().length() > 0 && version.getWorkInProgressVersion() > 0) {
                                    continue;
                                }
                            }
                            Constructor<T> constructor;
                            try {
                                constructor = inputIdClass.getConstructor(Namespace.class, XmlId.class);
                            } catch (Exception e) {
                                LOGGER.debug("Internal error at determining id constructor", e);
                                // abort everything, return invalid result
                                return res;
                            }
                            T id;
                            try {
                                id = constructor.newInstance(ns, xmlId);
                            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                                LOGGER.debug("Internal error at invocation of id constructor", e);
                                // abort everything, return invalid result
                                return res;
                            }
                            res.add(id);
                        }
                    }
                }
            }
        } catch (IOException e) {
            LOGGER.debug("Cannot close ds", e);
        }
    }
    return res;
}
Also used : Path(java.nio.file.Path) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Namespace(org.eclipse.winery.model.ids.Namespace) JAXBException(javax.xml.bind.JAXBException) InvocationTargetException(java.lang.reflect.InvocationTargetException) MultiException(org.eclipse.winery.model.converter.support.exception.MultiException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) OnlyNonHiddenDirectories(org.eclipse.winery.repository.backend.filebased.OnlyNonHiddenDirectories) TreeSet(java.util.TreeSet) XmlId(org.eclipse.winery.model.ids.XmlId) WineryVersion(org.eclipse.winery.common.version.WineryVersion)

Example 5 with WineryVersion

use of org.eclipse.winery.common.version.WineryVersion in project winery by eclipse.

the class BackendUtilsTestWithGitBackedRepository method getVersionListOfAnOldComponentVersionWhichIsEditable.

@Test
public void getVersionListOfAnOldComponentVersionWhichIsEditable() throws Exception {
    this.setRevisionTo("origin/plain");
    NodeTypeId id = new NodeTypeId("http://opentosca.org/nodetypes", "NodeTypeWithALowerReleasableManagementVersion_2-w2-wip1", false);
    // instead of creating a new NodeType, just make some changes to this element, which should create the same state
    makeSomeChanges(id);
    List<WineryVersion> versionList = WineryVersionUtils.getAllVersionsOfOneDefinition(id, repository);
    WineryVersion version = versionList.get(versionList.size() - 2);
    assertTrue(version.isEditable());
    assertTrue(version.isReleasable());
}
Also used : NodeTypeId(org.eclipse.winery.model.ids.definitions.NodeTypeId) WineryVersion(org.eclipse.winery.common.version.WineryVersion) Test(org.junit.jupiter.api.Test)

Aggregations

WineryVersion (org.eclipse.winery.common.version.WineryVersion)37 Test (org.junit.jupiter.api.Test)19 NodeTypeId (org.eclipse.winery.model.ids.definitions.NodeTypeId)14 DefinitionsChildId (org.eclipse.winery.model.ids.definitions.DefinitionsChildId)12 Produces (javax.ws.rs.Produces)8 IRepository (org.eclipse.winery.repository.backend.IRepository)8 IOException (java.io.IOException)7 POST (javax.ws.rs.POST)7 Path (javax.ws.rs.Path)7 ArrayList (java.util.ArrayList)6 List (java.util.List)6 QName (javax.xml.namespace.QName)6 ServiceTemplateId (org.eclipse.winery.model.ids.definitions.ServiceTemplateId)6 ResourceResult (org.eclipse.winery.repository.rest.resources._support.ResourceResult)6 QNameApiData (org.eclipse.winery.repository.rest.resources.apiData.QNameApiData)6 LinkedHashMap (java.util.LinkedHashMap)5 Response (javax.ws.rs.core.Response)5 Map (java.util.Map)4 Collectors (java.util.stream.Collectors)4 TNodeTemplate (org.eclipse.winery.model.tosca.TNodeTemplate)4