Search in sources :

Example 6 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project fabric8 by jboss-fuse.

the class GitPatchManagementServiceImpl method handleConflict.

private void handleConflict(File patchDirectory, Git fork, boolean preferNew, String cpPrefix, boolean performBackup, String choose, String backup, boolean rollback) throws GitAPIException, IOException {
    Map<String, IndexDiff.StageState> conflicts = fork.status().call().getConflictingStageState();
    DirCache cache = fork.getRepository().readDirCache();
    // path -> [oursObjectId, baseObjectId, theirsObjectId]
    Map<String, ObjectId[]> threeWayMerge = new HashMap<>();
    // collect conflicts info
    for (int i = 0; i < cache.getEntryCount(); i++) {
        DirCacheEntry entry = cache.getEntry(i);
        if (entry.getStage() == DirCacheEntry.STAGE_0) {
            continue;
        }
        if (!threeWayMerge.containsKey(entry.getPathString())) {
            threeWayMerge.put(entry.getPathString(), new ObjectId[] { null, null, null });
        }
        if (entry.getStage() == DirCacheEntry.STAGE_1) {
            // base
            threeWayMerge.get(entry.getPathString())[1] = entry.getObjectId();
        }
        if (entry.getStage() == DirCacheEntry.STAGE_2) {
            // ours
            threeWayMerge.get(entry.getPathString())[0] = entry.getObjectId();
        }
        if (entry.getStage() == DirCacheEntry.STAGE_3) {
            // theirs
            threeWayMerge.get(entry.getPathString())[2] = entry.getObjectId();
        }
    }
    // resolve conflicts
    ObjectReader objectReader = fork.getRepository().newObjectReader();
    for (Map.Entry<String, ObjectId[]> entry : threeWayMerge.entrySet()) {
        if (entry.getKey().equals("patch-info.txt")) {
            fork.rm().addFilepattern(entry.getKey()).call();
            continue;
        }
        Resolver resolver = conflictResolver.getResolver(entry.getKey());
        // resolved version - either by custom resolved or using automatic algorithm
        String resolved = null;
        if (resolver != null && entry.getValue()[0] != null && entry.getValue()[2] != null) {
            // custom conflict resolution (don't expect DELETED_BY_X kind of conflict, only BOTH_MODIFIED)
            String message = String.format(" - %s (%s): %s", entry.getKey(), conflicts.get(entry.getKey()), "Using " + resolver.getClass().getName() + " to resolve the conflict");
            Activator.log2(LogService.LOG_INFO, message);
            // when doing custom resolution of conflict, we know that both user and patch has changed the file
            // in non-mergeable way.
            // If there was no resolver, we simply check what to choose by "preferNew" flag
            // But because we have custom resolver, we use "preferNew" flag to check which STAGE points to patch'
            // version and we select this patch' version of conflicting file as less important file inside
            // custom resolver
            File base = null, first = null, second = null;
            try {
                ObjectLoader loader = null;
                if (entry.getValue()[1] != null) {
                    base = new File(fork.getRepository().getWorkTree(), entry.getKey() + ".1");
                    loader = objectReader.open(entry.getValue()[1]);
                    try (FileOutputStream fos = new FileOutputStream(base)) {
                        loader.copyTo(fos);
                    }
                }
                // if preferNew == true (P patch) then "first" file (less important) will be file
                // provided by patch ("theirs", STAGE_3)
                first = new File(fork.getRepository().getWorkTree(), entry.getKey() + ".2");
                loader = objectReader.open(entry.getValue()[preferNew ? 2 : 0]);
                try (FileOutputStream fos = new FileOutputStream(first)) {
                    loader.copyTo(fos);
                }
                // "second", more important file will be user change
                second = new File(fork.getRepository().getWorkTree(), entry.getKey() + ".3");
                loader = objectReader.open(entry.getValue()[preferNew ? 0 : 2]);
                try (FileOutputStream fos = new FileOutputStream(second)) {
                    loader.copyTo(fos);
                }
                // resolvers treat patch change as less important - user lines overwrite patch lines
                if (resolver instanceof PropertiesFileResolver) {
                    // TODO: use options from patch:install / patch:fabric-install command
                    // by default we use a file that comes from patch and we may add property changes
                    // from user
                    // in R patch, preferNew == false, because patch comes first
                    // in P patch, preferNew == true, because patch comes last
                    // in R patch + fabric mode, preferNew == true, because we *merge* patch branch into version
                    // branch
                    boolean useFirstChangeAsBase = true;
                    if (entry.getKey().startsWith("etc/")) {
                        // as base
                        if (rollback) {
                            useFirstChangeAsBase = true;
                        } else {
                            useFirstChangeAsBase = false;
                        }
                    }
                    resolved = ((ResolverEx) resolver).resolve(first, base, second, useFirstChangeAsBase, rollback);
                } else {
                    resolved = resolver.resolve(first, base, second);
                }
                if (resolved != null) {
                    FileUtils.write(new File(fork.getRepository().getWorkTree(), entry.getKey()), resolved);
                    fork.add().addFilepattern(entry.getKey()).call();
                }
            } finally {
                if (base != null) {
                    base.delete();
                }
                if (first != null) {
                    first.delete();
                }
                if (second != null) {
                    second.delete();
                }
            }
        }
        if (resolved == null) {
            // automatic conflict resolution
            String message = String.format(" - %s (%s): Choosing %s", entry.getKey(), conflicts.get(entry.getKey()), choose);
            ObjectLoader loader = null;
            ObjectLoader loaderForBackup = null;
            // longer code, but more readable then series of elvis operators (?:)
            if (preferNew) {
                switch(conflicts.get(entry.getKey())) {
                    case BOTH_ADDED:
                    case BOTH_MODIFIED:
                        loader = objectReader.open(entry.getValue()[2]);
                        loaderForBackup = objectReader.open(entry.getValue()[0]);
                        break;
                    case BOTH_DELETED:
                        break;
                    case DELETED_BY_THEM:
                        // ENTESB-6003: special case: when R patch removes something and we've modified it
                        // let's preserve our version
                        message = String.format(" - %s (%s): Keeping custom change", entry.getKey(), conflicts.get(entry.getKey()));
                        loader = objectReader.open(entry.getValue()[0]);
                        break;
                    case DELETED_BY_US:
                        loader = objectReader.open(entry.getValue()[2]);
                        break;
                }
            } else {
                switch(conflicts.get(entry.getKey())) {
                    case BOTH_ADDED:
                    case BOTH_MODIFIED:
                        loader = objectReader.open(entry.getValue()[0]);
                        loaderForBackup = objectReader.open(entry.getValue()[2]);
                        break;
                    case DELETED_BY_THEM:
                        loader = objectReader.open(entry.getValue()[0]);
                        break;
                    case BOTH_DELETED:
                    case DELETED_BY_US:
                        break;
                }
            }
            Activator.log2(LogService.LOG_WARNING, message);
            if (loader != null) {
                try (FileOutputStream fos = new FileOutputStream(new File(fork.getRepository().getWorkTree(), entry.getKey()))) {
                    loader.copyTo(fos);
                }
                fork.add().addFilepattern(entry.getKey()).call();
            } else {
                fork.rm().addFilepattern(entry.getKey()).call();
            }
            if (performBackup) {
                // the other entry should be backed up
                if (loaderForBackup != null) {
                    File target = new File(patchDirectory.getParent(), patchDirectory.getName() + ".backup");
                    if (isStandaloneChild()) {
                        target = new File(patchDirectory.getParent(), patchDirectory.getName() + "." + System.getProperty("karaf.name") + ".backup");
                    }
                    if (cpPrefix != null) {
                        target = new File(target, cpPrefix);
                    }
                    File file = new File(target, entry.getKey());
                    message = String.format("Backing up %s to \"%s\"", backup, file.getCanonicalPath());
                    Activator.log2(LogService.LOG_DEBUG, message);
                    file.getParentFile().mkdirs();
                    try (FileOutputStream fos = new FileOutputStream(file)) {
                        loaderForBackup.copyTo(fos);
                    }
                }
            }
        }
    }
}
Also used : DirCacheEntry(org.eclipse.jgit.dircache.DirCacheEntry) ConflictResolver(io.fabric8.patch.management.conflicts.ConflictResolver) PropertiesFileResolver(io.fabric8.patch.management.conflicts.PropertiesFileResolver) Resolver(io.fabric8.patch.management.conflicts.Resolver) HashMap(java.util.HashMap) DirCache(org.eclipse.jgit.dircache.DirCache) PropertiesFileResolver(io.fabric8.patch.management.conflicts.PropertiesFileResolver) EOLFixingFileOutputStream(io.fabric8.patch.management.io.EOLFixingFileOutputStream) FileOutputStream(java.io.FileOutputStream) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ObjectLoader(org.eclipse.jgit.lib.ObjectLoader) Map(java.util.Map) TreeMap(java.util.TreeMap) HashMap(java.util.HashMap) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File)

