Skip to content
37 changes: 32 additions & 5 deletions common-app-lib/src/cmr/common_app/api/request_logger.clj
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@
[cmr.common.log :as log :refer [error report]]
[cmr.common.util :as util]
[cmr.common.time-keeper :as tk]
[digest :as digest]
[ring.middleware.params :as params]
[ring.util.codec :as codec]))
[ring.util.codec :as codec])
(:import
(java.io OutputStream OutputStreamWriter)
(java.nio.charset Charset)
(java.security DigestOutputStream MessageDigest)
(java.util HexFormat)))

(defn- request->uri
"Reconstruct a url that a request client may have asked for (assuming port
Expand Down Expand Up @@ -85,6 +89,31 @@
(util/remove-nil-keys))
data)))

(def ^:private hash-chunk-length
"Number of characters encoded at a time when hashing a response body."
8192)

(defn- md5-and-sha1
"Returns the hex MD5 and SHA-1 digests of text, encoding it a chunk at a time
instead of copying the whole string into a byte array."
[^String text]
(let [md5 (MessageDigest/getInstance "MD5")
sha1 (MessageDigest/getInstance "SHA-1")
length (.length text)
buffer (char-array (min length hash-chunk-length))]
;; Default charset matches the String.getBytes the digest library used, so header values are unchanged.
(with-open [writer (OutputStreamWriter.
(DigestOutputStream. (DigestOutputStream. (OutputStream/nullOutputStream) md5) sha1)
(Charset/defaultCharset))]
(loop [start 0]
(when (< start length)
(let [end (min length (+ start (alength buffer)))]
(.getChars text start end buffer 0)
(.write writer buffer 0 (- end start))
(recur end)))))
[(.formatHex (HexFormat/of) (.digest md5))
(.formatHex (HexFormat/of) (.digest sha1))]))

;; *****************************************************************************
;; Ring Middleware Handlers

Expand All @@ -98,9 +127,7 @@
(fn [request]
(let [response (handler request)
;; This is run after all responses
text (str (:body response))
body-md5 (digest/md5 text)
body-sha1 (digest/sha-1 text)
[body-md5 body-sha1] (md5-and-sha1 (str (:body response)))
updated-response (-> response
(assoc-in [:headers "Content-MD5"] body-md5)
(assoc-in [:headers "Content-SHA1"] body-sha1))]
Expand Down
11 changes: 10 additions & 1 deletion common-app-lib/test/cmr/common_app/test/api/request_logger.clj
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,16 @@
(:require
[clojure.test :refer [deftest is testing]]
[cmr.common-app.api.request-logger :as req-logger]
[cmr.common.util :as util :refer [are3]]))
[cmr.common.util :as util :refer [are3]]
[digest :as digest]))

(deftest add-body-hashes-test
(testing "hash headers match the digest library for multibyte text spanning chunks"
(let [body (str (apply str (repeat 8191 "a")) "😀 café 中文")
handler (req-logger/add-body-hashes (constantly {:status 200 :body body}))
headers (:headers (handler {}))]
(is (= (digest/md5 body) (get headers "Content-MD5")))
(is (= (digest/sha-1 body) (get headers "Content-SHA1"))))))

(defn basic-request
[options]
Expand Down
6 changes: 6 additions & 0 deletions metadata-db-app/src/cmr/metadata_db/config.clj
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@
{:default 200
:type Long})

(defconfig parallel-chunk-threads
"Maximum number of chunks one get-concepts or get-latest-concepts call fetches at once, each on
its own database connection."
{:default 2
:type Long})

(defconfig result-set-fetch-size
"Gets the setting for query fetch-size (number of rows to fetch at once)"
{:default 200
Expand Down
96 changes: 53 additions & 43 deletions metadata-db-app/src/cmr/metadata_db/data/oracle/concepts.clj
Original file line number Diff line number Diff line change
Expand Up @@ -179,37 +179,49 @@
;; we want the temp table to persist for the main select
(concat concept-id-revision-id-tuples [:transaction? false])))

(def ^:private max-in-list-size
"Maximum number of items in one IN list."
64)

(defn- in-list-batches
"Splits items into batches of at most max-in-list-size, padding each with its last item to
either 8 or max-in-list-size items."
[items]
(for [batch (partition-all max-in-list-size items)
:let [size (count batch)
padded-size (if (<= size 8) 8 max-in-list-size)]]
;; Each list length is a separate cursor whose shared pool memory grows ~3 KB per item, so keep two short lengths.
(concat batch (repeat (- padded-size size) (last batch)))))

