Uploader.swift 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. let JAR_URL = "https://storage.googleapis.com/firebase-engprod-metrics/upload_tool.jar"
  18. let JAR_LOCAL_PATH = "upload.jar"
  19. let DATABASE_CONFIG = "database.config"
  20. let JSON_PATH = "database.json"
  21. /// Uploads metrics to the Cloud SQL database.
  22. public class Uploader {
  23. /// Uploads the provided metrics to the Cloud SQL database.
  24. public class func upload(metrics: UploadMetrics) throws {
  25. let jar = try downloadJar()
  26. let json = try writeJson(metrics: metrics)
  27. let returnCode = runJar(jar: jar, json: json, config: DATABASE_CONFIG)
  28. if returnCode == 0 {
  29. print("Successfully uploaded metrics!")
  30. } else {
  31. print("Failed to upload metrics... return code is \(returnCode).")
  32. }
  33. try FileManager.default.removeItem(atPath: jar)
  34. try FileManager.default.removeItem(atPath: json)
  35. }
  36. /// Writes the metrics to a local file in a JSON format and returns that path.
  37. private class func writeJson(metrics: UploadMetrics) throws -> String {
  38. try metrics.json().write(to: NSURL(fileURLWithPath: JSON_PATH) as URL,
  39. atomically: false,
  40. encoding: .utf8)
  41. return JSON_PATH
  42. }
  43. /// Downloads the uploader JAR and returns the path to it.
  44. private class func downloadJar() throws -> String {
  45. let jarData = try Data(contentsOf: URL(string: JAR_URL)!)
  46. try jarData.write(to: NSURL(fileURLWithPath: JAR_LOCAL_PATH) as URL)
  47. return JAR_LOCAL_PATH
  48. }
  49. /// Executes the uploader jar and returns the exit code.
  50. private class func runJar(jar: String, json: String, config: String) -> Int32 {
  51. let task = Process()
  52. task.launchPath = "/usr/bin/java"
  53. task.arguments = ["-jar", jar, "--json_path=\(json)", "--config_path=\(config)"]
  54. task.launch()
  55. task.waitUntilExit()
  56. return task.terminationStatus
  57. }
  58. }