Example 7 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project fabric8 by jboss-fuse.

the class OpenWireFormat method marshal.

public synchronized Buffer marshal(Object command) throws IOException {
    if (cacheEnabled) {
        runMarshallCacheEvictionSweep();
    }
    // MarshallAware ma = null;
    // // If not using value caching, then the marshaled form is always the
    // // same
    // if (!cacheEnabled && ((DataStructure)command).isMarshallAware()) {
    // ma = (MarshallAware)command;
    // }
    Buffer sequence = null;
    if (sequence == null) {
        int size = 1;
        if (command != null) {
            DataStructure c = (DataStructure) command;
            byte type = c.getDataStructureType();
            DataStreamMarshaller dsm = (DataStreamMarshaller) dataMarshallers[type & 0xFF];
            if (dsm == null) {
                throw new IOException("Unknown data type: " + type);
            }
            if (tightEncodingEnabled) {
                BooleanStream bs = new BooleanStream();
                size += dsm.tightMarshal1(this, c, bs);
                size += bs.marshalledSize();
                bytesOut.restart(size);
                if (!sizePrefixDisabled) {
                    bytesOut.writeInt(size);
                }
                bytesOut.writeByte(type);
                bs.marshal(bytesOut);
                dsm.tightMarshal2(this, c, bytesOut, bs);
                sequence = bytesOut.toBuffer();
            } else {
                bytesOut.restart();
                if (!sizePrefixDisabled) {
                    // we don't know the final size
                    bytesOut.writeInt(0);
                // yet but write this here for
                // now.
                }
                bytesOut.writeByte(type);
                dsm.looseMarshal(this, c, bytesOut);
                sequence = bytesOut.toBuffer();
                if (!sizePrefixDisabled) {
                    size = sequence.getLength() - 4;
                    int pos = sequence.offset;
                    sequence.offset = 0;
                    BufferEditor.big(sequence).writeInt(size);
                    sequence.offset = pos;
                }
            }
        } else {
            bytesOut.restart(5);
            bytesOut.writeInt(size);
            bytesOut.writeByte(NULL_TYPE);
            sequence = bytesOut.toBuffer();
        }
    // if( ma!=null ) {
    // ma.setCachedMarshalledForm(this, sequence);
    // }
    }
    return sequence;
}
Also used : Buffer(org.fusesource.hawtbuf.Buffer) DataStructure(io.fabric8.gateway.handlers.detecting.protocol.openwire.command.DataStructure) IOException(java.io.IOException)

