MCC/b2uploader: b2uploader - backup to server - SVN.BY: Go Git Service

b2uploader - backup to server

Program.cs 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. using B2Classes;
  2. using CommandLine;
  3. using Newtonsoft.Json;
  4. using NLog;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Security.Cryptography;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace B2Uploader
  16. {
  17. class CmdLineOptions
  18. {
  19. [Option('i', "accountid", HelpText = "Account ID", Required=true)]
  20. public string AccountId { get; set; }
  21. [Option('a', "appkey", HelpText = "Application Key", Required=true)]
  22. public string ApplicationKey { get; set; }
  23. [Option('d', "directory", HelpText = "Directory you want to upload", Required = true)]
  24. public string Directory { get; set; }
  25. [Option('m', "multithreads", HelpText = "Number of uploads you want to use at a time. Default is 2", Required = false)]
  26. public int Threads { get; set; }
  27. [Option('r', "recursive", HelpText = "Uploads the directory in Recursive mode. Any sub folders will also be uploaded", Required = false)]
  28. public bool recursive { get; set; }
  29. [Option('v', "verbose", HelpText="Verbose Output")]
  30. public bool Verbose{get;set;}
  31. }
  32. class Program
  33. {
  34. static Logger logger = LogManager.GetCurrentClassLogger();
  35. static void Main(string[] args)
  36. {
  37. var result = CommandLine.Parser.Default.ParseArguments<CmdLineOptions>(args);
  38. var existCode = result.MapResult(options => {
  39. if (!Directory.Exists(options.Directory))
  40. {
  41. Console.WriteLine("Directory to upload MUST EXIST!");
  42. return 0;
  43. }
  44. if (options.Verbose)
  45. {
  46. logger.Debug("Authorizing User");
  47. }
  48. var auth = AuthorizeUser(options.AccountId, options.ApplicationKey);
  49. if (options.Verbose)
  50. {
  51. logger.Debug("Listing Buckets");
  52. }
  53. var buckets = ListBuckets(new ListBucketsRequest() { accountId = auth.accountId }, auth.authorizationToken, auth.apiUrl);
  54. var bucket = buckets.buckets.First();
  55. logger.Debug("Using Bucket Named {0} for uploads", bucket.bucketName);
  56. SearchOption so = SearchOption.TopDirectoryOnly;
  57. if (options.recursive)
  58. {
  59. if (options.Verbose)
  60. {
  61. logger.Debug("Using Reurisve mode for uploads");
  62. }
  63. so = SearchOption.AllDirectories;
  64. }
  65. string[] FilesToProcess = Directory.GetFiles(options.Directory, "*", so);
  66. if (options.Verbose)
  67. {
  68. logger.Debug("Found {0} files to upload", FilesToProcess.Length);
  69. }
  70. int maxParallel = 2;
  71. if(options.Threads > 2)
  72. {
  73. if (options.Verbose)
  74. {
  75. logger.Debug("Mutliple threads for upload: {0}", options.Threads);
  76. }
  77. maxParallel = options.Threads;
  78. }
  79. Parallel.ForEach(FilesToProcess, new ParallelOptions() { MaxDegreeOfParallelism = maxParallel }, s =>
  80. {
  81. //check if file already exists
  82. string fileName = getValidFilename(s);
  83. var existingFiles = ListFileNames(new ListFileNamesRequest() { bucketId = bucket.bucketId, startFileName = fileName }, auth.apiUrl, auth.authorizationToken);
  84. bool found = false;
  85. foreach (var x in existingFiles.files)
  86. {
  87. if (x.fileName == fileName)
  88. {
  89. //check the file size
  90. System.IO.FileInfo fi = new System.IO.FileInfo(s);
  91. if (fi.Length == x.size)
  92. {
  93. found = true;
  94. break;
  95. }
  96. else
  97. {
  98. //delete old file? could just be an older version... going to upload again...
  99. break;
  100. }
  101. }
  102. }
  103. if (found)
  104. {
  105. logger.Debug("File {0} exists already, skipping", fileName);
  106. }
  107. else
  108. {
  109. bool uploaded = false;
  110. int retries = 0;
  111. while (!uploaded && retries < 3)
  112. {
  113. try {
  114. var uploadURL = GetUploadURL(new GetUploadURLRequest { bucketId = bucket.bucketId }, auth.apiUrl, auth.authorizationToken);
  115. var response = UploadFile(uploadURL.authorizationToken, "b2/x-auto", s, uploadURL.uploadUrl);
  116. if(response != null)
  117. {
  118. uploaded = true;
  119. }
  120. }
  121. catch(Exception ex)
  122. {
  123. logger.Error("Uploaded Failed. Retrying");
  124. logger.Error(ex.Message);
  125. uploaded = false;
  126. retries += 1;
  127. Thread.Sleep(TimeSpan.FromSeconds(30));
  128. }
  129. }
  130. if (!uploaded)
  131. {
  132. logger.Error("Uploaded Failed 3 times... Please retry later!");
  133. }
  134. }
  135. });
  136. return 1;
  137. },
  138. errors =>{
  139. Console.WriteLine(errors);
  140. return 1;
  141. });
  142. }
  143. static AuthorizeResponse AuthorizeUser(string accountId, string applicationKey)
  144. {
  145. HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.backblaze.com/b2api/v1/b2_authorize_account");
  146. string credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:{1}", accountId, applicationKey)));
  147. webRequest.Headers.Add("Authorization", "Basic " + credentials);
  148. webRequest.ContentType = "application/json; charset=utf-8";
  149. WebResponse response = (HttpWebResponse)webRequest.GetResponse();
  150. var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
  151. response.Close();
  152. return JsonConvert.DeserializeObject<AuthorizeResponse>(responseString);
  153. }
  154. static ListBucketsResponse ListBuckets(ListBucketsRequest request, string authToken, string apiUrl)
  155. {
  156. var headers = GetAuthHeaders(authToken);
  157. string responseString = MakeRequest(apiUrl + "/b2api/v1/b2_list_buckets", headers, JsonConvert.SerializeObject(request));
  158. return JsonConvert.DeserializeObject<ListBucketsResponse>(responseString);
  159. }
  160. static List<Tuple<string,string>> GetAuthHeaders(string authToken)
  161. {
  162. List<Tuple<string, string>> headers = new List<Tuple<string, string>>();
  163. headers.Add(new Tuple<string, string>("Authorization", authToken));
  164. return headers;
  165. }
  166. static GetUploadURLResponse GetUploadURL(GetUploadURLRequest request, string apiUrl, string authToken)
  167. {
  168. var headers = GetAuthHeaders(authToken);
  169. string responseString = MakeRequest(apiUrl + "/b2api/v1/b2_get_upload_url", headers, JsonConvert.SerializeObject(request));
  170. return JsonConvert.DeserializeObject<GetUploadURLResponse>(responseString);
  171. }
  172. static string getValidFilename(string input)
  173. {
  174. string fileName = input.Replace('\\', '/');
  175. if (fileName.StartsWith("/"))
  176. {
  177. fileName = fileName.Substring(1);
  178. }
  179. return fileName;
  180. }
  181. static UploadFileResponse UploadFile(string authToken, string contentType, string filePath, string uploadUrl)
  182. {
  183. logger.Debug("Starting Uploading {0}", filePath);
  184. String sha1 = GetSha1(filePath);
  185. var headers = GetAuthHeaders(authToken);
  186. string fileName = getValidFilename(filePath);
  187. headers.Add(new Tuple<string, string>("X-Bz-File-Name", fileName));
  188. headers.Add(new Tuple<string, string>("X-Bz-Content-Sha1", sha1));
  189. using (FileStream fs = System.IO.File.OpenRead(filePath))
  190. {
  191. string responseString = MakeRequest(uploadUrl, headers, fs, contentType);
  192. var resp = JsonConvert.DeserializeObject<UploadFileResponse>(responseString);
  193. if (resp.contentSha1 == sha1)
  194. {
  195. Console.WriteLine(responseString);
  196. return resp;
  197. }
  198. else
  199. {
  200. //something went wrong!
  201. return null;
  202. }
  203. }
  204. }
  205. static ListFileNamesResponse ListFileNames(ListFileNamesRequest request, string apiUrl, string authToken)
  206. {
  207. var headers = GetAuthHeaders(authToken);
  208. string responseString = MakeRequest(string.Format("{0}/b2api/v1/b2_list_file_names", apiUrl), headers, JsonConvert.SerializeObject(request));
  209. return JsonConvert.DeserializeObject<ListFileNamesResponse>(responseString);
  210. }
  211. static string MakeRequest(string url, List<Tuple<string,string>> headers, string data, string contentType = "application/json; charset=urf-8")
  212. {
  213. MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
  214. return MakeRequest(url, headers, ms, contentType);
  215. }
  216. static string MakeRequest(string url, List<Tuple<string,string>> headers, Stream data, string contentType="application/json; charset=utf-8")
  217. {
  218. string reqId = DateTime.Now.Ticks.ToString("X2");
  219. Stopwatch st = Stopwatch.StartNew();
  220. try
  221. {
  222. logger.Debug("Starting RequestID: {0}", reqId);
  223. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  224. req.Method = "POST";
  225. foreach (var head in headers)
  226. {
  227. req.Headers.Add(head.Item1, head.Item2);
  228. }
  229. using (var stream = req.GetRequestStream())
  230. {
  231. data.Position = 0;
  232. req.ContentType = contentType;
  233. data.CopyTo(stream);
  234. data.Flush();
  235. stream.Close();
  236. }
  237. WebResponse response = (HttpWebResponse)req.GetResponse();
  238. var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
  239. response.Close();
  240. Console.WriteLine("RequId: {0} MakeRequest Took {1}ms",reqId, st.ElapsedMilliseconds);
  241. return responseString;
  242. }
  243. catch (Exception ex)
  244. {
  245. logger.Error("ReqId: {1} Error talking to server: {0}", ex.Message, reqId);
  246. logger.Error("URL: {0}", url);
  247. throw;
  248. }
  249. }
  250. private static string GetSha1(string fileName)
  251. {
  252. using (SHA1Managed sha1 = new SHA1Managed())
  253. {
  254. using (FileStream fs = System.IO.File.OpenRead(fileName))
  255. {
  256. var hash = sha1.ComputeHash(fs);
  257. var sb = new StringBuilder(hash.Length * 2);
  258. foreach (byte b in hash)
  259. {
  260. // can be "x2" if you want lowercase
  261. sb.Append(b.ToString("X2"));
  262. }
  263. return sb.ToString();
  264. }
  265. }
  266. }
  267. }
  268. }