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.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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.MockSystemReader;
  75. import org.eclipse.jgit.junit.http.AppServer;
  76. import org.eclipse.jgit.lfs.errors.LfsException;
  77. import org.eclipse.jgit.lfs.lib.AnyLongObjectId;
  78. import org.eclipse.jgit.lfs.lib.Constants;
  79. import org.eclipse.jgit.lfs.lib.LongObjectId;
  80. import org.eclipse.jgit.lfs.server.LargeFileRepository;
  81. import org.eclipse.jgit.lfs.server.LfsProtocolServlet;
  82. import org.eclipse.jgit.lfs.test.LongObjectIdTestUtils;
  83. import org.eclipse.jgit.util.FS;
  84. import org.eclipse.jgit.util.FileUtils;
  85. import org.eclipse.jgit.util.IO;
  86. import org.eclipse.jgit.util.SystemReader;
  87. import org.junit.After;
  88. import org.junit.Before;
  89. public abstract class LfsServerTest {
  90. private static final long timeout = /* 10 sec */ 10 * 1000;
  91. protected static final int MiB = 1024 * 1024;
  92. /** In-memory application server; subclass must start. */
  93. protected AppServer server;
  94. private Path tmp;
  95. private Path dir;
  96. protected FileLfsRepository repository;
  97. protected FileLfsServlet servlet;
  98. public LfsServerTest() {
  99. super();
  100. }
  101. public Path getTempDirectory() {
  102. return tmp;
  103. }
  104. public Path getDir() {
  105. return dir;
  106. }
  107. @Before
  108. public void setup() throws Exception {
  109. SystemReader.setInstance(new MockSystemReader());
  110. tmp = Files.createTempDirectory("jgit_test_");
  111. // measure timer resolution before the test to avoid time critical tests
  112. // are affected by time needed for measurement
  113. FS.getFileStoreAttributes(tmp.getParent());
  114. server = new AppServer();
  115. ServletContextHandler app = server.addContext("/lfs");
  116. dir = Paths.get(tmp.toString(), "lfs");
  117. this.repository = new FileLfsRepository(null, dir);
  118. servlet = new FileLfsServlet(repository, timeout);
  119. app.addServlet(new ServletHolder(servlet), "/objects/*");
  120. LfsProtocolServlet protocol = new LfsProtocolServlet() {
  121. private static final long serialVersionUID = 1L;
  122. @Override
  123. protected LargeFileRepository getLargeFileRepository(
  124. LfsRequest request, String path, String auth)
  125. throws LfsException {
  126. return repository;
  127. }
  128. };
  129. app.addServlet(new ServletHolder(protocol), "/objects/batch");
  130. server.setUp();
  131. this.repository.setUrl(server.getURI() + "/lfs/objects/");
  132. }
  133. @After
  134. public void tearDown() throws Exception {
  135. server.tearDown();
  136. FileUtils.delete(tmp.toFile(), FileUtils.RECURSIVE | FileUtils.RETRY);
  137. }
  138. protected AnyLongObjectId putContent(String s)
  139. throws IOException, ClientProtocolException {
  140. AnyLongObjectId id = LongObjectIdTestUtils.hash(s);
  141. return putContent(id, s);
  142. }
  143. protected AnyLongObjectId putContent(AnyLongObjectId id, String s)
  144. throws ClientProtocolException, IOException {
  145. try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
  146. HttpEntity entity = new StringEntity(s,
  147. ContentType.APPLICATION_OCTET_STREAM);
  148. String hexId = id.name();
  149. HttpPut request = new HttpPut(
  150. server.getURI() + "/lfs/objects/" + hexId);
  151. request.setEntity(entity);
  152. try (CloseableHttpResponse response = client.execute(request)) {
  153. StatusLine statusLine = response.getStatusLine();
  154. int status = statusLine.getStatusCode();
  155. if (status >= 400) {
  156. throw new RuntimeException("Status: " + status + ". "
  157. + statusLine.getReasonPhrase());
  158. }
  159. }
  160. return id;
  161. }
  162. }
  163. protected LongObjectId putContent(Path f)
  164. throws FileNotFoundException, IOException {
  165. try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
  166. LongObjectId id1, id2;
  167. String hexId1, hexId2;
  168. try (DigestInputStream in = new DigestInputStream(
  169. new BufferedInputStream(Files.newInputStream(f)),
  170. Constants.newMessageDigest())) {
  171. InputStreamEntity entity = new InputStreamEntity(in,
  172. Files.size(f), ContentType.APPLICATION_OCTET_STREAM);
  173. id1 = LongObjectIdTestUtils.hash(f);
  174. hexId1 = id1.name();
  175. HttpPut request = new HttpPut(
  176. server.getURI() + "/lfs/objects/" + hexId1);
  177. request.setEntity(entity);
  178. HttpResponse response = client.execute(request);
  179. checkResponseStatus(response);
  180. id2 = LongObjectId.fromRaw(in.getMessageDigest().digest());
  181. hexId2 = id2.name();
  182. assertEquals(hexId1, hexId2);
  183. }
  184. return id1;
  185. }
  186. }
  187. private void checkResponseStatus(HttpResponse response) {
  188. StatusLine statusLine = response.getStatusLine();
  189. int status = statusLine.getStatusCode();
  190. if (statusLine.getStatusCode() >= 400) {
  191. String error;
  192. try {
  193. ByteBuffer buf = IO.readWholeStream(new BufferedInputStream(
  194. response.getEntity().getContent()), 1024);
  195. if (buf.hasArray()) {
  196. error = new String(buf.array(),
  197. buf.arrayOffset() + buf.position(), buf.remaining(),
  198. UTF_8);
  199. } else {
  200. final byte[] b = new byte[buf.remaining()];
  201. buf.duplicate().get(b);
  202. error = new String(b, UTF_8);
  203. }
  204. } catch (IOException e) {
  205. error = statusLine.getReasonPhrase();
  206. }
  207. throw new RuntimeException("Status: " + status + " " + error);
  208. }
  209. assertEquals(200, status);
  210. }
  211. protected long getContent(AnyLongObjectId id, Path f) throws IOException {
  212. String hexId = id.name();
  213. return getContent(hexId, f);
  214. }
  215. protected long getContent(String hexId, Path f) throws IOException {
  216. try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
  217. HttpGet request = new HttpGet(
  218. server.getURI() + "/lfs/objects/" + hexId);
  219. HttpResponse response = client.execute(request);
  220. checkResponseStatus(response);
  221. HttpEntity entity = response.getEntity();
  222. long pos = 0;
  223. try (InputStream in = entity.getContent();
  224. ReadableByteChannel inChannel = Channels.newChannel(in);
  225. FileChannel outChannel = FileChannel.open(f,
  226. StandardOpenOption.CREATE_NEW,
  227. StandardOpenOption.WRITE)) {
  228. long transferred;
  229. do {
  230. transferred = outChannel.transferFrom(inChannel, pos, MiB);
  231. pos += transferred;
  232. } while (transferred > 0);
  233. }
  234. return pos;
  235. }
  236. }
  237. /**
  238. * Creates a file with random content, repeatedly writing a random string of
  239. * 4k length to the file until the file has at least the specified length.
  240. *
  241. * @param f
  242. * file to fill
  243. * @param size
  244. * size of the file to generate
  245. * @return length of the generated file in bytes
  246. * @throws IOException
  247. */
  248. protected long createPseudoRandomContentFile(Path f, long size)
  249. throws IOException {
  250. SecureRandom rnd = new SecureRandom();
  251. byte[] buf = new byte[4096];
  252. rnd.nextBytes(buf);
  253. ByteBuffer bytebuf = ByteBuffer.wrap(buf);
  254. try (FileChannel outChannel = FileChannel.open(f,
  255. StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) {
  256. long len = 0;
  257. do {
  258. len += outChannel.write(bytebuf);
  259. if (bytebuf.position() == 4096) {
  260. bytebuf.rewind();
  261. }
  262. } while (len < size);
  263. }
  264. return Files.size(f);
  265. }
  266. }