(defn- in-list-placeholders
"Returns n comma separated copies of placeholder."
[n placeholder]
(string/join "," (repeat n placeholder)))

(defn get-latest-concept-id-revision-id-tuples
"Finds the latest pairs of concept id and revision ids for the given concept ids. If no revisions
exist for a given concept id it will not be returned."
[db concept-type provider concept-ids]
(let [start (System/currentTimeMillis)]
(j/with-db-transaction
[conn db]
;; use a temporary table to insert our values so we can use a join to
;; pull everything in one select
(apply j/insert! conn
"get_concepts_work_area"
["concept_id"]
;; set :transaction? false since we are already inside a transaction, and
;; we want the temp table to persist for the main select
(concat (map vector concept-ids) [:transaction? false]))
;; pull back all revisions of each concept-id and then take the latest
;; instead of using group-by in SQL
(let [table (tables/get-table-name provider concept-type)
stmt (su/build (select [:c.concept-id :c.revision-id]
(from (as (keyword table) :c)
(as :get-concepts-work-area :t))
(where `(and (= :c.concept-id :t.concept-id)))))
cid-rid-maps (su/query conn stmt)
concept-id-to-rev-id-maps (map #(hash-map (:concept_id %) (long (:revision_id %)))
cid-rid-maps)
latest (apply merge-with safe-max {}
concept-id-to-rev-id-maps)
concept-id-revision-id-tuples (seq latest)
latest-time (- (System/currentTimeMillis) start)]
(debug (format "Retrieving latest revision-ids took [%d] ms" latest-time))
concept-id-revision-id-tuples))))
(let [start (System/currentTimeMillis)
table (tables/get-table-name provider concept-type)
cid-rid-maps (j/with-db-connection
[conn db]
(doall
(mapcat (fn [batch]
(su/query conn (into [(format "SELECT concept_id, revision_id FROM %s WHERE concept_id IN (%s)"
table (in-list-placeholders (count batch) "?"))]
batch)))
(in-list-batches concept-ids))))
;; pull back all revisions of each concept-id and then take the latest
;; instead of using group-by in SQL
concept-id-to-rev-id-maps (map #(hash-map (:concept_id %) (long (:revision_id %)))
cid-rid-maps)
latest (apply merge-with safe-max {}
concept-id-to-rev-id-maps)
concept-id-revision-id-tuples (seq latest)
latest-time (- (System/currentTimeMillis) start)]
(debug (format "Retrieving latest revision-ids took [%d] ms" latest-time))
concept-id-revision-id-tuples))

(defn validate-concept-id-native-id-not-changing
"Validates that the concept-id native-id pair for a concept being saved is not changing. This
Expand Down Expand Up @@ -370,23 +382,21 @@
(defn get-concepts
[db concept-type provider concept-id-revision-id-tuples]
(if (pos? (count concept-id-revision-id-tuples))
(let [start (System/currentTimeMillis)]
(j/with-db-transaction
(let [start (System/currentTimeMillis)
provider-id (:provider-id provider)
table (tables/get-table-name provider concept-type)]
;; No temp table insert or transaction, so reads generate no undo or redo and need no commit.
(j/with-db-connection
[conn db]
;; use a temporary table to insert our values so we can use a join to
;; pull everything in one select
(save-concepts-to-tmp-table conn concept-id-revision-id-tuples)

(let [provider-id (:provider-id provider)
table (tables/get-table-name provider concept-type)
stmt (su/build (select [:c.*]
(from (as (keyword table) :c)
(as :get-concepts-work-area :t))
(where `(and (= :c.concept-id :t.concept-id)
(= :c.revision-id :t.revision-id)))))

result (doall (map (partial db-result->concept-map concept-type conn provider-id)
(su/query conn stmt)))
(let [concepts-by-tuple (into {}
(for [batch (in-list-batches concept-id-revision-id-tuples)
row (su/query conn (into [(format "SELECT * FROM %s WHERE (concept_id, revision_id) IN (%s)"
table (in-list-placeholders (count batch) "(?,?)"))]
(apply concat batch)))
:let [concept (db-result->concept-map concept-type conn provider-id row)]]
[[(:concept-id concept) (:revision-id concept)] concept]))
;; One result per requested tuple, duplicates included, for get-concepts' count check.
result (doall (keep concepts-by-tuple concept-id-revision-id-tuples))
millis (- (System/currentTimeMillis) start)]
(debug (format "Getting [%d] concepts took [%d] ms" (count result) millis))
result)))
Expand Down
29 changes: 19 additions & 10 deletions metadata-db-app/src/cmr/metadata_db/services/concept_service.clj
Original file line number Diff line number Diff line change
Expand Up @@ -528,13 +528,23 @@
provider
(errors/throw-service-error :not-found (msg/provider-does-not-exist provider-id))))

(defn- fetch-in-chunks
"Calls fetch-fn on chunks of chunk-size items, running at most max-threads chunks at once, and
returns all the results."
[fetch-fn chunk-size max-threads items]
(let [chunks (vec (partition-all chunk-size items))
chunks-per-thread (long (Math/ceil (/ (count chunks) (double (max 1 max-threads)))))]
(apply concat
(cutil/pmap-n-all #(doall (mapcat fetch-fn %)) chunks-per-thread chunks))))

(defn get-concepts
"Get multiple concepts by concept-id and revision-id. Returns concepts in order requested"
[context concept-id-revision-id-tuples allow-missing?]
(debug (format "Getting [%d] concepts by concept-id/revision-id"
(count concept-id-revision-id-tuples)))
(let [start (System/currentTimeMillis)
parallel-chunk-size (get-in context [:system :parallel-chunk-size])
parallel-chunk-threads (get-in context [:system :parallel-chunk-threads])
db (util/context->db context)
providers (conj (provider-db/get-providers db) pv/cmr-provider)
;; Split the tuples so they can be requested separately for each provider and concept type
Expand All @@ -552,11 +562,10 @@
(if (and (> parallel-chunk-size 0)
(< parallel-chunk-size (count tuples)))
;; retrieving chunks in parallel for faster read performance
(apply concat
(cutil/pmap-n-all
(partial c/get-concepts db concept-type provider)
parallel-chunk-size
tuples))
(fetch-in-chunks (partial c/get-concepts db concept-type provider)
parallel-chunk-size
parallel-chunk-threads
tuples)
(c/get-concepts db concept-type provider tuples))))
;; Create a map of tuples to concepts
concepts-by-tuple (into {} (for [c concepts] [[(:concept-id c) (:revision-id c)] c]))]
Expand Down Expand Up @@ -586,6 +595,7 @@
(doall (reduce #(str %1 " " %2) "" concept-ids))))
start (System/currentTimeMillis)
parallel-chunk-size (get-in context [:system :parallel-chunk-size])
parallel-chunk-threads (get-in context [:system :parallel-chunk-threads])
db (util/context->db context)
providers (conj (provider-db/get-providers db) pv/cmr-provider)
;; Split the concept-ids so they can be requested separately for each provider and concept type
Expand All @@ -603,11 +613,10 @@
(if (and (> parallel-chunk-size 0)
(< parallel-chunk-size (count cids)))
;; retrieving chunks in parallel for faster read performance
(apply concat
(cutil/pmap-n-all
(partial c/get-latest-concepts db concept-type provider)
parallel-chunk-size
cids))
(fetch-in-chunks (partial c/get-latest-concepts db concept-type provider)
parallel-chunk-size
parallel-chunk-threads
cids)
(c/get-latest-concepts db concept-type provider cids))))
;; Create a map of concept-ids to concepts
concepts-by-concept-id (into {} (for [c concepts] [(:concept-id c) c]))]
Expand Down
1 change: 1 addition & 0 deletions metadata-db-app/src/cmr/metadata_db/system.clj
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
:web (web/create-web-server (transmit-config/metadata-db-port) routes/make-api)
:nrepl (nrepl/create-nrepl-if-configured (config/metadata-db-nrepl-port))
:parallel-chunk-size (config/parallel-chunk-size)
:parallel-chunk-threads (config/parallel-chunk-threads)
:caches {acl/token-imp-cache-key (acl/create-token-imp-cache)
common-health/health-cache-key (common-health/create-health-cache)}
:scheduler (jobs/create-clustered-scheduler `system-holder :db mdb-jobs/jobs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,11 @@
"parent_collection_id" "delete_time" "granule_ur" "provider_id"]
["foo" "G7-PROV1" "<foo>" "ECHO10" 2 false "C5-PROV1" sql-timestamp "foo-ur" "PROV1"]]
(fix-result (c/concept->insert-args concept true)))))))

(deftest in-list-batches-test
(let [in-list-batches #'c/in-list-batches
items (range 600)
batches (in-list-batches items)]
(is (= (repeat 10 64) (map count batches)))
(is (= [1 2 3 3 3 3 3 3] (first (in-list-batches [1 2 3]))) "Pads short lists with the last item to 8")
(is (= (set items) (set (apply concat batches))))))
Original file line number Diff line number Diff line change
Expand Up @@ -254,3 +254,15 @@

"sets a collection concept id."
(dissoc example-concept :concept-id)))))

(deftest fetch-in-chunks-test
(let [fetch-in-chunks #'cs/fetch-in-chunks
running (atom 0)
peak (atom 0)
fetch (fn [chunk]
(swap! peak max (swap! running inc))
(Thread/sleep 20)
(swap! running dec)
chunk)]
(is (= (range 2000) (fetch-in-chunks fetch 200 2 (range 2000))))
(is (= 2 @peak) "Runs at most max-threads chunks at once")))
51 changes: 51 additions & 0 deletions oracle-lib/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,57 @@ To install the oracle jars for CMR:
4. In the project root directory, run `cmr install oracle-libs` which will
install the oracle jars in your local maven repository.

## Connection Dials

These settings control how many Oracle sessions CMR opens and how long requests
wait for one. They are read from environment variables when an app starts, so a
change takes effect on restart.

| Environment variable | Default | Controls |
|---|---|---|
| `CMR_DB_MAX_POOL_SIZE` | 100 | Most connections one pool opens. Must be at least 1; the app fails to start otherwise. |
| `CMR_DB_CONNECTION_WAIT_TIMEOUT` | 600 | Seconds one connection checkout waits on a full pool before it fails. It bounds each checkout, not the whole request. |
| `CMR_PARALLEL_CHUNK_SIZE` | 200 | Concepts per chunk when metadata-db fetches a batch of concepts; each chunk is read on one connection. 0 turns chunking off, so one connection reads the whole batch. |
| `CMR_PARALLEL_CHUNK_THREADS` | 2 | Most chunks one fetch reads at once, each on its own connection. |

The pool settings apply to every pool in a process: metadata-db, ingest and
search have one pool each (search embeds metadata-db), and bootstrap has two.
The chunk settings apply wherever metadata-db code fetches concepts: the
metadata-db app, search (for example umm_json results) and bootstrap.

### How they combine

- Sessions from one task: pools in the process × `CMR_DB_MAX_POOL_SIZE`.
- Sessions across CMR: add that up over every running task of every app. Keep
the total below the database's session limit, with headroom for other
clients.
- A fetch is split by provider and concept type, then into chunks of
`CMR_PARALLEL_CHUNK_SIZE`, read at most `CMR_PARALLEL_CHUNK_THREADS` at a
time. A page of 2000 granules from one provider with the defaults is 10
chunks, 2 at a time, holding 2 connections.
- A task can run about `CMR_DB_MAX_POOL_SIZE` / `CMR_PARALLEL_CHUNK_THREADS`
large fetches at once. Further fetches wait for connections. A fetch checks
a connection out once per chunk, so under load a full pool slows requests
rather than failing them.

### When to turn them

- Oracle near its session limit, or slowing under bursts: lower
`CMR_DB_MAX_POOL_SIZE` on the apps with the most tasks, usually search. Extra
requests then queue inside the app rather than open more sessions. Keep
metadata-db's pool well above its concurrent saves: a save holds one
connection while it borrows another, so a small pool there deadlocks until
`CMR_DB_CONNECTION_WAIT_TIMEOUT` runs out.
- Oracle stalled with connections held for minutes: lower
`CMR_DB_CONNECTION_WAIT_TIMEOUT` so waiting requests give up rather than hold
threads and memory for up to 10 minutes. Under ordinary load it rarely
triggers, because connections free up between chunks.
- Large pages slow while the database has spare capacity: raise
`CMR_PARALLEL_CHUNK_THREADS`. Each step adds one connection per large fetch;
10 runs every chunk of a 2000-concept fetch at once.
- `CMR_PARALLEL_CHUNK_SIZE`: smaller values mean more, shorter connection checkouts. Leave
it at 200 unless measurements say otherwise.

## License

Copyright © 2014-2021 NASA
Loading
Loading