View Javadoc
1   /**
2    * This file Copyright (c) 2016-2018 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.setup;
35  
36  import info.magnolia.cms.core.version.VersionManager;
37  import info.magnolia.jcr.util.NodeTypes;
38  import info.magnolia.jcr.util.NodeUtil;
39  import info.magnolia.module.InstallContext;
40  import info.magnolia.module.delta.AbstractRepositoryTask;
41  import info.magnolia.module.delta.TaskExecutionException;
42  import info.magnolia.repository.RepositoryConstants;
43  import info.magnolia.repository.RepositoryManager;
44  
45  import java.util.Collections;
46  import java.util.HashMap;
47  import java.util.List;
48  import java.util.Map;
49  import java.util.stream.Collectors;
50  
51  import javax.jcr.ItemNotFoundException;
52  import javax.jcr.Node;
53  import javax.jcr.RepositoryException;
54  import javax.jcr.Session;
55  
56  import org.apache.commons.lang3.RandomStringUtils;
57  import org.apache.commons.lang3.StringUtils;
58  import org.slf4j.Logger;
59  import org.slf4j.LoggerFactory;
60  
61  /**
62   * Migrates version store to the new structure.
63   * <p>New structure is generated from node's uuid, level 1 node - first two letters from the first part, level 2 node - two letters from the second part and level 3 node - two letters from third part.</p>
64   * <p>It might happen that versions are corrupted (when multiple nodes have same uuid across different workspaces), in that case we resolve new structure from the node where
65   * primary node type matches the versioned node node type, we also log warning so users can fix the problem.</p>
66   */
67  public class MigrateVersionWorkspacesToNewStructureTask extends AbstractRepositoryTask {
68  
69      private static final Logger log = LoggerFactory.getLogger(MigrateVersionWorkspacesToNewStructureTask.class);
70  
71      private static final String FOUND_IN_MULTIPLE_WORKSPACES_MESSAGE = "Node [%s:%s:%s] found in multiple workspaces [%s]. This means that versions for both nodes are most likely broken and versions needs to be removed.";
72      private static final String ORIGINAL_NODE_NOT_FOUND_MESSAGE = "Version found for node [%s:%s:%s], but original node no longer exists";
73      public static final String INCONSISTENT_VERSIONS = "inconsistentVersions";
74  
75      private final RepositoryManager repositoryManager;
76  
77      private Map<String, Session> sessions = new HashMap<>();
78  
79      public MigrateVersionWorkspacesToNewStructureTask(RepositoryManager repositoryManager) {
80          super("Migrate version workspace", "Migrate version workspace to new structure");
81          this.repositoryManager = repositoryManager;
82      }
83  
84      @Override
85      protected void doExecute(InstallContext installContext) throws RepositoryException, TaskExecutionException {
86          List<String> versionWorkspaces = repositoryManager.getWorkspaceNames().stream().filter(input -> StringUtils.endsWith(input, RepositoryConstants.VERSION_STORE)).collect(Collectors.toList());
87          // remove system and version workspaces
88          List<String> workspacesToSearchIn = repositoryManager.getWorkspaceNames().stream().filter(input -> !(StringUtils.endsWith(input, RepositoryConstants.VERSION_STORE) || StringUtils.endsWith(input, RepositoryConstants.SYSTEM))).collect(Collectors.toList());
89          // reorder workspaces to have most important ones in the beginning
90          Collections.swap(workspacesToSearchIn, workspacesToSearchIn.indexOf(RepositoryConstants.WEBSITE), 0);
91          if (workspacesToSearchIn.contains("dam")) {
92              Collections.swap(workspacesToSearchIn, workspacesToSearchIn.indexOf("dam"), 1);
93          }
94          if (workspacesToSearchIn.contains("contacts")) {
95              Collections.swap(workspacesToSearchIn, workspacesToSearchIn.indexOf("contacts"), 2);
96          }
97          if (workspacesToSearchIn.contains("segments")) {
98              Collections.swap(workspacesToSearchIn, workspacesToSearchIn.indexOf("segments"), 3);
99          }
100         if (workspacesToSearchIn.contains("personas")) {
101             Collections.swap(workspacesToSearchIn, workspacesToSearchIn.indexOf("personas"), 4);
102         }
103         // go through each version workspace and try to find original node for each version node
104         for (String versionWorkspace : versionWorkspaces) {
105             Session versionSession = installContext.getJCRSession(versionWorkspace);
106             final String tempNodeName = RandomStringUtils.randomAlphanumeric(10);
107             // temp node where all version nodes will be moved in order to to avoid collisions:
108             // - versionNode path is /99 and save path is /99/88/77/
109             final Node tempNode = versionSession.getRootNode().addNode(tempNodeName, NodeTypes.Folder.NAME);
110             // node where versions without original node will be moved
111             final Node inconsistentVersionsNode = versionSession.getRootNode().addNode(INCONSISTENT_VERSIONS, NodeTypes.Folder.NAME);
112 
113             for (Node versionNode : NodeUtil.getNodes(versionSession.getRootNode())) {
114                 if (versionNode.getName().equals(VersionManager.TMP_REFERENCED_NODES)
115                         || StringUtils.startsWith(versionNode.getName(), NodeTypes.REP_PREFIX)
116                         || StringUtils.equals(versionNode.getName(), tempNodeName)
117                         || StringUtils.equals(versionNode.getName(), INCONSISTENT_VERSIONS)) {
118                     continue;
119                 }
120 
121                 log.debug("Processing version node [{}] with uuid [{}]", versionNode.getPath(), versionNode.getIdentifier());
122                 String uuid = versionNode.getIdentifier();
123                 log.debug("Renaming version node [{}] to [{}]", versionNode.getName(), uuid);
124                 NodeUtil.renameNode(versionNode, uuid);
125 
126                 Map<String, Node> found = new HashMap<>();
127                 Node originalNode = null;
128                 for (String workspace : workspacesToSearchIn) {
129                     if (!sessions.containsKey(workspace)) {
130                         sessions.put(workspace, installContext.getJCRSession(workspace));
131                     }
132                     try {
133                         Node node = sessions.get(workspace).getNodeByIdentifier(uuid);
134                         if (node.getPrimaryNodeType().getName().equals(versionNode.getPrimaryNodeType().getName())) {
135                             originalNode = node;
136                         }
137                         found.put(workspace, node);
138                     } catch (ItemNotFoundException e) {
139                         // ignore - node was just not found
140                     }
141                 }
142 
143                 if (found.size() == 0 || originalNode == null) {
144                     // log if original node was not found
145                     log.debug(String.format(ORIGINAL_NODE_NOT_FOUND_MESSAGE, versionNode.getName(), versionNode.getIdentifier(), versionNode.getPrimaryNodeType().getName()));
146                     Node newParent = NodeUtil.createPath(inconsistentVersionsNode, getSavePath(versionNode), NodeTypes.Folder.NAME, false);
147                     NodeUtil.moveNode(versionNode, newParent);
148                     continue;
149                 } else if (found.size() > 1) {
150                     // if found in multiple workspaces, warn user that they will have probably broken versions and will need to fix them
151                     log.debug(String.format(FOUND_IN_MULTIPLE_WORKSPACES_MESSAGE, versionNode.getName(), versionNode.getIdentifier(), versionNode.getPrimaryNodeType().getName(), StringUtils.join(found, ":")));
152                 }
153                 Node newParent = NodeUtil.createPath(tempNode, getSavePath(originalNode), NodeTypes.Folder.NAME, false);
154                 // move node to the temp location
155                 NodeUtil.moveNode(versionNode, newParent);
156 
157                 originalNode.addMixin(NodeTypes.HasVersion.NAME);
158                 log.debug("Moved [{}] to the new location [{}]", versionNode.getPath(), newParent.getPath() + "/" + versionNode.getName());
159             }
160             // finally move all migrated nodes from the temp node to the root
161             for (Node node : NodeUtil.getNodes(tempNode)) {
162                 NodeUtil.moveNode(node, versionSession.getRootNode());
163             }
164             tempNode.remove();
165         }
166     }
167 
168     String getSavePath(Node node) throws RepositoryException {
169         String uuid = node.getIdentifier();
170         return String.format("%s/%s/%s", StringUtils.substring(uuid, 0, 2), StringUtils.substring(uuid, 9, 11), StringUtils.substring(uuid, 14, 16));
171     }
172 }