use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.
the class DeployToProfileMojo method uploadRequirements.
protected DeployResults uploadRequirements(J4pClient client, ProjectRequirements requirements) throws Exception {
String json = DtoHelper.getMapper().writeValueAsString(requirements);
ObjectName mbeanName = ProjectDeployerImpl.OBJECT_NAME;
getLog().info("Updating " + (requirements.isAbstractProfile() ? "abstract " : "") + "profile: " + requirements.getProfileId() + " with parent profile(s): " + requirements.getParentProfiles() + (requirements.isUseResolver() ? " using OSGi resolver" : "") + (requirements.isLocked() ? " locked" : ""));
getLog().info("About to invoke mbean " + mbeanName + " on jolokia URL: " + jolokiaUrl + " with user: " + fabricServer.getUsername());
getLog().debug("JSON: " + json);
try {
// Append bundles to existing profile bundles if we're not running the plugin at project root
Boolean appendBundles = !mavenSession.getExecutionRootDirectory().equalsIgnoreCase(project.getBasedir().toString());
J4pExecRequest request = new J4pExecRequest(mbeanName, "deployProjectJsonMergeOption(java.lang.String,boolean)", json, appendBundles);
J4pResponse<J4pExecRequest> response = client.execute(request, "POST");
Object value = response.getValue();
if (value == null) {
return null;
} else {
DeployResults answer = DtoHelper.getMapper().reader(DeployResults.class).readValue(value.toString());
if (answer != null) {
String profileUrl = answer.getProfileUrl();
if (profileUrl != null) {
getLog().info("");
getLog().info("Profile page: " + profileUrl);
getLog().info("");
} else {
getLog().info("Result: " + answer);
}
} else {
getLog().info("Result: " + value);
}
return answer;
}
} catch (J4pRemoteException e) {
if (e.getMessage().contains(".InstanceNotFoundException")) {
throw new MojoExecutionException("Could not find the mbean " + mbeanName + " in the JVM for " + jolokiaUrl + ". Are you sure this JVM is running the Fabric8 console?");
} else {
getLog().error("Failed to invoke mbean " + mbeanName + " on jolokia URL: " + jolokiaUrl + " with user: " + fabricServer.getUsername() + ". Error: " + e.getErrorType());
getLog().error("Stack: " + e.getRemoteStackTrace());
throw e;
}
}
}
use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.
the class CloudContainerInstallationTask method install.
public CreateJCloudsContainerMetadata install() {
LoginCredentials credentials = nodeMetadata.getCredentials();
// For some cloud providers return do not allow shell access to root, so the user needs to be overrided.
if (!Strings.isNullOrEmpty(options.getUser()) && credentials != null) {
credentials = credentials.toBuilder().user(options.getUser()).build();
} else {
credentials = nodeMetadata.getCredentials();
}
String id = nodeMetadata.getId();
Set<String> publicAddresses = nodeMetadata.getPublicAddresses();
// Make a copy of the addresses, because we don't want to return back a guice implementation of Set.
Set<String> copyOfPublicAddresses = new HashSet<String>();
for (String publicAddress : publicAddresses) {
copyOfPublicAddresses.add(publicAddress);
}
CreateJCloudsContainerMetadata jCloudsContainerMetadata = new CreateJCloudsContainerMetadata();
jCloudsContainerMetadata.setCreateOptions(options);
jCloudsContainerMetadata.setNodeId(nodeMetadata.getId());
jCloudsContainerMetadata.setContainerName(containerName);
jCloudsContainerMetadata.setPublicAddresses(copyOfPublicAddresses);
jCloudsContainerMetadata.setHostname(nodeMetadata.getHostname());
if (credentials != null) {
jCloudsContainerMetadata.setIdentity(credentials.identity);
jCloudsContainerMetadata.setCredential(credentials.credential);
}
String publicAddress = "";
Properties addresses = new Properties();
if (publicAddresses != null && !publicAddresses.isEmpty()) {
publicAddress = publicAddresses.iterator().next();
addresses.put(ZkDefs.PUBLIC_IP, publicAddress);
}
options.getSystemProperties().put(ContainerProviderUtils.ADDRESSES_PROPERTY_KEY, addresses);
options.getMetadataMap().put(containerName, jCloudsContainerMetadata);
// Setup firwall for node
try {
FirewallManager firewallManager = firewallManagerFactory.getFirewallManager(computeService);
if (firewallManager.isSupported()) {
listener.onStateChange("Configuring firewall.");
String source = getOriginatingIp();
Rule httpRule = Rule.create().source("0.0.0.0/0").destination(nodeMetadata).port(8181);
firewallManager.addRules(httpRule);
if (source != null) {
Rule jmxRule = Rule.create().source(source).destination(nodeMetadata).ports(44444, 1099);
Rule sshRule = Rule.create().source(source).destination(nodeMetadata).port(8101);
Rule zookeeperRule = Rule.create().source(source).destination(nodeMetadata).port(2181);
firewallManager.addRules(jmxRule, sshRule, zookeeperRule);
}
// where firewall configuration is shared among nodes of the same groups, e.g. EC2.
if (!Strings.isNullOrEmpty(publicAddress)) {
Rule zookeeperFromTargetRule = Rule.create().source(publicAddress + "/32").destination(nodeMetadata).port(2181);
firewallManager.addRule(zookeeperFromTargetRule);
}
} else {
listener.onStateChange(String.format("Skipping firewall configuration. Not supported for provider %s", options.getProviderName()));
}
} catch (FirewallNotSupportedOnProviderException e) {
LOGGER.warn("Firewall manager not supported. Firewall will have to be manually configured.");
} catch (IOException e) {
LOGGER.warn("Could not lookup originating ip. Firewall will have to be manually configured.", e);
} catch (Throwable t) {
LOGGER.warn("Failed to setup firewall", t);
}
try {
String script = buildInstallAndStartScript(containerName, options);
listener.onStateChange(String.format("Installing fabric agent on container %s. It may take a while...", containerName));
ExecResponse response = null;
String uploadPath = "/tmp/fabric8-karaf-" + FabricConstants.FABRIC_VERSION + ".zip";
URL distributionURL = options.getProxyUri().resolve("io/fabric8/fabric8-karaf/" + FabricConstants.FABRIC_VERSION + "/fabric8-karaf-" + FabricConstants.FABRIC_VERSION + ".zip").toURL();
try {
if (options.doUploadDistribution()) {
uploadToNode(computeService.getContext(), nodeMetadata, credentials, distributionURL, uploadPath);
}
if (credentials != null) {
response = computeService.runScriptOnNode(id, script, templateOptions.overrideLoginCredentials(credentials).runAsRoot(false));
} else {
response = computeService.runScriptOnNode(id, script, templateOptions);
}
} catch (AuthorizationException ex) {
throw new Exception("Failed to connect to the container via ssh.");
} catch (SshException ex) {
throw new Exception("Failed to connect to the container via ssh.");
}
if (response != null && response.getOutput() != null) {
if (response.getOutput().contains(ContainerProviderUtils.FAILURE_PREFIX)) {
jCloudsContainerMetadata.setFailure(new Exception(ContainerProviderUtils.parseScriptFailure(response.getOutput())));
}
String overridenResolverValue = ContainerProviderUtils.parseResolverOverride(response.getOutput());
if (overridenResolverValue != null) {
jCloudsContainerMetadata.setOverridenResolver(overridenResolverValue);
listener.onStateChange("Overriding resolver to " + overridenResolverValue + ".");
}
} else {
jCloudsContainerMetadata.setFailure(new Exception("No response received for fabric install script."));
}
} catch (Throwable t) {
jCloudsContainerMetadata.setFailure(t);
}
// Cleanup addresses.
options.getSystemProperties().clear();
return jCloudsContainerMetadata;
}
use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.
the class ContainerCreateCloud method doExecute.
@Override
protected Object doExecute() throws Exception {
// validate input before creating containers
preCreateContainer(name);
FabricValidations.validateProfileNames(profiles);
if (isEnsembleServer && newUserPassword == null) {
newUserPassword = zookeeperPassword != null ? zookeeperPassword : fabricService.getZookeeperPassword();
}
CreateJCloudsContainerOptions.Builder builder = CreateJCloudsContainerOptions.builder().name(name).bindAddress(bindAddress).resolver(resolver).manualIp(manualIp).ensembleServer(isEnsembleServer).credential(credential).group(group).hardwareId(hardwareId).identity(identity).osFamily(osFamily).osVersion(osVersion).imageId(imageId).instanceType(instanceType).locationId(locationId).number(number).nodeOptions(CloudUtils.parseProviderOptions(options)).owner(owner).adminAccess(!disableAdminAccess).publicKeyFile(publicKeyFile).contextName(contextName).providerName(providerName).apiName(apiName).user(user).password(password).proxyUri(proxyUri != null ? proxyUri : fabricService.getMavenRepoURI()).zookeeperUrl(fabricService.getZookeeperUrl()).zookeeperPassword(isEnsembleServer && zookeeperPassword != null ? zookeeperPassword : fabricService.getZookeeperPassword()).jvmOpts(jvmOpts).environmentalVariable(environmentalVariables).version(version).withUser(newUser, newUserPassword, newUserRole).profiles(getProfileNames()).dataStoreProperties(getDataStoreProperties()).uploadDistribution(!distributionUploadDisable);
if (path != null && !path.isEmpty()) {
builder.path(path);
}
CreateContainerMetadata[] metadatas = fabricService.createContainers(builder.build(), new PrintStreamCreationStateListener(System.out));
if (isEnsembleServer && metadatas != null && metadatas.length > 0 && metadatas[0].isSuccess()) {
ShellUtils.storeZookeeperPassword(session, metadatas[0].getCreateOptions().getZookeeperPassword());
}
// display containers
displayContainers(metadatas);
return null;
}
use of io.fabric8.openshift.api.model.User in project fabric8 by jboss-fuse.
the class GitPatchManagementServiceImpl method trackPatch.
/**
* <p>This method turns static information about a patch into managed patch - i.e., patch added to git
* repository.</p>
*
* <p>Such patch has its own branch ready to be merged (when patch is installed). Before installation we can verify
* the patch,
* examine the content, check the differences, conflicts and perform simulation (merge to temporary branch created
* from main patch branch)</p>
*
* <p>The strategy is as follows:<ul>
* <li><em>main patch branch</em> in git repository tracks all changes (from baselines, patch-management
* system, patches and user changes)</li>
* <li>Initially there are 3 commits: baseline, patch-management bundle installation in etc/startup.properties,
* initial user changes</li>
* <li>We always <strong>tag the baseline commit</strong></li>
* <li>User changes may be applied each time Framework is restarted</li>
* <li>When we add a patch, we create <em>named branch</em> from the <strong>latest baseline</strong></li>
* <li>When we install a patch, we <strong>merge</strong> the patch branch with the <em>main patch branch</em>
* (that may contain additional user changes)</li>
* <li>When patch ZIP contains new baseline distribution, after merging patch branch, we tag the merge commit
* in <em>main patch branch</em> branch as new baseline</li>
* <li>Branches for new patches will then be created from new baseline commit</li>
* </ul></p>
* @param patchData
* @return
*/
@Override
public Patch trackPatch(PatchData patchData) throws PatchException {
try {
awaitInitialization();
} catch (InterruptedException e) {
throw new PatchException("Patch management system is not ready yet");
}
Git fork = null;
try {
Git mainRepository = gitPatchRepository.findOrCreateMainGitRepository();
// prepare single fork for all the below operations
fork = gitPatchRepository.cloneRepository(mainRepository, true);
// 1. find current baseline
RevTag latestBaseline = gitPatchRepository.findCurrentBaseline(fork);
if (latestBaseline == null) {
throw new PatchException("Can't find baseline distribution tracked in patch management. Is patch management initialized?");
}
// the commit from the patch should be available from main patch branch
RevCommit commit = new RevWalk(fork.getRepository()).parseCommit(latestBaseline.getObject());
// create dedicated branch for this patch. We'll immediately add patch content there so we can examine the
// changes from the latest baseline
gitPatchRepository.checkout(fork).setCreateBranch(true).setName("patch-" + patchData.getId()).setStartPoint(commit).call();
// copy patch resources (but not maven artifacts from system/ or repository/) to working copy
if (patchData.getPatchDirectory() != null) {
boolean removeTargetDir = patchData.isRollupPatch();
copyManagedDirectories(patchData.getPatchDirectory(), fork.getRepository().getWorkTree(), removeTargetDir, false, false);
}
// add the changes
fork.add().addFilepattern(".").call();
// remove the deletes (without touching specially-managed etc/overrides.properties)
for (String missing : fork.status().call().getMissing()) {
if (!"etc/overrides.properties".equals(missing)) {
fork.rm().addFilepattern(missing).call();
}
}
// record information about other "patches" included in added patch (e.g., Fuse patch
// may contain patches to admin:create based containers in standalone mode)
StringWriter sw = new StringWriter();
sw.append("# tags for patches included in \"").append(patchData.getId()).append("\"\n");
for (String bundle : patchData.getBundles()) {
// containers that want to patch:install patches added in root containers
if (bundle.contains("mvn:org.apache.karaf.admin/org.apache.karaf.admin.core/")) {
Artifact a = Utils.mvnurlToArtifact(bundle, true);
if (a != null) {
sw.append(String.format(EnvType.STANDALONE_CHILD.getBaselineTagFormat(), a.getVersion())).append("\n");
}
break;
}
}
FileUtils.write(new File(fork.getRepository().getWorkTree(), "patch-info.txt"), sw.toString());
fork.add().addFilepattern(".").call();
// commit the changes (patch vs. baseline) to patch branch
gitPatchRepository.prepareCommit(fork, String.format("[PATCH] Tracking patch %s", patchData.getId())).call();
// push the patch branch
gitPatchRepository.push(fork, "patch-" + patchData.getId());
// track other kinds of baselines found in the patch
if (env.isFabric()) {
trackBaselinesForRootContainer(fork);
trackBaselinesForChildContainers(fork);
trackBaselinesForSSHContainers(fork);
} else {
// for admin:create child containers
trackBaselinesForChildContainers(fork);
}
return new Patch(patchData, gitPatchRepository.getManagedPatch(patchData.getId()));
} catch (IOException | GitAPIException e) {
throw new PatchException(e.getMessage(), e);
} finally {
if (fork != null) {
gitPatchRepository.closeRepository(fork, true);
}
}
}
use of io.fabric8.openshift.api.model.User 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);
}
}
}
}
}
}
Aggregations