001/* 002 * (C) Copyright 2006-2014 Nuxeo SA (http://nuxeo.com/) and contributors. 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the GNU Lesser General Public License 006 * (LGPL) version 2.1 which accompanies this distribution, and is available at 007 * http://www.gnu.org/licenses/lgpl-2.1.html 008 * 009 * This library is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * Contributors: 015 * bstefanescu, jcarsique 016 */ 017package org.nuxeo.connect.update.standalone; 018 019import java.io.File; 020import java.io.IOException; 021import java.nio.file.Files; 022import java.nio.file.Path; 023import java.nio.file.attribute.BasicFileAttributes; 024import java.nio.file.attribute.FileTime; 025import java.util.ArrayList; 026import java.util.HashMap; 027import java.util.List; 028import java.util.Map; 029import java.util.Map.Entry; 030import java.util.Random; 031 032import org.apache.commons.logging.Log; 033import org.apache.commons.logging.LogFactory; 034 035import org.nuxeo.common.Environment; 036import org.nuxeo.common.utils.FileUtils; 037import org.nuxeo.common.utils.ZipUtils; 038import org.nuxeo.connect.update.AlreadyExistsPackageException; 039import org.nuxeo.connect.update.LocalPackage; 040import org.nuxeo.connect.update.PackageException; 041import org.nuxeo.connect.update.PackageState; 042import org.nuxeo.connect.update.PackageUpdateService; 043 044/** 045 * The file {@code nxserver/data/packages/.packages} stores the state of all local features. 046 * <p> 047 * Each local package have a corresponding directory in {@code nxserver/data/features/store} which is named: 048 * {@code <package_uid>} ("id-version") 049 * 050 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a> 051 */ 052public class PackagePersistence { 053 054 private static final Log log = LogFactory.getLog(PackagePersistence.class); 055 056 protected final File root; 057 058 protected final File store; 059 060 protected final File temp; 061 062 protected final Random random = new Random(); 063 064 protected Map<String, PackageState> states; 065 066 private PackageUpdateService service; 067 068 public PackagePersistence(PackageUpdateService pus) throws IOException { 069 Environment env = Environment.getDefault(); 070 File mpDir = new File(env.getProperty(Environment.NUXEO_MP_DIR, Environment.DEFAULT_MP_DIR)); 071 if (mpDir.isAbsolute()) { 072 root = mpDir; 073 } else { 074 root = new File(env.getServerHome(), mpDir.getPath()); 075 } 076 root.mkdirs(); 077 store = new File(root, "store"); 078 store.mkdirs(); 079 temp = new File(root, "tmp"); 080 temp.mkdirs(); 081 this.service = pus; 082 states = loadStates(); 083 } 084 085 public File getRoot() { 086 return root; 087 } 088 089 /** 090 * @since 7.1 091 */ 092 public File getStore() { 093 return store; 094 } 095 096 public synchronized Map<String, PackageState> getStates() { 097 return new HashMap<>(states); 098 } 099 100 protected Map<String, PackageState> loadStates() throws IOException { 101 Map<String, PackageState> result = new HashMap<>(); 102 File file = new File(root, ".packages"); 103 if (file.isFile()) { 104 List<String> lines = FileUtils.readLines(file); 105 for (String line : lines) { 106 line = line.trim(); 107 if (line.length() == 0 || line.startsWith("#")) { 108 continue; 109 } 110 int i = line.indexOf('='); 111 String pkgId = line.substring(0, i).trim(); 112 String value = line.substring(i + 1).trim(); 113 PackageState state = null; 114 state = PackageState.getByLabel(value); 115 if (state == PackageState.UNKNOWN) { 116 try { 117 // Kept for backward compliance with int instead of enum 118 state = PackageState.getByValue(value); 119 } catch (NumberFormatException e) { 120 // Set as REMOTE if undefined/unreadable 121 state = PackageState.REMOTE; 122 } 123 } 124 result.put(pkgId, state); 125 } 126 } 127 return result; 128 } 129 130 protected void writeStates() throws IOException { 131 StringBuilder buf = new StringBuilder(); 132 for (Entry<String, PackageState> entry : states.entrySet()) { 133 buf.append(entry.getKey()).append('=').append(entry.getValue()).append("\n"); 134 } 135 File file = new File(root, ".packages"); 136 FileUtils.writeFile(file, buf.toString()); 137 } 138 139 public LocalPackage getPackage(String id) throws PackageException { 140 File file = new File(store, id); 141 if (file.isDirectory()) { 142 return new LocalPackageImpl(file, getState(id), service); 143 } 144 return null; 145 } 146 147 public synchronized LocalPackage addPackage(File file) throws PackageException { 148 if (file.isDirectory()) { 149 return addPackageFromDir(file); 150 } else if (file.isFile()) { 151 File tmp = newTempDir(file.getName()); 152 try { 153 ZipUtils.unzip(file, tmp); 154 return addPackageFromDir(tmp); 155 } catch (IOException e) { 156 throw new PackageException("Failed to unzip package: " + file.getName()); 157 } finally { 158 // cleanup if tmp still exists (should not happen) 159 org.apache.commons.io.FileUtils.deleteQuietly(tmp); 160 } 161 } else { 162 throw new PackageException("Not found: " + file); 163 } 164 } 165 166 /** 167 * Add unzipped packaged to local cache. It replaces SNAPSHOT packages if not installed 168 * 169 * @throws PackageException 170 * @throws AlreadyExistsPackageException If not replacing a SNAPSHOT or if the existing package is installed 171 */ 172 protected LocalPackage addPackageFromDir(File file) throws PackageException { 173 LocalPackageImpl pkg = new LocalPackageImpl(file, PackageState.DOWNLOADED, service); 174 File dir = null; 175 try { 176 dir = new File(store, pkg.getId()); 177 if (dir.exists()) { 178 LocalPackage oldpkg = getPackage(pkg.getId()); 179 if (!pkg.getVersion().isSnapshot()) { 180 throw new AlreadyExistsPackageException("Package " + pkg.getId() + " already exists"); 181 } 182 if (oldpkg.getPackageState().isInstalled()) { 183 throw new AlreadyExistsPackageException("Package " + pkg.getId() + " is already installed"); 184 } 185 log.info(String.format("Replacement of %s in local cache...", oldpkg)); 186 org.apache.commons.io.FileUtils.deleteQuietly(dir); 187 } 188 org.apache.commons.io.FileUtils.moveDirectory(file, dir); 189 pkg.getData().setRoot(dir); 190 updateState(pkg.getId(), pkg.state); 191 return pkg; 192 } catch (IOException e) { 193 throw new PackageException(String.format("Failed to move %s to %s", file, dir), e); 194 } 195 } 196 197 public synchronized PackageState getState(String packageId) { 198 PackageState state = states.get(packageId); 199 if (state == null) { 200 return PackageState.REMOTE; 201 } 202 return state; 203 } 204 205 /** 206 * Get the local package having the given name and which is in either one of the following states: 207 * <ul> 208 * <li> {@link PackageState#INSTALLING} 209 * <li> {@link PackageState#INSTALLED} 210 * <li> {@link PackageState#STARTED} 211 * </ul> 212 * 213 * @param name 214 */ 215 public LocalPackage getActivePackage(String name) throws PackageException { 216 String pkgId = getActivePackageId(name); 217 if (pkgId == null) { 218 return null; 219 } 220 return getPackage(pkgId); 221 } 222 223 public synchronized String getActivePackageId(String name) { 224 name = name + '-'; 225 for (Entry<String, PackageState> entry : states.entrySet()) { 226 if (entry.getKey().startsWith(name) && entry.getValue().isInstalled()) { 227 return entry.getKey(); 228 } 229 } 230 return null; 231 } 232 233 public synchronized List<LocalPackage> getPackages() throws PackageException { 234 File[] list = store.listFiles(); 235 if (list != null) { 236 List<LocalPackage> pkgs = new ArrayList<>(list.length); 237 for (File file : list) { 238 if (!file.isDirectory()) { 239 log.warn("Ignoring file '" + file.getName() + "' in package store"); 240 continue; 241 } 242 pkgs.add(new LocalPackageImpl(file, getState(file.getName()), service)); 243 } 244 return pkgs; 245 } 246 return new ArrayList<>(); 247 } 248 249 public synchronized void removePackage(String id) throws PackageException { 250 states.remove(id); 251 try { 252 writeStates(); 253 } catch (IOException e) { 254 throw new PackageException("Failed to write package states", e); 255 } 256 File file = new File(store, id); 257 org.apache.commons.io.FileUtils.deleteQuietly(file); 258 } 259 260 /** 261 * @deprecated Since 5.7. Use {@link #updateState(String, PackageState)} instead. 262 */ 263 @Deprecated 264 public synchronized void updateState(String id, int state) throws PackageException { 265 states.put(id, PackageState.getByValue(state)); 266 try { 267 writeStates(); 268 } catch (IOException e) { 269 throw new PackageException("Failed to write package states", e); 270 } 271 } 272 273 /** 274 * @since 5.7 275 */ 276 public synchronized void updateState(String id, PackageState state) throws PackageException { 277 states.put(id, state); 278 try { 279 writeStates(); 280 } catch (IOException e) { 281 throw new PackageException("Failed to write package states", e); 282 } 283 } 284 285 public synchronized void reset() throws PackageException { 286 String[] keys = states.keySet().toArray(new String[states.size()]); 287 for (String key : keys) { 288 states.put(key, PackageState.DOWNLOADED); 289 } 290 try { 291 writeStates(); 292 } catch (IOException e) { 293 throw new PackageException("Failed to write package states", e); 294 } 295 } 296 297 protected File newTempDir(String id) { 298 File tmp; 299 synchronized (temp) { 300 do { 301 tmp = new File(temp, id + "-" + random.nextInt()); 302 } while (tmp.exists()); 303 tmp.mkdirs(); 304 } 305 return tmp; 306 } 307 308 /** 309 * @since 5.8 310 */ 311 public FileTime getInstallDate(String id) { 312 File file = new File(store, id); 313 if (file.isDirectory()) { 314 Path path = file.toPath(); 315 try { 316 FileTime lastModifiedTime = Files.readAttributes(path, BasicFileAttributes.class).lastModifiedTime(); 317 return lastModifiedTime; 318 } catch (IOException e) { 319 log.error(e); 320 } 321 } 322 return null; 323 } 324}