Example 8 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project fabric8 by jboss-fuse.

the class ArchetypeGenerateAction method doExecute.

@Override
protected Object doExecute() throws Exception {
    // if no directory then use workspace
    if (directory == null) {
        // must have a workspace location configured
        Preferences preferences = Preferences.userNodeForPackage(getClass());
        String location = preferences.get(ArchetypeWorkspace.PREFERENCE_WORKSPACE, null);
        if (location == null) {
            System.out.println("No workspace location has been set.");
            System.out.println("Use the archetype-workspace command to set a workspace first.");
            System.out.println("");
            return null;
        } else {
            System.out.println("Using current workspace: " + location);
            directory = location;
        }
    } else {
        System.out.println("Using directory as workspace: " + directory);
    }
    File target = new File(directory);
    // make sure the directory exists, auto-creating if missing
    if (!target.exists()) {
        target.mkdirs();
    }
    if (!target.exists() || !target.isDirectory()) {
        System.err.println("Workspace does not exists or is not a directory: " + directory);
        return null;
    }
    Archetype archetype = null;
    // try artifact first
    if (!isNullOrBlank(archetypeOrFilter)) {
        archetype = archetypeService.getArchetypeByArtifact(archetypeOrFilter);
        if (archetype == null) {
            // then by coordinate
            archetype = archetypeService.getArchetype(archetypeOrFilter);
        }
    }
    // no archetype yet so present a list where the user can select
    while (archetype == null) {
        List<Archetype> archetypes = archetypeService.listArchetypes(archetypeOrFilter, true);
        System.out.println("Choose archetype:");
        Iterator<Archetype> it = archetypes.iterator();
        int i = 0;
        while (it.hasNext()) {
            Archetype select = it.next();
            System.out.println(String.format("%4d: -> %-50s %s", ++i, select.artifactId, select.description));
        }
        boolean choosing = true;
        while (choosing) {
            // default select last
            String choose = ShellUtils.readLine(session, String.format("Choose a number or apply filter (case insensitive): %d: ", i), false);
            if (Strings.isNullOrBlank(choose)) {
                // user pressed enter so we select the last
                choose = "" + i;
            }
            try {
                int no = Integer.valueOf(choose);
                // is the number within range
                if (no >= 1 && no <= archetypes.size()) {
                    archetype = archetypes.get(no - 1);
                    break;
                } else {
                    System.out.println("Number " + no + " out of range. Please try again!");
                    continue;
                }
            } catch (NumberFormatException e) {
                // no its a filter, so we use this as filter, and show the list again
                archetypeOrFilter = choose;
                choosing = false;
                archetype = null;
            }
        }
    }
    // okay we have selected an archetype now
    File archetypeFile = fetchArchetype(archetype);
    if (archetypeFile == null || !archetypeFile.exists()) {
        System.err.println("No archetype found for \"" + archetypeOrFilter + "\" coordinates");
        return null;
    }
    System.out.println("----------------------------------------------------------------------------");
    System.out.println("Using archetype: " + archetype.artifactId);
    String defaultGroupId = "io.fabric8";
    String defaultArtifactId = archetype.artifactId + "-example";
    String defaultVersion = "1.0-SNAPSHOT";
    String defaultName = archetype.name;
    String defaultDescription = isNotBlank(archetype.description) ? archetype.description : "";
    System.out.println("----- Configure archetype -----");
    String groupId = ShellUtils.readLine(session, String.format("Define value for property 'groupId' (%s): ", defaultGroupId), false);
    String artifactId = ShellUtils.readLine(session, String.format("Define value for property 'artifactId' (%s): ", defaultArtifactId), false);
    String version = ShellUtils.readLine(session, String.format("Define value for property 'version' (%s): ", defaultVersion), false);
    groupId = isNullOrBlank(groupId) ? defaultGroupId : groupId;
    artifactId = isNullOrBlank(artifactId) ? defaultArtifactId : artifactId;
    version = isNullOrBlank(version) ? defaultVersion : version;
    String defaultPackageName = (groupId + "." + artifactId).replaceAll("-", ".");
    String packageName = ShellUtils.readLine(session, String.format("Define value for property 'package' (%s): ", defaultPackageName), false);
    // use artifact id as default directory name (maven does this also)
    String defaultDirectoryName = isNullOrBlank(artifactId) ? defaultArtifactId : artifactId;
    directory = ShellUtils.readLine(session, String.format("Define value for property 'directoryName' (%s): ", defaultDirectoryName), false);
    packageName = isNullOrBlank(packageName) ? defaultPackageName : packageName;
    directory = isNullOrBlank(directory) ? artifactId : directory;
    String name = ShellUtils.readLine(session, String.format("Define value for property 'name' (%s): ", defaultName), false);
    String description = ShellUtils.readLine(session, String.format("Define value for property 'description' (%s): ", defaultDescription), false);
    // use null to indicate we want out of the box description
    name = isNullOrBlank(name) ? null : name;
    description = isNullOrBlank(description) ? null : description;
    File childDir = new File(target, directory);
    ArchetypeHelper helper = new ArchetypeHelper(archetypeFile, childDir, groupId, artifactId, version, name, description);
    helper.setPackageName(packageName);
    Map<String, String> properties = helper.parseProperties();
    // if we have fabric8.profile as a property then lets configured it now, as its mandatory
    // and use artifactId as its default suggested value
    String profile = null;
    if (properties.containsKey("fabric8-profile")) {
        profile = properties.remove("fabric8-profile");
        String defaultProfile = isNullOrBlank(profile) ? artifactId : profile;
        String p = ShellUtils.readLine(session, String.format("Define value for property 'fabric8.profile' (%s): ", defaultProfile), false);
        profile = isNullOrBlank(p) ? defaultProfile : p;
    }
    // show additional properties and ask to use them as-is
    boolean mustChoose = false;
    if (!properties.isEmpty()) {
        // check if we must choose if there is an empty value or a value that has a ${ } token so we dont have a default value
        for (String value : properties.values()) {
            if (isNullOrBlank(value) || value.contains("$")) {
                mustChoose = true;
                break;
            }
        }
        if (!mustChoose) {
            System.out.println("----- Additional properties -----");
            for (String key : properties.keySet()) {
                System.out.println(String.format("Using property '%s' (%s): ", key, properties.get(key)));
            }
        }
        boolean choosing = true;
        while (mustChoose || choosing) {
            String confirm = null;
            if (!mustChoose) {
                confirm = ShellUtils.readLine(session, "Confirm additional properties configuration: (Y): ", false);
                confirm = isNullOrBlank(confirm) ? "Y" : confirm;
            }
            if (mustChoose || !"Y".equalsIgnoreCase(confirm)) {
                // ask for replacement properties suggesting the defaults
                if (!properties.isEmpty()) {
                    System.out.println("----- Configure additional properties -----");
                    for (String key : properties.keySet()) {
                        String value = properties.get(key);
                        // if the value is empty or a token, then do not show any default value
                        if (isNullOrBlank(value) || value.contains("$")) {
                            value = "";
                        }
                        String p = ShellUtils.readLine(session, String.format("Define value for property '%s' (%s): ", key, value), false);
                        p = isNullOrBlank(p) ? value : p;
                        properties.put(key, p);
                    }
                }
                mustChoose = false;
            } else {
                choosing = false;
            }
        }
    }
    // remover to include the profile back into properties
    if (profile != null) {
        properties.put("fabric8-profile", profile);
    }
    if (!properties.isEmpty()) {
        // set override properties
        helper.setOverrideProperties(properties);
    }
    String confirm = ShellUtils.readLine(session, "Create project: (Y): ", false);
    confirm = confirm == null || confirm.trim().equals("") ? "Y" : confirm;
    if ("Y".equalsIgnoreCase(confirm)) {
        System.out.println("----------------------------------------------------------------------------");
        System.out.println(String.format("Creating project in directory: %s", childDir.getCanonicalPath()));
        helper.execute();
        System.out.println("Project created successfully");
        System.out.println("");
    } else {
        System.out.println("----------------------------------------------------------------------------");
        System.out.println("Creating project aborted!");
        System.out.println("");
    }
    return null;
}
Also used : Archetype(io.fabric8.tooling.archetype.catalog.Archetype) ArchetypeHelper(io.fabric8.tooling.archetype.generator.ArchetypeHelper) Preferences(java.util.prefs.Preferences) File(java.io.File)

