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 16KB

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