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.

LfsServerTest.java 9.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /*
  2. * Copyright (C) 2015, Matthias Sohn <matthias.sohn@sap.com>
  3. * and other copyright owners as documented in the project's IP log.
  4. *
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Distribution License v1.0 which
  7. * accompanies this distribution, is reproduced below, and is
  8. * available at http://www.eclipse.org/org/documents/edl-v10.php
  9. *
  10. * All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or
  13. * without modification, are permitted provided that the following
  14. * conditions are met:
  15. *
  16. * - Redistributions of source code must retain the above copyright
  17. * notice, this list of conditions and the following disclaimer.
  18. *
  19. * - Redistributions in binary form must reproduce the above
  20. * copyright notice, this list of conditions and the following
  21. * disclaimer in the documentation and/or other materials provided
  22. * with the distribution.
  23. *
  24. * - Neither the name of the Eclipse Foundation, Inc. nor the
  25. * names of its contributors may be used to endorse or promote
  26. * products derived from this software without specific prior
  27. * written permission.
  28. *
  29. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  30. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  31. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  32. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  33. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  35. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  36. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  37. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  38. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  39. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  41. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  42. */
  43. package org.eclipse.jgit.lfs.server.fs;
  44. import static java.nio.charset.StandardCharsets.UTF_8;
  45. import static org.junit.Assert.assertEquals;
  46. import java.io.BufferedInputStream;
  47. import java.io.FileNotFoundException;
  48. import java.io.IOException;
  49. import java.io.InputStream;
  50. import java.nio.ByteBuffer;
  51. import java.nio.channels.Channels;
  52. import java.nio.channels.FileChannel;
  53. import java.nio.channels.ReadableByteChannel;
  54. import java.nio.file.Files;
  55. import java.nio.file.Path;
  56. import java.nio.file.Paths;
  57. import java.nio.file.StandardOpenOption;
  58. import java.security.DigestInputStream;
  59. import java.security.SecureRandom;
  60. import org.apache.http.HttpEntity;
  61. import org.apache.http.HttpResponse;
  62. import org.apache.http.StatusLine;
  63. import org.apache.http.client.ClientProtocolException;
  64. import org.apache.http.client.methods.CloseableHttpResponse;
  65. import org.apache.http.client.methods.HttpGet;
  66. import org.apache.http.client.methods.HttpPut;
  67. import org.apache.http.entity.ContentType;
  68. import org.apache.http.entity.InputStreamEntity;
  69. import org.apache.http.entity.StringEntity;
  70. import org.apache.http.impl.client.CloseableHttpClient;
  71. import org.apache.http.impl.client.HttpClientBuilder;
  72. import org.eclipse.jetty.servlet.ServletContextHandler;
  73. import org.eclipse.jetty.servlet.ServletHolder;
  74. import org.eclipse.jgit.junit.http.AppServer;
  75. import org.eclipse.jgit.lfs.errors.LfsException;
  76. import org.eclipse.jgit.lfs.lib.AnyLongObjectId;
  77. import org.eclipse.jgit.lfs.lib.Constants;
  78. import org.eclipse.jgit.lfs.lib.LongObjectId;
  79. import org.eclipse.jgit.lfs.server.LargeFileRepository;
  80. import org.eclipse.jgit.lfs.server.LfsProtocolServlet;
  81. import org.eclipse.jgit.lfs.test.LongObjectIdTestUtils;
  82. import org.eclipse.jgit.util.FS;
  83. import org.eclipse.jgit.util.FileUtils;
  84. import org.eclipse.jgit.util.IO;
  85. import org.junit.After;
  86. import org.junit.Before;
  87. public abstract class LfsServerTest {
  88. private static final long timeout = /* 10 sec */ 10 * 1000;
  89. protected static final int MiB = 1024 * 1024;
  90. /** In-memory application server; subclass must start. */
  91. protected AppServer server;
  92. private Path tmp;
  93. private Path dir;
  94. protected FileLfsRepository repository;
  95. protected FileLfsServlet servlet;
  96. public LfsServerTest() {
  97. super();
  98. }
  99. public Path getTempDirectory() {
  100. return tmp;
  101. }
  102. public Path getDir() {
  103. return dir;
  104. }
  105. @Before
  106. public void setup() throws Exception {
  107. tmp = Files.createTempDirectory("jgit_test_");
  108. // measure timer resolution before the test to avoid time critical tests
  109. // are affected by time needed for measurement
  110. FS.getFileStoreAttributes(tmp.getParent());
  111. server = new AppServer();
  112. ServletContextHandler app = server.addContext("/lfs");
  113. dir = Paths.get(tmp.toString(), "lfs");
  114. this.repository = new FileLfsRepository(null, dir);
  115. servlet = new FileLfsServlet(repository, timeout);
  116. app.addServlet(new ServletHolder(servlet), "/objects/*");
  117. LfsProtocolServlet protocol = new LfsProtocolServlet() {
  118. private static final long serialVersionUID = 1L;
  119. @Override
  120. protected LargeFileRepository getLargeFileRepository(
  121. LfsRequest request, String path, String auth)
  122. throws LfsException {
  123. return repository;
  124. }
  125. };
  126. app.addServlet(new ServletHolder(protocol), "/objects/batch");
  127. server.setUp();
  128. this.repository.setUrl(server.getURI() + "/lfs/objects/");
  129. }
  130. @After
  131. public void tearDown() throws Exception {
  132. server.tearDown();
  133. FileUtils.delete(tmp.toFile(), FileUtils.RECURSIVE | FileUtils.RETRY);
  134. }
  135. protected AnyLongObjectId putContent(String s)
  136. throws IOException, ClientProtocolException {
  137. AnyLongObjectId id = LongObjectIdTestUtils.hash(s);
  138. return putContent(id, s);
  139. }
  140. protected AnyLongObjectId putContent(AnyLongObjectId id, String s)
  141. throws ClientProtocolException, IOException {
  142. try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
  143. HttpEntity entity = new StringEntity(s,
  144. ContentType.APPLICATION_OCTET_STREAM);
  145. String hexId = id.name();
  146. HttpPut request = new HttpPut(
  147. server.getURI() + "/lfs/objects/" + hexId);
  148. request.setEntity(entity);
  149. try (CloseableHttpResponse response = client.execute(request)) {
  150. StatusLine statusLine = response.getStatusLine();
  151. int status = statusLine.getStatusCode();
  152. if (status >= 400) {
  153. throw new RuntimeException("Status: " + status + ". "
  154. + statusLine.getReasonPhrase());
  155. }
  156. }
  157. return id;
  158. }
  159. }
  160. protected LongObjectId putContent(Path f)
  161. throws FileNotFoundException, IOException {
  162. try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
  163. LongObjectId id1, id2;
  164. String hexId1, hexId2;
  165. try (DigestInputStream in = new DigestInputStream(
  166. new BufferedInputStream(Files.newInputStream(f)),
  167. Constants.newMessageDigest())) {
  168. InputStreamEntity entity = new InputStreamEntity(in,
  169. Files.size(f), ContentType.APPLICATION_OCTET_STREAM);
  170. id1 = LongObjectIdTestUtils.hash(f);
  171. hexId1 = id1.name();
  172. HttpPut request = new HttpPut(
  173. server.getURI() + "/lfs/objects/" + hexId1);
  174. request.setEntity(entity);
  175. HttpResponse response = client.execute(request);
  176. checkResponseStatus(response);
  177. id2 = LongObjectId.fromRaw(in.getMessageDigest().digest());
  178. hexId2 = id2.name();
  179. assertEquals(hexId1, hexId2);
  180. }
  181. return id1;
  182. }
  183. }
  184. private void checkResponseStatus(HttpResponse response) {
  185. StatusLine statusLine = response.getStatusLine();
  186. int status = statusLine.getStatusCode();
  187. if (statusLine.getStatusCode() >= 400) {
  188. String error;
  189. try {
  190. ByteBuffer buf = IO.readWholeStream(new BufferedInputStream(
  191. response.getEntity().getContent()), 1024);
  192. if (buf.hasArray()) {
  193. error = new String(buf.array(),
  194. buf.arrayOffset() + buf.position(), buf.remaining(),
  195. UTF_8);
  196. } else {
  197. final byte[] b = new byte[buf.remaining()];
  198. buf.duplicate().get(b);
  199. error = new String(b, UTF_8);
  200. }
  201. } catch (IOException e) {
  202. error = statusLine.getReasonPhrase();
  203. }
  204. throw new RuntimeException("Status: " + status + " " + error);
  205. }
  206. assertEquals(200, status);
  207. }
  208. protected long getContent(AnyLongObjectId id, Path f) throws IOException {
  209. String hexId = id.name();
  210. return getContent(hexId, f);
  211. }
  212. protected long getContent(String hexId, Path f) throws IOException {
  213. try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
  214. HttpGet request = new HttpGet(
  215. server.getURI() + "/lfs/objects/" + hexId);
  216. HttpResponse response = client.execute(request);
  217. checkResponseStatus(response);
  218. HttpEntity entity = response.getEntity();
  219. long pos = 0;
  220. try (InputStream in = entity.getContent();
  221. ReadableByteChannel inChannel = Channels.newChannel(in);
  222. FileChannel outChannel = FileChannel.open(f,
  223. StandardOpenOption.CREATE_NEW,
  224. StandardOpenOption.WRITE)) {
  225. long transferred;
  226. do {
  227. transferred = outChannel.transferFrom(inChannel, pos, MiB);
  228. pos += transferred;
  229. } while (transferred > 0);
  230. }
  231. return pos;
  232. }
  233. }
  234. /**
  235. * Creates a file with random content, repeatedly writing a random string of
  236. * 4k length to the file until the file has at least the specified length.
  237. *
  238. * @param f
  239. * file to fill
  240. * @param size
  241. * size of the file to generate
  242. * @return length of the generated file in bytes
  243. * @throws IOException
  244. */
  245. protected long createPseudoRandomContentFile(Path f, long size)
  246. throws IOException {
  247. SecureRandom rnd = new SecureRandom();
  248. byte[] buf = new byte[4096];
  249. rnd.nextBytes(buf);
  250. ByteBuffer bytebuf = ByteBuffer.wrap(buf);
  251. try (FileChannel outChannel = FileChannel.open(f,
  252. StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) {
  253. long len = 0;
  254. do {
  255. len += outChannel.write(bytebuf);
  256. if (bytebuf.position() == 4096) {
  257. bytebuf.rewind();
  258. }
  259. } while (len < size);
  260. }
  261. return Files.size(f);
  262. }
  263. }