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

b2uploader - backup to server

Program.cs 12KB

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