Skip to main content

koji_diff/
koji.rs

1// SPDX-License-Identifier: MPL-2.0
2
3//! Koji build system API client.
4
5use std::path::Path;
6use std::process::Command;
7
8use crate::xmlrpc::{Client, Error, Value};
9
10/// Task state constants from Koji.
11pub const TASK_CLOSED: i64 = 2;
12pub const TASK_FAILED: i64 = 5;
13
14/// Koji API client.
15pub struct KojiClient {
16    client: Client,
17    instance: String,
18}
19
20/// Information about a Koji build.
21#[derive(Debug)]
22pub struct BuildInfo {
23    pub id: i64,
24    pub task_id: i64,
25    pub nvr: String,
26    pub state: i64,
27}
28
29/// Information about a Koji task.
30#[derive(Debug, Clone)]
31pub struct TaskInfo {
32    pub id: i64,
33    pub method: String,
34    pub arch: String,
35    pub state: i64,
36}
37
38impl TaskInfo {
39    pub fn state_name(&self) -> &'static str {
40        match self.state {
41            0 => "FREE",
42            1 => "OPEN",
43            2 => "CLOSED",
44            3 => "CANCELED",
45            4 => "ASSIGNED",
46            5 => "FAILED",
47            _ => "UNKNOWN",
48        }
49    }
50}
51
52impl KojiClient {
53    pub fn new(instance: &str) -> Self {
54        let hub_url = format!("https://{instance}/kojihub");
55        Self {
56            client: Client::new(&hub_url),
57            instance: instance.to_string(),
58        }
59    }
60
61    pub fn instance(&self) -> &str {
62        &self.instance
63    }
64
65    /// Fetch build information by build ID.
66    pub fn get_build(&self, build_id: i64) -> Result<BuildInfo, Error> {
67        let result = self.client.call("getBuild", &[Value::Int(build_id)])?;
68        Ok(BuildInfo {
69            id: result
70                .get("id")
71                .and_then(|v| v.as_int())
72                .unwrap_or(build_id),
73            task_id: result
74                .get("task_id")
75                .and_then(|v| v.as_int())
76                .ok_or_else(|| Error::Parse("missing task_id in build info".into()))?,
77            nvr: result
78                .get("nvr")
79                .and_then(|v| v.as_str())
80                .unwrap_or("")
81                .to_string(),
82            state: result.get("state").and_then(|v| v.as_int()).unwrap_or(-1),
83        })
84    }
85
86    /// Fetch task information by task ID.
87    pub fn get_task_info(&self, task_id: i64) -> Result<TaskInfo, Error> {
88        let result = self.client.call("getTaskInfo", &[Value::Int(task_id)])?;
89        Ok(TaskInfo {
90            id: result.get("id").and_then(|v| v.as_int()).unwrap_or(task_id),
91            method: result
92                .get("method")
93                .and_then(|v| v.as_str())
94                .unwrap_or("")
95                .to_string(),
96            arch: result
97                .get("arch")
98                .and_then(|v| v.as_str())
99                .unwrap_or("")
100                .to_string(),
101            state: result.get("state").and_then(|v| v.as_int()).unwrap_or(-1),
102        })
103    }
104
105    /// Fetch child tasks of a parent task.
106    pub fn get_task_children(&self, task_id: i64) -> Result<Vec<TaskInfo>, Error> {
107        let result = self
108            .client
109            .call("getTaskChildren", &[Value::Int(task_id)])?;
110        let items = result
111            .as_array()
112            .ok_or_else(|| Error::Parse("expected array for task children".into()))?;
113        items
114            .iter()
115            .map(|v| {
116                Ok(TaskInfo {
117                    id: v
118                        .get("id")
119                        .and_then(|v| v.as_int())
120                        .ok_or_else(|| Error::Parse("missing id in child task".into()))?,
121                    method: v
122                        .get("method")
123                        .and_then(|v| v.as_str())
124                        .unwrap_or("")
125                        .to_string(),
126                    arch: v
127                        .get("arch")
128                        .and_then(|v| v.as_str())
129                        .unwrap_or("")
130                        .to_string(),
131                    state: v.get("state").and_then(|v| v.as_int()).unwrap_or(-1),
132                })
133            })
134            .collect()
135    }
136
137    /// Resolve a task ID to the buildArch task for the given architecture.
138    ///
139    /// If the task is already a buildArch task, returns it directly.
140    /// If it is a parent build task, finds the matching child.
141    pub fn resolve_build_arch_task(&self, task_id: i64, arch: &str) -> Result<TaskInfo, Error> {
142        let info = self.get_task_info(task_id)?;
143        if info.method == "buildArch" {
144            return Ok(info);
145        }
146
147        let children = self.get_task_children(task_id)?;
148        let arch_tasks: Vec<_> = children
149            .iter()
150            .filter(|t| t.method == "buildArch" && t.arch == arch)
151            .collect();
152
153        if arch_tasks.is_empty() {
154            let available: Vec<_> = children
155                .iter()
156                .filter(|t| t.method == "buildArch")
157                .map(|t| t.arch.as_str())
158                .collect();
159            return Err(Error::Parse(format!(
160                "no buildArch task for arch '{arch}' under task {task_id}; \
161                 available: {}",
162                if available.is_empty() {
163                    "(none)".to_string()
164                } else {
165                    available.join(", ")
166                }
167            )));
168        }
169
170        Ok(arch_tasks[0].clone())
171    }
172
173    /// Download a log file from a task using `koji download-logs`.
174    ///
175    /// Downloads into `dest_dir` and returns the content of `filename`.
176    pub fn download_log(
177        &self,
178        task_id: i64,
179        filename: &str,
180        dest_dir: &Path,
181    ) -> Result<String, Error> {
182        let mut cmd = Command::new("koji");
183
184        if let Some(profile) = self.koji_profile() {
185            cmd.arg("-p").arg(profile);
186        }
187
188        let output = cmd
189            .arg("download-logs")
190            .arg("--dir")
191            .arg(dest_dir)
192            .arg(task_id.to_string())
193            .output()
194            .map_err(|e| Error::Parse(format!("failed to run koji download-logs: {e}")))?;
195
196        if !output.status.success() {
197            let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
198            return Err(Error::Parse(format!(
199                "koji download-logs {task_id} failed: {stderr}"
200            )));
201        }
202
203        let path = dest_dir.join(filename);
204        if path.exists() {
205            return std::fs::read_to_string(&path).map_err(|e| {
206                Error::Parse(format!("failed to read {filename} for task {task_id}: {e}"))
207            });
208        }
209
210        // koji download-logs may use a different layout — search for the
211        // file anywhere under dest_dir.
212        if let Some(found) = find_file_recursive(dest_dir, filename) {
213            return std::fs::read_to_string(&found)
214                .map_err(|e| Error::Parse(format!("failed to read {}: {e}", found.display())));
215        }
216
217        // List what was actually downloaded for diagnostics.
218        let mut files = Vec::new();
219        collect_files(dest_dir, &mut files);
220        Err(Error::Parse(format!(
221            "{filename} not found for task {task_id}\n\
222             koji download-logs produced: {}",
223            if files.is_empty() {
224                "(no files)".to_string()
225            } else {
226                files
227                    .iter()
228                    .map(|p| p.strip_prefix(dest_dir).unwrap_or(p).display().to_string())
229                    .collect::<Vec<_>>()
230                    .join(", ")
231            }
232        )))
233    }
234
235    /// Return the koji CLI profile for this instance, if any.
236    fn koji_profile(&self) -> Option<&'static str> {
237        match self.instance.as_str() {
238            "koji.fedoraproject.org" => None,
239            "cbs.centos.org" => Some("cbs"),
240            "kojihub.stream.centos.org" => Some("stream"),
241            _ => None,
242        }
243    }
244}
245
246/// Recursively find a file by name under a directory.
247pub fn find_file_in(dir: &Path, name: &str) -> Option<std::path::PathBuf> {
248    find_file_recursive(dir, name)
249}
250
251fn find_file_recursive(dir: &Path, name: &str) -> Option<std::path::PathBuf> {
252    let entries = std::fs::read_dir(dir).ok()?;
253    for entry in entries.flatten() {
254        let path = entry.path();
255        if path.is_file() && path.file_name().and_then(|n| n.to_str()) == Some(name) {
256            return Some(path);
257        }
258        if path.is_dir() {
259            if let Some(found) = find_file_recursive(&path, name) {
260                return Some(found);
261            }
262        }
263    }
264    None
265}
266
267/// Collect all file paths under a directory.
268fn collect_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
269    if let Ok(entries) = std::fs::read_dir(dir) {
270        for entry in entries.flatten() {
271            let path = entry.path();
272            if path.is_file() {
273                out.push(path);
274            } else if path.is_dir() {
275                collect_files(&path, out);
276            }
277        }
278    }
279}