ProtoCommon.java 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. /**
  2. * Copyright (C) 2008 Happy Fish / YuQing
  3. * <p>
  4. * FastDFS Java Client may be copied only under the terms of the GNU Lesser
  5. * General Public License (LGPL).
  6. * Please visit the FastDFS Home Page http://www.csource.org/ for more detail.
  7. **/
  8. package com.kmall.common.fileserver.fastdfs;
  9. import com.kmall.common.fileserver.common.MyException;
  10. import com.kmall.common.fileserver.common.NameValuePair;
  11. import java.io.IOException;
  12. import java.io.InputStream;
  13. import java.io.UnsupportedEncodingException;
  14. import java.net.Socket;
  15. import java.security.NoSuchAlgorithmException;
  16. import java.util.Arrays;
  17. /**
  18. * protocol common functions
  19. *
  20. * @author Happy Fish / YuQing
  21. * @version Version 1.18
  22. */
  23. public class ProtoCommon {
  24. public static final byte FDFS_PROTO_CMD_QUIT = 82;
  25. public static final byte TRACKER_PROTO_CMD_SERVER_LIST_GROUP = 91;
  26. public static final byte TRACKER_PROTO_CMD_SERVER_LIST_STORAGE = 92;
  27. public static final byte TRACKER_PROTO_CMD_SERVER_DELETE_STORAGE = 93;
  28. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_STORE_WITHOUT_GROUP_ONE = 101;
  29. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_FETCH_ONE = 102;
  30. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_UPDATE = 103;
  31. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_STORE_WITH_GROUP_ONE = 104;
  32. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_FETCH_ALL = 105;
  33. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_STORE_WITHOUT_GROUP_ALL = 106;
  34. public static final byte TRACKER_PROTO_CMD_SERVICE_QUERY_STORE_WITH_GROUP_ALL = 107;
  35. public static final byte TRACKER_PROTO_CMD_RESP = 100;
  36. public static final byte FDFS_PROTO_CMD_ACTIVE_TEST = 111;
  37. public static final byte STORAGE_PROTO_CMD_UPLOAD_FILE = 11;
  38. public static final byte STORAGE_PROTO_CMD_DELETE_FILE = 12;
  39. public static final byte STORAGE_PROTO_CMD_SET_METADATA = 13;
  40. public static final byte STORAGE_PROTO_CMD_DOWNLOAD_FILE = 14;
  41. public static final byte STORAGE_PROTO_CMD_GET_METADATA = 15;
  42. public static final byte STORAGE_PROTO_CMD_UPLOAD_SLAVE_FILE = 21;
  43. public static final byte STORAGE_PROTO_CMD_QUERY_FILE_INFO = 22;
  44. public static final byte STORAGE_PROTO_CMD_UPLOAD_APPENDER_FILE = 23; //create appender file
  45. public static final byte STORAGE_PROTO_CMD_APPEND_FILE = 24; //append file
  46. public static final byte STORAGE_PROTO_CMD_MODIFY_FILE = 34; //modify appender file
  47. public static final byte STORAGE_PROTO_CMD_TRUNCATE_FILE = 36; //truncate appender file
  48. public static final byte STORAGE_PROTO_CMD_RESP = TRACKER_PROTO_CMD_RESP;
  49. public static final byte FDFS_STORAGE_STATUS_INIT = 0;
  50. public static final byte FDFS_STORAGE_STATUS_WAIT_SYNC = 1;
  51. public static final byte FDFS_STORAGE_STATUS_SYNCING = 2;
  52. public static final byte FDFS_STORAGE_STATUS_IP_CHANGED = 3;
  53. public static final byte FDFS_STORAGE_STATUS_DELETED = 4;
  54. public static final byte FDFS_STORAGE_STATUS_OFFLINE = 5;
  55. public static final byte FDFS_STORAGE_STATUS_ONLINE = 6;
  56. public static final byte FDFS_STORAGE_STATUS_ACTIVE = 7;
  57. public static final byte FDFS_STORAGE_STATUS_NONE = 99;
  58. /**
  59. * for overwrite all old metadata
  60. */
  61. public static final byte STORAGE_SET_METADATA_FLAG_OVERWRITE = 'O';
  62. /**
  63. * for replace, insert when the meta item not exist, otherwise update it
  64. */
  65. public static final byte STORAGE_SET_METADATA_FLAG_MERGE = 'M';
  66. public static final int FDFS_PROTO_PKG_LEN_SIZE = 8;
  67. public static final int FDFS_PROTO_CMD_SIZE = 1;
  68. public static final int FDFS_GROUP_NAME_MAX_LEN = 16;
  69. public static final int FDFS_IPADDR_SIZE = 16;
  70. public static final int FDFS_DOMAIN_NAME_MAX_SIZE = 128;
  71. public static final int FDFS_VERSION_SIZE = 6;
  72. public static final int FDFS_STORAGE_ID_MAX_SIZE = 16;
  73. public static final String FDFS_RECORD_SEPERATOR = "\u0001";
  74. public static final String FDFS_FIELD_SEPERATOR = "\u0002";
  75. public static final int TRACKER_QUERY_STORAGE_FETCH_BODY_LEN = FDFS_GROUP_NAME_MAX_LEN
  76. + FDFS_IPADDR_SIZE - 1 + FDFS_PROTO_PKG_LEN_SIZE;
  77. public static final int TRACKER_QUERY_STORAGE_STORE_BODY_LEN = FDFS_GROUP_NAME_MAX_LEN
  78. + FDFS_IPADDR_SIZE + FDFS_PROTO_PKG_LEN_SIZE;
  79. public static final byte FDFS_FILE_EXT_NAME_MAX_LEN = 6;
  80. public static final byte FDFS_FILE_PREFIX_MAX_LEN = 16;
  81. public static final byte FDFS_FILE_PATH_LEN = 10;
  82. public static final byte FDFS_FILENAME_BASE64_LENGTH = 27;
  83. public static final byte FDFS_TRUNK_FILE_INFO_LEN = 16;
  84. public static final byte ERR_NO_ENOENT = 2;
  85. public static final byte ERR_NO_EIO = 5;
  86. public static final byte ERR_NO_EBUSY = 16;
  87. public static final byte ERR_NO_EINVAL = 22;
  88. public static final byte ERR_NO_ENOSPC = 28;
  89. public static final byte ECONNREFUSED = 61;
  90. public static final byte ERR_NO_EALREADY = 114;
  91. public static final long INFINITE_FILE_SIZE = 256 * 1024L * 1024 * 1024 * 1024 * 1024L;
  92. public static final long APPENDER_FILE_SIZE = INFINITE_FILE_SIZE;
  93. public static final long TRUNK_FILE_MARK_SIZE = 512 * 1024L * 1024 * 1024 * 1024 * 1024L;
  94. public static final long NORMAL_LOGIC_FILENAME_LENGTH = FDFS_FILE_PATH_LEN + FDFS_FILENAME_BASE64_LENGTH + FDFS_FILE_EXT_NAME_MAX_LEN + 1;
  95. public static final long TRUNK_LOGIC_FILENAME_LENGTH = NORMAL_LOGIC_FILENAME_LENGTH + FDFS_TRUNK_FILE_INFO_LEN;
  96. protected static final int PROTO_HEADER_CMD_INDEX = FDFS_PROTO_PKG_LEN_SIZE;
  97. protected static final int PROTO_HEADER_STATUS_INDEX = FDFS_PROTO_PKG_LEN_SIZE + 1;
  98. private ProtoCommon() {
  99. }
  100. public static String getStorageStatusCaption(byte status) {
  101. switch (status) {
  102. case FDFS_STORAGE_STATUS_INIT:
  103. return "INIT";
  104. case FDFS_STORAGE_STATUS_WAIT_SYNC:
  105. return "WAIT_SYNC";
  106. case FDFS_STORAGE_STATUS_SYNCING:
  107. return "SYNCING";
  108. case FDFS_STORAGE_STATUS_IP_CHANGED:
  109. return "IP_CHANGED";
  110. case FDFS_STORAGE_STATUS_DELETED:
  111. return "DELETED";
  112. case FDFS_STORAGE_STATUS_OFFLINE:
  113. return "OFFLINE";
  114. case FDFS_STORAGE_STATUS_ONLINE:
  115. return "ONLINE";
  116. case FDFS_STORAGE_STATUS_ACTIVE:
  117. return "ACTIVE";
  118. case FDFS_STORAGE_STATUS_NONE:
  119. return "NONE";
  120. default:
  121. return "UNKOWN";
  122. }
  123. }
  124. /**
  125. * pack header by FastDFS transfer protocol
  126. *
  127. * @param cmd which command to send
  128. * @param pkg_len package body length
  129. * @param errno status code, should be (byte)0
  130. * @return packed byte buffer
  131. */
  132. public static byte[] packHeader(byte cmd, long pkg_len, byte errno) throws UnsupportedEncodingException {
  133. byte[] header;
  134. byte[] hex_len;
  135. header = new byte[FDFS_PROTO_PKG_LEN_SIZE + 2];
  136. Arrays.fill(header, (byte) 0);
  137. hex_len = ProtoCommon.long2buff(pkg_len);
  138. System.arraycopy(hex_len, 0, header, 0, hex_len.length);
  139. header[PROTO_HEADER_CMD_INDEX] = cmd;
  140. header[PROTO_HEADER_STATUS_INDEX] = errno;
  141. return header;
  142. }
  143. /**
  144. * receive pack header
  145. *
  146. * @param in input stream
  147. * @param expect_cmd expect response command
  148. * @param expect_body_len expect response package body length
  149. * @return RecvHeaderInfo: errno and pkg body length
  150. */
  151. public static RecvHeaderInfo recvHeader(InputStream in, byte expect_cmd, long expect_body_len) throws IOException {
  152. byte[] header;
  153. int bytes;
  154. long pkg_len;
  155. header = new byte[FDFS_PROTO_PKG_LEN_SIZE + 2];
  156. if ((bytes = in.read(header)) != header.length) {
  157. throw new IOException("recv package size " + bytes + " != " + header.length);
  158. }
  159. if (header[PROTO_HEADER_CMD_INDEX] != expect_cmd) {
  160. throw new IOException("recv cmd: " + header[PROTO_HEADER_CMD_INDEX] + " is not correct, expect cmd: " + expect_cmd);
  161. }
  162. if (header[PROTO_HEADER_STATUS_INDEX] != 0) {
  163. return new RecvHeaderInfo(header[PROTO_HEADER_STATUS_INDEX], 0);
  164. }
  165. pkg_len = ProtoCommon.buff2long(header, 0);
  166. if (pkg_len < 0) {
  167. throw new IOException("recv body length: " + pkg_len + " < 0!");
  168. }
  169. if (expect_body_len >= 0 && pkg_len != expect_body_len) {
  170. throw new IOException("recv body length: " + pkg_len + " is not correct, expect length: " + expect_body_len);
  171. }
  172. return new RecvHeaderInfo((byte) 0, pkg_len);
  173. }
  174. /**
  175. * receive whole pack
  176. *
  177. * @param in input stream
  178. * @param expect_cmd expect response command
  179. * @param expect_body_len expect response package body length
  180. * @return RecvPackageInfo: errno and reponse body(byte buff)
  181. */
  182. public static RecvPackageInfo recvPackage(InputStream in, byte expect_cmd, long expect_body_len) throws IOException {
  183. RecvHeaderInfo header = recvHeader(in, expect_cmd, expect_body_len);
  184. if (header.errno != 0) {
  185. return new RecvPackageInfo(header.errno, null);
  186. }
  187. byte[] body = new byte[(int) header.body_len];
  188. int totalBytes = 0;
  189. int remainBytes = (int) header.body_len;
  190. int bytes;
  191. while (totalBytes < header.body_len) {
  192. if ((bytes = in.read(body, totalBytes, remainBytes)) < 0) {
  193. break;
  194. }
  195. totalBytes += bytes;
  196. remainBytes -= bytes;
  197. }
  198. if (totalBytes != header.body_len) {
  199. throw new IOException("recv package size " + totalBytes + " != " + header.body_len);
  200. }
  201. return new RecvPackageInfo((byte) 0, body);
  202. }
  203. /**
  204. * split metadata to name value pair array
  205. *
  206. * @param meta_buff metadata
  207. * @return name value pair array
  208. */
  209. public static NameValuePair[] split_metadata(String meta_buff) {
  210. return split_metadata(meta_buff, FDFS_RECORD_SEPERATOR, FDFS_FIELD_SEPERATOR);
  211. }
  212. /**
  213. * split metadata to name value pair array
  214. *
  215. * @param meta_buff metadata
  216. * @param recordSeperator record/row seperator
  217. * @param filedSeperator field/column seperator
  218. * @return name value pair array
  219. */
  220. public static NameValuePair[] split_metadata(String meta_buff,
  221. String recordSeperator, String filedSeperator) {
  222. String[] rows;
  223. String[] cols;
  224. NameValuePair[] meta_list;
  225. rows = meta_buff.split(recordSeperator);
  226. meta_list = new NameValuePair[rows.length];
  227. for (int i = 0; i < rows.length; i++) {
  228. cols = rows[i].split(filedSeperator, 2);
  229. meta_list[i] = new NameValuePair(cols[0]);
  230. if (cols.length == 2) {
  231. meta_list[i].setValue(cols[1]);
  232. }
  233. }
  234. return meta_list;
  235. }
  236. /**
  237. * pack metadata array to string
  238. *
  239. * @param meta_list metadata array
  240. * @return packed metadata
  241. */
  242. public static String pack_metadata(NameValuePair[] meta_list) {
  243. if (meta_list.length == 0) {
  244. return "";
  245. }
  246. StringBuffer sb = new StringBuffer(32 * meta_list.length);
  247. sb.append(meta_list[0].getName()).append(FDFS_FIELD_SEPERATOR).append(meta_list[0].getValue());
  248. for (int i = 1; i < meta_list.length; i++) {
  249. sb.append(FDFS_RECORD_SEPERATOR);
  250. sb.append(meta_list[i].getName()).append(FDFS_FIELD_SEPERATOR).append(meta_list[i].getValue());
  251. }
  252. return sb.toString();
  253. }
  254. /**
  255. * send quit command to server and close socket
  256. *
  257. * @param sock the Socket object
  258. */
  259. public static void closeSocket(Socket sock) throws IOException {
  260. byte[] header;
  261. header = packHeader(FDFS_PROTO_CMD_QUIT, 0, (byte) 0);
  262. sock.getOutputStream().write(header);
  263. sock.close();
  264. }
  265. /**
  266. * send ACTIVE_TEST command to server, test if network is ok and the server is alive
  267. *
  268. * @param sock the Socket object
  269. */
  270. public static boolean activeTest(Socket sock) throws IOException {
  271. byte[] header;
  272. header = packHeader(FDFS_PROTO_CMD_ACTIVE_TEST, 0, (byte) 0);
  273. sock.getOutputStream().write(header);
  274. RecvHeaderInfo headerInfo = recvHeader(sock.getInputStream(), TRACKER_PROTO_CMD_RESP, 0);
  275. return headerInfo.errno == 0 ? true : false;
  276. }
  277. /**
  278. * long convert to buff (big-endian)
  279. *
  280. * @param n long number
  281. * @return 8 bytes buff
  282. */
  283. public static byte[] long2buff(long n) {
  284. byte[] bs;
  285. bs = new byte[8];
  286. bs[0] = (byte) ((n >> 56) & 0xFF);
  287. bs[1] = (byte) ((n >> 48) & 0xFF);
  288. bs[2] = (byte) ((n >> 40) & 0xFF);
  289. bs[3] = (byte) ((n >> 32) & 0xFF);
  290. bs[4] = (byte) ((n >> 24) & 0xFF);
  291. bs[5] = (byte) ((n >> 16) & 0xFF);
  292. bs[6] = (byte) ((n >> 8) & 0xFF);
  293. bs[7] = (byte) (n & 0xFF);
  294. return bs;
  295. }
  296. /**
  297. * buff convert to long
  298. *
  299. * @param bs the buffer (big-endian)
  300. * @param offset the start position based 0
  301. * @return long number
  302. */
  303. public static long buff2long(byte[] bs, int offset) {
  304. return (((long) (bs[offset] >= 0 ? bs[offset] : 256 + bs[offset])) << 56) |
  305. (((long) (bs[offset + 1] >= 0 ? bs[offset + 1] : 256 + bs[offset + 1])) << 48) |
  306. (((long) (bs[offset + 2] >= 0 ? bs[offset + 2] : 256 + bs[offset + 2])) << 40) |
  307. (((long) (bs[offset + 3] >= 0 ? bs[offset + 3] : 256 + bs[offset + 3])) << 32) |
  308. (((long) (bs[offset + 4] >= 0 ? bs[offset + 4] : 256 + bs[offset + 4])) << 24) |
  309. (((long) (bs[offset + 5] >= 0 ? bs[offset + 5] : 256 + bs[offset + 5])) << 16) |
  310. (((long) (bs[offset + 6] >= 0 ? bs[offset + 6] : 256 + bs[offset + 6])) << 8) |
  311. ((long) (bs[offset + 7] >= 0 ? bs[offset + 7] : 256 + bs[offset + 7]));
  312. }
  313. /**
  314. * buff convert to int
  315. *
  316. * @param bs the buffer (big-endian)
  317. * @param offset the start position based 0
  318. * @return int number
  319. */
  320. public static int buff2int(byte[] bs, int offset) {
  321. return (((int) (bs[offset] >= 0 ? bs[offset] : 256 + bs[offset])) << 24) |
  322. (((int) (bs[offset + 1] >= 0 ? bs[offset + 1] : 256 + bs[offset + 1])) << 16) |
  323. (((int) (bs[offset + 2] >= 0 ? bs[offset + 2] : 256 + bs[offset + 2])) << 8) |
  324. ((int) (bs[offset + 3] >= 0 ? bs[offset + 3] : 256 + bs[offset + 3]));
  325. }
  326. /**
  327. * buff convert to ip address
  328. *
  329. * @param bs the buffer (big-endian)
  330. * @param offset the start position based 0
  331. * @return ip address
  332. */
  333. public static String getIpAddress(byte[] bs, int offset) {
  334. if (bs[0] == 0 || bs[3] == 0) //storage server ID
  335. {
  336. return "";
  337. }
  338. int n;
  339. StringBuilder sbResult = new StringBuilder(16);
  340. for (int i = offset; i < offset + 4; i++) {
  341. n = (bs[i] >= 0) ? bs[i] : 256 + bs[i];
  342. if (sbResult.length() > 0) {
  343. sbResult.append(".");
  344. }
  345. sbResult.append(String.valueOf(n));
  346. }
  347. return sbResult.toString();
  348. }
  349. /**
  350. * md5 function
  351. *
  352. * @param source the input buffer
  353. * @return md5 string
  354. */
  355. public static String md5(byte[] source) throws NoSuchAlgorithmException {
  356. char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
  357. java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
  358. md.update(source);
  359. byte tmp[] = md.digest();
  360. char str[] = new char[32];
  361. int k = 0;
  362. for (int i = 0; i < 16; i++) {
  363. str[k++] = hexDigits[tmp[i] >>> 4 & 0xf];
  364. str[k++] = hexDigits[tmp[i] & 0xf];
  365. }
  366. return new String(str);
  367. }
  368. /**
  369. * get token for file URL
  370. *
  371. * @param remote_filename the filename return by FastDFS server
  372. * @param ts unix timestamp, unit: second
  373. * @param secret_key the secret key
  374. * @return token string
  375. */
  376. public static String getToken(String remote_filename, int ts, String secret_key) throws UnsupportedEncodingException, NoSuchAlgorithmException, MyException {
  377. byte[] bsFilename = remote_filename.getBytes(ClientGlobal.g_charset);
  378. byte[] bsKey = secret_key.getBytes(ClientGlobal.g_charset);
  379. byte[] bsTimestamp = (new Integer(ts)).toString().getBytes(ClientGlobal.g_charset);
  380. byte[] buff = new byte[bsFilename.length + bsKey.length + bsTimestamp.length];
  381. System.arraycopy(bsFilename, 0, buff, 0, bsFilename.length);
  382. System.arraycopy(bsKey, 0, buff, bsFilename.length, bsKey.length);
  383. System.arraycopy(bsTimestamp, 0, buff, bsFilename.length + bsKey.length, bsTimestamp.length);
  384. return md5(buff);
  385. }
  386. /**
  387. * generate slave filename
  388. *
  389. * @param master_filename the master filename to generate the slave filename
  390. * @param prefix_name the prefix name to generate the slave filename
  391. * @param ext_name the extension name of slave filename, null for same as the master extension name
  392. * @return slave filename string
  393. */
  394. public static String genSlaveFilename(String master_filename,
  395. String prefix_name, String ext_name) throws MyException {
  396. String true_ext_name;
  397. int dotIndex;
  398. if (master_filename.length() < 28 + FDFS_FILE_EXT_NAME_MAX_LEN) {
  399. throw new MyException("master filename \"" + master_filename + "\" is invalid");
  400. }
  401. dotIndex = master_filename.indexOf('.', master_filename.length() - (FDFS_FILE_EXT_NAME_MAX_LEN + 1));
  402. if (ext_name != null) {
  403. if (ext_name.length() == 0) {
  404. true_ext_name = "";
  405. } else if (ext_name.charAt(0) == '.') {
  406. true_ext_name = ext_name;
  407. } else {
  408. true_ext_name = "." + ext_name;
  409. }
  410. } else {
  411. if (dotIndex < 0) {
  412. true_ext_name = "";
  413. } else {
  414. true_ext_name = master_filename.substring(dotIndex);
  415. }
  416. }
  417. if (true_ext_name.length() == 0 && prefix_name.equals("-m")) {
  418. throw new MyException("prefix_name \"" + prefix_name + "\" is invalid");
  419. }
  420. if (dotIndex < 0) {
  421. return master_filename + prefix_name + true_ext_name;
  422. } else {
  423. return master_filename.substring(0, dotIndex) + prefix_name + true_ext_name;
  424. }
  425. }
  426. /**
  427. * receive package info
  428. */
  429. public static class RecvPackageInfo {
  430. public byte errno;
  431. public byte[] body;
  432. public RecvPackageInfo(byte errno, byte[] body) {
  433. this.errno = errno;
  434. this.body = body;
  435. }
  436. }
  437. /**
  438. * receive header info
  439. */
  440. public static class RecvHeaderInfo {
  441. public byte errno;
  442. public long body_len;
  443. public RecvHeaderInfo(byte errno, long body_len) {
  444. this.errno = errno;
  445. this.body_len = body_len;
  446. }
  447. }
  448. }