Search in sources :

Example 1 with FederationProposal

use of com.gitblit.models.FederationProposal in project gitblit by gitblit.

the class FederationManager method createFederationProposal.

/**
	 * Creates a proposal from the token.
	 *
	 * @param gitblitUrl
	 *            the url of this Gitblit instance
	 * @param token
	 * @return a potential proposal
	 */
@Override
public FederationProposal createFederationProposal(String gitblitUrl, String token) {
    FederationToken tokenType = FederationToken.REPOSITORIES;
    for (FederationToken type : FederationToken.values()) {
        if (token.equals(getFederationToken(type))) {
            tokenType = type;
            break;
        }
    }
    Map<String, RepositoryModel> repositories = getRepositories(gitblitUrl, token);
    FederationProposal proposal = new FederationProposal(gitblitUrl, tokenType, token, repositories);
    return proposal;
}
Also used : FederationProposal(com.gitblit.models.FederationProposal) RepositoryModel(com.gitblit.models.RepositoryModel) FederationToken(com.gitblit.Constants.FederationToken)

Example 2 with FederationProposal

use of com.gitblit.models.FederationProposal in project gitblit by gitblit.

the class FederationServlet method processRequest.

/**
	 * Processes a federation request.
	 *
	 * @param request
	 * @param response
	 * @throws javax.servlet.ServletException
	 * @throws java.io.IOException
	 */
