You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PluginManager.java 18KB

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