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
use crate::*;
use curl::easy::Easy;
use derive_more::*;
use std::fs;

pub const VALID_CONFIGS: &[&str] = &[
    "mkl-dynamic-ilp64-iomp",
    "mkl-dynamic-ilp64-seq",
    "mkl-dynamic-lp64-iomp",
    "mkl-dynamic-lp64-seq",
    "mkl-static-ilp64-iomp",
    "mkl-static-ilp64-seq",
    "mkl-static-lp64-iomp",
    "mkl-static-lp64-seq",
];

#[derive(Debug, Clone, Copy, PartialEq, Display)]
pub enum LinkType {
    #[display(fmt = "static")]
    Static,
    #[display(fmt = "dynamic")]
    Shared,
}

#[derive(Debug, Clone, Copy, PartialEq, Display)]
pub enum Interface {
    #[display(fmt = "lp64")]
    LP64,
    #[display(fmt = "ilp64")]
    ILP64,
}

#[derive(Debug, Clone, Copy, PartialEq, Display)]
pub enum Threading {
    #[display(fmt = "iomp")]
    OpenMP,
    #[display(fmt = "seq")]
    Sequential,
}

/// Configure for linking, downloading and packaging Intel MKL
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Config {
    pub link: LinkType,
    pub index_size: Interface,
    pub parallel: Threading,
}

impl Config {
    pub fn from_str(name: &str) -> Result<Self> {
        let parts: Vec<_> = name.split("-").collect();
        if parts.len() != 4 {
            bail!("Invalid name: {}", name);
        }

        if parts[0] != "mkl" {
            bail!("Name must start with 'mkl': {}", name);
        }

        let link = match parts[1] {
            "static" => LinkType::Static,
            "dynamic" => LinkType::Shared,
            another => bail!("Invalid link spec: {}", another),
        };

        let index_size = match parts[2] {
            "lp64" => Interface::LP64,
            "ilp64" => Interface::ILP64,
            another => bail!("Invalid index spec: {}", another),
        };

        let parallel = match parts[3] {
            "iomp" => Threading::OpenMP,
            "seq" => Threading::Sequential,
            another => bail!("Invalid parallel spec: {}", another),
        };

        Ok(Config {
            link,
            index_size,
            parallel,
        })
    }

    pub fn possibles() -> Vec<Self> {
        VALID_CONFIGS
            .iter()
            .map(|name| Self::from_str(name).unwrap())
            .collect()
    }

    /// identifier used in pkg-config
    pub fn name(&self) -> String {
        format!("mkl-{}-{}-{}", self.link, self.index_size, self.parallel)
    }

    /// Common components
    ///
    /// The order must be following (or equivalent libs)
    ///
    /// mkl_intel_lp64 > mkl_intel_thread > mkl_core > iomp5
    ///
    pub fn libs(&self) -> Vec<String> {
        let mut libs = Vec::new();
        match self.index_size {
            Interface::LP64 => {
                libs.push("mkl_intel_lp64".into());
            }
            Interface::ILP64 => {
                libs.push("mkl_intel_ilp64".into());
            }
        };
        match self.parallel {
            Threading::OpenMP => {
                libs.push("mkl_intel_thread".into());
            }
            Threading::Sequential => {
                libs.push("mkl_sequential".into());
            }
        };
        libs.push("mkl_core".into());
        if matches!(self.parallel, Threading::OpenMP) {
            libs.push("iomp5".into());
        }
        libs
    }

    /// Dynamically loaded libraries, e.g. `libmkl_vml_avx2.so`
    ///
    /// - MKL seeks additional shared library **on runtime**.
    ///   This function lists these files for packaging.
    pub fn additional_libs(&self) -> Vec<String> {
        match self.link {
            LinkType::Static => Vec::new(),
            LinkType::Shared => {
                let mut libs = Vec::new();
                for prefix in &["mkl", "mkl_vml"] {
                    for suffix in &["def", "avx", "avx2", "avx512", "avx512_mic", "mc", "mc3"] {
                        libs.push(format!("{}_{}", prefix, suffix));
                    }
                }
                libs.push("mkl_rt".into());
                libs.push("mkl_vml_mc2".into());
                libs.push("mkl_vml_cmpt".into());
                libs
            }
        }
    }

    /// Download archive from AWS S3, and expand into `${out_dir}/*.so`
    pub fn download<P: AsRef<Path>>(&self, out_dir: P) -> Result<()> {
        let out_dir = out_dir.as_ref();
        if out_dir.exists() {
            fs::create_dir_all(&out_dir)?;
        }
        let data = read_from_url(&format!("{}/{}.tar.zst", s3_addr(), self.name()))?;
        let zstd = zstd::stream::read::Decoder::new(data.as_slice())?;
        let mut arc = tar::Archive::new(zstd);
        arc.unpack(&out_dir)?;
        Ok(())
    }
}

/// Helper for download file from URL
///
/// - This function expands obtained data into memory space
///
fn read_from_url(url: &str) -> Result<Vec<u8>> {
    let mut data = Vec::new();
    let mut handle = Easy::new();
    handle.fail_on_error(true)?;
    handle.url(url)?;
    {
        let mut transfer = handle.transfer();
        transfer
            .write_function(|new_data| {
                data.extend_from_slice(new_data);
                Ok(new_data.len())
            })
            .unwrap();
        transfer.perform().unwrap();
    }
    Ok(data)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn name_to_config() -> Result<()> {
        let cfg = Config::from_str("mkl-static-lp64-iomp")?;
        assert_eq!(
            cfg,
            Config {
                link: LinkType::Static,
                index_size: Interface::LP64,
                parallel: Threading::OpenMP
            }
        );
        Ok(())
    }

    #[test]
    fn name_to_config_to_name() -> Result<()> {
        for name in VALID_CONFIGS {
            let cfg = Config::from_str(name)?;
            assert_eq!(&cfg.name(), name);
        }
        Ok(())
    }

    #[test]
    fn invalid_names() -> Result<()> {
        assert!(Config::from_str("").is_err());
        assert!(Config::from_str("static-lp64-iomp").is_err());
        assert!(Config::from_str("mkll-static-lp64-iomp").is_err());
        assert!(Config::from_str("mkl-sttic-lp64-iomp").is_err());
        assert!(Config::from_str("mkl-static-l64-iomp").is_err());
        assert!(Config::from_str("mkl-static-lp64-omp").is_err());
        Ok(())
    }

    macro_rules! impl_test_download {
        ($name:expr) => {
            paste::item! {
                #[test]
                fn [<download_$name>]() -> Result<()> {
                    let name = $name;
                    let cfg = Config::from_str(name)?;
                    cfg.download(format!("test_download/{}", name))?;
                    Ok(())
                }
            }
        };
    }

    mod dynamic {
        use super::*;
        impl_test_download!("mkl-dynamic-lp64-seq");
        impl_test_download!("mkl-dynamic-lp64-iomp");
        impl_test_download!("mkl-dynamic-ilp64-seq");
        impl_test_download!("mkl-dynamic-ilp64-iomp");
    }

    #[cfg(all(target_os = "linux", target_arch = "x86_64"))]
    mod static_ {
        use super::*;
        impl_test_download!("mkl-static-lp64-seq");
        impl_test_download!("mkl-static-lp64-iomp");
        impl_test_download!("mkl-static-ilp64-seq");
        impl_test_download!("mkl-static-ilp64-iomp");
    }
}