+
+static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+
+bool get_scratch_volume(JCR *jcr, bool InChanger, MEDIA_DBR *mr)
+{
+ MEDIA_DBR smr; /* for searching scratch pool */
+ POOL_DBR spr, pr;
+ bool ok = false;
+ bool found = false;
+
+ /* Only one thread at a time can pull from the scratch pool */
+ P(mutex);
+ /*
+ * Get Pool record for Scratch Pool
+ * choose between ScratchPoolId and Scratch
+ * db_get_pool_record will first try ScratchPoolId,
+ * and then try the pool named Scratch
+ */
+ memset(&spr, 0, sizeof(spr));
+ bstrncpy(spr.Name, "Scratch", sizeof(spr.Name));
+ spr.PoolId = mr->ScratchPoolId;
+ if (db_get_pool_record(jcr, jcr->db, &spr)) {
+ memset(&smr, 0, sizeof(smr));
+ smr.PoolId = spr.PoolId;
+ if (InChanger) {
+ smr.StorageId = mr->StorageId; /* want only Scratch Volumes in changer */
+ }
+ bstrncpy(smr.VolStatus, "Append", sizeof(smr.VolStatus)); /* want only appendable volumes */
+ bstrncpy(smr.MediaType, mr->MediaType, sizeof(smr.MediaType));
+
+ /*
+ * If we do not find a valid Scratch volume, try
+ * recycling any existing purged volumes, then
+ * try to take the oldest volume.
+ */
+ if (db_find_next_volume(jcr, jcr->db, 1, InChanger, &smr)) {
+ found = true;
+
+ } else if (find_recycled_volume(jcr, InChanger, &smr)) {
+ found = true;
+
+ } else if (recycle_oldest_purged_volume(jcr, InChanger, &smr)) {
+ found = true;
+ }
+
+ if (found) {
+ POOL_MEM query(PM_MESSAGE);
+
+ /*
+ * Get pool record where the Scratch Volume will go to ensure
+ * that we can add a Volume.
+ */
+ memset(&pr, 0, sizeof(pr));
+ bstrncpy(pr.Name, jcr->pool->name(), sizeof(pr.Name));
+
+ if (!db_get_pool_record(jcr, jcr->db, &pr)) {
+ Jmsg(jcr, M_WARNING, 0, _("Unable to get Pool record: ERR=%s"),
+ db_strerror(jcr->db));
+ goto bail_out;
+ }
+
+ /* Make sure there is room for another volume */
+ if (pr.MaxVols > 0 && pr.NumVols >= pr.MaxVols) {
+ Jmsg(jcr, M_WARNING, 0, _("Unable add Scratch Volume, Pool \"%s\" full MaxVols=%d\n"),
+ jcr->pool->name(), pr.MaxVols);
+ goto bail_out;
+ }
+
+ memcpy(mr, &smr, sizeof(MEDIA_DBR));
+
+ /* Set default parameters from current pool */
+ set_pool_dbr_defaults_in_media_dbr(mr, &pr);
+
+ /*
+ * set_pool_dbr_defaults_in_media_dbr set VolStatus to Append,
+ * we could have Recycled media, also, we retain the old
+ * RecyclePoolId.
+ */
+ bstrncpy(mr->VolStatus, smr.VolStatus, sizeof(smr.VolStatus));
+ mr->RecyclePoolId = smr.RecyclePoolId;
+
+ if (!db_update_media_record(jcr, jcr->db, mr)) {
+ Jmsg(jcr, M_WARNING, 0, _("Failed to move Scratch Volume. ERR=%s\n"),
+ db_strerror(jcr->db));
+ goto bail_out;
+ }
+
+ Jmsg(jcr, M_INFO, 0, _("Using Volume \"%s\" from 'Scratch' pool.\n"),
+ mr->VolumeName);
+
+ ok = true;
+ }
+ }
+bail_out:
+ V(mutex);
+ return ok;
+}