@Override
protected void processRequest(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, java.io.IOException {
    FederationRequest reqType = FederationRequest.fromName(request.getParameter("req"));
    logger.info(MessageFormat.format("Federation {0} request from {1}", reqType, request.getRemoteAddr()));
    if (FederationRequest.POKE.equals(reqType)) {
        // Gitblit always responds to POKE requests to verify a connection
        logger.info("Received federation POKE from " + request.getRemoteAddr());
        return;
    }
    if (!settings.getBoolean(Keys.git.enableGitServlet, true)) {
        logger.warn(Keys.git.enableGitServlet + " must be set TRUE for federation requests.");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    String uuid = settings.getString(Keys.federation.passphrase, "");
    if (StringUtils.isEmpty(uuid)) {
        logger.warn(Keys.federation.passphrase + " is not properly set!  Federation request denied.");
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    if (FederationRequest.PROPOSAL.equals(reqType)) {
        // Receive a gitblit federation proposal
        FederationProposal proposal = deserialize(request, response, FederationProposal.class);
        if (proposal == null) {
            return;
        }
        // reject proposal, if not receipt prohibited
        if (!settings.getBoolean(Keys.federation.allowProposals, false)) {
            logger.error(MessageFormat.format("Rejected {0} federation proposal from {1}", proposal.tokenType.name(), proposal.url));
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
        // poke the origin Gitblit instance that is proposing federation
        boolean poked = false;
        try {
            poked = FederationUtils.poke(proposal.url);
        } catch (Exception e) {
            logger.error("Failed to poke origin", e);
        }
        if (!poked) {
            logger.error(MessageFormat.format("Failed to send federation poke to {0}", proposal.url));
            response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
            return;
        }
        String gitblitUrl = settings.getString(Keys.web.canonicalUrl, null);
        if (StringUtils.isEmpty(gitblitUrl)) {
            gitblitUrl = HttpUtils.getGitblitURL(request);
        }
        federationManager.submitFederationProposal(proposal, gitblitUrl);
        logger.info(MessageFormat.format("Submitted {0} federation proposal to pull {1} repositories from {2}", proposal.tokenType.name(), proposal.repositories.size(), proposal.url));
        response.setStatus(HttpServletResponse.SC_OK);
        return;
    }
    if (FederationRequest.STATUS.equals(reqType)) {
        // Receive a gitblit federation status acknowledgment
        String remoteId = StringUtils.decodeFromHtml(request.getParameter("url"));
        String identification = MessageFormat.format("{0} ({1})", remoteId, request.getRemoteAddr());
        // deserialize the status data
        FederationModel results = deserialize(request, response, FederationModel.class);
        if (results == null) {
            return;
        }
        // setup the last and netx pull dates
        results.lastPull = new Date();
        int mins = TimeUtils.convertFrequencyToMinutes(results.frequency, 5);
        results.nextPull = new Date(System.currentTimeMillis() + (mins * 60 * 1000L));
        // acknowledge the receipt of status
        federationManager.acknowledgeFederationStatus(identification, results);
        logger.info(MessageFormat.format("Received status of {0} federated repositories from {1}", results.getStatusList().size(), identification));
        response.setStatus(HttpServletResponse.SC_OK);
        return;
    }
    // Determine the federation tokens for this gitblit instance
    String token = request.getParameter("token");
    List<String> tokens = federationManager.getFederationTokens();
    if (!tokens.contains(token)) {
        logger.warn(MessageFormat.format("Received Federation token ''{0}'' does not match the server tokens", token));
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    Object result = null;
    if (FederationRequest.PULL_REPOSITORIES.equals(reqType)) {
        String gitblitUrl = settings.getString(Keys.web.canonicalUrl, null);
        if (StringUtils.isEmpty(gitblitUrl)) {
            gitblitUrl = HttpUtils.getGitblitURL(request);
        }
        result = federationManager.getRepositories(gitblitUrl, token);
    } else {
        if (FederationRequest.PULL_SETTINGS.equals(reqType)) {
            // pull settings
            if (!federationManager.validateFederationRequest(reqType, token)) {
                // invalid token to pull users or settings
                logger.warn(MessageFormat.format("Federation token from {0} not authorized to pull SETTINGS", request.getRemoteAddr()));
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            Map<String, String> map = new HashMap<String, String>();
            List<String> keys = settings.getAllKeys(null);
            for (String key : keys) {
                map.put(key, settings.getString(key, ""));
            }
            result = map;
        } else if (FederationRequest.PULL_USERS.equals(reqType)) {
            // pull users
            if (!federationManager.validateFederationRequest(reqType, token)) {
                // invalid token to pull users or settings
                logger.warn(MessageFormat.format("Federation token from {0} not authorized to pull USERS", request.getRemoteAddr()));
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            List<String> usernames = userManager.getAllUsernames();
            List<UserModel> users = new ArrayList<UserModel>();
            for (String username : usernames) {
                UserModel user = userManager.getUserModel(username);
                if (!user.excludeFromFederation) {
                    users.add(user);
                }
            }
            result = users;
        } else if (FederationRequest.PULL_TEAMS.equals(reqType)) {
            // pull teams
            if (!federationManager.validateFederationRequest(reqType, token)) {
                // invalid token to pull teams
                logger.warn(MessageFormat.format("Federation token from {0} not authorized to pull TEAMS", request.getRemoteAddr()));
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            List<String> teamnames = userManager.getAllTeamNames();
            List<TeamModel> teams = new ArrayList<TeamModel>();
            for (String teamname : teamnames) {
                TeamModel user = userManager.getTeamModel(teamname);
                teams.add(user);
            }
            result = teams;
        } else if (FederationRequest.PULL_SCRIPTS.equals(reqType)) {
            // pull scripts
            if (!federationManager.validateFederationRequest(reqType, token)) {
                // invalid token to pull script
                logger.warn(MessageFormat.format("Federation token from {0} not authorized to pull SCRIPTS", request.getRemoteAddr()));
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
            Map<String, String> scripts = new HashMap<String, String>();
            Set<String> names = new HashSet<String>();
            names.addAll(settings.getStrings(Keys.groovy.preReceiveScripts));
            names.addAll(settings.getStrings(Keys.groovy.postReceiveScripts));
            for (TeamModel team : userManager.getAllTeams()) {
                names.addAll(team.preReceiveScripts);
                names.addAll(team.postReceiveScripts);
            }
            File scriptsFolder = repositoryManager.getHooksFolder();
            for (String name : names) {
                File file = new File(scriptsFolder, name);
                if (!file.exists() && !file.getName().endsWith(".groovy")) {
                    file = new File(scriptsFolder, name + ".groovy");
                }
                if (file.exists()) {
                    // read the script
                    String content = FileUtils.readContent(file, "\n");
                    scripts.put(name, content);
                } else {
                    // missing script?!
                    logger.warn(MessageFormat.format("Failed to find push script \"{0}\"", name));
                }
            }
            result = scripts;
        }
    }
    // send the result of the request
    serialize(response, result);
}
Also used : FederationModel(com.gitblit.models.FederationModel) FederationProposal(com.gitblit.models.FederationProposal) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Date(java.util.Date) UserModel(com.gitblit.models.UserModel) TeamModel(com.gitblit.models.TeamModel) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File) FederationRequest(com.gitblit.Constants.FederationRequest)

Example 3 with FederationProposal

use of com.gitblit.models.FederationProposal in project gitblit by gitblit.

the class FederationManager method getPendingFederationProposals.

/**
	 * Returns the list of pending federation proposals
	 *
	 * @return list of federation proposals
	 */
@Override
public List<FederationProposal> getPendingFederationProposals() {
    List<FederationProposal> list = new ArrayList<FederationProposal>();
    File folder = getProposalsFolder();
    if (folder.exists()) {
        File[] files = folder.listFiles(new FileFilter() {

            @Override
            public boolean accept(File file) {
                return file.isFile() && file.getName().toLowerCase().endsWith(Constants.PROPOSAL_EXT);
            }
        });
        if (files == null) {
            return list;
        }
        for (File file : files) {
            String json = com.gitblit.utils.FileUtils.readContent(file, null);
            FederationProposal proposal = JsonUtils.fromJsonString(json, FederationProposal.class);
            list.add(proposal);
        }
    }
    return list;
}
Also used : FederationProposal(com.gitblit.models.FederationProposal) ArrayList(java.util.ArrayList) FileFilter(java.io.FileFilter) File(java.io.File)

Example 4 with FederationProposal

use of com.gitblit.models.FederationProposal in project gitblit by gitblit.

the class FederationTests method testProposal.

@Test
public void testProposal() throws Exception {
    // create dummy repository data
    Map<String, RepositoryModel> repositories = new HashMap<String, RepositoryModel>();
    for (int i = 0; i < 5; i++) {
        RepositoryModel model = new RepositoryModel();
        model.accessRestriction = AccessRestrictionType.VIEW;
        model.description = "cloneable repository " + i;
        model.lastChange = new Date();
        model.addOwner("adminuser");
        model.name = "repo" + i + ".git";
        model.size = "5 MB";
        model.hasCommits = true;
        repositories.put(model.name, model);
    }
    FederationProposal proposal = new FederationProposal("http://testurl", FederationToken.ALL, "testtoken", repositories);
    // propose federation
    assertEquals("proposal refused", FederationUtils.propose(url, proposal), FederationProposalResult.NO_PROPOSALS);
}
Also used : FederationProposal(com.gitblit.models.FederationProposal) HashMap(java.util.HashMap) RepositoryModel(com.gitblit.models.RepositoryModel) Date(java.util.Date) Test(org.junit.Test)

Aggregations

FederationProposal (com.gitblit.models.FederationProposal)4 RepositoryModel (com.gitblit.models.RepositoryModel)2 File (java.io.File)2 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 FederationRequest (com.gitblit.Constants.FederationRequest)1 FederationToken (com.gitblit.Constants.FederationToken)1 FederationModel (com.gitblit.models.FederationModel)1 TeamModel (com.gitblit.models.TeamModel)1 UserModel (com.gitblit.models.UserModel)1 FileFilter (java.io.FileFilter)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 Test (org.junit.Test)1