frontends.rst 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. .. include:: ../global.rst.inc
  2. .. highlight:: none
  3. .. _json_output:
  4. All about JSON: How to develop frontends
  5. ========================================
  6. Borg does not have a public API on the Python level. That does not keep you from writing :code:`import borg`,
  7. but does mean that there are no release-to-release guarantees on what you might find in that package, not
  8. even for point releases (1.1.x), and there is no documentation beyond the code and the internals documents.
  9. Borg does on the other hand provide an API on a command-line level. In other words, a frontend should to
  10. (for example) create a backup archive just invoke :ref:`borg_create`, give commandline parameters/options
  11. as needed and parse JSON output from borg.
  12. Important: JSON output is expected to be UTF-8, but currently borg depends on the locale being configured
  13. for that (must be a UTF-8 locale and *not* "C" or "ascii"), so that Python will choose to encode to UTF-8.
  14. The same applies to any inputs read by borg, they are expected to be UTF-8 encoded also.
  15. We consider this a bug (see :issue:`2273`) and might fix it later, so borg will use UTF-8 independent of
  16. the locale.
  17. On POSIX systems, you can usually set environment vars to choose a UTF-8 locale:
  18. ::
  19. export LANG=en_US.UTF-8
  20. export LC_CTYPE=en_US.UTF-8
  21. Logging
  22. -------
  23. Especially for graphical frontends it is important to be able to convey and reformat progress information
  24. in meaningful ways. The ``--log-json`` option turns the stderr stream of Borg into a stream of JSON lines,
  25. where each line is a JSON object. The *type* key of the object determines its other contents.
  26. .. warning:: JSON logging requires successful argument parsing. Even with ``--log-json`` specified, a
  27. parsing error will be printed in plain text, because logging set-up happens after all arguments are
  28. parsed.
  29. Since JSON can only encode text, any string representing a file system path may miss non-text parts.
  30. The following types are in use. Progress information is governed by the usual rules for progress information,
  31. it is not produced unless ``--progress`` is specified.
  32. archive_progress
  33. Output during operations creating archives (:ref:`borg_create` and :ref:`borg_recreate`).
  34. The following keys exist, each represents the current progress.
  35. original_size
  36. Original size of data processed so far (before compression and deduplication)
  37. compressed_size
  38. Compressed size
  39. deduplicated_size
  40. Deduplicated size
  41. nfiles
  42. Number of (regular) files processed so far
  43. path
  44. Current path
  45. time
  46. Unix timestamp (float)
  47. progress_message
  48. A message-based progress information with no concrete progress information, just a message
  49. saying what is currently being worked on.
  50. operation
  51. unique, opaque integer ID of the operation
  52. :ref:`msgid <msgid>`
  53. Message ID of the operation (may be *null*)
  54. finished
  55. boolean indicating whether the operation has finished, only the last object for an *operation*
  56. can have this property set to *true*.
  57. message
  58. current progress message (may be empty/absent)
  59. time
  60. Unix timestamp (float)
  61. progress_percent
  62. Absolute progress information with defined end/total and current value.
  63. operation
  64. unique, opaque integer ID of the operation
  65. :ref:`msgid <msgid>`
  66. Message ID of the operation (may be *null*)
  67. finished
  68. boolean indicating whether the operation has finished, only the last object for an *operation*
  69. can have this property set to *true*.
  70. message
  71. A formatted progress message, this will include the percentage and perhaps other information
  72. current
  73. Current value (always less-or-equal to *total*)
  74. info
  75. Array that describes the current item, may be *null*, contents depend on *msgid*
  76. total
  77. Total value
  78. time
  79. Unix timestamp (float)
  80. file_status
  81. This is only output by :ref:`borg_create` and :ref:`borg_recreate` if ``--list`` is specified. The usual
  82. rules for the file listing applies, including the ``--filter`` option.
  83. status
  84. Single-character status as for regular list output
  85. path
  86. Path of the file system object
  87. log_message
  88. Any regular log output invokes this type. Regular log options and filtering applies to these as well.
  89. time
  90. Unix timestamp (float)
  91. levelname
  92. Upper-case log level name (also called severity). Defined levels are: DEBUG, INFO, WARNING, ERROR, CRITICAL
  93. name
  94. Name of the emitting entity
  95. message
  96. Formatted log message
  97. :ref:`msgid <msgid>`
  98. Message ID, may be *null* or absent
  99. See Prompts_ for the types used by prompts.
  100. .. rubric:: Examples (reformatted, each object would be on exactly one line)
  101. .. highlight:: json
  102. :ref:`borg_extract` progress::
  103. {"message": "100.0% Extracting: src/borgbackup.egg-info/entry_points.txt",
  104. "current": 13000228, "total": 13004993, "info": ["src/borgbackup.egg-info/entry_points.txt"],
  105. "operation": 1, "msgid": "extract", "type": "progress_percent", "finished": false}
  106. {"message": "100.0% Extracting: src/borgbackup.egg-info/SOURCES.txt",
  107. "current": 13004993, "total": 13004993, "info": ["src/borgbackup.egg-info/SOURCES.txt"],
  108. "operation": 1, "msgid": "extract", "type": "progress_percent", "finished": false}
  109. {"operation": 1, "msgid": "extract", "type": "progress_percent", "finished": true}
  110. :ref:`borg_create` file listing with progress::
  111. {"original_size": 0, "compressed_size": 0, "deduplicated_size": 0, "nfiles": 0, "type": "archive_progress", "path": "src"}
  112. {"type": "file_status", "status": "U", "path": "src/borgbackup.egg-info/entry_points.txt"}
  113. {"type": "file_status", "status": "U", "path": "src/borgbackup.egg-info/SOURCES.txt"}
  114. {"type": "file_status", "status": "d", "path": "src/borgbackup.egg-info"}
  115. {"type": "file_status", "status": "d", "path": "src"}
  116. {"original_size": 13176040, "compressed_size": 11386863, "deduplicated_size": 503, "nfiles": 277, "type": "archive_progress", "path": ""}
  117. Internal transaction progress::
  118. {"message": "Saving files cache", "operation": 2, "msgid": "cache.commit", "type": "progress_message", "finished": false}
  119. {"message": "Saving cache config", "operation": 2, "msgid": "cache.commit", "type": "progress_message", "finished": false}
  120. {"message": "Saving chunks cache", "operation": 2, "msgid": "cache.commit", "type": "progress_message", "finished": false}
  121. {"operation": 2, "msgid": "cache.commit", "type": "progress_message", "finished": true}
  122. A debug log message::
  123. {"message": "35 self tests completed in 0.08 seconds",
  124. "type": "log_message", "created": 1488278449.5575905, "levelname": "DEBUG", "name": "borg.archiver"}
  125. Prompts
  126. -------
  127. Prompts assume a JSON form as well when the ``--log-json`` option is specified. Responses
  128. are still read verbatim from *stdin*, while prompts are JSON messages printed to *stderr*,
  129. just like log messages.
  130. Prompts use the *question_prompt* and *question_prompt_retry* types for the prompt itself,
  131. and *question_invalid_answer*, *question_accepted_default*, *question_accepted_true*,
  132. *question_accepted_false* and *question_env_answer* types for information about
  133. prompt processing.
  134. The *message* property contains the same string displayed regularly in the same situation,
  135. while the *msgid* property may contain a msgid_, typically the name of the
  136. environment variable that can be used to override the prompt. It is the same for all JSON
  137. messages pertaining to the same prompt.
  138. .. rubric:: Examples (reformatted, each object would be on exactly one line)
  139. .. highlight:: none
  140. Providing an invalid answer::
  141. {"type": "question_prompt", "msgid": "BORG_CHECK_I_KNOW_WHAT_I_AM_DOING",
  142. "message": "... Type 'YES' if you understand this and want to continue: "}
  143. incorrect answer # input on stdin
  144. {"type": "question_invalid_answer", "msgid": "BORG_CHECK_I_KNOW_WHAT_I_AM_DOING", "is_prompt": false,
  145. "message": "Invalid answer, aborting."}
  146. Providing a false (negative) answer::
  147. {"type": "question_prompt", "msgid": "BORG_CHECK_I_KNOW_WHAT_I_AM_DOING",
  148. "message": "... Type 'YES' if you understand this and want to continue: "}
  149. NO # input on stdin
  150. {"type": "question_accepted_false", "msgid": "BORG_CHECK_I_KNOW_WHAT_I_AM_DOING",
  151. "message": "Aborting.", "is_prompt": false}
  152. Providing a true (affirmative) answer::
  153. {"type": "question_prompt", "msgid": "BORG_CHECK_I_KNOW_WHAT_I_AM_DOING",
  154. "message": "... Type 'YES' if you understand this and want to continue: "}
  155. YES # input on stdin
  156. # no further output, just like the prompt without --log-json
  157. Passphrase prompts
  158. ------------------
  159. Passphrase prompts should be handled differently. Use the environment variables *BORG_PASSPHRASE*
  160. and *BORG_NEW_PASSPHRASE* (see :ref:`env_vars` for reference) to pass passphrases to Borg, don't
  161. use the interactive passphrase prompts.
  162. When setting a new passphrase (:ref:`borg_init`, :ref:`borg_key_change-passphrase`) normally
  163. Borg prompts whether it should display the passphrase. This can be suppressed by setting
  164. the environment variable *BORG_DISPLAY_PASSPHRASE* to *no*.
  165. When "confronted" with an unknown repository, where the application does not know whether
  166. the repository is encrypted, the following algorithm can be followed to detect encryption:
  167. 1. Set *BORG_PASSPHRASE* to gibberish (for example a freshly generated UUID4, which cannot
  168. possibly be the passphrase)
  169. 2. Invoke ``borg list repository ...``
  170. 3. If this fails, due the repository being encrypted and the passphrase obviously being
  171. wrong, you'll get an error with the *PassphraseWrong* msgid.
  172. The repository is encrypted, for further access the application will need the passphrase.
  173. 4. If this does not fail, then the repository is not encrypted.
  174. Standard output
  175. ---------------
  176. *stdout* is different and more command-dependent than logging. Commands like :ref:`borg_info`, :ref:`borg_create`
  177. and :ref:`borg_list` implement a ``--json`` option which turns their regular output into a single JSON object.
  178. Dates are formatted according to ISO 8601 in local time. No explicit time zone is specified *at this time*
  179. (subject to change). The equivalent strftime format string is '%Y-%m-%dT%H:%M:%S.%f',
  180. e.g. ``2017-08-07T12:27:20.123456``.
  181. The root object at least contains a *repository* key with an object containing:
  182. id
  183. The ID of the repository, normally 64 hex characters
  184. location
  185. Canonicalized repository path, thus this may be different from what is specified on the command line
  186. last_modified
  187. Date when the repository was last modified by the Borg client
  188. The *encryption* key, if present, contains:
  189. mode
  190. Textual encryption mode name (same as :ref:`borg_init` ``--encryption`` names)
  191. keyfile
  192. Path to the local key file used for access. Depending on *mode* this key may be absent.
  193. The *cache* key, if present, contains:
  194. path
  195. Path to the local repository cache
  196. stats
  197. Object containing cache stats:
  198. total_chunks
  199. Number of chunks
  200. total_unique_chunks
  201. Number of unique chunks
  202. total_size
  203. Total uncompressed size of all chunks multiplied with their reference counts
  204. total_csize
  205. Total compressed and encrypted size of all chunks multiplied with their reference counts
  206. unique_size
  207. Uncompressed size of all chunks
  208. unique_csize
  209. Compressed and encrypted size of all chunks
  210. .. highlight: json
  211. Example *borg info* output::
  212. {
  213. "cache": {
  214. "path": "/home/user/.cache/borg/0cbe6166b46627fd26b97f8831e2ca97584280a46714ef84d2b668daf8271a23",
  215. "stats": {
  216. "total_chunks": 511533,
  217. "total_csize": 17948017540,
  218. "total_size": 22635749792,
  219. "total_unique_chunks": 54892,
  220. "unique_csize": 1920405405,
  221. "unique_size": 2449675468
  222. }
  223. },
  224. "encryption": {
  225. "mode": "repokey"
  226. },
  227. "repository": {
  228. "id": "0cbe6166b46627fd26b97f8831e2ca97584280a46714ef84d2b668daf8271a23",
  229. "last_modified": "2017-08-07T12:27:20.789123",
  230. "location": "/home/user/testrepo"
  231. },
  232. "security_dir": "/home/user/.config/borg/security/0cbe6166b46627fd26b97f8831e2ca97584280a46714ef84d2b668daf8271a23",
  233. "archives": []
  234. }
  235. Archive formats
  236. +++++++++++++++
  237. :ref:`borg_info` uses an extended format for archives, which is more expensive to retrieve, while
  238. :ref:`borg_list` uses a simpler format that is faster to retrieve. Either return archives in an
  239. array under the *archives* key, while :ref:`borg_create` returns a single archive object under the
  240. *archive* key.
  241. Both formats contain a *name* key with the archive name, the *id* key with the hexadecimal archive ID,
  242. and the *start* key with the start timestamp.
  243. *borg info* and *borg create* further have:
  244. end
  245. End timestamp
  246. duration
  247. Duration in seconds between start and end in seconds (float)
  248. stats
  249. Archive statistics (freshly calculated, this is what makes "info" more expensive)
  250. original_size
  251. Size of files and metadata before compression
  252. compressed_size
  253. Size after compression
  254. deduplicated_size
  255. Deduplicated size (against the current repository, not when the archive was created)
  256. nfiles
  257. Number of regular files in the archive
  258. limits
  259. Object describing the utilization of Borg limits
  260. max_archive_size
  261. Float between 0 and 1 describing how large this archive is relative to the maximum size allowed by Borg
  262. command_line
  263. Array of strings of the command line that created the archive
  264. The note about paths from above applies here as well.
  265. chunker_params
  266. The chunker parameters the archive has been created with.
  267. :ref:`borg_info` further has:
  268. hostname
  269. Hostname of the creating host
  270. username
  271. Name of the creating user
  272. comment
  273. Archive comment, if any
  274. Some keys/values are more expensive to compute than others (e.g. because it requires opening the archive,
  275. not just the manifest). To optimize for speed, `borg list repo` does not determine these values except
  276. when they are requested. The `--format` option is used for that (for normal mode as well as for `--json`
  277. mode), so, to have the comment included in the json output, you will need:
  278. ::
  279. borg list repo --format "{name}{comment}" --json`
  280. Example of a simple archive listing (``borg list --last 1 --json``)::
  281. {
  282. "archives": [
  283. {
  284. "id": "80cd07219ad725b3c5f665c1dcf119435c4dee1647a560ecac30f8d40221a46a",
  285. "name": "host-system-backup-2017-02-27",
  286. "start": "2017-08-07T12:27:20.789123"
  287. }
  288. ],
  289. "encryption": {
  290. "mode": "repokey"
  291. },
  292. "repository": {
  293. "id": "0cbe6166b46627fd26b97f8831e2ca97584280a46714ef84d2b668daf8271a23",
  294. "last_modified": "2017-08-07T12:27:20.789123",
  295. "location": "/home/user/repository"
  296. }
  297. }
  298. The same archive with more information (``borg info --last 1 --json``)::
  299. {
  300. "archives": [
  301. {
  302. "chunker_params": [
  303. 13,
  304. 23,
  305. 16,
  306. 4095
  307. ],
  308. "command_line": [
  309. "/home/user/.local/bin/borg",
  310. "create",
  311. "/home/user/repository",
  312. "..."
  313. ],
  314. "comment": "",
  315. "duration": 5.641542,
  316. "end": "2017-02-27T12:27:20.789123",
  317. "hostname": "host",
  318. "id": "80cd07219ad725b3c5f665c1dcf119435c4dee1647a560ecac30f8d40221a46a",
  319. "limits": {
  320. "max_archive_size": 0.0001330855110409714
  321. },
  322. "name": "host-system-backup-2017-02-27",
  323. "start": "2017-02-27T12:27:20.789123",
  324. "stats": {
  325. "compressed_size": 1880961894,
  326. "deduplicated_size": 2791,
  327. "nfiles": 53669,
  328. "original_size": 2400471280
  329. },
  330. "username": "user"
  331. }
  332. ],
  333. "cache": {
  334. "path": "/home/user/.cache/borg/0cbe6166b46627fd26b97f8831e2ca97584280a46714ef84d2b668daf8271a23",
  335. "stats": {
  336. "total_chunks": 511533,
  337. "total_csize": 17948017540,
  338. "total_size": 22635749792,
  339. "total_unique_chunks": 54892,
  340. "unique_csize": 1920405405,
  341. "unique_size": 2449675468
  342. }
  343. },
  344. "encryption": {
  345. "mode": "repokey"
  346. },
  347. "repository": {
  348. "id": "0cbe6166b46627fd26b97f8831e2ca97584280a46714ef84d2b668daf8271a23",
  349. "last_modified": "2017-08-07T12:27:20.789123",
  350. "location": "/home/user/repository"
  351. }
  352. }
  353. File listings
  354. +++++++++++++
  355. Listing the contents of an archive can produce *a lot* of JSON. Since many JSON implementations
  356. don't support a streaming mode of operation, which is pretty much required to deal with this amount of
  357. JSON, output is generated in the `JSON lines <http://jsonlines.org/>`_ format, which is simply
  358. a number of JSON objects separated by new lines.
  359. Each item (file, directory, ...) is described by one object in the :ref:`borg_list` output.
  360. Refer to the *borg list* documentation for the available keys and their meaning.
  361. Example (excerpt) of ``borg list --json-lines``::
  362. {"type": "d", "mode": "drwxr-xr-x", "user": "user", "group": "user", "uid": 1000, "gid": 1000, "path": "linux", "healthy": true, "source": "", "linktarget": "", "flags": null, "mtime": "2017-02-27T12:27:20.023407", "size": 0}
  363. {"type": "d", "mode": "drwxr-xr-x", "user": "user", "group": "user", "uid": 1000, "gid": 1000, "path": "linux/baz", "healthy": true, "source": "", "linktarget": "", "flags": null, "mtime": "2017-02-27T12:27:20.585407", "size": 0}
  364. .. _msgid:
  365. Message IDs
  366. -----------
  367. Message IDs are strings that essentially give a log message or operation a name, without actually using the
  368. full text, since texts change more frequently. Message IDs are unambiguous and reduce the need to parse
  369. log messages.
  370. Assigned message IDs are:
  371. .. See scripts/errorlist.py; this is slightly edited.
  372. Errors
  373. Archive.AlreadyExists
  374. Archive {} already exists
  375. Archive.DoesNotExist
  376. Archive {} does not exist
  377. Archive.IncompatibleFilesystemEncodingError
  378. Failed to encode filename "{}" into file system encoding "{}". Consider configuring the LANG environment variable.
  379. Cache.CacheInitAbortedError
  380. Cache initialization aborted
  381. Cache.EncryptionMethodMismatch
  382. Repository encryption method changed since last access, refusing to continue
  383. Cache.RepositoryAccessAborted
  384. Repository access aborted
  385. Cache.RepositoryIDNotUnique
  386. Cache is newer than repository - do you have multiple, independently updated repos with same ID?
  387. Cache.RepositoryReplay
  388. Cache is newer than repository - this is either an attack or unsafe (multiple repos with same ID)
  389. Buffer.MemoryLimitExceeded
  390. Requested buffer size {} is above the limit of {}.
  391. ExtensionModuleError
  392. The Borg binary extension modules do not seem to be properly installed
  393. IntegrityError
  394. Data integrity error: {}
  395. NoManifestError
  396. Repository has no manifest.
  397. PlaceholderError
  398. Formatting Error: "{}".format({}): {}({})
  399. KeyfileInvalidError
  400. Invalid key file for repository {} found in {}.
  401. KeyfileMismatchError
  402. Mismatch between repository {} and key file {}.
  403. KeyfileNotFoundError
  404. No key file for repository {} found in {}.
  405. PassphraseWrong
  406. passphrase supplied in BORG_PASSPHRASE is incorrect
  407. PasswordRetriesExceeded
  408. exceeded the maximum password retries
  409. RepoKeyNotFoundError
  410. No key entry found in the config of repository {}.
  411. UnsupportedManifestError
  412. Unsupported manifest envelope. A newer version is required to access this repository.
  413. UnsupportedPayloadError
  414. Unsupported payload type {}. A newer version is required to access this repository.
  415. NotABorgKeyFile
  416. This file is not a borg key backup, aborting.
  417. RepoIdMismatch
  418. This key backup seems to be for a different backup repository, aborting.
  419. UnencryptedRepo
  420. Keymanagement not available for unencrypted repositories.
  421. UnknownKeyType
  422. Keytype {0} is unknown.
  423. LockError
  424. Failed to acquire the lock {}.
  425. LockErrorT
  426. Failed to acquire the lock {}.
  427. ConnectionClosed
  428. Connection closed by remote host
  429. InvalidRPCMethod
  430. RPC method {} is not valid
  431. PathNotAllowed
  432. Repository path not allowed
  433. RemoteRepository.RPCServerOutdated
  434. Borg server is too old for {}. Required version {}
  435. UnexpectedRPCDataFormatFromClient
  436. Borg {}: Got unexpected RPC data format from client.
  437. UnexpectedRPCDataFormatFromServer
  438. Got unexpected RPC data format from server:
  439. {}
  440. Repository.AlreadyExists
  441. Repository {} already exists.
  442. Repository.CheckNeeded
  443. Inconsistency detected. Please run "borg check {}".
  444. Repository.DoesNotExist
  445. Repository {} does not exist.
  446. Repository.InsufficientFreeSpaceError
  447. Insufficient free space to complete transaction (required: {}, available: {}).
  448. Repository.InvalidRepository
  449. {} is not a valid repository. Check repo config.
  450. Repository.AtticRepository
  451. Attic repository detected. Please run "borg upgrade {}".
  452. Repository.ObjectNotFound
  453. Object with key {} not found in repository {}.
  454. Operations
  455. - cache.begin_transaction
  456. - cache.download_chunks, appears with ``borg create --no-cache-sync``
  457. - cache.commit
  458. - cache.sync
  459. *info* is one string element, the name of the archive currently synced.
  460. - repository.compact_segments
  461. - repository.replay_segments
  462. - repository.check
  463. - check.verify_data
  464. - check.rebuild_manifest
  465. - extract
  466. *info* is one string element, the name of the path currently extracted.
  467. - extract.permissions
  468. - archive.delete
  469. - archive.calc_stats
  470. - prune
  471. - upgrade.convert_segments
  472. Prompts
  473. BORG_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK
  474. For "Warning: Attempting to access a previously unknown unencrypted repository"
  475. BORG_RELOCATED_REPO_ACCESS_IS_OK
  476. For "Warning: The repository at location ... was previously located at ..."
  477. BORG_CHECK_I_KNOW_WHAT_I_AM_DOING
  478. For "Warning: 'check --repair' is an experimental feature that might result in data loss."
  479. BORG_DELETE_I_KNOW_WHAT_I_AM_DOING
  480. For "You requested to completely DELETE the repository *including* all archives it contains:"
  481. BORG_RECREATE_I_KNOW_WHAT_I_AM_DOING
  482. For "recreate is an experimental feature."