Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright 2005-2014 Red Hat, Inc. Red Hat licenses this file to you under the Apache License, version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 package io.fabric8.openshift.agent;
 
 import java.io.File;
 import java.util.List;
 import java.util.Map;
 
 
A Fabric agent which manages arbitrary Java cartridges on OpenShift; so that changes to the Fabric profile metadata (such as WARs, bundles, features) leads to the git configuration being updated for the managed cartridges.
 
 @Component(name = "io.fabric8.openshift.agent", label = "Fabric8 agent for deploying applications into external OpenShift cartridges", policy = ., immediate = true, metatype = true)
 public final class OpenShiftDeployAgent extends AbstractComponent implements GroupListener<ControllerNode> {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(OpenShiftDeployAgent.class);
     private static final String REALM_PROPERTY_NAME = "realm";
     private static final String ROLE_PROPERTY_NAME = "role";
     private static final String DEFAULT_REALM = "karaf";
     private static final String DEFAULT_ROLE = "admin";
 
     @Reference(referenceInterface = ConfigurationAdmin.class)
     @Reference(referenceInterface = CuratorFramework.class)
     @Reference(referenceInterface = FabricService.class)
 
     private final ExecutorService downloadExecutor = Executors.newSingleThreadExecutor();
     private final Runnable runnable = new Runnable() {
         @Override
         public void run() {
             onConfigurationChanged();
         }
     };
 
     @GuardedBy("volatile"private volatile Group<ControllerNodegroup;
 
     @Activate
     void activate(Map<String, ?> configuration) {
         //this.realm =  properties != null && properties.containsKey(REALM_PROPERTY_NAME) ? properties.get(REALM_PROPERTY_NAME) : DEFAULT_REALM;
        //this.role =  properties != null && properties.containsKey(ROLE_PROPERTY_NAME) ? properties.get(ROLE_PROPERTY_NAME) : DEFAULT_ROLE;
         = new ZooKeeperGroup(.get(), ..getPath(), ControllerNode.class);
        .add(this);
        .update(createState());
        .start();
        activateComponent();
    }
    @Deactivate
    void deactivate() {
        deactivateComponent();
        try {
            if ( != null) {
                .close();
            }
        } catch (Exception e) {
            .warn("Failed to remove git server from registry."e);
        }
    }
    private void shutdownExecutor(ExecutorService executor) {
        executor.shutdown();
        try {
            executor.awaitTermination(1, .);
        } catch (InterruptedException e) {
            // Ignore
        }
        executor.shutdownNow();
    }
    @Override
    public void groupEvent(Group<ControllerNodegroupGroupEvent event) {
        if (isValid()) {
            if (group.isMaster()) {
                .info("OpenShiftDeployAgent is the master");
            } else {
                .info("OpenShiftDeployAgent is not the master");
            }
            try {
                DataStore dataStore = null;
                if ( != null) {
                    dataStore = .get().getDataStore();
                } else {
                    .warn("No fabricService yet!");
                }
                if (group.isMaster()) {
                    ControllerNode state = createState();
                    group.update(state);
                }
                if (dataStore != null) {
                    if (group.isMaster()) {
                        dataStore.trackConfiguration();
                        onConfigurationChanged();
                    } else {
                        dataStore.untrackConfiguration();
                    }
                }
            } catch (IllegalStateException e) {
                // Ignore
            }
        }
    }
    protected void onConfigurationChanged() {
        .info("Configuration has changed; so checking the Fabric managed Java cartridges on OpenShift are up to date");
        Container[] containers = .get().getContainers();
        for (Container container : containers) {
            Profile profile = container.getOverlayProfile();
            Map<StringStringopenshiftConfiguration = profile.getConfiguration(.);
            if (openshiftConfiguration != null) {
                DeploymentUpdater deployTask = null;
                try {
                    deployTask = createDeployTask(containeropenshiftConfiguration);
                } catch (MalformedURLException e) {
                    .error("Failed to create DeploymentUpdater. " + ee);
                }
                if (deployTask != null && OpenShiftUtils.isFabricManaged(openshiftConfiguration)) {
                    String containerId = container.getId();
                    IOpenShiftConnection connection = OpenShiftUtils.createConnection(container);
                    CreateOpenshiftContainerOptions options = OpenShiftUtils.getCreateOptions(container);
                    if (connection == null || options == null) {
                        .warn(
                                "Ignoring container which has no openshift connection or options. connection: "
                                        + connection + " options: " + options);
                    } else {
                        try {
                            IApplication application = OpenShiftUtils.getApplication(containerconnection);
                            if (application != null) {
                                final String gitUrl = application.getGitUrl();
                                if (gitUrl != null) {
                                    .info("Git URL is " + gitUrl);
                                    final CartridgeGitRepository repo = new CartridgeGitRepository(containerId);
                                    final List<IOpenShiftSSHKeysshkeys = application.getDomain().getUser()
                                            .getSSHKeys();
                                    final CredentialsProvider credentials = new CredentialsProvider() {
                                        @Override
                                        public boolean supports(CredentialItem... items) {
                                            return true;
                                        }
                                        @Override
                                        public boolean isInteractive() {
                                            return true;
                                        }
                                        @Override
                                        public boolean get(URIish uriCredentialItem... items)
                                                throws UnsupportedCredentialItem {
                                            .info("Credential request " + uri + " items " + Arrays.asList(items));
                                            int i = -1;
                                            for (CredentialItem item : items) {
                                                if (item instanceof CredentialItem.StringType) {
                                                    CredentialItem.StringType stringType
                                                            = (CredentialItem.StringType)item;
                                                    int idx = ++i < sshkeys.size() ? i : 0;
                                                    if (idx < sshkeys.size()) {
                                                        IOpenShiftSSHKey sshKey = sshkeys
                                                                .get(idx);
                                                        String passphrase = sshKey.getPublicKey();
                                                        .info("For item " + item + " index " + i
                                                                + " using passphrase: " + passphrase);
                                                        stringType.setValue(passphrase);
                                                    } else {
                                                        .warn("No ssh keys we can pass into git!");
                                                    }
                                                    continue;
                                                } else {
                                                    .warn("Unknown CredentialItem " + item);
                                                }
                                            }
                                            return true;
                                        }
                                    };
                                    final DeploymentUpdater finalDeployTask = deployTask;
                                    SshSessionFactoryUtils.useOpenShiftSessionFactory(new Callable<Object>() {
                                        @Override
                                        public Object call()
                                                throws Exception {
                                            repo.cloneOrPull(gitUrlcredentials);
                                            finalDeployTask.updateDeployment(repo.getGit(), repo.getLocalRepo(),
                                                            credentials);
                                            return null;
                                        }
                                    });
                                }
                            }
                        } catch (Exception e) {
                            .error("Failed to update container " + containerId + ". Reason: " + ee);
                        } finally {
                            OpenShiftUtils.close(connection);
                        }
                    }
                }
            }
        }
    }
    private DeploymentUpdater createDeployTask(Container containerMap<String,StringopenshiftConfigurationthrows MalformedURLException {
        String webappDir = relativePath(containeropenshiftConfiguration.);
        String deployDir = relativePath(containeropenshiftConfiguration.);
        if (webappDir != null || deployDir != null) {
            FabricService fabric = .get();
            DownloadManager downloadManager = DownloadManagers.createDownloadManager(fabric);
            DeploymentUpdater deploymentUpdater = new DeploymentUpdater(downloadManagerfabriccontainerwebappDirdeployDir);
            deploymentUpdater.setRepositories(Maps.stringValue(openshiftConfiguration..));
            deploymentUpdater.setCopyFilesIntoGit(Maps.booleanValue(openshiftConfiguration.false));
            return deploymentUpdater;
        }
        return null;
    }
    private String relativePath(Container containerMap<StringStringconfigurationString propertyName) {
        String value = Maps.stringValue(configurationpropertyName);
        if (Strings.isNotBlank(value)) {
            if (value.startsWith("..") || value.startsWith("/") || value.startsWith(.)) {
                throw new IllegalStateException("Invalid relative path '" + value + "' for property " + propertyName + " for container " + container.getId());
            } else {
                return value;
            }
        }
        return null;
    }
    private ControllerNode createState() {
        ControllerNode state = new ControllerNode();
        return state;
    }
    void bindConfigAdmin(ConfigurationAdmin service) {
        this..bind(service);
    }
    void unbindConfigAdmin(ConfigurationAdmin service) {
        this..unbind(service);
    }
    void bindCurator(CuratorFramework curator) {
        this..bind(curator);
    }
    void unbindCurator(CuratorFramework curator) {
        this..unbind(curator);
    }
    void bindFabricService(FabricService fabricService) {
        this..bind(fabricService);
    }
    void unbindFabricService(FabricService fabricService) {
        this..unbind(fabricService);
    }
New to GrepCode? Check out our FAQ X