Example 9 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project fabric8-maven-plugin by fabric8io.

the class ClientToolsService method getKubeCtlExecutable.

public File getKubeCtlExecutable() {
    OpenShiftClient openShiftClient = controller.getOpenShiftClientOrNull();
    String command = openShiftClient != null ? "oc" : "kubectl";
    String missingCommandMessage;
    File file = ProcessUtil.findExecutable(log, command);
    if (file == null && command.equals("oc")) {
        file = ProcessUtil.findExecutable(log, command);
        missingCommandMessage = "commands oc or kubectl";
    } else {
        missingCommandMessage = "command " + command;
    }
    if (file == null) {
        throw new IllegalStateException("Could not find " + missingCommandMessage + ". Please install the necessary binaries and ensure they get added to your $PATH");
    }
    return file;
}
Also used : OpenShiftClient(io.fabric8.openshift.client.OpenShiftClient) File(java.io.File)

Example 10 with Command

use of io.fabric8.gateway.handlers.detecting.protocol.openwire.command.Command in project fabric8-maven-plugin by fabric8io.

the class ApplyMojo method overrideTemplateParameters.

/**
 * Before applying the given template lets allow template parameters to be overridden via the maven
 * properties - or optionally - via the command line if in interactive mode.
 */
protected static void overrideTemplateParameters(Template template, MavenProject project, Logger log) {
    List<io.fabric8.openshift.api.model.Parameter> parameters = template.getParameters();
    if (parameters != null && project != null) {
        Properties properties = getProjectAndFabric8Properties(project);
        boolean missingProperty = false;
        for (io.fabric8.openshift.api.model.Parameter parameter : parameters) {
            String parameterName = parameter.getName();
            String name = "fabric8.apply." + parameterName;
            String propertyValue = properties.getProperty(name);
            if (propertyValue != null) {
                log.info("Overriding template parameter " + name + " with value: " + propertyValue);
                parameter.setValue(propertyValue);
            } else {
                missingProperty = true;
                log.info("No property defined for template parameter: " + name);
            }
        }
        if (missingProperty) {
            log.debug("Current properties " + new TreeSet<>(properties.keySet()));
        }
    }
}
Also used : TreeSet(java.util.TreeSet) Parameter(org.apache.maven.plugins.annotations.Parameter) KubernetesHelper.createIntOrString(io.fabric8.kubernetes.api.KubernetesHelper.createIntOrString) Properties(java.util.Properties)

Aggregations

IOException (java.io.IOException)9 File (java.io.File)6 HashMap (java.util.HashMap)6 Map (java.util.Map)6 Container (io.fabric8.api.Container)5 JMXRequest (io.fabric8.api.commands.JMXRequest)4 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 FabricService (io.fabric8.api.FabricService)3 ContainerCreateConfig (io.fabric8.maven.docker.access.ContainerCreateConfig)3 Arguments (io.fabric8.maven.docker.config.Arguments)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Properties (java.util.Properties)3 TemplatedResource (com.netflix.spinnaker.halyard.core.resource.v1.TemplatedResource)2 ArtifactService (com.netflix.spinnaker.halyard.deploy.services.v1.ArtifactService)2 GenerateService (com.netflix.spinnaker.halyard.deploy.services.v1.GenerateService)2 SpinnakerRuntimeSettings (com.netflix.spinnaker.halyard.deploy.spinnaker.v1.SpinnakerRuntimeSettings)2 Container (io.fabric8.kubernetes.api.model.Container)2