001/*
002 * (C) Copyright 2006-2015 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bstefanescu, jcarsique
018 */
019package org.nuxeo.connect.update.standalone;
020
021import java.io.File;
022import java.io.IOException;
023import java.nio.file.Files;
024import java.nio.file.Path;
025import java.nio.file.attribute.BasicFileAttributes;
026import java.nio.file.attribute.FileTime;
027import java.util.ArrayList;
028import java.util.HashMap;
029import java.util.List;
030import java.util.Map;
031import java.util.Map.Entry;
032import java.util.Random;
033
034import org.apache.commons.logging.Log;
035import org.apache.commons.logging.LogFactory;
036
037import org.nuxeo.common.Environment;
038import org.nuxeo.common.utils.FileUtils;
039import org.nuxeo.common.utils.ZipUtils;
040import org.nuxeo.connect.update.AlreadyExistsPackageException;
041import org.nuxeo.connect.update.LocalPackage;
042import org.nuxeo.connect.update.PackageException;
043import org.nuxeo.connect.update.PackageState;
044import org.nuxeo.connect.update.PackageUpdateService;
045
046/**
047 * The file {@code nxserver/data/packages/.packages} stores the state of all local features.
048 * <p>
049 * Each local package have a corresponding directory in {@code nxserver/data/features/store} which is named:
050 * {@code <package_uid>} ("id-version")
051 *
052 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
053 */
054public class PackagePersistence {
055
056    private static final Log log = LogFactory.getLog(PackagePersistence.class);
057
058    protected final File root;
059
060    protected final File store;
061
062    protected final File temp;
063
064    protected final Random random = new Random();
065
066    protected Map<String, PackageState> states;
067
068    private PackageUpdateService service;
069
070    public PackagePersistence(PackageUpdateService pus) throws IOException {
071        Environment env = Environment.getDefault();
072        root = env.getPath(Environment.NUXEO_MP_DIR, Environment.DEFAULT_MP_DIR);
073        if (!root.isAbsolute()) {
074            throw new RuntimeException();
075        }
076        root.mkdirs();
077        store = new File(root, "store");
078        store.mkdirs();
079        temp = new File(root, "tmp");
080        temp.mkdirs();
081        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}