/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see .
*/
package org.alfresco.repo.tenant;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;
import javax.transaction.UserTransaction;
import net.sf.acegisecurity.providers.encoding.PasswordEncoder;
import org.alfresco.error.AlfrescoRuntimeException;
import org.alfresco.repo.admin.RepoModelDefinition;
import org.alfresco.repo.content.ContentStore;
import org.alfresco.repo.dictionary.DictionaryComponent;
import org.alfresco.repo.domain.tenant.TenantAdminDAO;
import org.alfresco.repo.domain.tenant.TenantEntity;
import org.alfresco.repo.domain.tenant.TenantUpdateEntity;
import org.alfresco.repo.importer.ImporterBootstrap;
import org.alfresco.repo.node.db.DbNodeServiceImpl;
import org.alfresco.repo.security.authentication.AuthenticationContext;
import org.alfresco.repo.security.authentication.AuthenticationException;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.tenant.TenantUtil.TenantRunAsWork;
import org.alfresco.repo.thumbnail.ThumbnailRegistry;
import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback;
import org.alfresco.repo.usage.UserUsageTrackingComponent;
import org.alfresco.repo.workflow.WorkflowDeployer;
import org.alfresco.service.cmr.admin.RepoAdminService;
import org.alfresco.service.cmr.module.ModuleService;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.repository.StoreRef;
import org.alfresco.service.cmr.view.RepositoryExporterService;
import org.alfresco.service.cmr.workflow.WorkflowDefinition;
import org.alfresco.service.cmr.workflow.WorkflowService;
import org.alfresco.service.transaction.TransactionService;
import org.alfresco.util.PropertyCheck;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.extensions.surf.util.I18NUtil;
import org.springframework.extensions.surf.util.ParameterCheck;
/**
* MT Admin Service Implementation.
*
*/
public class MultiTAdminServiceImpl implements TenantAdminService, ApplicationContextAware, InitializingBean
{
// Logger
private static Log logger = LogFactory.getLog(MultiTAdminServiceImpl.class);
// Keep hold of the app context
protected ApplicationContext ctx;
// Dependencies
private NodeService nodeService;
private RepoAdminService repoAdminService;
private AuthenticationContext authenticationContext;
private MultiTServiceImpl tenantService;
protected TransactionService transactionService;
protected DictionaryComponent dictionaryComponent;
protected TenantAdminDAO tenantAdminDAO;
protected PasswordEncoder passwordEncoder;
protected ContentStore tenantFileContentStore;
private ThumbnailRegistry thumbnailRegistry;
private String contentRootContainerPath = null;
private WorkflowService workflowService;
private RepositoryExporterService repositoryExporterService;
private ModuleService moduleService;
private List workflowDeployers = new ArrayList();
private String baseAdminUsername = null;
// Experimental: Thor
private TenantRoutingDataSource trds;
/*
* Tenant domain/ids are unique strings that are case-insensitive. Tenant ids must be valid filenames.
* They may also map onto domains and hence should allow valid FQDN.
*
* The following PCRE-style
* regex defines a valid label within a FQDN:
*
* ^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$
*
* Less formally:
*
* o Case insensitive
* o First/last character: alphanumeric
* o Interior characters: alphanumeric plus hyphen
* o Minimum length: 2 characters
* o Maximum length: 63 characters
*
* The FQDN (fully qualified domain name) has the following constraints:
*
* o Maximum 255 characters (***)
* o Must contain at least one alpha
*
* Note: (***) Due to various internal restrictions (such as store identifier) we restrict tenant ids to 75 characters.
*/
protected final static String REGEX_VALID_DNS_LABEL = "^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$";
protected final static String REGEX_CONTAINS_ALPHA = "^(.*)[a-zA-Z](.*)$";
protected final static int MAX_LEN = 75;
public void setNodeService(DbNodeServiceImpl dbNodeService)
{
this.nodeService = dbNodeService;
}
public void setDictionaryComponent(DictionaryComponent dictionaryComponent)
{
this.dictionaryComponent = dictionaryComponent;
}
public void setRepoAdminService(RepoAdminService repoAdminService)
{
this.repoAdminService = repoAdminService;
}
public void setAuthenticationContext(AuthenticationContext authenticationContext)
{
this.authenticationContext = authenticationContext;
}
public void setTransactionService(TransactionService transactionService)
{
this.transactionService = transactionService;
}
public void setTenantService(MultiTServiceImpl tenantService)
{
this.tenantService = tenantService;
}
public void setTenantAdminDAO(TenantAdminDAO tenantAdminDAO)
{
this.tenantAdminDAO = tenantAdminDAO;
}
public void setPasswordEncoder(PasswordEncoder passwordEncoder)
{
this.passwordEncoder = passwordEncoder;
}
public void setTenantFileContentStore(ContentStore tenantFileContentStore)
{
this.tenantFileContentStore = tenantFileContentStore;
}
public void setWorkflowService(WorkflowService workflowService)
{
this.workflowService = workflowService;
}
public void setRepositoryExporterService(RepositoryExporterService repositoryExporterService)
{
this.repositoryExporterService = repositoryExporterService;
}
/**
* @deprecated see setWorkflowDeployers
*/
public void setWorkflowDeployer(WorkflowDeployer workflowDeployer)
{
// NOOP
logger.warn(WARN_MSG);
}
public void setModuleService(ModuleService moduleService)
{
this.moduleService = moduleService;
}
public void setThumbnailRegistry(ThumbnailRegistry thumbnailRegistry)
{
this.thumbnailRegistry = thumbnailRegistry;
}
public void setBaseAdminUsername(String baseAdminUsername)
{
this.baseAdminUsername = baseAdminUsername;
}
public void setTenantRoutingDataSource(TenantRoutingDataSource trds)
{
this.trds = trds;
}
// if set then tenant are not co-mingled and all content roots will appear below this container (in sub-folder)
public void setContentRootContainerPath(String contentRootContainerPath)
{
this.contentRootContainerPath = contentRootContainerPath;
}
public static final String PROTOCOL_STORE_USER = "user";
public static final String PROTOCOL_STORE_WORKSPACE = "workspace";
public static final String PROTOCOL_STORE_SYSTEM = "system";
public static final String PROTOCOL_STORE_ARCHIVE = "archive";
public static final String STORE_BASE_ID_USER = "alfrescoUserStore";
public static final String STORE_BASE_ID_SYSTEM = "system";
public static final String STORE_BASE_ID_VERSION1 = "lightWeightVersionStore"; // deprecated
public static final String STORE_BASE_ID_VERSION2 = "version2Store";
public static final String STORE_BASE_ID_SPACES = "SpacesStore";
public static final String TENANTS_ATTRIBUTE_PATH = "alfresco-tenants";
public static final String TENANT_ATTRIBUTE_ENABLED = "enabled";
public static final String TENANT_ATTRIBUTE_ROOT_CONTENT_STORE_DIR = "rootContentStoreDir";
public static final String TENANT_ATTRIBUTE_DB_URL = "dbUrl"; // if not co-mingled
private List tenantDeployers = new ArrayList();
private static final String WARN_MSG = "system.mt.warn.upgrade_mt_admin_context";
@Override
public void afterPropertiesSet() throws Exception
{
// for upgrade/backwards compatibility with 3.0.x (mt-admin-context.xml)
if (baseAdminUsername == null)
{
logger.warn(I18NUtil.getMessage(WARN_MSG));
}
PropertyCheck.mandatory(this, "NodeService", nodeService);
PropertyCheck.mandatory(this, "DictionaryComponent", dictionaryComponent);
PropertyCheck.mandatory(this, "RepoAdminService", repoAdminService);
PropertyCheck.mandatory(this, "TransactionService", transactionService);
PropertyCheck.mandatory(this, "TenantService", tenantService);
PropertyCheck.mandatory(this, "TenantAdminDAO", tenantAdminDAO);
PropertyCheck.mandatory(this, "PasswordEncoder", passwordEncoder);
PropertyCheck.mandatory(this, "TenantFileContentStore", tenantFileContentStore);
PropertyCheck.mandatory(this, "WorkflowService", workflowService);
PropertyCheck.mandatory(this, "RepositoryExporterService", repositoryExporterService);
PropertyCheck.mandatory(this, "moduleService", moduleService);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException
{
this.ctx = applicationContext;
}
@Override
public void startTenants()
{
AuthenticationUtil.setMtEnabled(true);
// initialise the tenant admin service and status of tenants (using attribute service)
// note: this requires that the repository schema has already been initialised
// register dictionary - to allow enable/disable tenant callbacks
register(dictionaryComponent);
if (tenantFileContentStore instanceof TenantDeployer)
{
// register file store - to allow enable/disable tenant callbacks
// note: tenantFileContentStore must be registed before dictionaryRepositoryBootstrap
register((TenantDeployer)tenantFileContentStore, 0);
}
UserTransaction userTransaction = transactionService.getUserTransaction();
try
{
authenticationContext.setSystemUserAsCurrentUser();
userTransaction.begin();
// bootstrap Tenant Service internal cache
List tenants = getAllTenants();
int enabledCount = 0;
int disabledCount = 0;
for (Tenant tenant : tenants)
{
if ((! (tenantFileContentStore instanceof TenantRoutingContentStore)) && (! tenantFileContentStore.getRootLocation().equals(tenant.getRootContentStoreDir())))
{
// eg. ALF-14121 - MT will not work with replicating-content-services-context.sample if tenants are not co-mingled
throw new AlfrescoRuntimeException("MT: cannot start tenants - TenantRoutingContentStore is not configured AND not all tenants use co-mingled content store");
}
String tenantDomain = tenant.getTenantDomain();
if (tenant.isEnabled())
{
// notify tenant deployers registered so far ...
notifyAfterEnableTenant(tenantDomain);
enabledCount++;
}
else
{
disabledCount++;
if (logger.isDebugEnabled())
{
logger.debug("Tenant disabled: " + tenantDomain);
}
}
}
userTransaction.commit();
if ((enabledCount+disabledCount) == 0)
{
AuthenticationUtil.setMtEnabled(false); // explicitly disable if there are no tenants
}
if (logger.isInfoEnabled() && ((enabledCount+disabledCount) > 0))
{
logger.info(String.format("Alfresco Multi-Tenant startup - %d enabled tenants, %d disabled tenants",
enabledCount, disabledCount));
}
else if (logger.isDebugEnabled())
{
logger.debug(String.format("Alfresco Multi-Tenant startup - %d enabled tenants, %d disabled tenants",
enabledCount, disabledCount));
}
}
catch(Throwable e)
{
// rollback the transaction
try { if (userTransaction != null) {userTransaction.rollback();} } catch (Exception ex) {}
throw new AlfrescoRuntimeException("Failed to bootstrap tenants", e);
}
finally
{
authenticationContext.clearCurrentSecurityContext();
}
}
@Override
public void stopTenants()
{
tenantDeployers.clear();
tenantDeployers = null;
AuthenticationUtil.setMtEnabled(false);
}
@Override
public void createTenant(final String tenantDomain, final char[] tenantAdminRawPassword)
{
createTenant(tenantDomain, tenantAdminRawPassword, null);
}
@Override
public void createTenant(final String tenantDomain, final char[] tenantAdminRawPassword, String contentRoot)
{
createTenant(tenantDomain, tenantAdminRawPassword, contentRoot, null);
}
@Override
public void createTenant(final String tenantDomainIn, final char[] tenantAdminRawPassword, String contentRootPath, final String dbUrl)
{
ParameterCheck.mandatory("tenantAdminRawPassword", tenantAdminRawPassword);
final String tenantDomain = getTenantDomain(tenantDomainIn);
AuthenticationUtil.setMtEnabled(true); // in case this is the 1st tenant
long start = System.currentTimeMillis();
if ((contentRootContainerPath != null) && (! contentRootContainerPath.isEmpty()))
{
String defaultContentRoot = null;
if (! contentRootContainerPath.endsWith("/"))
{
defaultContentRoot = contentRootContainerPath + "/" + tenantDomain;
}
else
{
defaultContentRoot = contentRootContainerPath + tenantDomain;
}
if ((contentRootPath != null) && (! contentRootPath.isEmpty()))
{
logger.warn("Use default content root path: "+defaultContentRoot+" (ignoring: "+contentRootPath+")");
}
contentRootPath = defaultContentRoot;
}
initTenant(tenantDomain, contentRootPath, dbUrl);
if ((dbUrl != null) && (trds != null))
{
try
{
// note: experimental - currently assumes a bootstrapped DB schema exists for this dbUrl !
trds.addTenantDataSource(tenantDomain, dbUrl);
}
catch (SQLException se)
{
throw new AlfrescoRuntimeException("Failed to create tenant '"+tenantDomain+"' for dbUrl '"+dbUrl+"'", se);
}
}
try
{
// note: runAs would cause auditable property "creator" to be "admin" instead of "System@xxx"
AuthenticationUtil.pushAuthentication();
AuthenticationUtil.setFullyAuthenticatedUser(getSystemUser(tenantDomain));
TenantUtil.runAsSystemTenant(new TenantRunAsWork