1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
//! Managing functions. These functions wrap the functions from LHAPDF that mail fail due to data
//! not being downloaded. In that case we do the best to download them from locations and to a
//! directory specified in our configuration file.
use super::ffi::{self, PDFSet, PDF};
use super::unmanaged;
use super::{Error, Result};
use cxx::UniquePtr;
use flate2::read::GzDecoder;
use fs2::FileExt;
use reqwest::{blocking, StatusCode};
use serde::{Deserialize, Serialize};
use std::env;
use std::fs::{self, File};
use std::io::{ErrorKind, Write};
use std::path::Path;
use std::sync::{Mutex, OnceLock};
use tar::Archive;
const LHAPDF_CONFIG: &str = "Verbosity: 1
Interpolator: logcubic
Extrapolator: continuation
ForcePositive: 0
AlphaS_Type: analytic
MZ: 91.1876
MUp: 0.002
MDown: 0.005
MStrange: 0.10
MCharm: 1.29
MBottom: 4.19
MTop: 172.9
Pythia6LambdaV5Compat: true
";
/// Configuration for this library.
#[derive(Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
lhapdf_data_path_read: Vec<String>,
lhapdf_data_path_write: String,
pdfsets_index_url: String,
pdfset_urls: Vec<String>,
}
struct LhapdfData;
impl Config {
/// Return the only instance of this type.
pub fn get() -> &'static Self {
static SINGLETON: OnceLock<Result<Config>> = OnceLock::new();
let config = SINGLETON.get_or_init(|| {
let config_path = dirs::config_dir()
.ok_or_else(|| Error::General("no configuration directory found".to_owned()))?;
// create the configuration directory if it doesn't exist yet - in practice this only
// happens in our CI
fs::create_dir_all(&config_path)?;
let config_path = config_path.join("managed-lhapdf.toml");
// TODO: it's possible that multiple processes try to create the default configuration
// file and/or that while the file is created, other processes try to read from it
// MSRV 1.77.0: use `File::create_new` instead
let config = match File::options()
.read(true)
.write(true)
.create_new(true)
.open(&config_path)
{
// the file didn't exist before
Ok(mut file) => {
// use a default configuration
let mut config = Self {
lhapdf_data_path_read: vec![],
lhapdf_data_path_write: dirs::data_dir()
.ok_or_else(|| Error::General("no data directory found".to_owned()))?
.join("managed-lhapdf")
.to_str()
// UNWRAP: if the string isn't valid unicode we can't proceed
.unwrap()
.to_owned(),
pdfsets_index_url: "https://lhapdfsets.web.cern.ch/current/pdfsets.index"
.to_owned(),
pdfset_urls: vec!["https://lhapdfsets.web.cern.ch/current/".to_owned()],
};
// if there's an environment variable that the user set use its value
if let Some(os_str) =
env::var_os("LHAPDF_DATA_PATH").or_else(|| env::var_os("LHAPATH"))
{
config.lhapdf_data_path_read =
// UNWRAP: if the string isn't valid unicode we can't proceed
os_str.to_str().unwrap().split(':').map(ToOwned::to_owned).collect();
}
file.write_all(toml::to_string_pretty(&config)?.as_bytes())?;
config
}
Err(err) if err.kind() == ErrorKind::AlreadyExists => {
// the file already exists, simply read it
toml::from_str(&fs::read_to_string(&config_path)?)?
}
Err(err) => Err(err)?,
};
if let Some(lhapdf_data_path_write) = config.lhapdf_data_path_write() {
// create download directory for `lhapdf.conf`
fs::create_dir_all(lhapdf_data_path_write)?;
// MSRV 1.77.0: use `File::create_new` instead
if let Ok(mut file) = File::options()
.read(true)
.write(true)
.create_new(true)
.open(Path::new(lhapdf_data_path_write).join("lhapdf.conf"))
{
// if `lhapdf.conf` doesn't exist, create it
file.write_all(LHAPDF_CONFIG.as_bytes())?;
}
let pdfsets_index = Path::new(lhapdf_data_path_write).join("pdfsets.index");
// MSRV 1.77.0: use `File::create_new` instead
if let Ok(mut file) = File::options()
.read(true)
.write(true)
.create_new(true)
.open(pdfsets_index)
{
// if `pdfsets.index` doesn't exist, download it
let content = blocking::get(config.pdfsets_index_url())?.text()?;
file.write_all(content.as_bytes())?;
}
}
// we use the environment variable `LHAPDF_DATA_PATH` to let LHAPDF know where we've
// stored our PDFs
let mut lhapdf_data_path = config
.lhapdf_data_path_write()
.map_or_else(Vec::new, |path| vec![path.to_owned()]);
lhapdf_data_path.extend(config.lhapdf_data_path_read.iter().cloned());
// as long as `static Config _cfg` in LHAPDF's `src/Config.cc` is `static` and not
// `thread_local`, this belongs here; otherwise move it out of the singleton
// initialization
env::set_var("LHAPDF_DATA_PATH", lhapdf_data_path.join(":"));
Ok(config)
});
// TODO: change return type and propagate the result - difficult because we can't clone the
// error type
config.as_ref().unwrap()
}
/// Return the path where `managed-lhapdf` will download PDF sets and `pdfsets.index` to.
pub fn lhapdf_data_path_write(&self) -> Option<&str> {
if self.lhapdf_data_path_write.is_empty() {
None
} else {
Some(&self.lhapdf_data_path_write)
}
}
/// Return the URL where the file `pdfsets.index` will downloaded from.
pub fn pdfsets_index_url(&self) -> &str {
&self.pdfsets_index_url
}
/// Return the URLs that should be searched for PDF sets, if they are not available in the
/// local cache.
pub fn pdfset_urls(&self) -> &[String] {
&self.pdfset_urls
}
}
impl From<toml::ser::Error> for Error {
fn from(err: toml::ser::Error) -> Self {
Self::Other(anyhow::Error::new(err))
}
}
impl From<toml::de::Error> for Error {
fn from(err: toml::de::Error) -> Self {
Self::Other(anyhow::Error::new(err))
}
}
impl From<reqwest::Error> for Error {
fn from(err: reqwest::Error) -> Self {
Self::Other(anyhow::Error::new(err))
}
}
impl LhapdfData {
fn get() -> &'static Mutex<Self> {
static SINGLETON: Mutex<LhapdfData> = Mutex::new(LhapdfData);
&SINGLETON
}
fn download_set(&self, name: &str, config: &Config) -> Result<()> {
if let Some(lhapdf_data_path_write) = config.lhapdf_data_path_write() {
let lock_file =
File::create(Path::new(lhapdf_data_path_write).join(format!("{name}.lock")))?;
lock_file.lock_exclusive()?;
for url in config.pdfset_urls() {
let response = blocking::get(format!("{url}/{name}.tar.gz"))?;
if response.status() == StatusCode::NOT_FOUND {
continue;
}
let content = response.bytes()?;
// TODO: what if multiple threads/processes try to write to the same file?
Archive::new(GzDecoder::new(&content[..])).unpack(lhapdf_data_path_write)?;
// we found a PDF set, now it's LHAPDF's turn
break;
}
lock_file.unlock()?;
}
Ok(())
}
fn update_pdfsets_index(&self, config: &Config) -> Result<()> {
if let Some(lhapdf_data_path_write) = config.lhapdf_data_path_write() {
let lock_file = File::create(Path::new(lhapdf_data_path_write).join("pdfsets.lock"))?;
lock_file.lock_exclusive()?;
// empty the `static thread_local` variable sitting in `getPDFIndex` to trigger the
// re-initialization of this variable
ffi::empty_lhaindex();
// download `pdfsets.index`
let content = blocking::get(config.pdfsets_index_url())?.text()?;
let pdfsets_index = Path::new(lhapdf_data_path_write).join("pdfsets.index");
// TODO: what if multiple threads/processes try to write to the same file?
File::create(pdfsets_index)?.write_all(content.as_bytes())?;
lock_file.unlock()?;
}
Ok(())
}
pub fn pdf_name_and_member_via_lhaid(&self, lhaid: i32) -> Option<(String, i32)> {
unmanaged::pdf_name_and_member_via_lhaid(lhaid)
}
fn pdf_with_setname_and_member(&self, setname: &str, member: i32) -> Result<UniquePtr<PDF>> {
unmanaged::pdf_with_setname_and_member(setname, member)
}
fn pdfset_new(&self, setname: &str) -> Result<UniquePtr<PDFSet>> {
unmanaged::pdfset_new(setname)
}
fn set_verbosity(&self, verbosity: i32) {
unmanaged::set_verbosity(verbosity);
}
fn verbosity(&self) -> i32 {
unmanaged::verbosity()
}
}
pub fn pdf_name_and_member_via_lhaid(lhaid: i32) -> Option<(String, i32)> {
// this must be the first call before anything from LHAPDF
let config = Config::get();
// TODO: change return type of this function and handle the error properly
let lock = LhapdfData::get().lock().unwrap();
lock.pdf_name_and_member_via_lhaid(lhaid).or_else(|| {
// TODO: change return type of this function and handle the error properly
lock.update_pdfsets_index(config).unwrap();
lock.pdf_name_and_member_via_lhaid(lhaid)
})
}
pub fn pdf_with_setname_and_member(setname: &str, member: i32) -> Result<UniquePtr<PDF>> {
// this must be the first call before anything from LHAPDF
let config = Config::get();
// TODO: handle error properly
let lock = LhapdfData::get().lock().unwrap();
lock.pdf_with_setname_and_member(setname, member)
.or_else(|err: Error| {
// here we rely on exactly matching LHAPDF's exception string
if err.to_string() == format!("Info file not found for PDF set '{setname}'") {
lock.download_set(setname, config)
.and_then(|()| lock.pdf_with_setname_and_member(setname, member))
} else {
Err(err)
}
})
}
pub fn pdfset_new(setname: &str) -> Result<UniquePtr<PDFSet>> {
// this must be the first call before anything from LHAPDF
let config = Config::get();
// TODO: handle error properly
let lock = LhapdfData::get().lock().unwrap();
lock.pdfset_new(setname).or_else(|err: Error| {
// here we rely on exactly matching LHAPDF's exception string
if err.to_string() == format!("Info file not found for PDF set '{setname}'") {
lock.download_set(setname, config)
.and_then(|()| lock.pdfset_new(setname))
} else {
Err(err)
}
})
}
pub fn set_verbosity(verbosity: i32) {
// this must be the first call before anything from LHAPDF
let _ = Config::get();
// TODO: handle error properly
let lock = LhapdfData::get().lock().unwrap();
lock.set_verbosity(verbosity);
}
pub fn verbosity() -> i32 {
// this must be the first call before anything from LHAPDF
let _ = Config::get();
// TODO: handle error properly
let lock = LhapdfData::get().lock().unwrap();
lock.verbosity()
}