James Moger
2015-11-22 ed552ba47c02779c270ffd62841d6d1048dade70
commit | author | age
84f406 1 /*
DO 2  * Copyright 2014 gitblit.com.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package com.gitblit.manager;
17
413e9b 18 import java.io.File;
e5d0ba 19 import java.io.FileFilter;
b2fec2 20 import java.io.FileInputStream;
006651 21 import java.io.FileOutputStream;
e5d0ba 22 import java.io.IOException;
JM 23 import java.io.InputStream;
006651 24 import java.io.OutputStream;
e5d0ba 25 import java.net.HttpURLConnection;
d86f4a 26 import java.net.InetSocketAddress;
e5d0ba 27 import java.net.Proxy;
JM 28 import java.net.URL;
29 import java.net.URLConnection;
b2fec2 30 import java.security.DigestInputStream;
JM 31 import java.security.MessageDigest;
32 import java.security.NoSuchAlgorithmException;
e5d0ba 33 import java.util.ArrayList;
b2fec2 34 import java.util.Iterator;
e5d0ba 35 import java.util.List;
JM 36 import java.util.Map;
37 import java.util.TreeMap;
413e9b 38
84f406 39 import org.slf4j.Logger;
DO 40 import org.slf4j.LoggerFactory;
41
22ed6a 42 import ro.fortsoft.pf4j.DefaultPluginFactory;
84f406 43 import ro.fortsoft.pf4j.DefaultPluginManager;
22ed6a 44 import ro.fortsoft.pf4j.ExtensionFactory;
JM 45 import ro.fortsoft.pf4j.Plugin;
b2fec2 46 import ro.fortsoft.pf4j.PluginClassLoader;
22ed6a 47 import ro.fortsoft.pf4j.PluginFactory;
b2fec2 48 import ro.fortsoft.pf4j.PluginState;
JM 49 import ro.fortsoft.pf4j.PluginStateEvent;
50 import ro.fortsoft.pf4j.PluginStateListener;
413e9b 51 import ro.fortsoft.pf4j.PluginWrapper;
027267 52 import ro.fortsoft.pf4j.Version;
84f406 53
027267 54 import com.gitblit.Constants;
84f406 55 import com.gitblit.Keys;
cf4004 56 import com.gitblit.extensions.GitblitPlugin;
e5d0ba 57 import com.gitblit.models.PluginRegistry;
b2fec2 58 import com.gitblit.models.PluginRegistry.InstallState;
e5d0ba 59 import com.gitblit.models.PluginRegistry.PluginRegistration;
JM 60 import com.gitblit.models.PluginRegistry.PluginRelease;
61 import com.gitblit.utils.Base64;
413e9b 62 import com.gitblit.utils.FileUtils;
e5d0ba 63 import com.gitblit.utils.JsonUtils;
JM 64 import com.gitblit.utils.StringUtils;
006651 65 import com.google.common.io.ByteStreams;
f9980e 66 import com.google.inject.Inject;
JM 67 import com.google.inject.Singleton;
84f406 68
DO 69 /**
70  * The plugin manager maintains the lifecycle of plugins. It is exposed as
b2fec2 71  * Dagger bean. The extension consumers supposed to retrieve plugin manager from
JM 72  * the Dagger DI and retrieve extensions provided by active plugins.
e5d0ba 73  *
84f406 74  * @author David Ostrovsky
027267 75  * @author James Moger
e5d0ba 76  *
84f406 77  */
f9980e 78 @Singleton
b2fec2 79 public class PluginManager implements IPluginManager, PluginStateListener {
84f406 80
DO 81     private final Logger logger = LoggerFactory.getLogger(getClass());
b2fec2 82
413e9b 83     private final IRuntimeManager runtimeManager;
3610dc 84
JM 85     private DefaultPluginManager pf4j;
e5d0ba 86
JM 87     // timeout defaults of Maven 3.0.4 in seconds
88     private int connectTimeout = 20;
89
90     private int readTimeout = 12800;
84f406 91
1b34b0 92     @Inject
84f406 93     public PluginManager(IRuntimeManager runtimeManager) {
413e9b 94         this.runtimeManager = runtimeManager;
027267 95     }
JM 96
97     @Override
98     public Version getSystemVersion() {
99         return pf4j.getSystemVersion();
b2fec2 100     }
JM 101
102     @Override
103     public void pluginStateChanged(PluginStateEvent event) {
104         logger.debug(event.toString());
84f406 105     }
DO 106
107     @Override
108     public PluginManager start() {
3610dc 109         File dir = runtimeManager.getFileOrFolder(Keys.plugins.folder, "${baseFolder}/plugins");
JM 110         dir.mkdirs();
22ed6a 111
1c301b 112         pf4j = new DefaultPluginManager(dir) {
22ed6a 113
1c301b 114             @Override
22ed6a 115             protected PluginFactory createPluginFactory() {
JM 116                 return new GuicePluginFactory();
117             }
1c301b 118
22ed6a 119             @Override
JM 120             protected ExtensionFactory createExtensionFactory() {
121                 return new GuiceExtensionFactory();
122             }
1c301b 123         };
3610dc 124
JM 125         try {
126             Version systemVersion = Version.createVersion(Constants.getVersion());
127             pf4j.setSystemVersion(systemVersion);
128         } catch (Exception e) {
129             logger.error(null, e);
130         }
b2fec2 131         pf4j.loadPlugins();
JM 132         logger.debug("Starting plugins");
133         pf4j.startPlugins();
84f406 134         return this;
DO 135     }
136
137     @Override
138     public PluginManager stop() {
b2fec2 139         logger.debug("Stopping plugins");
JM 140         pf4j.stopPlugins();
84f406 141         return null;
DO 142     }
e5d0ba 143
b2fec2 144     /**
JM 145      * Installs the plugin from the url.
146      *
147      * @param url
148      * @param verifyChecksum
149      * @return true if successful
150      */
413e9b 151     @Override
b2fec2 152     public synchronized boolean installPlugin(String url, boolean verifyChecksum) throws IOException {
JM 153         File file = download(url, verifyChecksum);
154         if (file == null || !file.exists()) {
155             logger.error("Failed to download plugin {}", url);
156             return false;
157         }
e5d0ba 158
b2fec2 159         String pluginId = pf4j.loadPlugin(file);
JM 160         if (StringUtils.isEmpty(pluginId)) {
161             logger.error("Failed to load plugin {}", file);
162             return false;
413e9b 163         }
b2fec2 164
cf4004 165         // allow the plugin to prepare for operation after installation
JM 166         PluginWrapper pluginWrapper = pf4j.getPlugin(pluginId);
167         if (pluginWrapper.getPlugin() instanceof GitblitPlugin) {
168             ((GitblitPlugin) pluginWrapper.getPlugin()).onInstall();
169         }
170
b2fec2 171         PluginState state = pf4j.startPlugin(pluginId);
JM 172         return PluginState.STARTED.equals(state);
413e9b 173     }
e5d0ba 174
027267 175     @Override
74f3d9 176     public synchronized boolean upgradePlugin(String pluginId, String url, boolean verifyChecksum) throws IOException {
JM 177         // ensure we can download the update BEFORE we remove the existing one
178         File file = download(url, verifyChecksum);
179         if (file == null || !file.exists()) {
180             logger.error("Failed to download plugin {}", url);
181             return false;
182         }
183
cf4004 184         Version oldVersion = pf4j.getPlugin(pluginId).getDescriptor().getVersion();
JM 185         if (removePlugin(pluginId, false)) {
74f3d9 186             String newPluginId = pf4j.loadPlugin(file);
JM 187             if (StringUtils.isEmpty(newPluginId)) {
188                 logger.error("Failed to load plugin {}", file);
189                 return false;
cf4004 190             }
JM 191
192             // the plugin to handle an upgrade
193             PluginWrapper pluginWrapper = pf4j.getPlugin(newPluginId);
194             if (pluginWrapper.getPlugin() instanceof GitblitPlugin) {
195                 ((GitblitPlugin) pluginWrapper.getPlugin()).onUpgrade(oldVersion);
74f3d9 196             }
JM 197
198             PluginState state = pf4j.startPlugin(newPluginId);
199             return PluginState.STARTED.equals(state);
200         } else {
201             logger.error("Failed to delete plugin {}", pluginId);
202         }
203         return false;
204     }
205
e5d0ba 206     @Override
b2fec2 207     public synchronized boolean disablePlugin(String pluginId) {
JM 208         return pf4j.disablePlugin(pluginId);
209     }
210
211     @Override
212     public synchronized boolean enablePlugin(String pluginId) {
213         if (pf4j.enablePlugin(pluginId)) {
214             return PluginState.STARTED == pf4j.startPlugin(pluginId);
215         }
216         return false;
217     }
218
219     @Override
cf4004 220     public synchronized boolean uninstallPlugin(String pluginId) {
JM 221         return removePlugin(pluginId, true);
222     }
223
224     protected boolean removePlugin(String pluginId, boolean isUninstall) {
b2fec2 225         PluginWrapper pluginWrapper = getPlugin(pluginId);
JM 226         final String name = pluginWrapper.getPluginPath().substring(1);
cf4004 227
JM 228         if (isUninstall) {
229             // allow the plugin to prepare for uninstallation
230             if (pluginWrapper.getPlugin() instanceof GitblitPlugin) {
231                 ((GitblitPlugin) pluginWrapper.getPlugin()).onUninstall();
232             }
233         }
234
b2fec2 235         if (pf4j.deletePlugin(pluginId)) {
JM 236
237             // delete the checksums
238             File pFolder = runtimeManager.getFileOrFolder(Keys.plugins.folder, "${baseFolder}/plugins");
239             File [] checksums = pFolder.listFiles(new FileFilter() {
240                 @Override
241                 public boolean accept(File file) {
242                     if (!file.isFile()) {
243                         return false;
244                     }
245
246                     return file.getName().startsWith(name) &&
247                             (file.getName().toLowerCase().endsWith(".sha1")
248                                     || file.getName().toLowerCase().endsWith(".md5"));
249                 }
250             });
251
252             if (checksums != null) {
253                 for (File checksum : checksums) {
254                     checksum.delete();
255                 }
256             }
257             return true;
258         }
259         return false;
260     }
261
262     @Override
263     public synchronized PluginState startPlugin(String pluginId) {
264         return pf4j.startPlugin(pluginId);
265     }
266
267     @Override
268     public synchronized PluginState stopPlugin(String pluginId) {
269         return pf4j.stopPlugin(pluginId);
270     }
271
272     @Override
273     public synchronized void startPlugins() {
274         pf4j.startPlugins();
275     }
276
277     @Override
278     public synchronized void stopPlugins() {
279         pf4j.stopPlugins();
280     }
281
282     @Override
283     public synchronized List<PluginWrapper> getPlugins() {
284         return pf4j.getPlugins();
285     }
286
287     @Override
288     public synchronized PluginWrapper getPlugin(String pluginId) {
289         return pf4j.getPlugin(pluginId);
290     }
291
292     @Override
293     public synchronized List<Class<?>> getExtensionClasses(String pluginId) {
294         List<Class<?>> list = new ArrayList<Class<?>>();
295         PluginClassLoader loader = pf4j.getPluginClassLoader(pluginId);
296         for (String className : pf4j.getExtensionClassNames(pluginId)) {
297             try {
298                 list.add(loader.loadClass(className));
299             } catch (ClassNotFoundException e) {
300                 logger.error(String.format("Failed to find %s in %s", className, pluginId), e);
301             }
302         }
303         return list;
304     }
305
306     @Override
307     public synchronized <T> List<T> getExtensions(Class<T> type) {
308         return pf4j.getExtensions(type);
309     }
310
311     @Override
312     public synchronized PluginWrapper whichPlugin(Class<?> clazz) {
313         return pf4j.whichPlugin(clazz);
314     }
315
316     @Override
ec53f7 317     public synchronized boolean refreshRegistry(boolean verifyChecksum) {
e5d0ba 318         String dr = "http://gitblit.github.io/gitblit-registry/plugins.json";
JM 319         String url = runtimeManager.getSettings().getString(Keys.plugins.registry, dr);
320         try {
ec53f7 321             File file = download(url, verifyChecksum);
b2fec2 322             if (file != null && file.exists()) {
JM 323                 URL selfUrl = new URL(url.substring(0, url.lastIndexOf('/')));
324                 // replace ${self} with the registry url
325                 String content = FileUtils.readContent(file, "\n");
326                 content = content.replace("${self}", selfUrl.toString());
327                 FileUtils.writeContent(file, content);
328             }
e5d0ba 329         } catch (Exception e) {
JM 330             logger.error(String.format("Failed to retrieve plugins.json from %s", url), e);
331         }
332         return false;
333     }
334
335     protected List<PluginRegistry> getRegistries() {
336         List<PluginRegistry> list = new ArrayList<PluginRegistry>();
337         File folder = runtimeManager.getFileOrFolder(Keys.plugins.folder, "${baseFolder}/plugins");
338         FileFilter jsonFilter = new FileFilter() {
339             @Override
340             public boolean accept(File file) {
341                 return !file.isDirectory() && file.getName().toLowerCase().endsWith(".json");
342             }
343         };
344
b2fec2 345         File[] files = folder.listFiles(jsonFilter);
e5d0ba 346         if (files == null || files.length == 0) {
JM 347             // automatically retrieve the registry if we don't have a local copy
ec53f7 348             refreshRegistry(true);
e5d0ba 349             files = folder.listFiles(jsonFilter);
JM 350         }
351
352         if (files == null || files.length == 0) {
353             return list;
354         }
355
356         for (File file : files) {
357             PluginRegistry registry = null;
358             try {
359                 String json = FileUtils.readContent(file, "\n");
360                 registry = JsonUtils.fromJsonString(json, PluginRegistry.class);
b2fec2 361                 registry.setup();
e5d0ba 362             } catch (Exception e) {
JM 363                 logger.error("Failed to deserialize " + file, e);
364             }
365             if (registry != null) {
366                 list.add(registry);
367             }
368         }
369         return list;
370     }
371
372     @Override
b2fec2 373     public synchronized List<PluginRegistration> getRegisteredPlugins() {
e5d0ba 374         List<PluginRegistration> list = new ArrayList<PluginRegistration>();
JM 375         Map<String, PluginRegistration> map = new TreeMap<String, PluginRegistration>();
376         for (PluginRegistry registry : getRegistries()) {
b2fec2 377             list.addAll(registry.registrations);
JM 378             for (PluginRegistration reg : list) {
e5d0ba 379                 reg.installedRelease = null;
JM 380                 map.put(reg.id, reg);
381             }
382         }
74f3d9 383
b2fec2 384         for (PluginWrapper pw : pf4j.getPlugins()) {
e5d0ba 385             String id = pw.getDescriptor().getPluginId();
027267 386             Version pv = pw.getDescriptor().getVersion();
e5d0ba 387             PluginRegistration reg = map.get(id);
JM 388             if (reg != null) {
389                 reg.installedRelease = pv.toString();
390             }
391         }
392         return list;
393     }
394
395     @Override
b2fec2 396     public synchronized List<PluginRegistration> getRegisteredPlugins(InstallState state) {
JM 397         List<PluginRegistration> list = getRegisteredPlugins();
398         Iterator<PluginRegistration> itr = list.iterator();
399         while (itr.hasNext()) {
67278f 400             if (state != itr.next().getInstallState(getSystemVersion())) {
b2fec2 401                 itr.remove();
JM 402             }
403         }
404         return list;
405     }
406
407     @Override
fad6b4 408     public synchronized PluginRegistration lookupPlugin(String pluginId) {
b2fec2 409         for (PluginRegistration reg : getRegisteredPlugins()) {
fad6b4 410             if (reg.id.equalsIgnoreCase(pluginId)) {
e5d0ba 411                 return reg;
JM 412             }
413         }
414         return null;
415     }
416
417     @Override
fad6b4 418     public synchronized PluginRelease lookupRelease(String pluginId, String version) {
JM 419         PluginRegistration reg = lookupPlugin(pluginId);
b2fec2 420         if (reg == null) {
JM 421             return null;
e5d0ba 422         }
JM 423
b2fec2 424         PluginRelease pv;
JM 425         if (StringUtils.isEmpty(version)) {
80cf76 426             pv = reg.getCurrentRelease(getSystemVersion());
b2fec2 427         } else {
JM 428             pv = reg.getRelease(version);
429         }
430         return pv;
e5d0ba 431     }
JM 432
433     /**
b2fec2 434      * Downloads a file with optional checksum verification.
e5d0ba 435      *
JM 436      * @param url
b2fec2 437      * @param verifyChecksum
JM 438      * @return
439      * @throws IOException
e5d0ba 440      */
b2fec2 441     protected File download(String url, boolean verifyChecksum) throws IOException {
JM 442         File file = downloadFile(url);
443
c57a28 444         if (!verifyChecksum) {
JM 445             return file;
446         }
447
b2fec2 448         File sha1File = null;
e5d0ba 449         try {
b2fec2 450             sha1File = downloadFile(url + ".sha1");
e5d0ba 451         } catch (IOException e) {
JM 452         }
b2fec2 453
JM 454         File md5File = null;
455         try {
456             md5File = downloadFile(url + ".md5");
457         } catch (IOException e) {
458
459         }
460
c57a28 461         if (sha1File == null && md5File == null) {
b2fec2 462             throw new IOException("Missing SHA1 and MD5 checksums for " + url);
JM 463         }
464
465         String expected;
466         MessageDigest md = null;
467         if (sha1File != null && sha1File.exists()) {
468             // prefer SHA1 to MD5
469             expected = FileUtils.readContent(sha1File, "\n").split(" ")[0].trim();
470             try {
471                 md = MessageDigest.getInstance("SHA-1");
472             } catch (NoSuchAlgorithmException e) {
473                 logger.error(null, e);
474             }
475         } else {
476             expected = FileUtils.readContent(md5File, "\n").split(" ")[0].trim();
477             try {
478                 md = MessageDigest.getInstance("MD5");
479             } catch (Exception e) {
480                 logger.error(null, e);
481             }
482         }
483
484         // calculate the checksum
485         FileInputStream is = null;
486         try {
487             is = new FileInputStream(file);
488             DigestInputStream dis = new DigestInputStream(is, md);
489             byte [] buffer = new byte[1024];
490             while ((dis.read(buffer)) > -1) {
491                 // read
492             }
493             dis.close();
494
495             byte [] digest = md.digest();
496             String calculated = StringUtils.toHex(digest).trim();
497
498             if (!expected.equals(calculated)) {
499                 String msg = String.format("Invalid checksum for %s\nAlgorithm:  %s\nExpected:   %s\nCalculated: %s",
500                         file.getAbsolutePath(),
501                         md.getAlgorithm(),
502                         expected,
503                         calculated);
504                 file.delete();
505                 throw new IOException(msg);
506             }
507         } finally {
508             if (is != null) {
509                 is.close();
510             }
511         }
512         return file;
e5d0ba 513     }
JM 514
515     /**
516      * Download a file to the plugins folder.
517      *
518      * @param url
b2fec2 519      * @return the downloaded file
e5d0ba 520      * @throws IOException
JM 521      */
b2fec2 522     protected File downloadFile(String url) throws IOException {
e5d0ba 523         File pFolder = runtimeManager.getFileOrFolder(Keys.plugins.folder, "${baseFolder}/plugins");
f7e977 524         pFolder.mkdirs();
e5d0ba 525         File tmpFile = new File(pFolder, StringUtils.getSHA1(url) + ".tmp");
JM 526         if (tmpFile.exists()) {
527             tmpFile.delete();
528         }
529
530         URL u = new URL(url);
531         final URLConnection conn = getConnection(u);
532
533         // try to get the server-specified last-modified date of this artifact
534         long lastModified = conn.getHeaderFieldDate("Last-Modified", System.currentTimeMillis());
535
006651 536         try (InputStream is = conn.getInputStream(); OutputStream os = new FileOutputStream(tmpFile);) {
JM 537             ByteStreams.copy(is, os);
538         }
e5d0ba 539
JM 540         File destFile = new File(pFolder, StringUtils.getLastPathElement(u.getPath()));
541         if (destFile.exists()) {
542             destFile.delete();
543         }
544         tmpFile.renameTo(destFile);
545         destFile.setLastModified(lastModified);
546
b2fec2 547         return destFile;
e5d0ba 548     }
JM 549
550     protected URLConnection getConnection(URL url) throws IOException {
551         java.net.Proxy proxy = getProxy(url);
552         HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
553         if (java.net.Proxy.Type.DIRECT != proxy.type()) {
554             String auth = getProxyAuthorization(url);
555             conn.setRequestProperty("Proxy-Authorization", auth);
556         }
557
558         String username = null;
559         String password = null;
560         if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
561             // set basic authentication header
562             String auth = Base64.encodeBytes((username + ":" + password).getBytes());
563             conn.setRequestProperty("Authorization", "Basic " + auth);
564         }
565
566         // configure timeouts
567         conn.setConnectTimeout(connectTimeout * 1000);
568         conn.setReadTimeout(readTimeout * 1000);
569
570         switch (conn.getResponseCode()) {
571         case HttpURLConnection.HTTP_MOVED_TEMP:
572         case HttpURLConnection.HTTP_MOVED_PERM:
573             // handle redirects by closing this connection and opening a new
574             // one to the new location of the requested resource
575             String newLocation = conn.getHeaderField("Location");
576             if (!StringUtils.isEmpty(newLocation)) {
577                 logger.info("following redirect to {0}", newLocation);
578                 conn.disconnect();
579                 return getConnection(new URL(newLocation));
580             }
581         }
582
583         return conn;
584     }
585
586     protected Proxy getProxy(URL url) {
d86f4a 587         String proxyHost = runtimeManager.getSettings().getString(Keys.plugins.httpProxyHost, "");
DB 588         String proxyPort = runtimeManager.getSettings().getString(Keys.plugins.httpProxyPort, "");
fbc7a7 589
d86f4a 590         if (!StringUtils.isEmpty(proxyHost)  && !StringUtils.isEmpty(proxyPort)) {
DB 591             return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort)));
592         } else {
593             return java.net.Proxy.NO_PROXY;
594         }
e5d0ba 595     }
JM 596
597     protected String getProxyAuthorization(URL url) {
fbc7a7 598         String proxyAuth = runtimeManager.getSettings().getString(Keys.plugins.httpProxyAuthorization, "");
JM 599         return proxyAuth;
e5d0ba 600     }
22ed6a 601
JM 602     /**
603      * Instantiates a plugin using pf4j but injects member fields
604      * with Guice.
605      */
606     private class GuicePluginFactory extends DefaultPluginFactory {
607
608         @Override
609         public Plugin create(PluginWrapper pluginWrapper) {
610             // use pf4j to create the plugin
611             Plugin plugin = super.create(pluginWrapper);
612
613             if (plugin != null) {
614                 // allow Guice to inject member fields
615                 runtimeManager.getInjector().injectMembers(plugin);
616             }
617
618             return plugin;
619         }
620     }
621
622     /**
623      * Instantiates an extension using Guice.
624      */
625     private class GuiceExtensionFactory implements ExtensionFactory {
626         @Override
627         public Object create(Class<?> extensionClass) {
628             // instantiate && inject the extension
629             logger.debug("Create instance for extension '{}'", extensionClass.getName());
630             try {
631                 return runtimeManager.getInjector().getInstance(extensionClass);
632             } catch (Exception e) {
633                 logger.error(e.getMessage(), e);
634             }
635             return null;
636         }
637     }
84f406 638 }